0
votes

What I'm attempting to do should be SO easy. Here's my question:

Using VB.NET (If you do C# that's cool too.) with the Google Calendar API, upon a simple GetRequest for one event, with four measly lines of code as shown below, why on earth am I getting

Message[Not Found] Location[ - ] Reason[notFound] Domain[global]

Private Function GetEvent(ByVal CalID As String, ByVal EventID As String) As [Event]
    Dim service As CalendarService = GetCalendarService()
    Dim request As EventsResource.GetRequest = service.Events.Get(CalID, EventID)
    Dim ThisEvent As [Event] = request.Execute()
    Return ThisEvent
End Function

It seems this should be easy... I can already retrieve a list of all my calendars, lists of events from any calendar, and I can insert events into any calendar. All of that is working great. I almost thought I knew what I was doing, until this cropped up.

Since I think the reader may be inclined to point to scope, proper credentials, or that my EventID and CalendarID don't match up, those aren't it. The EventID and the CalendarID were both obtained from a previous event ListRequest.

I'm aware that I could "cheat" and use an event ListRequest (since I'm doing that successfully) to get just the one event, but that's not the proper way to go about it and I'm pretty sure a GetRequest (using EventID) will be faster. I only want the one event.

Any guidance would be much appreciated.

2
I am pretty sure you are using right ids, but could you please check if your calendar id and event id exists? This error will be shown only if that is not the case.Dipen Shah
Both do exist. Also, I edited the code in my question since Alessandro's response... He was correct that I had CalID and EventID switched, but that didn't solve the problem. I have edited my code in the question above to show them in proper order.PaulOTron2000
May be you could use fiddler to see actual request and send it from browser to see if there are any discrepancy there.Dipen Shah

2 Answers

1
votes

Solution

If you take a look at the implementation of the Events.Get method you will see that the parameters are passed in the opposite way: first calendarId, then eventId

  /// <summary>Returns an event.</summary>
  /// <param name="calendarId">Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you
  /// want to access the primary calendar of the currently logged in user, use the "primary" keyword.</param>
  ///
  /// <param name="eventId">Event identifier.</param>
  public virtual GetRequest Get(string calendarId, string eventId)
   {
         return new GetRequest(service, calendarId, eventId);
   }

Reference

.NET Google Client API

1
votes

I have to be honest, I don't know how I solved it. I decided to start a whole new project from scratch to test all of the features of the API I have tried so far:

  • Getting a list of calendars
  • Getting Lists of events within calendars
  • Inserting events
  • And (what failed before) a get request. ...which now works.

WHY it works and it didn't before, I still have no idea. The problem must be elsewhere in my project where it fails, but I'll find it.

For those who may find it helpful (there are very few VB examples out there), make a new project with Form1, add four buttons, a textbox, and a combobox with their default names.

So here's the code:

Imports System.IO
Imports System.Threading
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.Windows.Forms


Public Class Form1
    Private Shared Scopes() As String = {CalendarService.Scope.CalendarEvents, CalendarService.Scope.CalendarReadonly} ', CalendarService.Scope.Calendar}
    'If I ever need to create calendars, or read them
    Private objCalendars As Data.CalendarList '///Holds all calendars.
    Private selectedCalendarID As String = "" '//Holds the currently selected Calendar ID.
    Private Const calendarTimeZone = "America/Los_Angeles"
    'Both of these are for testing purposes.
    Dim TestEventID As String = ""
    Dim TestCalendarID As String = "primary"

    Private Function GetCalendarService() As CalendarService
        Dim credential As UserCredential
        Using stream = New FileStream("credentials.json", FileMode.Open, FileAccess.ReadWrite)
            Dim credPath As String = "token.json"
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
        End Using
        Return New CalendarService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential})

    End Function

    Private Sub LoadCalendars()
        Dim service As CalendarService = GetCalendarService()
        Dim objCalendarListRequest As CalendarListResource.ListRequest = service.CalendarList.List
        objCalendars = objCalendarListRequest.Execute()
        If objCalendars Is Nothing Or objCalendars.Items.Count = 0 Then
            '** No calendars.  Something is wrong.  Give up and die.
            MsgBox("No calendars found?  That's weird.")
            End
        Else
            ComboBox1.Items.Clear()
            ComboBox1.Items.Add("primary")
            For Each objCal As Data.CalendarListEntry In objCalendars.Items
                Console.WriteLine(objCal.Summary)
                ComboBox1.Items.Add(objCal.Summary)
            Next
            ComboBox1.SelectedIndex = 0
        End If
    End Sub

    Private Function GetCalendarIDFromSummary(ByVal Summary) As String
        If Summary = "primary" Then Return Summary
        If objCalendars IsNot Nothing AndAlso objCalendars.Items.Count > 0 Then
            For Each objCal As Data.CalendarListEntry In objCalendars.Items
                If objCal.Summary = Summary Then
                    Return objCal.Id
                End If
            Next
        End If
        Return "" 'Should have found a match if objCalendars was properly loaded.
    End Function

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Call LoadCalendars()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim summary As String = "Hello World"
        If Trim(TextBox1.Text) <> "" Then summary = Trim(TextBox1.Text)
        Call InsertEvent(summary, "1600 Pennsylvania Avenue NW, Washington, DC 20500", "My Description of this event.", Now, 60, GetCalendarIDFromSummary(ComboBox1.SelectedItem.ToString))
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        If TestEventID <> "" Then
            MsgBox(GetEvent(TestCalendarID, TestEventID).Summary)
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Call SearchEvents()
    End Sub


    Private Sub SearchEvents()
        Me.Cursor = Cursors.WaitCursor
        Dim EventCount As Integer = 0
        Dim service As CalendarService = GetCalendarService()
        If objCalendars IsNot Nothing AndAlso objCalendars.Items.Count > 0 Then
            For Each objCal As Data.CalendarListEntry In objCalendars.Items
                If InStr(objCal.Description, "#") = 1 Then 'OPTIONAL: I decided adding this character in the first postion of the description of the calendar is a flag to indicate we search it.
                    Console.WriteLine("***NEW CALENDAR***: " & objCal.Summary)
                    Dim request As EventsResource.ListRequest = service.Events.List(objCal.Id)
                    If TextBox1.Text <> "" Then request.Q = Trim(TextBox1.Text)
                    request.SingleEvents = True
                    request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
                    Dim events As Events = request.Execute()
                    If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
                        For Each eventItem In events.Items
                            If eventItem.Start.DateTime IsNot Nothing Then
                                Dim DateToShow As String = Format(eventItem.Start.DateTime, "MMM dd, \'yy hh:mmtt")
                                Console.WriteLine(DateToShow & ":" & eventItem.Summary & " > EventID: " & eventItem.Id & " > CalID:" & objCal.Id)
                            End If
                            EventCount += 1
                            Me.Text = EventCount.ToString
                        Next eventItem
                    End If
                End If
            Next objCal
        End If
        Me.Cursor = Cursors.Default
        MsgBox("Total items: " & EventCount.ToString)
    End Sub

    Private Sub InsertEvent(ByVal Summary As String, ByVal Location As String, ByVal Description As String, ByVal StartDateTime As DateTime, ByVal DurationMinutes As Integer, ByVal CalendarID As String)
        Dim service As CalendarService = GetCalendarService()
        Dim newEvent As New [Event]() With {
        .Summary = Summary,
        .Location = Location,
        .Description = Description,
        .Start = New EventDateTime() With {.DateTime = StartDateTime, .TimeZone = calendarTimeZone},
        .End = New EventDateTime() With {.DateTime = DateAdd(DateInterval.Minute, DurationMinutes, StartDateTime), .TimeZone = calendarTimeZone}
        }
        Dim request As EventsResource.InsertRequest = service.Events.Insert(newEvent, CalendarID)
        Dim createdEvent As [Event] = request.Execute()
        TestEventID = createdEvent.Id
        TestCalendarID = CalendarID
        Console.WriteLine("Event created:", createdEvent.Id)
    End Sub

    Private Function GetEvent(ByVal CalID As String, ByVal EventID As String) As [Event]
        Dim service As CalendarService = GetCalendarService()
        Dim request As EventsResource.GetRequest = service.Events.Get(CalID, EventID)
        Dim ThisEvent As [Event] = request.Execute()
        Return ThisEvent
    End Function

End Class