Advertisement
hubert17

Google Calendar API v3 Integration in ASP.NET

Dec 19th, 2014
1,638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.63 KB | None | 0 0
  1. // Google Calendar Integration in ASP.NET: Create / Edit / Delete events by m.waqasiqbal
  2. // http://www.codeproject.com/Articles/565032/Google-Calendar-Integration-in-ASP-NET-Create-ed
  3. // Rewritten for Google Calendar API v3 by Hewbert Gabon
  4.  
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Web.UI;
  10.  
  11. using System.IO;
  12. using System.Threading;
  13. using Google.Apis.Calendar.v3;
  14. using Google.Apis.Calendar.v3.Data;
  15. using Google.Apis.Auth.OAuth2;
  16. using Google.Apis.Auth.OAuth2.Flows;
  17. using Google.Apis.Auth.OAuth2.Web;
  18. using Google.Apis.Services;
  19. using Google.Apis.Util.Store;
  20.  
  21.  
  22. public class GoogleCalendarManager
  23. {
  24.         private static string calID = "xxxxxxxxxxxxxxxxxxxxx@group.calendar.google.com"; //System.Configuration.ConfigurationManager.AppSettings["GoogleCalendarID"].ToString()
  25.         private static string UserId = "user-id"; //System.Web.HttpContext.Current.User.Identity.Name
  26.         private static string gFolder = System.Web.HttpContext.Current.Server.MapPath("/App_Data/MyGoogleStorage");
  27.  
  28.         public static CalendarService GetCalendarService()
  29.         {
  30.             CalendarService service = null;
  31.  
  32.             IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
  33.                 new GoogleAuthorizationCodeFlow.Initializer
  34.                 {
  35.                     ClientSecrets = GetClientConfiguration().Secrets,
  36.                     DataStore = new FileDataStore(gFolder),
  37.                     Scopes = new[] { CalendarService.Scope.Calendar }
  38.                 });
  39.  
  40.             var uri = System.Web.HttpContext.Current.Request.Url.ToString();
  41.             var code = System.Web.HttpContext.Current.Request["code"];
  42.             if (code != null)
  43.             {
  44.                 var token = flow.ExchangeCodeForTokenAsync(UserId, code,
  45.                     uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
  46.  
  47.                 // Extract the right state.
  48.                 var oauthState = AuthWebUtility.ExtracRedirectFromState(
  49.                     flow.DataStore, UserId, System.Web.HttpContext.Current.Request["state"]).Result;
  50.                 System.Web.HttpContext.Current.Response.Redirect(oauthState);
  51.             }
  52.             else
  53.             {
  54.                 var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
  55.                     CancellationToken.None).Result;
  56.                 if (result.RedirectUri != null)
  57.                 {
  58.                     // Redirect the user to the authorization server.
  59.                     //System.Web.HttpContext.Current.Response.Redirect(result.RedirectUri);    
  60.                     var page = System.Web.HttpContext.Current.CurrentHandler as Page;
  61.                     page.ClientScript.RegisterClientScriptBlock(page.GetType(),
  62.                         "RedirectToGoogleScript", "window.top.location = '" + result.RedirectUri + "'", true);
  63.                 }
  64.                 else
  65.                 {
  66.                     // The data store contains the user credential, so the user has been already authenticated.
  67.                     service = new CalendarService(new BaseClientService.Initializer
  68.                     {
  69.                         ApplicationName = "My ASP.NET Google Calendar App",
  70.                         HttpClientInitializer = result.Credential
  71.                     });
  72.                 }
  73.             }
  74.  
  75.             return service;
  76.         }
  77.  
  78.         public static GoogleClientSecrets GetClientConfiguration()
  79.         {
  80.             using (var stream = new FileStream(gFolder + @"\client_secrets.json", FileMode.Open, FileAccess.Read))
  81.             {
  82.                 return GoogleClientSecrets.Load(stream);
  83.             }
  84.         }
  85.  
  86.         public static bool AddUpdateDeleteEvent(List<GoogleCalendarAppointmentModel> GoogleCalendarAppointmentModelList, double TimeOffset)
  87.         {          
  88.             //Get the calendar service for a user to add/update/delete events
  89.             CalendarService calService = GetCalendarService();
  90.  
  91.             if (GoogleCalendarAppointmentModelList != null && GoogleCalendarAppointmentModelList.Count > 0)
  92.             {
  93.                 foreach (GoogleCalendarAppointmentModel GoogleCalendarAppointmentModelObj in GoogleCalendarAppointmentModelList)
  94.                 {
  95.                     EventsResource er = new EventsResource(calService);
  96.                     string ExpKey = "EventID";
  97.                     string ExpVal = GoogleCalendarAppointmentModelObj.EventID;
  98.  
  99.                     var queryEvent = er.List(calID);
  100.                     queryEvent.SharedExtendedProperty = ExpKey + "=" + ExpVal; //"EventID=9999"
  101.                     var EventsList = queryEvent.Execute();
  102.  
  103.                     //to restrict the appointment for specific staff only
  104.                     //Delete this appointment from google calendar
  105.                     if (GoogleCalendarAppointmentModelObj.DeleteAppointment == true)
  106.                     {
  107.                         string FoundEventID = String.Empty;
  108.                         foreach (Event evItem in EventsList.Items)
  109.                         {
  110.                             FoundEventID = evItem.Id;
  111.                             if (!String.IsNullOrEmpty(FoundEventID))
  112.                             {
  113.                                 er.Delete(calID, FoundEventID).Execute();
  114.                             }
  115.                         }
  116.                         return true;
  117.                     }
  118.                     //Add if not found OR update if appointment already present on google calendar
  119.                     else
  120.                     {
  121.                         Event eventEntry = new Event();
  122.  
  123.                         EventDateTime StartDate = new EventDateTime();
  124.                         EventDateTime EndDate = new EventDateTime();
  125.                         StartDate.Date = GoogleCalendarAppointmentModelObj.EventStartTime.ToString("yyyy-MM-dd"); //"2014-11-17";
  126.                         EndDate.Date = StartDate.Date; //GoogleCalendarAppointmentModelObj.EventEndTime
  127.  
  128.                         //Always append Extended Property whether creating or updating event
  129.                         Event.ExtendedPropertiesData exp = new Event.ExtendedPropertiesData();
  130.                         exp.Shared = new Dictionary<string, string>();
  131.                         exp.Shared.Add(ExpKey, ExpVal);
  132.  
  133.                         eventEntry.Summary = GoogleCalendarAppointmentModelObj.EventTitle;
  134.                         eventEntry.Start = StartDate;
  135.                         eventEntry.End = EndDate;
  136.                         eventEntry.Location = GoogleCalendarAppointmentModelObj.EventLocation;
  137.                         eventEntry.Description = GoogleCalendarAppointmentModelObj.EventDetails;
  138.                         eventEntry.ExtendedProperties = exp;
  139.  
  140.                         string FoundEventID = String.Empty;
  141.                         foreach (var evItem in EventsList.Items)
  142.                         {
  143.                             FoundEventID = evItem.Id;
  144.                             if(!String.IsNullOrEmpty(FoundEventID))
  145.                             {
  146.                                 //Update the event
  147.                                 er.Update(eventEntry, calID, FoundEventID).Execute();
  148.                             }
  149.                         }
  150.  
  151.                         if (String.IsNullOrEmpty(FoundEventID))
  152.                         {
  153.                             //create the event
  154.                             er.Insert(eventEntry, calID).Execute();
  155.                         }
  156.  
  157.                         return true;                        
  158.                     }
  159.                 }
  160.             }
  161.  
  162.             return false;
  163.         }
  164. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement