401 Unauthorized - Google Drive API - asp.net

I'm working with the Google APIs for the first time and I'm having problems trying to download files with the File object "downloadUrl" property. I'm currently using the "Service Account" option with the associated service account email and P12 certificate.
However, the URL returned "https://doc-08-68-docs.googleusercontent.com/docs/securesc/bteg36c1tifegg79l2ov17og25612tet/gk7kn52ahe4d0to7d6hte9f0f2hv47e4/1434132000000/11750183130219432819/11750183130219432819/0BziIKv2_NWCxc3RhcnRlcl9maWxl?e=download&gd=true" returns a 401 - Unauthorized response.
Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Namespace Videos
Partial Class List
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Const serviceAccountEmail As String = "#developer.gserviceaccount.com"
Dim certificate = New X509Certificate2(
Server.MapPath("~/bin/key.p12"),
"notasecret",
X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
)
Dim credential = New ServiceAccountCredential(
New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = New String() {DriveService.Scope.Drive}
}.FromCertificate(certificate)
)
Dim service = New DriveService(
New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "LexVid-VideoEncode/1.0"
}
)
UxFiles.DataSource = RetrieveAllFiles(service)
UxFiles.DataBind()
End Sub
Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)
Dim result = New List(Of Data.File)()
Dim request As FilesResource.ListRequest = service.Files.List()
Do
Try
Dim files As FileList = request.Execute()
result.AddRange(files.Items)
request.PageToken = files.NextPageToken
Catch e As Exception
request.PageToken = Nothing
End Try
Loop While (Not String.IsNullOrEmpty(request.PageToken))
Return result
End Function
Public Shared Function DownloadFile(ByVal service As DriveService, ByVal file As Data.File) As System.IO.Stream
If (Not String.IsNullOrEmpty(file.DownloadUrl)) Then
Try
Dim x = service.HttpClient.GetByteArrayAsync(file.DownloadUrl)
Dim result As [Byte]() = x.Result
Return New MemoryStream(result)
Catch e As Exception
Return Nothing
End Try
Else
Return Nothing
End If
End Function
Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound
Dim dataItem = CType(e.Item.DataItem, Data.File)
Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
file.NavigateUrl = dataItem.DownloadUrl
file.Text = dataItem.Title
End Sub
End Class
End Namespace

I got this resolved through some trial and error. Although I'm building the links manually now, so the request token isn't even necessary anymore. However, I'm posting here in case anyone else is looking to resolve a similar issue.
Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports System.Threading
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Namespace Videos
Partial Class List
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Const serviceAccountEmail As String = "#developer.gserviceaccount.com"
Dim certificate = New X509Certificate2(
Server.MapPath("~/bin/key.p12"),
"notasecret",
X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
)
Dim credential As ServiceAccountCredential = New ServiceAccountCredential(
New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = New String() {DriveService.Scope.Drive}
}.FromCertificate(certificate)
)
If (credential.RequestAccessTokenAsync(CancellationToken.None).Result) Then
Dim service = New DriveService(
New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "LexVid-VideoEncode/1.0"
}
)
UxFiles.DataSource = RetrieveAllFiles(service)
UxFiles.DataBind()
End If
End Sub
Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)
Dim result = New List(Of Data.File)()
Dim request As FilesResource.ListRequest = service.Files.List()
Do
Try
Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"
request.Q = String.Format("'{0}' in parents and trashed=false", folderID)
Dim files As FileList = request.Execute()
result.AddRange(files.Items)
request.PageToken = files.NextPageToken
Catch e As Exception
request.PageToken = Nothing
End Try
Loop While (Not String.IsNullOrEmpty(request.PageToken))
Return result
End Function
Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound
Dim dataItem = CType(e.Item.DataItem, Data.File)
Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"
Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
file.NavigateUrl = String.Format("http://googledrive.com/host/{0}/{1}", folderID, dataItem.Title)
' Large files prompt for virus scan; no bypass available.
' file.NavigateUrl = String.Format("https://drive.google.com/uc?export=download&id={0}", dataItem.Id)
file.Text = dataItem.Title
End Sub
End Class
End Namespace

Related

QueryStringModule with FriendlyUrls does not working

Good morning, I need to encrypt my querystring and i found an interesting method in this link and I convert it in vb.net:
Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports System.Security.Cryptography
Public Class QueryStringModule
Implements IHttpModule
Public Sub Dispose() Implements IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
AddHandler context.BeginRequest, New EventHandler(AddressOf context_BeginRequest)
End Sub
Private Const PARAMETER_NAME As String = "enc="
Private Const ENCRYPTION_KEY As String = "key"
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.Url.OriginalString.Contains("aspx") AndAlso context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
Private Shared Function GetVirtualPath() As String
Dim path As String = HttpContext.Current.Request.RawUrl
path = path.Substring(0, path.IndexOf("?"))
path = path.Substring(path.LastIndexOf("/") + 1)
Return path
End Function
Private Shared Function ExtractQuery(ByVal url As String) As String
Dim index As Integer = url.IndexOf("?") + 1
Return url.Substring(index)
End Function
Private ReadOnly Shared SALT As Byte() = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString())
Public Shared Function Encrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim plainText As Byte() = Encoding.Unicode.GetBytes(inputText)
Dim SecretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using encryptor As ICryptoTransform = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream()
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainText, 0, plainText.Length)
cryptoStream.FlushFinalBlock()
Return "?" & PARAMETER_NAME & Convert.ToBase64String(memoryStream.ToArray())
End Using
End Using
End Using
End Function
Public Shared Function Decrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim encryptedData As Byte() = Convert.FromBase64String(inputText)
Dim secretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using decryptor As ICryptoTransform = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream(encryptedData)
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainText As Byte() = New Byte(encryptedData.Length - 1) {}
Dim decryptedCount As Integer = cryptoStream.Read(plainText, 0, plainText.Length)
Return Encoding.Unicode.GetString(plainText, 0, decryptedCount)
End Using
End Using
End Using
End Function
End Class
but also my project use FriendlyUrls and I figured out that with FriendlyUrls the things does not working and always return the url without the extension ".aspx" but with the querystring not encrypted
Imports System.Web.Routing
Imports Microsoft.AspNet.FriendlyUrls
Public Module RouteConfig
Sub RegisterRoutes(ByVal routes As RouteCollection)
Dim settings As FriendlyUrlSettings = New FriendlyUrlSettings() With {
.AutoRedirectMode = RedirectMode.Permanent
}
routes.EnableFriendlyUrls(settings)
End Sub
End Module
of course if I set .AutoRedirectMode to Off it works but without friendlyurls.
Am I doing something wrong?
EDIT 09/10/2019:
We figured out that remove the test of OriginalString.Contains("aspx") in the context_BeginRequest the encryption works, now the code is like:
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
But now the question is: there is other method to target an aspx page without test the extension? I think there is a risk that targeting things that not should target like "ashx" or cache-busting code that use querystring.

How do I print to the default printer on my Laptop from a VB.NET app I deployed to a IIS 8 server?

I've developed a VB.Net App using Visual studio 2015 on my Laptop which will print a rdlc local report for each selected row from a Gridview control directly to my laptop's default printer (which is a network printer) using the Microsoft code for 'walkthrough: Printing a Local Report without Preview' (and runs successfully on my local IIS express). When I deploy this App to a virtual company windows 2012 server that has IIS8 running, it no longer sees the default printer on my laptop (and tries to use the default printer on the windows 2012 server). I've searched the web to no success. I assume it's possible because when I use the reportviewer control in other apps I've developed and deployed on the Windows 2012 server, it can see the list of printers from my local laptop. Any ideas?
Here's the relevant VB code I'm using now...
Imports System.Management
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Collections.Generic
Imports Microsoft.Reporting.WebForms
Partial Class _Default
Inherits System.Web.UI.Page
Implements IDisposable
Private m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Public Shared ViewID As String
Public Shared UserID As String
Public Shared StampID As String
Public Shared GridViewQry As String
Public Shared OpenCntr As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sqlConnection2 As New SqlConnection("DataSource=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
Response.Cache.SetNoStore()
OpenCntr = OpenCntr + 1
ViewID = Request.QueryString("ViewID")
If ViewID = "" Then
Response.Redirect("http://AOXWEBAPP1.SCOTT.COM/login/login.aspx")
Else
UserID = Request.QueryString("UserID")
StampID = Request.QueryString("StampID")
End If
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=1 WHERE Printed = 1"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
If OpenCntr = 1 Then
GridViewQry = "SELECT [Printed], [Customer], [AssySN], [Dte], [AssyPartNbr], [Operator], [PrintDate] FROM [Super_FinalChk] ORDER BY [Dte]"
End If
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
If (superfinalchk.Tables.Count > 0) Then
PrintATRs.DataSource = superfinalchk
If Not IsPostBack Then
PrintATRs.DataBind()
End If
Else
TextBox1.Text = "Unable to Connect to Database"
End If
' TextBox1.Text = DefaultPrinterName()
End Sub
' Routine to provide to the report renderer, in order to
' save an image for each page of the report.
Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As Stream = New MemoryStream()
m_streams.Add(stream)
Return stream
End Function
' Export the given report as an EMF (Enhanced Metafile) file.
Private Sub Export(ByVal report As LocalReport)
Dim deviceInfo As String = "<DeviceInfo>" &
"<OutputFormat>EMF</OutputFormat>" &
"<PageWidth>8.5in</PageWidth>" &
"<PageHeight>11in</PageHeight>" &
"<MarginTop>0.25in</MarginTop>" &
"<MarginLeft>0.50in</MarginLeft>" &
"<MarginRight>0.50in</MarginRight>" &
"<MarginBottom>0.25in</MarginBottom>" &
"</DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
End Sub
' Handler for PrintPageEvents
Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX),
ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY),
ev.PageBounds.Width,
ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
Private Sub PrintRep()
If m_streams Is Nothing OrElse m_streams.Count = 0 Then
Throw New Exception("Error: no stream to print.")
End If
Dim printDoc As New PrintDocument()
If Not printDoc.PrinterSettings.IsValid Then
**
It FAILS HERE!!!!
**
Throw New Exception("Error: cannot find the printer.")
Else
AddHandler printDoc.PrintPage, AddressOf PrintPage
m_currentPageIndex = 0
printDoc.Print()
End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If m_streams IsNot Nothing Then
For Each stream As Stream In m_streams
stream.Close()
Next
m_streams = Nothing
End If
End Sub
Private Function LoadSuperFinalChkVwData(AssySN As String) As DataTable
Dim sqlConnection1 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim querystring As String = "SELECT * FROM dbo.Super_FinalChkVw WHERE AssySN = '" & AssySN & "'"
Dim adapter As New SqlDataAdapter(querystring, sqlConnection1)
Dim superfinalchkvw As New DataSet("DataSet1")
adapter.Fill(superfinalchkvw, "Super_FinalChkVw")
Return superfinalchkvw.Tables(0)
End Function
Protected Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click
Dim report As New LocalReport()
Dim sqlConnection2 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Dim cudate As DateTime
Dim AssySN As String
Dim cntr As Integer = 0
Dim SelectCount As Integer = 0
cudate = DateTime.Now
cmd2.Parameters.AddWithValue("#cudate", cudate)
For Each row As GridViewRow In PrintATRs.Rows
cntr = cntr + 1
Dim cb As CheckBox = DirectCast(row.FindControl("checkbox3"), CheckBox)
AssySN = row.Cells(3).Text
If cb.Checked Then
SelectCount = SelectCount + 1
report.ReportPath = "..\..\Manufacture\Superiox\ATR.rdlc"
report.DataSources.Clear()
report.DataSources.Add(New ReportDataSource("DataSet1", LoadSuperFinalChkVwData(AssySN)))
Export(report)
PrintRep()
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=0, Printed=1, PrintDate=#cudate WHERE AssySN = '" & AssySN & "';"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
End If
Next
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
PrintATRs.DataSource = superfinalchk
PrintATRs.DataBind()
If SelectCount > 0 Then
TextBox1.Text = "Reports Have Been Printed!"
Else
TextBox1.Text = "Please Select Reports to Print!"
End If
End Sub

Cannot refer to an instance member of a class from a shared method

How you get a public shared function outside of a Protected Sub, use the values from within a protected sub to postBack to the same webpage. The postback reply works, but the query of the function fails at (Line 44 Char 17 "fqdom = dom & ".forest.local")
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Partial Class _Default
Inherits System.Web.UI.Page
Dim dom As String
Dim Group1 As String
Dim Group2 As String
Dim usrname As String
Dim fqdom As String
Dim netdom As String
Private Function GetDataFromArrayList() As ArrayList
Dim DomainList As New ArrayList()
DomainList.Add(New ListItem("d1", "dom1"))
DomainList.Add(New ListItem("d2", "dom2"))
Return DomainList
End Function
Protected Sub Selection_Changed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
For Each item As ListItem In GetDataFromArrayList()
DropDownList1.Items.Add(item)
Next
End If
End Sub
Public Shared Function GetGroups() As ArrayList
Dim groupList As New ArrayList()
Dim usrname As String
Dim fqdom As String
'Dim netdom As String
Dim groupCheck As String
fqdom = dom & ".forest.local"
Dim entry As System.DirectoryServices.DirectoryEntry
Dim searcher As System.DirectoryServices.DirectorySearcher
Dim result As System.DirectoryServices.SearchResult
Try
entry = New System.DirectoryServices.DirectoryEntry("LDAP://" & fqdom)
searcher = New DirectorySearcher()
searcher.SearchRoot = entry
searcher.Filter = "(samAccountName=" & usrname & ")"
searcher.PropertiesToLoad.Add("memberOf")
result = searcher.FindOne()
Dim groupCount As Integer = result.Properties("memberOf").Count
For groupCounter As Integer = 0 To groupCount - 1
groupCheck = CStr(result.Properties("memberOf")(groupCounter))
groupCheck = groupCheck.Remove(groupCheck.LastIndexOf(",CN="))
groupCheck = groupCheck.Replace("CN=", "")
groupList.Add(groupCheck)
Next groupCounter
Catch ex As Exception
End Try
Return groupList
End Function
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Dim name As Boolean = False
If Not TextBox1.Text = String.Empty Then
name = True
End If
If name = False Then
StatusLabel.Text = "Update Status: Please Enter Name"
ElseIf name = True Then
Group1 = "groupb1"
Group2 = "groupb2"
Try
form1.Visible = False
Dim groups As New ArrayList()
groups = GetGroups()
Dim group As String
For Each group In groups
'NameLabel.Text = group
If (group.Contains(Group1)) Then
Group1.Text = "User: " & usrname & " is in group1"
End If
If (group.Contains(Group2)) Then
Group1.Text = "User: " & usrname & " is in group2"
End If
Next
fqdn.Text = "Domain: " & dom & ".forest.local"
NameLabel.Text = "User: " & usrname
Catch ex As Exception
End Try
Else
StatusLabel.Text = "Upload status: Error Please Retry later"
End If
End If
End Sub
End Class
Remove the Shared keyword from the method, so replace
Public Shared Function GetGroups() As ArrayList
with
Public Function GetGroups() As ArrayList
You cannot use instance variables like dom from within a Shared method.
You could also make those fields Shared. But that's not a good idea in ASP.NET since it could cause locks and concurrency issues and every request shared the same values(even of different users).
It's also not necessary since you want to use that method from a page method(button-click), so you need an instance of the page anyway.
If you need to persist a value across postback you can use a different way like using ViewState, Session or a HiddenField.

DataSet not defined?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim AppName As String = Session("App_Name").ToString()
Dim username As String = Session("username").ToString()
Dim password As String = Session("password").ToString()
Dim ds As DataSet = GContactsImport.GetGmailContacts(AppName, username, password)
GridView1.DataSource = ds
GridView1.DataBind()
End Sub
how do i fix it??
This is my class file
Imports Microsoft.VisualBasic
Imports Google.GData.Contacts
Imports Google.GData.Client
Imports Google.GData.Extensions
Imports Google.Contacts
Public Class Google
Public Shared Function GetGmailContacts(ByVal AppName As String, ByVal Uname As String, ByVal UPassword As String) As DataSet
Dim ds As New DataSet()
Dim dt As New DataTable()
Dim C2 As New DataColumn()
C2.DataType = Type.GetType
C2.ColumnName = "EmailID"
dt.Columns.Add(C2)
Dim rs As New RequestSettings(AppName, Uname, UPassword)
rs.AutoPaging = True
Dim cr As New ContactsRequest(rs)
Dim f As Feed(Of Contact) = cr.GetContacts()
For Each t As Contact In f.Entries
For Each email As EMail In t.Emails
Dim dr1 As DataRow = dt.NewRow()
dr1("EmailID") = email.Address.ToString()
dt.Rows.Add(dr1)
Next
Next
ds.Tables.Add(dt)
Return ds
End Function
End Class
Verify that DataSet is in scope (you may need to add an Import statement) or, alternatively, fully qualify the DataSet references in your code by replacing Dim ds As DataSet with Dim ds As System.Data.DataSet.
You might need to reference the System.Data assembly from the GAC and Imports System.Data (at the top of your file) in order to bring the DataSet class into scope.

ASP NET Stop other sub proc from executing after error

I am having a problem with my try catch block runs in the error:
database is not available
My problem is the try catch runs and catches the error, but it will not redirect to my error page. The code continues to execute the other subs. I have tried adding: exit, return, response.end. None of them worked. Thank you for your help.
Imports System.Data
Imports EUC
Imports System.Threading
Imports System.Data.SqlClient
Partial Class mpMain
Inherits System.Web.UI.MasterPage
Dim strSQL As String
Dim objData As clsDataAccess = New clsDataAccess()
Dim ds As New D
ataSet
Dim t1 As DataTable
Dim intSecurityLevel As String = 0
Dim strUser As String = UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4))
Protected Sub ExpandNode(ByVal NodeName As String, ByVal PageName As String)
'More Code
End Sub
Protected Sub ExpandNode2(ByVal NodeNameMain As String, ByVal NodeName As String, ByVal PageName As String)
'More Code
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (IsPostBack) Then
Try
strSQL = "Select SecurityLevel from tblSecurity where SFID = #SFID order by SecurityLevel"
Dim MyParameters1 As SqlParameter() = { _
New SqlParameter("#SFID", SqlDbType.VarChar) _
}
MyParameters1(0).Value = UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4))
ds = objData.SQLExecuteDataset(strSQL, CommandType.Text, MyParameters1)
t1 = ds.Tables(0)
Catch ex As Exception
Dim sendError As New clsExceptionMessage
sendError.sendMessage(ex.Message, Request.Path, strSQL)
Response.Redirect("ErrorMessage.aspx", False)
End Try
End If
End Sub
Protected Sub TreeView1_TreeNodeDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles TreeView1.TreeNodeDataBound
'More Code
End Sub
Protected Sub TreeView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.DataBound
'More Code
End Sub
End Class
Firstly I would catch SQLException, you rarely want to catch a general exception.
In the catch block, set a boolean parameter such as
hasError = True
and once outside the try..catch block check for this to be true and redirect from there.

Resources