Creating Event in Googles Calendar using VB and Googles API - vb.net

I'm having problems trying to write a VB program using VS2015 to create an event in Googles Calendar using their API, there seems a distinct lack of information regarding the API and VB. I've posted my entire code below and the problem I'm getting is on the line : -
Dim createdEvent As [Event] = request.Execute(), the error I get is
Insufficient Permission [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
can anyone help please
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Calendar.v3
Imports Google.Apis.Calendar.v3.Data
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports Google.Apis.Calendar.v3.EventsResource
Imports Google.Apis.Requests
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SurroundingSub()
End Sub
Private Sub SurroundingSub()
Dim service = Authenticate()
Dim newEvent As [Event] = New [Event]() With {
.Summary = "Google I/O 2015",
.Location = "800 Howard St., San Francisco, CA 94103",
.Description = "A chance to hear more about Google's developer products.",
.Start = New EventDateTime() With {
.DateTime = DateTime.Parse("2015-05-28T09:00:00-07:00"),
.TimeZone = "America/Los_Angeles"
},
.[End] = New EventDateTime() With {
.DateTime = DateTime.Parse("2015-05-28T17:00:00-07:00"),
.TimeZone = "America/Los_Angeles"
},
.Recurrence = New String() {"RRULE:FREQ=DAILY;COUNT=2"},
.Attendees = New EventAttendee() {New EventAttendee() With {
.Email = "mickburden#btinternet.com"
}, New EventAttendee() With {
.Email = "mickburden#btinternet.com"
}},
.Reminders = New [Event].RemindersData() With {
.UseDefault = False,
.[Overrides] = New EventReminder() {New EventReminder() With {
.Method = "email",
.Minutes = 24 * 60
}, New EventReminder() With {
.Method = "sms",
.Minutes = 10
}}
}
}
Dim calendarId As String = "primary"
Dim request As EventsResource.InsertRequest = service.Events.Insert(newEvent, calendarId)
Dim createdEvent As [Event] = request.Execute()
End Sub
Private Function Authenticate()
Dim scopes = New List(Of String)
scopes.Add(CalendarService.Scope.Calendar)
Dim credential As UserCredential
Using stream As New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
' Using stream As New FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None,
New FileDataStore("Calendar.VB.Sample")).Result
End Using
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "VB.NET Calendar Sample"
Dim service
service = New CalendarService(initializer)
Return service
End Function
end class

Related

How to search a song on YouTube and get the first video ID

I'm using YouTube API v3 and using the endpoint Search:list I want to get the ID of the first video searched by a title. YouTube gives some code samples and this is one in c# that I'm trying to make it work in vb.net
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: search by keyword.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://developers.google.com/api-client-library/dotnet/get_started
///
/// Set ApiKey to the API key value from the APIs & auth > Registered apps tab of
/// https://cloud.google.com/console
/// Please ensure that you have enabled the YouTube Data API for your project.
/// </summary>
internal class Search
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Search");
Console.WriteLine("========================");
try
{
new Search().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "REPLACE_ME",
ApplicationName = this.GetType().ToString()
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = "Google"; // Replace with your search term.
searchListRequest.MaxResults = 50;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = await searchListRequest.ExecuteAsync();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
}
}
}
Using few online converters, I managed to get this vb.net code
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Reflection
Imports System.Threading
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Upload
Imports Google.Apis.Util.Store
Imports Google.Apis.YouTube.v3
Imports Google.Apis.YouTube.v3.Data
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
New Search.Run().Wait()
Catch ex As AggregateException
For Each e In ex.InnerExceptions
MsgBox("Error: " & e.Message)
Next
End Try
End Sub
Private Async Function Run() As Task
Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
.ApiKey = "REPLACE_ME",
.ApplicationName = Me.[GetType]().ToString()
})
Dim searchListRequest = youtubeService.Search.List("snippet")
searchListRequest.Q = TextBox1.Text
searchListRequest.MaxResults = 1
Dim searchListResponse = Await searchListRequest.ExecuteAsync()
Dim videos As List(Of String) = New List(Of String)()
Dim channels As List(Of String) = New List(Of String)()
Dim playlists As List(Of String) = New List(Of String)()
For Each searchResult In searchListResponse.Items
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId))
Next
MsgBox(String.Format("Videos:" & vbLf & "{0}" & vbLf, String.Join(vbLf, videos)))
End Function
End Class
I setted a limit on searchListRequest.MaxResults to return me only 1 result, which means I want to get only the first searched video ID and searchListRequest.Q is connected to a textbox.
In this textbox I'll then write a qwery and I want that once I press the button, a msgbox will appear with the ID of the first searched video..
I'm having 3 errors at debug:
Syntax error on the line New Search.Run().Wait()
'Message' is not a member of 'EventArgs'. on the line MsgBox("Error: " & e.Message)
Value of type 'Exception' cannot be converted to 'EventArgs'. on the line For Each e In ex.InnerExceptions
What Am I supposed to fix them? Thanks
edit:
The complete working code is:
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Reflection
Imports System.Threading
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Upload
Imports Google.Apis.Util.Store
Imports Google.Apis.YouTube.v3
Imports Google.Apis.YouTube.v3.Data
Public Class Form1
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Await Run()
Catch ex As AggregateException
For Each inner In ex.InnerExceptions
MsgBox("Error: " & inner.Message)
Next
End Try
End Sub
Private Async Function Run() As Task
Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
.ApiKey = "your api key ",
.ApplicationName = Me.[GetType]().ToString()
})
Dim searchListRequest = youtubeService.Search.List("snippet")
searchListRequest.Q = TextBox1.Text
searchListRequest.MaxResults = 1
Dim searchListResponse = Await searchListRequest.ExecuteAsync()
Dim videos As List(Of String) = New List(Of String)()
Dim channels As List(Of String) = New List(Of String)()
Dim playlists As List(Of String) = New List(Of String)()
For Each searchResult In searchListResponse.Items
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId))
Next
MsgBox(String.Format("Videos:" & vbLf & "{0}" & vbLf, String.Join(vbLf, videos)))
End Function
End Class

vb.net 2017 unable to insert Calendar event

I have looked at all the examples I could find and hobbled together the code below. The first time I ran it a web page asked if I wanted to allow my user to update Google calendar and then it asked me to select an account. After that it just sat there and my windows application never finished painting the screen and displaying the simple button I had placed on a form from which to run the insert calendar event. Now when I run the code it comes up, a small gray window appears and it just sits there. What am I doing wrong?
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports Google.Apis.Calendar.v3
Imports Google.Apis.Calendar.v3.Data
Imports Google.Apis.Calendar.v3.EventsResource
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Util.Store
Imports Google.Apis.Requests
Public Class Form1
Dim service As CalendarService
Dim GRPS As IList(Of String) = New List(Of String)()
Sub New()
Authenticate()
End Sub
Private Function Authenticate()
GRPS.Add(CalendarService.Scope.Calendar)
Dim credential As UserCredential
Using stream As New FileStream("client_secret.json", FileMode.Open,
FileAccess.Read)
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, GRPS, "user",
CancellationToken.None, New
FileDataStore("Vanguard")).Result
End Using
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "Vanguard"
service = New CalendarService(initializer)
Return 0
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
InsertCalendar()
MessageBox.Show("Done")
Application.Exit()
End Sub
Public Sub InsertCalendar()
Dim CalendarEvent As New Data.Event
Dim SDT As New Data.EventDateTime
Dim A As Date = DateSerial(2017, 8, 11)
A = A.AddHours(10)
A = A.AddMinutes(30)
SDT.DateTime = A
Dim b As Date
b = A.AddHours(2)
Dim EDT As New Data.EventDateTime
EDT.DateTime = b
CalendarEvent.Start = SDT
CalendarEvent.End = EDT
CalendarEvent.Id = System.Guid.NewGuid.ToString
CalendarEvent.Description = "Test Event"
Dim list As IList(Of CalendarListEntry) =
service.CalendarList.List().Execute().Items()
service.Events.Insert(CalendarEvent, list(0).Id).Execute()
End Sub
End Class

Error 401 with Google contacts API on VB Net

I made today a vb net application to fetch my contacts and it was working for one hour then when I try to use my app I get this error:
This is the code I´m using:
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports Google.Contacts
Imports Google.GData.Contacts
Imports Google.GData.Client
Imports Google.GData.Extensions
Public Class Form1
Dim initializer = New BaseClientService.Initializer
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Secrets = New ClientSecrets()
Secrets.ClientId = "MYCLIENTID"
Secrets.ClientSecret = "MYCLIENTSECRET"
Dim scopes As String() = New String() {"https://www.googleapis.com/auth/contacts.readonly"}
Try
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scopes, "email#email.com", CancellationToken.None, New FileDataStore("MYAPPNAME")).Result()
Dim parameters As New OAuth2Parameters()
parameters.AccessToken = credential.Token.AccessToken
parameters.RefreshToken = credential.Token.RefreshToken
Dim settings As New RequestSettings("MYAPPNAME", parameters)
Dim cr As New ContactsRequest(settings)
Dim f As Feed(Of Contact) = cr.GetContacts()
For Each c As Contact In f.Entries
MsgBox(c.Name.FullName)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
How can I solve this issue?
Why this is happening after a good performance?
Thanks
I solved it changing the form of this line:
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scopes,"email#email.com", CancellationToken.None, New FileDataStore("MYAPPNAME")).Result()
by this lines:
Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {
.ClientId = "MYCLIENTID",
.ClientSecret = "MYCLIENTSECRET"
}, scopes, "email#gmail.com", CancellationToken.None, New FileDataStore("MYAPPNAME")).Result
And taking out the secrets section.
Thank you all for your advices.

How can I get the events for one day (Google calendar Api) using TimeMax and TimeMin in net?

I have a code for get a event list of calendar but retrieves ALL events. How can I get the events for just ONE day?
Here is the code that Im using:
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports System.Collections.Generic
Imports Google.Apis.Calendar.v3
Imports Google.Apis.Calendar.v3.Data
Imports Google.Apis.Calendar.v3.Data.Event
Imports Google.Apis.Util.Store
Imports Google.Apis.Calendar.v3.EventsResource
Imports System.Threading
Public Class Form1
Dim scopes As IList(Of String) = New List(Of String)
Dim service As CalendarService
Dim initializer = New BaseClientService.Initializer
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
Dim service As CalendarService
Try
scopes.Add(CalendarService.Scope.Calendar)
Dim Secrets = New ClientSecrets()
Secrets.ClientId = "CLIENT ID"
Secrets.ClientSecret = "CLIENT SECRET"
Dim scope = New List(Of String)
scope.Add(CalendarService.Scope.Calendar)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scopes, "xxxxxxxxxxx#developer.gserviceaccount.com", CancellationToken.None).Result()
Dim initializer = New BaseClientService.Initializer
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "APP NAME"
service = New CalendarService(initializer)
Dim list As IList(Of CalendarListEntry) = service.CalendarList.List().Execute().Items
Dim requeust As ListRequest = service.Events.List("MY EMAIL")
Me.DataGridView1.DataSource = requeust.Execute.Items
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Try to add your searching range with these few lines of code
requeust.TimeMax = Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")
requeust.TimeMin = "2014-12-01T16:00:00" 'changing the time whenever you want
I think it's work :)

VB Net: How to call this Public Shared Function?

Can anybody help me with a couple of doubts?
How can I call this Public Shared Function from a button? and how can I show "result" (list of files) in a datagridview?
Thanks.
Imports System.Threading
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'?
End Sub
Public Shared Function retrieveAllFiles(service As DriveService) As List(Of File)
Dim Secrets = New ClientSecrets()
Secrets.ClientId = "CLIENT ID"
Secrets.ClientSecret = "CLIENT SECRET"
Dim scope = New List(Of String)
scope.Add(DriveService.Scope.Drive)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scope, "USER", CancellationToken.None).Result()
Dim initializer = New BaseClientService.Initializer
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "APPLICATION NAME"
Dim service = New DriveService(initializer)
Dim request As FilesResource.ListRequest = service.Files.List()
Dim result As New List(Of 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
Console.WriteLine("An error occurred: " + e.Message)
request.PageToken = Nothing
End Try
Loop While Not [String].IsNullOrEmpty(request.PageToken)
Return result
End Function
End Class
If it's in the same class, you can just call it by name, same as a non-shared function:
lst = retrieveAllFiles(service)
If it's in another class, you need to prefix it with class name:
lst = className.retrieveAllFiles(service)
Official reference:
Shared Members in Visual Basic