Delete and update Google events [Google Calendar] using ASP.NET - c#

How I can add in my website the update and delete events to my Google Calendar using ASP.NET C#?

You can use the methods Calendars: update to update metadata for a calendar. and Calendars: delete to delete a secondary calendar. Use Calendars.clear for clearing all events on primary calendars.
Sample HTTP requests:
Update: PUT https://www.googleapis.com/calendar/v3/calendars/calendarId
Delete: DELETE https://www.googleapis.com/calendar/v3/calendars/calendarId
Clear: POST https://www.googleapis.com/calendar/v3/calendars/calendarId/clear
Found this thread with a working .NET code for Google Calendar API V3.
Update Event:
public string CreateUpdateEvent(string ExpKey, string ExpVal, string evTitle, string evDate)
{
EventsResource er = new EventsResource(calService);
var queryEvent = er.List(calID);
queryEvent.SharedExtendedProperty = ExpKey + "=" + ExpVal; //"EventKey=9999"
var EventsList = queryEvent.Execute();
Event ev = new Event();
EventDateTime StartDate = new EventDateTime();
StartDate.Date = evDate; //"2014-11-17";
EventDateTime EndDate = new EventDateTime();
EndDate.Date = evDate;
ev.Start = StartDate;
ev.End = EndDate;
ev.Summary = evTitle; //"My Google Calendar V3 Event!";
string FoundEventID = String.Empty;
foreach(var evItem in EventsList.Items)
{
FoundEventID = evItem.Id;
}
if (String.IsNullOrEmpty(FoundEventID))
{
//If event does not exist, Append Extended Property and create the event
Event.ExtendedPropertiesData exp = new Event.ExtendedPropertiesData();
exp.Shared = new Dictionary<string, string>();
exp.Shared.Add(ExpKey, ExpVal);
ev.ExtendedProperties = exp;
return er.Insert(ev, calID).Execute().Summary;
}
else
{
//If existing, Update the event
return er.Update(ev, calID, FoundEventID).Execute().Summary;
}
}
Delete Event:
public bool DeleteEvent(string ExpKey, string ExpVal)
{
EventsResource er = new EventsResource(calService);
var queryEvent = er.List(calID);
queryEvent.SharedExtendedProperty = ExpKey + "=" + ExpVal; //"EventKey=9999"
var EventsList = queryEvent.Execute();
string FoundEventID = String.Empty;
foreach (Event ev in EventsList.Items)
{
FoundEventID = ev.Id;
er.Delete(calID, FoundEventID).Execute();
return true;
}
return false;
}
Check also this Quickstart tutorial from Google documentation.

Related

How to have multiple Firebase AddSnapshotListener(s) inside a single class?

I have a class in android which has a listener setup to get visitorlist updates.
var visitorDetailsCollection = FirebaseFirestore.Instance.Collection("visitorDetails");
var visitorDetailsquery = visitorDetailsCollection.WhereEqualTo("UserID", Firebase.Auth.FirebaseAuth.Instance.CurrentUser.Uid);
visitorlistner = visitorDetailsquery.AddSnapshotListener(this);
and when the firestore db is updated the following method runs and gets the updates
public void OnEvent(Java.Lang.Object obj, FirebaseFirestoreException error)
{
try
{
var docs = (QuerySnapshot)obj;
visitorDetails.Clear();
foreach (var doc in docs.Documents)
{
var visitordetails = new VisitorDetails
{
Name = doc.Get("VisitorName").ToString(),
ContactNumber = doc.Get("VisitorContact").ToString(),
VehicleNumber = doc.Get("VisitorVehicleNo").ToString(),
IsApproved = doc.Get("VisitorIsApproved").ToString(),
IsActive = doc.Get("VisitorIsActive").ToString(),
Purpose = doc.Get("PurposeOfVisit").ToString(),
Email = doc.Get("VisitorEmail").ToString(),
FromDate = toDatetime(doc.GetDate("FromDate") as Date),
ToDate = toDatetime(doc.GetDate("ToDate") as Date),
docID = doc.Id
};
visitorDetails.Add(visitordetails);
}
Now I want to add another listener to get residentdetails like this
residentlistner = residentDetailsquery.AddSnapshotListener(this);
How do I tell this listener to run a different function like
public void OnEvent2(Java.Lang.Object obj, FirebaseFirestoreException error)
{}
when the firestore db is updated?

Creating recurring events via Google Calendar API v3

I've got a web application that a user fills out a form and on submit it adds an event to a google calendar. I can insert a single instance of an event onto the calendar but when I try to set the recurrence of the event I am unable to do so. My methods so far have either accomplished nothing or the event is created, but only for a single occurrence.
I am using google api calendar v3 below is my code to insert the event.
try{
Google.Apis.Calendar.v3.CalendarService g = new
Google.Apis.Calendar.v3.CalendarService();
Google.Apis.Calendar.v3.Data.Event ev = new
Google.Apis.Calendar.v3.Data.Event();
//Create Date Times for start and end time
EventDateTime starter = new EventDateTime();
starter.DateTime = start;
EventDateTime ender = new EventDateTime();
ender.DateTime = end;
//Add values to the event
ev.Start = starter;
ev.End = ender;
ev.Summary = summary.Text;
ev.Location = location.Text;
ev.Description = description.Text;
String[] recd = {"RRULE:FREQ=WEEKLY;COUNT=2"};
Random rnd = new Random();
ev.RecurringEventId = "asdf" + rnd.Next(9999).ToString();
ev.Recurrence = recd;
//Add to calendar
addEvent(service, ev);
g.Events.Insert(ev, "********");
}
EDIT 1:
I've rewritten my event creation code as follows:
EventDateTime starter = new EventDateTime();
starter.DateTime = start;
EventDateTime ender = new EventDateTime();
ender.DateTime = end;
Event newEvent = new Event()
{
Summary = summary.Text,
Location = location.Text,
Description = description.Text,
Start = starter,
End = ender,
Recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"}
};
String calendarId = "****#group.calendar.google.com";
EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
Event createdEvent = request.Execute();
The only problem being that the event will not be created nor its recurrence. If I leave off that line, the code will run and insert the single event into the calendar.
Did you forget to call .execute() ?
Event newEvent = new Event()
{
Summary = "Read Awesome Blog posts by Linda ",
Location = "1600 Amphitheatre Parkway., Mountain View, CA 94043",
Description = "A chance to learn more about Google APIs.",
Start = new EventDateTime()
{
DateTime = DateTime.Parse("2015-09-20T09:00:00-07:00"),
TimeZone = "America/Los_Angeles",
},
End = new EventDateTime()
{
DateTime = DateTime.Parse("2015-09-20T17:00:00-07:00"),
TimeZone = "America/Los_Angeles",
},
Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" },
Attendees = new EventAttendee[] {
new EventAttendee() { Email = "test#test.com" },
},
Reminders = new Event.RemindersData()
{
UseDefault = false,
Overrides = new EventReminder[] {
new EventReminder() { Method = "email", Minutes = 24 * 60 },
new EventReminder() { Method = "sms", Minutes = 10 },
}
}
};
String calendarId = "primary";
EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
Event createdEvent = request.Execute();

Why invitees/details of Windows.ApplicationModel.Appointments.Appointment are empty

I am working on a Windows Phone 8.1 application, and this app want to get the meetings from Calendar.
I am using the Windows Runtime api to get all appointment like this:
AppointmentStore appointmentStore = await AppointmentManager.RequestStoreAsync(AppointmentStoreAccessType.AllCalendarsReadOnly);
IReadOnlyList<Windows.ApplicationModel.Appointments.Appointment> appointments = await appointmentStore.FindAppointmentsAsync(DateTime.Now, TimeSpan.FromHours(24)); ;
foreach (var appointment in appointments)
{
var persistentId = appointment.RoamingId;
var details = appointment.Details;//the details is empty, why
var invitees = appointment.Invitees;//the invitees is also empty, why?
}
Actually, I tried the Microsoft Phone api, I can get the details and attendees(invitees). However, the Microsoft Phone api can't get the appointment ID. Can anybody throw me some light how to get both appointment ID, and details/invitees? Thanks!
Appointments appts = new Appointments();
//Identify the method that runs after the asynchronous search completes.
appts.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(Calendar_SearchCompleted);
DateTime start = DateTime.Now;
DateTime end = start.AddDays(1);
int max = 100;
appts.SearchAsync(start, end, max, "test");
private async void Calendar_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
foreach (Microsoft.Phone.UserData.Appointment appt in e.Results)
{
var details = appt.Details;//I can get the details
var participants = new ObservableCollection<Person>();
var attendees = appt.Attendees;
if (attendees != null)
{
foreach (var attende in attendees)
{
Person attendPerson = new Person()
{
Email = attende.EmailAddress,
FullName = attende.DisplayName,
PersonID = attende.EmailAddress
};
participants.Add(attendPerson);
}
}
....
}
}
Your need to add FindAppointmentsOptions to get get whatever detail you want, try below code
AppointmentStore appointmentStore = await AppointmentManager.RequestStoreAsync(AppointmentStoreAccessType.AllCalendarsReadOnly);
FindAppointmentsOptions options = new FindAppointmentsOptions();
options.MaxCount = 100;
options.FetchProperties.Add(AppointmentProperties.Subject);
options.FetchProperties.Add(AppointmentProperties.Location);
options.FetchProperties.Add(AppointmentProperties.Invitees);
options.FetchProperties.Add(AppointmentProperties.Details);
options.FetchProperties.Add(AppointmentProperties.StartTime);
options.FetchProperties.Add(AppointmentProperties.ReplyTime);
IReadOnlyList<Windows.ApplicationModel.Appointments.Appointment> appointments = await appointmentStore.FindAppointmentsAsync(DateTime.Now, TimeSpan.FromHours(24), options);
foreach (var appointment in appointments)
{
var persistentId = appointment.RoamingId;
var details = appointment.Details;//the details is empty, why
var invitees = appointment.Invitees;//the invitees is also empty, why?
}

Getting the wrong event from google calendar api

Here is my current code:
Service = new CalendarService("googleid.apps.googleusercontent.com");
Service.setUserCredentials("calenderusername#gmail.com", "passwordforaccount");
var calendarquery = new EventQuery
{
Uri =new Uri("https://www.google.com/calendar/feeds/calenderusername#gmail.com/private/full"),
StartTime = DateTime.Now,
NumberToRetrieve = 1,
SortOrder = CalendarSortOrder.#ascending
};
var feedItem = Service.Query(calendarquery).Entries.FirstOrDefault() as EventEntry;
var times = new Google.GData.Extensions.When();
times = feedItem.Times[0];
var item = new CalendarEvent
{
Description = feedItem.Content.Content,
EventDateStart = times.StartTime,
Title = feedItem.Title.Text,
EventDateEnd = times.EndTime,
URL = feedItem.Links.FirstOrDefault().HRef.Content
};
However, i get the item listed out:
EventStartDate: {10.02.2014 11:00:00}
EventEndDate: {10.02.2014 23:30:00}
But i know there is an event today(07.02.2014). Anyone have any idea what im doing wrong?
I'm confused wether to use startDate or startTime in my calendarQuery.

Sharepoint Out of the box Approval Workflow Approve/Reject comments issue when programmatically altering it

I have a re-usable out of the box sharepoint approval workflow 2010, and I am programmatically approve/reject workflow using the below code snippet inside infopath formcode (2010).
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.Completed] = "TRUE";
ht["Completed"] = "TRUE";
ht[SPBuiltInFieldId.PercentComplete] = 1.0f;
ht["PercentComplete"] = 1.0f;
ht["Status"] = "Completed";
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString
(new CultureInfo((int)task.Web.Language, false),
Strings.WorkflowStatusCompleted, new object[0]);
if (isApprove)
{
ht[SPBuiltInFieldId.WorkflowOutcome] = "Approved";
ht["TaskStatus"] = "Approved";
ht[SPBuiltInFieldId.Comments] = "Approved by Manager";
ht["Comments"] = "Approved by Manager";
}
else
{
XPathNavigator navigatorRejectComments
= this.MainDataSource.CreateNavigator().SelectSingleNode
(XPATH_REJECT_COMMENTS, this.NamespaceManager);
ht[SPBuiltInFieldId.WorkflowOutcome] = "Rejected";
ht["TaskStatus"] = "Rejected";
ht[SPBuiltInFieldId.Comments] = navigatorRejectComments.Value.Trim();
ht["Comments"] = navigatorRejectComments.Value.Trim();
}
ht["FormData"] = SPWorkflowStatus.Completed;
web.AllowUnsafeUpdates = true;
isApproveReject = AlterTask(task, ht, true, 5, 100);
web.AllowUnsafeUpdates = false;
Task Alter method
private static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int millisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
Thread.Sleep(millisecondsTimeout);
}
}
return SPWorkflowTask.AlterTask(task, htData, fSynchronous);
}
This code works fine, but the comments of the task is not getting altered and it is not included in the e-mail as well. Is there anything wrong with ht["Comments"] that I use? It is not getting altered in task comments. This is SharePoint 2010 workflows and infopath form i am using is also 2010.
Anyone faced similar problem ?
If you need code only for Lists (not for DocLibs) you can use item.ModerationInformation.Status property. Like the the following example:
var url = #"http://server/Lists/ContentApList";
var web = new SPSite(url).OpenWeb();
var list = web.GetList(url);
var item = list.GetItemById(1);
item["MyCheck"] = "test23";
item.ModerationInformation.Status = SPModerationStatusType.Pending;
item.ModerationInformation.Comment = "my coment";
item.SystemUpdate();
But if you want to do it for all list types, you can use internal method UpdateInternal, with the following parameters:
static void UpdateMigrate(SPListItem item)
{
UpdateInternal(item, true, false, Guid.Empty, true, false,false, false, false, false);
}
static void CheckList5()
{
var url = #"http://server/Lists/ContentApList";
var web = new SPSite(url).OpenWeb();
var file = web.GetFile("CheckDocLib/logo.gif");
var item = file.ListItemAllFields;
item["MyComments"] = "test23ddd";
item.ModerationInformation.Status = SPModerationStatusType.Approved;
item.ModerationInformation.Comment = "my coment";
UpdateMigrate(item);
}
You can use examples from this russian blog Item ModerationInformation and SPListItem.UpdateInternal()
To add a comment to a task when you Approve/Reject it, you just need to use the line before AlterTask:
ht["ows_FieldName_Comments"] = comments;
After the task is approved you can see the comments in the Workflow History List.
You can also get all the consolidated comments from a task with:
Hashtable extProperties = SPWorkflowTask.GetExtendedPropertiesAsHashtable(currentTask);
string consolidatedComments = extProperties["FieldName_ConsolidatedComments"].ToString();
Good luck!

Categories