Batch processing with Google Calendar V3 API - google-calendar-api

I've been working with the new google Calendar V3 API and I've coded all my class methods to process Adds, Updates, retrievals etc but I was wondering if there is a way to send a batch of adds + updates + deletes all at once rather than sending each request separately and possible exceeding the trans/sec threshold. I understand the .Batch method has been depreciated in V3 and I found another methodology that uses web services that will notify a client that changes are ready but I'm trying to do this from a .NET Winform application so it needs to be something initiated from the client and not dependent upon online services or a PUSH methodology.
Regards,
Kerry

I got this to work using the BatchRequest object:
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "My App"
Dim service = New CalendarService(initializer)
'fetch the calendars
Dim list = service.CalendarList.List().Execute().Items()
'get the calendar you want to work with
Dim calendar = list.First(Function(x) x.Summary = "{Calendar Name}")
Dim br As New Google.Apis.Requests.BatchRequest(service)
'make 5 events
For i = 1 To 5
'create a new event
Dim e As New [Event]
'set the event properties
e.Summary = "Test Event"
e.Description = "Test Description"
e.Location = "Test Location"
...
'make a request to insert the event
Dim ins As New InsertRequest(service, e, calendar.Id)
'queue the request
br.Queue(Of Dummy)(ins, AddressOf OnResponse)
Next
'execute the batch request
Dim t = br.ExecuteAsync()
'wait for completion
t.Wait()
For some reason, you can't have a deferred request without specifying a callback to the Queue method, and that method requires a generic type parameter. So I defined the following:
Class Dummy
End Class
Sub OnResponse(content As Dummy, err As Google.Apis.Requests.RequestError, index As Integer, message As System.Net.Http.HttpResponseMessage)
End Sub
With this in place, the batch inserts worked fine.

Related

execute code on load in vb.net aspx page

I appreciate help for this issue which stoled a lot of hours.
I have this code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Label1.Text = "924 695 302"
Label2.Text = "690 142 449"
Dim ipvisitante = Request.ServerVariables("remote_addr")
Dim hoje = DateTime.Now
Dim informacao = ipvisitante & " --- " & hoje
'Send e-mail
Dim strFrom = "fernandopessoa#fpessoa.net" ''IMPORTANT: This must be same as your smtp authentication address.
Dim strTo = "francopessoa.espana#hotmail.com"
Dim MailMsg As New MailMessage(New MailAddress(strFrom.Trim()), New MailAddress(strTo))
MailMsg.BodyEncoding = Encoding.Default
MailMsg.Subject = "This is a test"
MailMsg.Body = "This is a sample message using SMTP authentication"
MailMsg.Priority = MailPriority.High
MailMsg.IsBodyHtml = True
'Smtpclient to send the mail message
Dim SmtpMail As New SmtpClient
Dim basicAuthenticationInfo As New Net.NetworkCredential("fernandopessoa#fpessoa.net", "---------")
''IMPORANT: Your smtp login email MUST be same as your FROM address.
SmtpMail.Host = "mail.fpessoa.net"
SmtpMail.UseDefaultCredentials = False
SmtpMail.Credentials = basicAuthenticationInfo
MsgBox("O ficheiro existe", MsgBoxStyle.Information, "SIM")
'Write to txt File
FileOpen(1, "visitas.txt", OpenMode.Append)
WriteLine(1, informacao)
FileClose()
End Sub
Now, when the page Loads, the text apears in the Labels.
Surprisingly, it doesn't execute the rest of the code, Display Msgbox, Write to the .txt File and send the e-mail.
Can anyone give me a clue of what's going wrong with my code?
Thanks in advance.
The code does execute... it runs on the Web Server. It does not run in the client's web browser, and never will.
That explains the MsBox() and file, though the web server may also be getting hung up waiting for someone to click "Okay" on a MsgBox no one will ever see. For the e-mail, you never call SmtpMail.Send(MailMsg)
While I'm here, that file code is using an antique api.
It sounds like you need a quick primer on how this all works, so here is what happens step by step:
User clicks a link to your page or types your page address in their address bar.
The browser sends an HTTP request to your server.
Your server receives the request, creates a new instance of your page class in a worker thread.
Code runs in your page class for ALL phases of the ASP.Net Page Lifecycle .
The ASP.Net runtime uses your page class instance to render an HTTP response (usually in html) and send it to the browser.
Your page class instance is destroyed.
The browser receives the response, parses a new Document Object Model (DOM), and renders that DOM to the display.
The user sees and interacts with your page, causing a post-back.
Go to step 2, taking special note of the "new instance" phrase when you reach step 3.

Setting reminders in google calendar through .net api

I am writing an asp.net webpage that creates events in google calendar. I want to add a "notification" to the event that will send an email 30 minutes before the event begins.
Reading through the api, I see that there is an attribute for inserting events called "reminders" that seems to be the same thing. Using google's api playground, I can successfully create the event and specify the reminder.
However, using the .net api version 1.9.0.990 I can create the event, but no reminders are set for it. Below is the code I have written:
Shared Sub eventWithReminder(calendarIdentifier As String, startTime As DateTime, endTime As DateTime, eventTitle As String)
Dim calendarID As String
Dim calList As CalendarList = RoomReservations_RoomReservationsServiceAccount.calService.CalendarList.List().Execute
For Each Calendar In calList.Items
If Calendar.Id = calendarIdentifier Then
calendarID = Calendar.Id
End If
Next
Dim anotherNewEvent As New [Event]
anotherNewEvent.Summary = eventTitle
Dim edtStart As New EventDateTime
edtStart.DateTime = startTime
Dim edtEnd As New EventDateTime
edtEnd.DateTime = endTime
anotherNewEvent.Start = edtStart
anotherNewEvent.End = edtEnd
Dim reminder As New EventReminder
reminder.Method = "email"
reminder.Minutes = 30
Dim reminderList As New List(Of EventReminder)
reminderList.Add(reminder)
Dim remindData As New [Event].RemindersData
remindData.UseDefault = False
remindData.Overrides = reminderList
anotherNewEvent.Reminders = remindData
System.Net.ServicePointManager.Expect100Continue = False
RoomReservations_RoomReservationsServiceAccount.calService.Events.Insert(anotherNewEvent, calendarID).Execute()
End Sub
I then view the event in the google calendar web interface, but the Notifications section reads "No notifications set"
Is this functionality not yet built in to the api?
If it is, am I using it incorrectly?
Reminders are tied to the authenticated user. In this case Bob was creating events using service account but on user's calendar. Service accounts do not have privileges to modify reminders for users.
In order to change reminders for someone, you need to be authenticated as that person (use their Oauth token).

VB.NET mailto: Run-time error '91'

Can anyone take a look at my code below and recommend how I can stop receiving the dreaded error 91. Error: Object variable or With block variable not set.
I am using the mailto: function to send an email using the native email client and populating the email w/ data from a gridview. After the error pops up, I simply click ok and the email is loaded w/ the exact data I want!
Protected Sub GridView2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView2.SelectedIndexChanged, GridView1.SelectedIndexChanged
Dim MailFormat, Number, BodyOfEmail, FullName As String
Dim RowValue As Double
RowValue = GridView1.SelectedDataKey.Value - 1
Number = GridView1.Rows(RowValue).Cells(5).Text.ToString
FullName = GridView1.Rows(RowValue).Cells(25).Text.ToString
BodyOfEmail = “SomeTextInTheBody”
MailFormat = "mailto:" & Number & "?" & "subject= A subject here" & "&body=" & BodyOfEmail
System.Diagnostics.Process.Start(MailFormat)
End Sub
I can execute the following code from the .aspx page just fine:
a href="mailto:someone#example.com?Subject=Hello%20again"
and outlook opens without issue. It appears to only be an issue when the aspx.vb code up at the top is executed...
Thanks
<a href="mailto:xxx"/> works fine because it is executing in the user's browser, and will use the user's locally-installed interactive email application, whatever it happens to be.
Process.Start("mailto:xxx") will always fail because it is executing on the web server, which will probably not have a locally-installed interactive email application available, and even if it did, you would not be able to start it interactively on a desktop that does not exist. The fact that it happens to throw error 91 in your test environment is irrelevant. Don't do it, full stop.
What you need to do is arrange for a bit of JavaScript to execute on page render after the server-side event has completed. Something like location.href = "mailto:xxx" may do the trick. Exactly where you should insert this depends on your page design.
Alternatively, if you want to keep the email generation code entirely on the server-side, and you know that your users will always be using Outlook, you could look at calling Exchange Server directly. See here for a starting point.
Have you considered using the SmtpClient class?
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New Net.NetworkCredential("sender address", "sender password")
SmtpServer.Port = 587 'If sending from gmail...
SmtpServer.Host = "smtp.gmail.com" 'If sending from gmail...
mail = New MailMessage()
mail.From = New MailAddress("sender address")
mail.To.Add("recipient address")
mail.Subject = ""
mail.Body = ""
SmtpServer.Send(mail)

Exception thrown when using GData .NET Analytics API

I am facing an issue while trying to fetch data from GoogleAnalytics API on piece of code that has been working well just a couple of days ago.
For this I am referencing the following DLL's:
Google.GData.Analytics.dll
Google.GData.Client.dll
Google.GData.Extensions.dll
And I am using the following code:
Dim visits As String = String.Empty
Dim username As String = "myuser#mydomain.com"
Dim pass As String = "mypassword"
Const dataFeedUrl As String = "https://www.google.com/analytics/feeds/data"
Dim query As AccountQuery = New AccountQuery()
Dim service As AnalyticsService = New AnalyticsService("MyWebAnalyticsService")
service.setUserCredentials(username, pass)
Dim accountFeed As AccountFeed = service.Query(query) ''----------> Exception thrown in this line: GDataRequestException Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
I thought it had to do with a blocking to the account I was using but it wasn't the case because I verified registering the site for another analytics account and is still not working.
This code has been working flawlessly as I've said but all of a sudden has stopped doing so yesterday.
Could you please help me figuring out what's wrong?. Maybe the way the user credentials are set has changed and I am missing something.
Thank you very much for your help.
'----Update----
I managed to make it work and now I can query the visits for a desired domain. The code goes as follows:
Dim visits As String = String.Empty
Dim username As String = "myuser#mydomain.com"
Dim pass As String = "mypassword"
'Follow the instructions on https://developers.google.com/analytics/resources/articles/gdata-migration-guide (Create a Project in the Google APIs Console) to generate your key
'Once you have it set it as part of the querystring to request our GA service
Dim gkey As String = "key=yourkeystring"
'Set the new URI to retrieve the feed data and append it the generated key
Dim dataFeedUrl As String = "https://www.google.com/analytics/feeds/data?" & gkey
'Create and authenticate on our service instance
Dim service As AnalyticsService = New AnalyticsService("MyAnaliticsService")
service.setUserCredentials(username, pass)
'Use the profile id for the account you want to get ths visits from, you can find it
'logging in your analytics account, select the desired domain on your list (blue link)
click on the administrator button and on the profiles tab find the profile
'configuration subtab, right there you will find the profile id in this case the eight characters long id 12345678
Dim query1 As DataQuery = New DataQuery(dataFeedUrl)
With query1
.Ids = "ga:12345678"
.Metrics = "ga:visits"
.Sort = "ga:visits"
.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd")
.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
.StartIndex = 1
End With
'Use the generated datafeed based on the former query to get the visits
Dim dataFeedVisits As DataFeed = service.Query(query1)
For Each entry As DataEntry In dataFeedVisits.Entries
Dim st As String = entry.Title.Text
Dim ss As String = entry.Metrics(0).Value
visits = ss
Next
I have the same problem and it looks like google recently shut down the feed. It is answered in another post. Issue com.google.gdata.util.ResourceNotFoundException: Not Found with Google Analytic
Please make sure you registered your project in the APIs Console and you are sending the API Key with your requests.
If that is not the issue, inspecting the inner exception will give you more details about the error. As an alternative, you can use Fiddler to capture the HTTP request and the response. The latter will include a more descriptive error message.

BackgroundWorker for YouTube DirectUpload in VB.NET?

I'm trying to implement a direct upload of videos on my server to YouTube. When a user adds a video, it gets copied to YouTube.
The user action of adding the video should begin the upload process, which could take a while. The form, even an asynchronous form, should not sit there and wait for this to happen. It should just begin and allow the user to move on, trusting that it is being taken care of in the background.
To allow this, I am attempting to use system.threading.backgroundworker. My hope is that the process would begin, and the web app would move on. It's not. It's hanging, whether it's an asynchronous or full postback, and waiting for the upload to finish before returning and updating the lblmsg.text.
Is there a different way I should be going about this, so the user can initiate the upload procedure and not wait around for it to complete? Here is my code so far:
Sub up_load(s As Object, e As EventArgs)
Dim worker As BackgroundWorker = New BackgroundWorker
worker.WorkerReportsProgress = True
worker.WorkerSupportsCancellation = True
AddHandler (worker.DoWork), AddressOf begin_upload
'call this and move on?
worker.RunWorkerAsync()
lblmsg.Text = "Successfully initiated upload"
End Sub
Sub begin_upload(s As Object, e As DoWorkEventArgs)
Dim request As New YouTubeRequest(settings)
Dim vidupload As New Video()
vidupload.Title = "My Big Test Movie"
vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
vidupload.Keywords = "church, jesus"
vidupload.Description = "See the entire video"
vidupload.YouTubeEntry.Private = False
vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")
Dim createdVideo As Video = Request.Upload(vidupload)
End Sub
You might want to look into the Task Parallel Library for adding multithreading to your code. Given the code that you provided:
Add this import statement
Imports System.Threading.Tasks
And replace all backgroundworker logic with this simple statement:
Dim uploadTask As Task = Task.Factory.StartNew(Sub()
Dim request As New YouTubeRequest(settings)
Dim vidupload As New Video()
vidupload.Title = "My Big Test Movie"
vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
vidupload.Keywords = "church, jesus"
vidupload.Description = "See the entire video"
vidupload.YouTubeEntry.Private = False
vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")
Dim createdVideo As Video = request.Upload(vidupload)
End Sub)
Now you have the uploadTask uploading your video in the background and your UI thread will be free to process other code. It does get a bit more complicated if you want cancellation and progress reporting, but the link at the top should get you started.

Resources