How to add recurring entry Google Calendar - c#

I would like to add a recurring event with C#. I found on the Web that the following should work. When I run the method to insert the entry, It fails on the
EventEntry insertedEntry = service.Insert(calendarUri, entry); statement !
I get this error :
"Execution of request failed:
https://www.google.com/calendar/feeds/user#gmail.com/private/full?gsessionid=6eGsOTuhQ-YUVWp2BV_25g"
When I remove the recurrence code, everything works fine ! I noticed that this piece of code is pretty old ! How can I simply add a recurring event on Google Calendar with the .NET library ?
EventEntry entry = new EventEntry();
entry.Title.Text = "Hello World !";
// Recurring event:
String recurData =
"RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20131010;BYDAY=SU\r\n";
Recurrence recurrence = new Recurrence();
recurrence.Value = recurData;
entry.Recurrence = recurrence;
string htmlDescription = "Woww, really ?";
if (htmlDescription != null && htmlDescription.Length > 0)
{
entry.Content.Type = "html";
entry.Content.Content = htmlDescription;
}
Where eventLocation = new Where();
eventLocation.ValueString = "Somewhere";
entry.Locations.Add(eventLocation);
DateTime start = DateTime.Now;
When eventTime = new When();
eventTime.StartTime = start;
DateTime endTime = DateTime.Now.AddHours(2);
eventTime.EndTime = endTime;
entry.Times.Add(eventTime);
eventTime.AllDay = true;
EventEntry insertedEntry = service.Insert(calendarUri, entry);

Straight from Google (click the .NET example if it doens't come up as a default):Create Recurring Events
Hopefully this will give you some ideas if not out-right answer your question.
Cheers.

Your recurrence string telling it when to end requires a full time entry. You simply said UNTIL=20131010. The question is 20131010 where? We can assume you want midnight, but then... midnight where?
String recurData =
"RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20131010T000000-05:00;BYDAY=SU\r\n";
The above change should make your event recur until Midnight US Eastern time on 2013-10-10.

Related

EWS Performance in C# WinForms application

I'm using EWS in my winforms application to create a new appointment in my Outlook (+ to get items from my Outlook Calendar).
The issue i'm having is the following:
Everything works perfect but currently it takes 20-25 seconds to retrieve my appointments (= calendar items in Outlook) and 13-20 seconds to create an appointment
The code that does this comes straight from 'Google':
private void btn_Test_Click(object sender, EventArgs e)
{
DateTime d1 = DateTime.Now;
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
try
{
service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new WebCredentials("mail", "pass");
/*service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;*/
service.AutodiscoverUrl("mail", RedirectionUrlValidationCallback);
service.Url = new Uri("https://mail.domain.com/EWS/Exchange.asmx");
}
catch (Exception ml2)
{
MessageBox.Show(ml2.ToString());
}
// We get 10 items in the calendar for the next week
DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddDays(7);
const int NUM_APPTS = 10;
// Initialize the calendar folder object with only the folder ID.
CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
// Set the start and end time and number of appointments to retrieve.
CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);
// Limit the properties returned to the appointment's subject, start time, and end time.
cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
// Retrieve a collection of appointments by using the calendar view.
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
Console.WriteLine("\nThe first " + NUM_APPTS + " appointments on your calendar from " + startDate.Date.ToShortDateString() +
" to " + endDate.Date.ToShortDateString() + " are: \n");
foreach (Appointment a in appointments)
{
Console.Write("Subject: " + a.Subject.ToString() + " ");
Console.Write("Start: " + a.Start.ToString() + " ");
Console.Write("End: " + a.End.ToString());
Console.WriteLine();
}
DateTime d2 = DateTime.Now;
MessageBox.Show( "Seconds: " + (d2 - d1).TotalSeconds.ToString());
}
Since I have absolutely 0 experience with EWS (or developing while using API's) I was wondering if there was room for performance or I wanted to know if this is just normal? I haven't found anything EWS = SLOW related so I was worrying a bit.
Could it be that my code is wrong or that i need to configure one thing or another server sided to improve results?
Thanks
The most likely thing to slow down you code is
service.AutodiscoverUrl("mail", RedirectionUrlValidationCallback);
service.Url = new Uri("https://mail.domain.com/EWS/Exchange.asmx");
You do an AutoDiscover and then set the link manually which is make the first AutoDiscover Call redundant. Auto-discover will do multiple searches of Local AD domain, DNS records to try and discover the correct URL to use so I would suggest if you are going to hardcode the URL you remark out the first line.
Also your testing logic only looks at the total time to execute you function which isn't going to be helpfully you should look at the time to complete each operation eg
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
or
CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
or any Save, Send type method call when the actually call to the server is made if you time this that will give you a true indication of the speed of each call.

Google.Apis.Calendar.v3 Time zone issue when getting events

I am getting Events with below code:
EventsResource.ListRequest req = service.Events.List(calresult[i].Id);
DateTime minLimit = DateTime.Now.AddMonths(-1);
DateTime maxLimit = DateTime.Now.AddMonths(3);
req.TimeZone = googleapiTimezone; //Pacific/Honolulu
req.TimeMin = minLimit;
req.TimeMax = maxLimit;
var events = req.Execute().Items;
The code is working find except it is not considering the Timezone parameter in any case it returns the Event DateTime info in the default event timezone.
What am i doing wrong here?

how to make DateTime and "SetWallpaperAsync" work together?

I am trying to do a UWP app that changes wallpaper and lockscreen based on the time of the day (as a start). I am facing difficulties implementing this:
I have the task "SetWallpaperAsync" on main page (I am making sure it works before shifting it to a background task) as fallowing:
private async Task<bool> SetWallpaperAsync()
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
var imageID = DateTime.Now.Hour.ToString("HH");
var uri = new Uri($"ms-appx:///Dynamic/Dynamic-{imageID}.jpg");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file);
success = await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file);
}
return success;
}
But it only worked once then it stopped, which lead me to believe that the imageID string is not returning the correct value (the value is between 00 and 23, corresponding to the hours in a day in a 24 format).
I have also tried to link a textblock to the same value and different formats, but it did not appear on the app homepage. I am not sure at all where its going wrong!
// Time format
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("hour");
DateTime dateToFormat = DateTime.Now;
var mydate = formatter.Format(dateToFormat);
TimeDescriptionTextBlock.Text = mydate.ToString();
// another try with the time
TimeHours.Text = DateTime.Now.ToString("HH:mm:ss");
How can I debug this code and see where its stopping?
If you output the imageID variable in the Output windows using Debug.Writeline:
var imageID = DateTime.Now.Hour.ToString("HH");
Debug.WriteLine(imageID);
You can see that the output is: HH.
The reason for this is that the format string HH works on DateTime variables, but you are actually calling it on the Hour variable only, which is just a number.
There are two possible solutions:
Remove the .Hour from the call: var imageID = DateTime.Now.ToString("HH");
Just use the Hour as a number: var imageID = DateTime.Now.Hour.ToString();
Both solutions are equivalent and will yield a 24-hour format hour number.

EWS API trying get appointment starting from a modified date

I am currently working on an app that checks all appointments on an individual email, it can update appointments, delete them, create new etc. This part is working already.
I am now trying to put all appointment starting from a specified last modified time into a list, and here is my issue. Code:
public void getByModifiedDate(CalendarFolder calendar)
{
bool found = false;
string date;
Console.WriteLine("Modified date: ");
date = Convert.ToString(Console.ReadLine());
List<TAppointments> tempList = new List<TAppointments>();
var appointments = getAppointments(calendar);
//loop through every appts on calendar
foreach (Appointment a in appointments)
{
if (a.LastModifiedTime.ToString() == date)
{
TAppointments app = new TAppointments(a.ICalUid.ToString(), a.Subject.ToString(), a.Start.ToString(), a.End.ToString(), a.LastModifiedTime.ToString());
currentApp = app;
tempList.Add(app);
found = true;
}
}
if (!found)
{
Console.WriteLine("No appointment found.");
}
printAppointments(tempList);
}
Here I can only find a single item, because well that's what I coded. Is there a way to specified a starting date? Something like lastmodifiedtime >= date? I've made some researched and did not find anything.
I fixed my case. I simply converted my specified date to DateTime, then I could compare it properly, as seen below. I hope it helps some people who has the same issue.
foreach (Appointment a in appointments)
{
if (a.LastModifiedTime >= Convert.ToDateTime(date))
{
i++;
TAppointments app = new TAppointments(a.ICalUid.ToString(), a.Subject.ToString(), a.Start.ToString(), a.End.ToString(), a.LastModifiedTime.ToString());
currentApp = app;
tempList.Add(app);
found = true;
}
}

iCal Time Zone issue

I'm trying to allow a user to download an iCal for their calendar in ASP.Net, but am having a timezone issue.
If I download the file on my computer, the time appears correct and within the correct timeframe. However, when I try to download it on a phone, the timezone switches and it becomes 5 hours behind (aka 7:00 AM becomes 3:00 AM).
Does anyone know how to fix this issue/set the timezone?
Here is the code:
iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();
DateTime dt = (DateTime)Convert.ToDateTime(lblTicketDue.Text);
Console.Write(dt);
evt.Start = new iCalDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
evt.End = new iCalDateTime((DateTime)Convert.ToDateTime(lblTicketDue.Text).AddMinutes(15.0));
Alarm alarm = new Alarm();
alarm.Action = AlarmAction.Display;
alarm.Summary = "Ticket due!";
Trigger t = new Trigger();
iCalDateTime icdt = new iCalDateTime(dt.Subtract(TimeSpan.FromMinutes(120.0)));
t.DateTime = icdt;
alarm.Trigger = t;
evt.Alarms.Add(alarm);
iCal.Events.Add(evt);
iCalendarSerializer serializer = new iCalendarSerializer();
string output = serializer.SerializeToString(iCal);
Response.ContentType = "text/calendar";
Response.Write(output);
Response.End();
Hard to tell without looking at the actual iCalendar stream that gets generated but it is quite likely that you are generating your DTSTART/DTEND using floating time (e.g. "20160517T070000" ).
If the event is not recurring (no RRULE), what you want to do is convert your datetime to UTC and use the "date with UTC time" format described in https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5
i.e. something like "20160517Txx0000Z"
If the event is recurring you would then need to use the last form (date with local time and timezone reference).

Categories