method not found Google.apis.Calendar.v3.CalendarService..ctor(Initializer) - vb.net

I have a VB NET application that works correctly in the development environment(windows 8.1).
When I distributed to a computer with windows 7 operates properly.
But when distributed to a computer with Windows 10 I get this error.
Method not found: Void
Google.apis.Calendar.v3.CalendarService..ctor(Initializer).
The procedure that gives me error is as follows:
Try
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add(CalendarService.Scope.Calendar)
Dim credential As UserCredential
Dim cs As New ClientSecrets
cs.ClientId = wclientId
cs.ClientSecret = wclientSecret
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, scopes, "user", CancellationToken.None).Result
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = wapplicationName
service = New CalendarService(initializer)
clientIdAutenticado = wclientId
Catch ex As Exception
Throw New Exception("autenticate:" & ex.Message & ":" & ex.StackTrace)
End Try

Related

How do I insert new sheet in Existing google spreadsheet using vb.net?

I am manage to create spreadsheet on google drive using following code.
Now I want to add new sheets in that created spreadsheet.
When I Create new spreadsheet , it contains default sheet having name Sheet1 but I want to rename that sheet or insert more than one sheets in Spreadsheet
Public Function Create(ByVal FileName As String) As String
Try
Dim service = GetGoogleAPPDriveService()
Dim fileMetadata = New Google.Apis.Drive.v3.Data.File()
fileMetadata.Name = FileName
fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet"
Dim request As FilesResource.CreateRequest = service.Files.Create(fileMetadata)
request.SupportsTeamDrives = True
request.Fields = "id"
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllcertification)
Dim file = request.Execute
Return file.Id
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPDriveService() As DriveService
Try
Dim Scopes1 As String() = {DriveService.Scope.Drive, DriveService.Scope.DriveFile}
Dim ClientId As String = ""
Dim ClientSecret As String = ""
Dim UserCredentials As UserCredential
Dim stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientId = GoogleClientSecrets.Load(stream).Secrets.ClientId
Dim stream1 = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientSecret = GoogleClientSecrets.Load(stream1).Secrets.ClientSecret
Dim cs = New ClientSecrets()
cs.ClientId = ClientId
cs.ClientSecret = ClientSecret
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, Scopes1, Environment.UserName,
CancellationToken.None, New FileDataStore("MyAppsToken", True)).Result
Dim service = New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function
Public Function AcceptAllcertification(ByVal sender As Object, ByVal Certification As X509Certificate, ByVal Chain As X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
You need to use the Sheets API for that. Have a look at the AddSheetRequest
Its hard to identify which request has to be used in .net from json file .
I succeed to add sheet in existing Spread sheet . Here I am put vb.net code if any one needed
Public Function Addsheet(ByVal FileId As String, ByVal sheetName As String) As String
Try
Dim serv = GetGoogleAPPSheetService()
Dim updatesheet = New BatchUpdateSpreadsheetRequest
Dim Req_Request As Request = New Request
Dim Req_AddSheet As New AddSheetRequest
Dim prop As New SheetProperties
prop.Title = sheetName
Req_AddSheet.Properties = prop
Req_Request.AddSheet = Req_AddSheet
Dim IList_req As IList(Of Request)
Dim List_req1 = New List(Of Request)
List_req1.Add(Req_Request)
IList_req = List_req1.ToList
updatesheet.Requests = IList_req
Dim req = serv.Spreadsheets.BatchUpdate(updatesheet, FileId)
Dim response = req.Execute
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPSheetService() As SheetsService
Try
Dim UserCredentials As UserCredential
Using stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "token.json" 'System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)
'credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function

Google drive API v2 upload fails

I am trying to upload to a Google drive using Google Drive API v2, vb.net 2015,
Windows 10 Pro ver 1909. My code throws an "Error: redirect_uri_mismatch" when the following 'CreateService' procedure is called:
Public Sub CreateService()
Dim ClientId = "xxxxxxxxxxxe9gqt7105uofe6q1hmks4e89m.apps.googleusercontent.com"
Dim ClientSecret = "xxxxxxxxxxxxxxxxxxxxx"
'
Dim MyUserCredential As UserCredential = _
GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() _
With {.ClientId = ClientId, .ClientSecret = ClientSecret}, _
{DriveService.Scope.Drive}, "user", CancellationToken.None).Result
Service = New DriveService(New BaseClientService.Initializer() with _
{.HttpClientInitializer = MyUserCredential, .ApplicationName = "My Drive"})
End Sub

Acessing Google Calendar API from Windows Service

I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})

Connecting a VB.NET application with a Google Docs Spreadsheet

I'm creating a small application that can order stuff. The way a user can order something is to input the correct information through a google form, which then would be automatically converted to a Google Spreadsheet.
Now, I want to connect it to my VB application. How can I do that?
You should install sheetsapi v4 to your app.
Here is the code:
Public Class Form3
Shared Scopes As String() = {SheetsService.Scope.SpreadsheetsReadonly}
Shared ApplicationName As String = "Google Sheets API .NET Quickstart"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential, _
.ApplicationName = ApplicationName })
Dim spreadsheetId As [String] = "your sheet id"
Dim range As [String] = "A2:F"
Dim request As SpreadsheetsResource.ValuesResource.GetRequest = service.Spreadsheets.Values.[Get](spreadsheetId, range)
Dim response As ValueRange = request.Execute()
Dim values As IList(Of IList(Of [Object])) = response.Values
Dim son As String
If values IsNot Nothing AndAlso values.Count > 0 Then
ListBox1.Items.Add("Name, Major")
For Each rol In values
son = rol(0) + " " + rol(1) + " " + rol(2) + " " + rol(4)
' Print columns A and E, which correspond to indices 0 and 4.
ListBox1.Items.Add(son)
Next
End If
End Sub
End Class

VB NET Read Remote Registry

I'm trying to get the architecture and the operating system of many remote pcs.
In order to do that i'm querying Win32_OperatingSystem and parsing the "Caption" for the O.S. and for the architecture im reading OSArchitecture .
In Windows XP this value does not exists, so i thought that reading the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE
would have done the trick like this code:
Try
Dim co As New ConnectionOptions
co.Impersonation = ImpersonationLevel.Impersonate
co.Authentication = AuthenticationLevel.PacketPrivacy
co.EnablePrivileges = True
co.Username = username
co.Password = password
Dim scope As New ManagementScope("\\" & machine.Text & "\root\cimv2", co)
scope.Connect()
Dim environmentKey, asd2 As Microsoft.Win32.RegistryKey
Dim asd As String
environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine.Text)
asd2 = environmentKey.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", True)
asd = asd2.GetValue("PROCESSOR_ARCHITECTURE")
Debug.Print("asd: " + asd)
environmentKey.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
My problem is: if im trying this code I get an System.Security.SecurityException: "Accessing remote registry not permitted"
I am, and i know the administrator username and password.
In fact if I run a simple cmdkey /add:targetname /user:username /pass:password
It works.
So why do I have to run a cmdkey /add even if i have alredy specified the username and password in the ConnectionOptions ??
P.S. Sorry for my bad English
This may very well be because remote registry access is not enabled on the target PC.
Even if you know the administrator credentials, remote access to the registry will not work if the feature isn't enabled on the target PC.
To enable it, see the following Microsoft Knowledge Base Article, which covers a variety of Windows Operating Systems: https://support.microsoft.com/en-us/kb/314837
All right, i got it:
Const HKEY_current_user As String = "80000002"
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = ".\administrator"
options.Password = "my_password"
Dim myScope As New ManagementScope("\\" & RemotePCHostname & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_current_user,System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
inParams("sValueName") = "PROCESSOR_ARCHITECTURE"
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
MessageBox.Show(outParams("sValue").ToString())
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If