public CalendarService CreateService(string applicationName) { UserCredential credential; string[] scopes = { CalendarService.Scope.CalendarReadonly }; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { var credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); return service; }
protected override void Render(HtmlTextWriter writer) { if(Request.QueryString["action"] != null) { var start = Request.QueryString["start"]; var end = Request.QueryString["end"]; var filter = Request.QueryString["filter"]; var service = new CalendarService(); var json = service.GetDataAsJson(start, end, filter); // Write the JSON Response.Clear(); writer.Write(json); Response.End(); // Write the JSON Response.Clear(); writer.Write(json); Response.End(); } else { base.Render(writer); } }
public static void addEvent(CalendarService service, string email, string summary, string[] participants, TimePeriod timePeriod) { Event myEvent = new Event { Summary = summary, //Location = "Somewhere", Start = new EventDateTime() { DateTime = timePeriod.Start.Value, TimeZone = "Europe/London" }, End = new EventDateTime() { DateTime = timePeriod.End.Value, TimeZone = "Europe/London" }, /*Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO" },*/ //Attendees = getAttendees(participants) }; //or Insert(myEvent, "primary") Event recurringEvent = service.Events.Insert(myEvent, email).Execute(); }
public void GoogleMain() { UserCredential credential; using (FileStream stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } CalendarService service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; Events events = request.Execute(); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { string when = eventItem.Start.DateTime.ToString(); if (String.IsNullOrEmpty(when)) { when = eventItem.Start.Date; } gcevents.Add(eventItem.Summary); dates.Add(when); } } else { } }
private void AddCalendarEventClick(object sender, RoutedEventArgs e) { const string calendarEventDescription = "Test event for DrZob"; var timeFrom = DateTime.Today.AddHours(4); var timeTo = DateTime.Today.AddHours(6); var calendarEvent = CreateCalendarEvent(calendarEventDescription, timeFrom, timeTo); try { var credentials = GetCredentials(new[] { CalendarService.Scope.Calendar }, User.Text); var calendarService = new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = credentials, ApplicationName = ApplicationName }); var calendars = calendarService.CalendarList.List().Execute(); var calendar = calendars.Items.SingleOrDefault(x => x.Summary == "DrZob"); if (calendar == null) { MessageBox.Show("The calendar 'DrZob' does not exist!"); return; } var calendarEventResponse = calendarService.Events.Insert(calendarEvent, calendar.Id).Execute(); } catch (Exception ex) { Console.WriteLine("A Google Apps error occurred:"); Console.WriteLine(ex.Message); } }
public ApiMethods() { using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); }
/// <summary> /// <see cref="Authenticate" /> to Google Using Oauth2 Documentation /// https://developers.google.com/accounts/docs/OAuth2 /// </summary> /// <param name="clientId"> /// From Google Developer console https://console.developers.google.com /// </param> /// <param name="clientSecret"> /// From Google Developer console https://console.developers.google.com /// </param> /// <param name="userName"> /// A string used to identify a user (locally). /// </param> /// <param name="fileDataStorePath"> /// Name/Path where the Auth Token and refresh token are stored (usually /// in %APPDATA%) /// </param> /// <param name="applicationName">Applicaiton Name</param> /// <param name="isFullPath"> /// <paramref name="fileDataStorePath" /> is completePath or Directory /// Name /// </param> /// <returns> /// </returns> public CalendarService AuthenticateCalendarOauth(string clientId, string clientSecret, string userName, string fileDataStorePath, string applicationName, bool isFullPath = false) { try { var authTask = Authenticate(clientId, clientSecret, userName, fileDataStorePath, isFullPath); authTask.Wait(30000); if (authTask.Status == TaskStatus.WaitingForActivation) { return null; } var service = new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = authTask.Result, ApplicationName = applicationName }); return service; } catch (AggregateException exception) { Logger.Error(exception); return null; } catch (Exception exception) { Logger.Error(exception); return null; } }
public GoogleCalendar() { //UserCredential credential; //using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) //{ // //var clientSecrets = GoogleClientSecrets.Load(stream).Secrets; // credential = GoogleWebAuthorizationBroker.AuthorizeAsync( // stream, // new[] { CalendarService.Scope.Calendar }, // "user", CancellationToken.None, new FileDataStore("Calendar.ListMyLibrary")).Result; // service = new CalendarService(new BaseClientService.Initializer() // { // HttpClientInitializer = credential, // ApplicationName = "Outlook Google Sync" , // }); // //credential = authorizeAsync.Result; //} var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = "646754649922-g2p0157e4q3d5qv25ia3ur09vrc455k6.apps.googleusercontent.com"; provider.ClientSecret = "ZyPfCdrOFb6y-VWrdVZ65_8M"; service = new CalendarService(new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication)); service.Key = "AIzaSyCg7QtvUT6V3Hh3ZG7M5KfDiFScRkaYix0"; }
/// <summary> /// Initialise la connexion avec Google Calendar /// </summary> /// <param name="privateKey"></param> /// <param name="googleAccount"></param> /// <returns></returns> public bool InitCnx() { Log.Debug("Initialisation de la connexion avec Google ..."); // Si la fonction n'est pas activée, on passe tout de suite if (!p_isActivated) { return false; } try { string[] scopes = new string[] { CalendarService.Scope.Calendar, // Manage your calendars CalendarService.Scope.CalendarReadonly // View your Calendars }; var certificate = new X509Certificate2(p_privateKey, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(p_googleAccount) { Scopes = scopes }.FromCertificate(certificate)); // Create Google Calendar API service. p_myService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "PlanningLAB", }); } catch (Exception err) { Log.Error("Erreur Authentification Google {" + p_googleAccount + "} - {" + p_privateKey + "} :", err); return false; } return true; }/// <summary>
protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { // Ensure we have at least one calendar. If not, let's move them back to the calendar and explain that this feature is not yet ready. var service = new CalendarService(); var calendars = service.GetCalendars(); if(calendars.First().CalendarID == 0) { Response.Redirect(URL_CALENDAR + "?status=0"); } // Ensure that, if we are editing an event, it is the backoffice owner's event. if(CalendarItemID != 0) { if(!service.ValidateCalendarItem(CalendarItemID)) { Response.Redirect(URL_CALENDARDETAILS + "?id=" + CalendarItemID); } } PopulateCalendarOptions(); PopulateCalendarItemRepeatTypeOptions(); PopulateCalendarItemTypeOptions(); PopulateDefaultFormOptions(); PopulateTimeZones(); PopulateExistingData(); } }
public static void createEvent(string eventName, string eventDescription, IList<string> attendees, DateTime startDate, DateTime endDate, CalendarService service, string calId) { //Creating new event IList<EventAttendee> attending = new List<EventAttendee>(); Event newEvent = new Event(); newEvent.Summary = eventName; newEvent.Description = eventDescription; newEvent.Start = new EventDateTime(); newEvent.Start.DateTime = startDate; newEvent.End = new EventDateTime(); newEvent.End.DateTime = endDate; //Iterate through attendees List and add new EventAttendee to our attending list foreach (var eventAttendee in attendees) { attending.Add(new EventAttendee() { Email = eventAttendee }); } //set attending to new event attendees newEvent.Attendees = attending; //Insert new event into calendar using calendar ID var eventResult = service.Events.Insert(newEvent, calId); //set notification to be sent. eventResult.SendNotifications = true; Event createdEvent = eventResult.Execute(); }
/// <summary> /// Authenticate to Google Using Oauth2 /// Documentation https://developers.google.com/accounts/docs/OAuth2 /// </summary> /// <param name="clientId">From Google Developer console https://console.developers.google.com</param> /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param> /// <param name="userName">A string used to identify a user.</param> /// <returns></returns> public static CalendarService AuthenticateOauth(string clientId, string clientSecret, string userName) { string[] scopes = new string[] { CalendarService.Scope.Calendar , // Manage your calendars CalendarService.Scope.CalendarReadonly // View your Calendars }; try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , new FileDataStore("Daimto.GoogleCalendar.Auth.Store")).Result; CalendarService service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Calendar API Sample", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } }
// GET: /Calendar/UpcomingEvents public async Task<ActionResult> UpcomingEvents() { const int MaxEventsPerCalendar = 20; const int MaxEventsOverall = 50; var model = new UpcomingEventsViewModel(); var credential = await GetCredentialForApiAsync(); var initializer = new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "ASP.NET MVC5 Calendar Sample", }; var service = new CalendarService(initializer); // Fetch the list of calendars. var calendars = await service.CalendarList.List().ExecuteAsync(); // Fetch some events from each calendar. var fetchTasks = new List<Task<Google.Apis.Calendar.v3.Data.Events>>(calendars.Items.Count); foreach (var calendar in calendars.Items) { var request = service.Events.List(calendar.Id); request.MaxResults = MaxEventsPerCalendar; request.SingleEvents = true; request.TimeMin = DateTime.Now; fetchTasks.Add(request.ExecuteAsync()); } var fetchResults = await Task.WhenAll(fetchTasks); // Sort the events and put them in the model. var upcomingEvents = from result in fetchResults from evt in result.Items where evt.Start != null let date = evt.Start.DateTime.HasValue ? evt.Start.DateTime.Value.Date : DateTime.ParseExact(evt.Start.Date, "yyyy-MM-dd", null) let sortKey = evt.Start.DateTimeRaw ?? evt.Start.Date orderby sortKey select new { evt, date }; var eventsByDate = from result in upcomingEvents.Take(MaxEventsOverall) group result.evt by result.date into g orderby g.Key select g; var eventGroups = new List<CalendarEventGroup>(); foreach (var grouping in eventsByDate) { eventGroups.Add(new CalendarEventGroup { GroupTitle = grouping.Key.ToLongDateString(), Events = grouping, }); } model.EventGroups = eventGroups; return View(model); }
public void AddEvent() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); Console.WriteLine("Enter sumary"); string sum = Console.ReadLine(); Console.WriteLine("Enter Location"); string location = Console.ReadLine(); Event myEvent = new Event { Summary = sum, Location = location, Start = new EventDateTime() { DateTime = new DateTime(2016,03,06), TimeZone = "America/Chicago" }, End = new EventDateTime() { DateTime = new DateTime(2016,03,07), TimeZone = "America/Chicago" }, Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO" }, Attendees = new List<EventAttendee>() { new EventAttendee() { Email = "*****@*****.**" } } }; Event recurringEvent = service.Events.Insert(myEvent, "primary").Execute(); }
public static void Main(string[] args) { Console.WriteLine("Google Calender API v3"); var clientId = ConfigurationManager.AppSettings["ClientId"]; var clientSecret = ConfigurationManager.AppSettings["ClientSecret"]; var calendarId = ConfigurationManager.AppSettings["CalendarId"]; try { var credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret, }, new[] { CalendarService.Scope.Calendar }, "user", CancellationToken.None).Result; var service = new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Google Calender API v3", }); var queryStart = DateTime.Now; var queryEnd = queryStart.AddYears(1); var query = service.Events.List(calendarId); // query.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; - not supported :( query.TimeMin = queryStart; query.TimeMax = queryEnd; var events = query.Execute().Items; var eventList = events.Select(e => new Tuple<DateTime, string>(DateTime.Parse(e.Start.Date), e.Summary)).ToList(); eventList.Sort((e1, e2) => e1.Item1.CompareTo(e2.Item1)); Console.WriteLine("Query from {0} to {1} returned {2} results", queryStart, queryEnd, eventList.Count); foreach (var item in eventList) { Console.WriteLine("{0}\t{1}", item.Item1, item.Item2); } } catch (Exception e) { Console.WriteLine("Exception encountered: {0}", e.Message); } Console.WriteLine("Press any key to continue..."); while (!Console.KeyAvailable) { } }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now.AddYears(-1);//DateTime.Now.AddYears(-7); request.TimeMax = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 1000;//{Default:25, Max:2500} request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = request.Execute(); Console.WriteLine(String.Format("Event Count: {0}", events.Items.Count)); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { Thread.Sleep(200); eventItem.Visibility = "private"; eventItem.Transparency = "transparent"; EventsResource.UpdateRequest updateReq = service.Events.Update(eventItem, "primary", eventItem.Id); Event updatedEvent = updateReq.Execute(); Console.WriteLine("Event Updated: " + updatedEvent.Id + " " + updatedEvent.Visibility + " " + updatedEvent.Description); } } else { Console.WriteLine("No events found."); } Console.Read(); Console.Read(); }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream(@"Components\client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath(System.Environment .SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; //Console.WriteLine("Credential file saved to: " + credPath); } // Create Calendar Service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; Console.WriteLine("Upcoming events:"); Events events = request.Execute(); if (events.Items.Count > 0) { foreach (var eventItem in events.Items) { string when = eventItem.Start.DateTime.ToString(); if (String.IsNullOrEmpty(when)) { when = eventItem.Start.Date; } Console.WriteLine("{0} ({1})", eventItem.Summary, when); } } else { Console.WriteLine("No upcoming events found."); } Console.Read(); }
public void push_event() { CalendarService service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); EventsResource.InsertRequest newevent = service.Events.Insert(googleevent, "primary"); newevent.SendNotifications = true; newevent.Execute(); }
/// <summary> /// Loads calendar events /// </summary> /// <returns>Awaitable task of Events in list form</returns> public List<Cal.Event> GetData() { string serviceAccount = "*****@*****.**"; string fileName = System.Web.HttpContext.Current.Server.MapPath("..\\") + "MagicMirror.p12"; var certificate = new X509Certificate2(fileName, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccount) { Scopes = new[] { CalendarService.Scope.CalendarReadonly }, User = serviceAccount }.FromCertificate(certificate)); var calendarService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MagicMirror" }); var calendarListResource = calendarService.CalendarList.List().Execute(); //await calendarService.CalendarList.List().ExecuteAsync(); //calendarService.CalendarList.List().Execute().Items; var myCalendar = calendarListResource.Items[0]; string pageToken = null; Events = new List<Cal.Event>(); //do //{ //TODO: Make configuration items var activeCalendarList = calendarService.Events.List(calendarOwner); activeCalendarList.PageToken = pageToken; activeCalendarList.MaxResults = 3; activeCalendarList.TimeMax = DateTime.Now.AddMonths(3); activeCalendarList.TimeMin = DateTime.Now; activeCalendarList.SingleEvents = true; activeCalendarList.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; var calEvents = activeCalendarList.Execute(); var items = calEvents.Items; foreach (var item in items) { Events.Add(new Cal.Event() { Summary = item.Summary, StartTimeStr = (item.Start.DateTime.HasValue ? item.Start.DateTime.Value : DateTime.Parse(item.Start.Date)).ToString(), EndTimeStr = (item.End.DateTime.HasValue ? item.End.DateTime.Value : DateTime.Parse(item.End.Date)).ToString() }); } return Events; }
/// <summary> /// Deletes an event /// Documentation:https://developers.google.com/google-apps/calendar/v3/reference/events/delete /// </summary> /// <param name="service">Valid Autenticated Calendar service</param> /// <param name="id">Calendar identifier.</param> /// <param name="eventid">Event identifier.</param> /// <returns>If successful, this method returns an empty response body. </returns> public static string delete(CalendarService service, string id,string eventid) { try { return service.Events.Delete(id,eventid).Execute(); } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } }
/// <summary> /// Imports an event. This operation is used to add a private copy of an existing event to a calendar. /// Documentation:https://developers.google.com/google-apps/calendar/v3/reference/events/import /// </summary> /// <param name="service">Valid Autenticated Calendar service</param> /// <param name="id">Calendar identifier.</param> /// <param name="body">an event</param> /// <returns>Events resorce: https://developers.google.com/google-apps/calendar/v3/reference/events#resource </returns> public static Event get(CalendarService service, string id,Event body) { try { return service.Events.Import(body,id).Execute(); } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } }
/// <summary> /// Returns metadata for a calendar. /// Documentation:https://developers.google.com/google-apps/calendar/v3/reference/calendars/get /// </summary> /// <param name="service">Valid Autenticated Calendar service</param> /// <param name="id">Calendar identifier.</param> /// <returns>Calendar resorce: https://developers.google.com/google-apps/calendar/v3/reference/calendars#resource </returns> public static Calendar get(CalendarService service, string id) { try { return service.Calendars.Get(id).Execute(); } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } }
private void ServiceInstance(string accountId, string certPath) { var auth = new ServiceOAuth(accountId, certPath); DirectoryService = auth.DirectoryService(); GroupSettingsService = auth.GroupSettingsService(); LicensingService = auth.LicensingService(); ReportsService = auth.ReportsService(); CalendarService = auth.CalendarService(); DriveService = auth.DriveService(); AuditService = auth.AuditService(); TasksService = auth.TasksService(); }
internal static void AddCommands(CommandGroupBuilder group) { var secret_file = "calendar_client_secret.json"; if (File.Exists(secret_file)) { UserCredential credential; using (var stream = new FileStream(secret_file, FileMode.Open, FileAccess.Read)) { credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[]{CalendarService.Scope.CalendarReadonly}, Program.Config.AppName, CancellationToken.None).Result; } Func<string> timezone = () => { var offset = TimeZoneInfo.Local.BaseUtcOffset.ToString(); return $"(UTC{offset.Substring(0, offset.LastIndexOf(':'))})"; }; foreach (var calendar_cmd in (JObject)Program.config["GoogleCalendar"]) { Helpers.CreateJsonCommand(group, calendar_cmd, (cmd, val) => { var include_desc = Helpers.FieldExistsSafe<bool>(val, "includeDescription"); cmd.Parameter("count or event id", ParameterType.Optional) .Do(async e => { var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Program.Config.AppName }); Func<Event, string> header = item => $"**{item.Summary}:**\n{(item.Start.DateTime == null ? $"All day {(item.Start.Date.Equals(DateTime.Now.ToString("yyyy-MM-dd")) ? "today" : $"on {item.Start.Date}")}" : $"{(DateTime.Now > item.Start.DateTime ? $"Happening until" : $"Will happen {item.Start.DateTime} and end at")} {item.End.DateTime} {timezone()}")}.\n"; Func<Event, string> header_desc = item => $"{header(item)}{item.Description}"; int results = 1; if (Helpers.HasArg(e.Args)) if (!int.TryParse(e.Args[0], out results)) // Must be an event ID { var r = await service.Events.Get(val["calendarId"].ToString(), e.Args[0]).ExecuteAsync(); await e.Channel.SendMessage(header_desc(r)); return; } var request = service.Events.List(val["calendarId"].ToString()); request.TimeMin = DateTime.Now; request.SingleEvents = true; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; request.MaxResults = results; var events = await request.ExecuteAsync(); if (events.Items?.Count > 0) foreach (var item in events.Items) await e.Channel.SendMessage(include_desc ? header_desc(item) : $"{header(item)}ID: {item.Id}"); else await e.Channel.SendMessage("Apparently, there's nothing coming up nor taking place right now..."); }); });
public GoogleCalendarHandler() { var credential = GetUserCredential(); // Create Calendar Service. service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); colorCount = service.Colors.Get().Execute().Event.Count(); }
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["status"] == "1") { Error.Type = Exigo.WebControls.ErrorMessageType.Success; Error.Header = "Success!"; Error.Message = "Your changes have been saved. Please allow up to one minute for your calendar to reflect your changes."; } // Ensure at least one calendar var service = new CalendarService(); service.EnsureAtLeastOneCalendar(); }
public List<String> GetCalendars(string authCode) { List<String> calendarSummaries = new List<string>(); this.authCode = authCode; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); service = new CalendarService(auth); calendars = service.CalendarList.List().Fetch().Items; foreach (CalendarListEntry calendar in calendars) { calendarSummaries.Add(calendar.Summary); } return calendarSummaries; }
/// <summary> /// Clears a primary calendar. This operation deletes all data associated with the primary calendar of an account and cannot be undone. /// Documentation: https://developers.google.com/google-apps/calendar/v3/reference/calendars/clear /// </summary> /// <param name="service">Calendar identifier</param> /// <param name="id">If successful, this method returns an empty response body.</param> /// <returns></returns> public static CalendarsResource.ClearRequest clear(CalendarService service, string id) { try { return service.Calendars.Clear(id); } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } }
// see https://developers.google.com/google-apps/calendar/v3/reference/calendars/get public Calendar GetCalendar(string calendarId) { var calendarService = new CalendarService(_authenticator); var calendar = calendarService.CalendarList.List().Fetch().Items.FirstOrDefault(c => c.Summary.Contains(calendarId)); if (calendar == null) throw new GoogleCalendarServiceProxyException("There's no calendar with that id"); return new Calendar() { Id = calendar.Id, Title = calendar.Summary, Location = calendar.Location, Description = calendar.Description }; }
public ActionResult Show(string token, string email, string name) { UserCredential credential; var listOfEvents = new List<EventViewModel>(); var json = JsonParser(); ClientSecrets cs = new ClientSecrets() { ClientId = json["installed"]["client_id"].ToString(), ClientSecret = json["installed"]["client_secret"].ToString() }; credential = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, Scopes, "user", CancellationToken.None).Result; credential.Token.AccessToken = token; // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = request.Execute(); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { var eventName = (string.IsNullOrEmpty(eventItem.Summary)) ? "No Title" : eventItem.Summary; var userEvent = new EventViewModel(eventName, eventItem.Start.DateTime, eventItem.End.DateTime); listOfEvents.Add(userEvent); } } ViewData["Events"] = listOfEvents; ViewData["Email"] = email; ViewData["Name"] = name; return View(); }
public List <MisEventos> VerEventos() { List <MisEventos> eventos = new List <MisEventos>(); UserCredential credential = GetCredential(UserRole.User); // Creat Google Calendar API service. CalendarService service = GetService(credential); // Define parameters of request EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = request.Execute(); // Print upcomming events if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { string inicio = eventItem.Start.DateTime.ToString(); string fin = eventItem.End.DateTime.ToString(); if (String.IsNullOrEmpty(inicio)) { inicio = eventItem.Start.Date; fin = eventItem.End.Date; } MisEventos ev = new MisEventos(eventItem.Summary, inicio, Convert.ToDateTime(fin)); eventos.Add(ev); } } else { Console.WriteLine("Nothing."); } return(eventos); }
public GoogleCalendarScheduler(IDateTimeProvider dateTimeProvider, IFlexKidsConfig flexKidsConfig /*IGoogleCalendarService googleCalendarService*/) { // if (googleCalendarService == null) // throw new ArgumentNullException("googleCalendarService"); // calendarService = googleCalendarService; googleCalendarId = flexKidsConfig.GoogleCalendarId; googleCalendarAccount = flexKidsConfig.GoogleCalendarAccount; //TODO Check if file exists and make it more robust. var certificate = new X509Certificate2(@flexKidsConfig.GoogleCalendarKeyFile, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(googleCalendarAccount) { Scopes = new[] { CalendarService.Scope.Calendar } }.FromCertificate(certificate)); // Create the service. var service = new CalendarService(new BaseClientService.Initializer { HttpClientFactory = new Google.Apis.Http.HttpClientFactory(), HttpClientInitializer = credential, ApplicationName = "FlexKids Rooster by CoenM", }); if (service == null) { throw new Exception("Cannot create service."); } calendarService = new GoogleCalendarService(service); var calendar = calendarService.GetCalendarById(googleCalendarId); if (calendar == null) { throw new Exception("Cannot find calendar"); } }
/// <summary> /// Runs the methods above to demonstrate usage of the .NET /// client library. The methods that add, update, or remove /// users on access control lists will not run by default. /// </summary> static void RunSample() { CalendarService service = new CalendarService("exampleCo-exampleApp-1"); service.setUserCredentials(userName, userPassword); // Demonstrate retrieving a list of the user's calendars. PrintUserCalendars(service); // Demonstrate various feed queries. PrintAllEvents(service); FullTextQuery(service, "Tennis"); DateRangeQuery(service, new DateTime(2007, 1, 5), new DateTime(2007, 1, 7)); // Demonstrate creating a single-occurrence event. EventEntry singleEvent = CreateSingleEvent(service, "Tennis with Mike"); Console.WriteLine("Successfully created event {0}", singleEvent.Title.Text); // Demonstrate creating a recurring event. AtomEntry recurringEvent = CreateRecurringEvent(service, "Tennis with Dan"); Console.WriteLine("Successfully created recurring event {0}", recurringEvent.Title.Text); // Demonstrate updating the event's text. singleEvent = UpdateTitle(singleEvent, "Important meeting"); Console.WriteLine("Event's new title is {0}", singleEvent.Title.Text); // Demonstrate adding a reminder. Note that this will only work on a primary // calendar. singleEvent = AddReminder(singleEvent, 15); Console.WriteLine("Set a {0}-minute reminder for the event.", singleEvent.Reminder.Minutes); // Demonstrate adding an extended property. AddExtendedProperty(singleEvent); // Demonstrate deleting the item. singleEvent.Delete(); // Demonstrate retrieving access control lists for all calendars. RetrieveAcls(service); }
private static IEnumerable <CalendarEvent> GetEvents(int?numToTake, bool?registerEventsOnly) { var service = new CalendarService(new BaseClientService.Initializer() { ApiKey = _apiKey }); EventsResource.ListRequest request = service.Events.List(_calendarID); request.TimeMin = DateTime.UtcNow; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = int.Parse(ConfigurationManager.AppSettings["TakeGoogleCalendarItemsCount"]); request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; Events events = request.Execute(); if (events.Items == null) { return(new CalendarEvent[] { }); } var eventsQuery = events.Items .Where(evt => !string.IsNullOrEmpty(evt.Description)) .Select(evt => MapToEventDto(evt)) .Where(ce => ce.IncludeOnHomeEvents()); if (registerEventsOnly.GetValueOrDefault()) { eventsQuery = eventsQuery.Where(evt => evt.RegistrationAllowed == true); } if (ConfigurationManager.AppSettings["TestMode"] == "true") { var baseQuery = eventsQuery.Take(numToTake.GetValueOrDefault(int.Parse(ConfigurationManager.AppSettings["TakeCalendarItemsCount"]) - 1)).ToList(); baseQuery.Insert(0, CreateTestEvent()); return(baseQuery); } return(eventsQuery.Take(numToTake.GetValueOrDefault(int.Parse(ConfigurationManager.AppSettings["TakeCalendarItemsCount"])))); }
public CalendarService CreateGoogleCalendarService() { try { // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/calendar-dotnet-quickstart.json string[] Scopes = { CalendarService.Scope.Calendar }; //string ApplicationName = "Google Calendar API .NET Quickstart"; string ApplicationName = "TrivselApp"; UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Google Calendar API service. var calendarService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); return(calendarService); } catch (Exception e) { e.Message.ToString(); } return(null); }
private async Task Auth(string[] scopes) { var credentialPath = AppDomain.CurrentDomain.GetData("GoogleCalendarCredentialPath").ToString(); var tokenPath = AppDomain.CurrentDomain.GetData("GoogleCalendarTokenPath").ToString(); if (!File.Exists(credentialPath)) { throw new FileNotFoundException("Client credential file not found"); } using (var stream = new FileStream(credentialPath, FileMode.Open, FileAccess.Read)) { // Stores the user's access and refresh tokens after the authorization flow completes var authTask = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, new FileDataStore(tokenPath, true)); using (var cancelTokenSource = new CancellationTokenSource()) { var completed = await Task.WhenAny(authTask, Task.Delay(_authTimeout, cancelTokenSource.Token)); if (completed != authTask) { throw new TimeoutException("Google Calendar authorization timed out"); } else { cancelTokenSource.Cancel(); credential = await authTask; } } } // Google Calendar Api service calService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName }); }
/// <summary> /// Shares a calendar with the specified user. Note that this method /// will not run by default. /// </summary> /// <param name="service">The authenticated CalendarService object.</param> /// <param name="aclFeedUri">the ACL feed URI of the calendar being shared.</param> /// <param name="userEmail">The email address of the user with whom to share.</param> /// <param name="role">The role of the user with whom to share.</param> /// <returns>The AclEntry returned by the server.</returns> static AclEntry AddAccessControl(CalendarService service, string aclFeedUri, string userEmail, AclRole role) { AclEntry entry = new AclEntry(); entry.Scope = new AclScope(); entry.Scope.Type = AclScope.SCOPE_USER; entry.Scope.Value = userEmail; entry.Role = role; Uri aclUri = new Uri("http://www.google.com/calendar/feeds/[email protected]/acl/full"); AclEntry insertedEntry = service.Insert(aclUri, entry); Console.WriteLine("Added user {0}", insertedEntry.Scope.Value); return(insertedEntry); }
public void DeleteAppointmentTest() { Storage _storage = new Storage(); TestControllerBuilder builder = new TestControllerBuilder(); HomeController controller = new HomeController(); builder.InitializeController(controller); var today = DateTime.Today; controller.HttpContext.Session["userID"] = "adama"; controller.HttpContext.Session["firstDate"] = CalendarService.GetFirstDateOfWeek(today); var appointment = CreateAppointment(today); controller.AddAppointment(appointment, today); controller.HttpContext.Session["appointment"] = appointment; controller.DeleteAppointment(); Appointment foundAppointment = _storage.GetAppointment(appointment.AppointmentID); Assert.IsNull(foundAppointment); }
public void OAuth2LeggedAuthenticationTest() { Tracing.TraceMsg("Entering OAuth2LeggedAuthenticationTest"); CalendarService service = new CalendarService("OAuthTestcode"); GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode"); requestFactory.ConsumerKey = this.oAuthConsumerKey; requestFactory.ConsumerSecret = this.oAuthConsumerSecrect; service.RequestFactory = requestFactory; CalendarEntry calendar = new CalendarEntry(); calendar.Title.Text = "Test OAuth"; OAuthUri postUri = new OAuthUri("http://www.google.com/calendar/feeds/default/owncalendars/full", this.oAuthUser, this.oAuthDomain); CalendarEntry createdCalendar = (CalendarEntry)service.Insert(postUri, calendar); }
public void GetWorkingToday_AllDatesWorking_ReturnsTomorrow() { // Arrange var today = new DateTime(2020, 10, 02); var dayOfWeekService = new Mock <IDayOfWeekService>(); dayOfWeekService .Setup(x => x.IsWeekend(It.IsAny <DateTime>())) .Returns(false); var service = new CalendarService(new DayShiftService(dayOfWeekService.Object)); // Act var result = service.GetWorkingTomorrow(today); // Assert result.Should().Be(new DateTime(2020, 10, 05)); // result.Should().Be(new DateTime(2020, 10, 03)); }
private static bool createCalendarService() { try { // Create Drive API service. calendarService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); return(true); } catch (Exception exc) { System.Diagnostics.Debug.WriteLine(exc.Message + " Create Calendar Service Error.\n"); Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() + Environment.NewLine + exc.Message + " Create Calendar Service Error.\n"); return(false); } }
public async Task <string> AddEmployeDayOff(DateTime startDate, DateTime endDate, string eventTitle, string colorId) { CalendarService service = await GetService(); Event dayOffEvent = new Event() { Summary = eventTitle, Start = new EventDateTime() { DateTime = startDate }, End = new EventDateTime() { DateTime = endDate }, ColorId = colorId }; return((await service.Events.Insert(dayOffEvent, "primary").ExecuteAsync()).Id); }
public Events getRaptorsCalendar(string applicationName, UserCredential googCalCred) { var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = googCalCred, ApplicationName = applicationName, }); EventsResource.ListRequest request = service.Events.List("nba_28_%54oronto+%52aptors#[email protected]"); request.TimeMin = DateTime.Today.Date.AddDays(-30); //request.TimeMin = DateTime.Today.Date; //request.TimeMax = DateTime.Today.Date.AddDays(1).AddSeconds(-1); request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; Events events = request.Execute(); return(events); }
private static Events FindEvents(ILog logger, CalendarService service, string calendarId) { EventsResource.ListRequest request = service.Events.List(calendarId); //request.TimeMin = DateTime.Now; request.UpdatedMin = DateTime.Now.AddMinutes(-GetBeforeMinutesModifiedDate()); request.TimeZone = GetTimeZone(); request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 100; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; try { // List events. return(request.Execute()); } catch (Exception e) { logger.Info($"Not found data:CalendarId:{calendarId} Error:{e.Message}{e.StackTrace}"); return(null); } }
public CalenderFilterService() { UserCredential credential; using (var stream = new FileStream("secrets/credentials.json", FileMode.Open, FileAccess.Read)) { credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore("token.json", true)).Result; } _service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Work calender", }); }
public static System.Collections.Generic.IList <Google.Apis.Calendar.v3.Data.Event> GetNextBirthday() { var service = new CalendarService(new BaseClientService.Initializer() { ApiKey = Token.apikey, ApplicationName = "DiscordBot" }); var request = service.Events.List(Token.calendarID); request.SingleEvents = true; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; request.MaxResults = Convert.ToInt32(Global.GetByName("max_birthdays_a_day").value); request.TimeMin = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); request.Fields = "items(summary,description,start)"; var response = request.Execute(); return(response.Items); }
public CalendarService GetCalendarService() { var FilePath = Environment.CurrentDirectory + @"\Modules\client_secret.json"; string ApplicationName = AppName; GoogleCredential credential; using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream).CreateScoped(CalendarService.Scope.Calendar); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); return(service); }
public void Should_return_calendar_with_only_working_days() { var sut = new CalendarService(_timeService); var calendar = sut .WithoutHolidays() .WithoutWeekEnd() .Build() .ToList(); const int expectedCount = 20; Assert.AreEqual(expectedCount, calendar.Count()); const string expected = "Monday, December 2, 2019;Tuesday, December 3, 2019;Wednesday, December 4, 2019;Thursday, December 5, 2019;Friday, December 6, 2019;Monday, December 9, 2019;Tuesday, December 10, 2019;Wednesday, December 11, 2019;Thursday, December 12, 2019;Friday, December 13, 2019;Monday, December 16, 2019;Tuesday, December 17, 2019;Wednesday, December 18, 2019;Thursday, December 19, 2019;Friday, December 20, 2019;Monday, December 23, 2019;Tuesday, December 24, 2019;Friday, December 27, 2019;Monday, December 30, 2019;Tuesday, December 31, 2019"; var actual = string.Join(";", calendar.Select(day => day.ToString())); Assert.AreEqual(expected, actual); }
public async Task SetupAsync() { UserCredential credential; using (var stream = new FileStream(SecretsPath, FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { CalendarService.Scope.CalendarReadonly }, "user", CancellationToken.None, new FileDataStore(TokenPath, true)); } service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName }); }
public void ModifyModifiedAppointmentTest() { Storage _storage = new Storage(); TestControllerBuilder builder = new TestControllerBuilder(); HomeController controller = new HomeController(); builder.InitializeController(controller); var today = DateTime.Today; controller.HttpContext.Session["userID"] = "adama"; controller.HttpContext.Session["firstDate"] = CalendarService.GetFirstDateOfWeek(today); var appointment = CreateAppointment(today); controller.AddAppointment(appointment, today); appointment.Title = "wyd2"; controller.EditAppointment(appointment); appointment.Title = "wyd3"; controller.EditAppointment(appointment); Assert.IsNotNull(controller.HttpContext.Session["errorText"]); }
/// <summary> /// Calendars that are supported. /// </summary> /// <returns>A vertical range of calendars supported.</returns> public object[,] CalendarsSupported() { var calsList = CalendarService.CalendarsSupported(); var unqVals = new List <object>(); foreach (var obj in calsList) { if (!unqVals.Contains(obj)) { unqVals.Add(obj); } } var resVals = new object[unqVals.Count, 1]; for (int idx = 0; idx < resVals.Length; ++idx) { resVals[idx, 0] = unqVals[idx]; } return(resVals); }
public ActionResult Calendar() { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = request.Execute(); EventsList model = new EventsList(); model.Events = events; return(View("Calendar", model)); }
public async static Task GetEventList() { try { // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = GlobalVariable.GoogleCalendarUserCredential, ApplicationName = ApplicationName, }); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = DateTime.Now; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 2; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = await request.ExecuteAsync(); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { string when = eventItem.Start.DateTime.ToString(); if (String.IsNullOrEmpty(when)) { when = eventItem.Start.Date; } } } else { } } catch (Exception ex) { } }
public static void LoadCredential() { try { if (!isInit) { string credentialPath = GetCredentialPath(); using (var stream = new FileStream(credentialPath, FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/PersonalGrowthSystem-Calendar.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); isInit = true; Colors colors = service.Colors.Get().Execute(); } } catch (Exception e) { //MessageBox.Show(e.ToString()); } }
public void OnGet() { //Get Meals var upcomingMeals = CalendarService.GetUpcomingMeals(); //Get Food Items var upcomingItems = CalendarService.GetUpcomingItems(); //Get Favorite Meals FavoriteMeals = MealRepo.GetFavoriteMealsForUser(this.CurrentUser.User).ToList(); TodaysMeals = upcomingMeals.TodaysMeals; TomorrowsMeals = upcomingMeals.TomorrowsMeals; TodaysItems = upcomingItems.TodaysItems; TomorrowsItems = upcomingItems.TomorrowsItems; //How do we transform events into meals //technically, we c //Load Today's Mejals and Tomorrows Meals //get events -> then get meals //this.DbContext.Events //calculate the right metrics //the goal of this app is to eat healthy and delicious foods for every meal, and to minimize time spent planning and thinking about food. //create this as a customizable dashboard? //! Alert - you have 0 meals planned for the next 5 days //check to see if meals are planned for the next 5 days, and display an error message if nothign is planned... //else pull the data from "events" and show it in a dashboard... }
/// <summary> /// Инициализация класса /// </summary> /// <param name="keyFilePath"></param> /// <param name="user"></param> public CalendarWork(string keyFilePath, string user, string pass) { User = user; Identity = NewIdent(); Check_Connect(); timer1.Interval = 5000; timer1.Tick += TimerCheck_Tick; StartTimer(); try { string[] Scopes = { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarEvents }; UserCredential credential; using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read)) { string credPath = "UsersToken"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, User, CancellationToken.None, new FileDataStore(credPath, true)).Result; } Service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "My Calendar v0.1", }); WorkBD.Execution_query($"if not exists(select Id from Users where UserName = N'{user}') insert into Users (UserName, userPass) values (N'{user}', N'{pass}')"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public CalendarData GetFeedOfCalendar(String feedUrl, String user, String pass) { var myService = new CalendarService("Newgen_Calendar"); myService.setUserCredentials(user, pass); var myQuery = new EventQuery(feedUrl); myQuery.StartTime = DateTime.Now; myQuery.EndTime = DateTime.Today.AddDays(2); // we search two days after EventFeed calFeed = myService.Query(myQuery); // now populate the calendar if (calFeed.Entries.Count > 0) { var entry = (EventEntry)calFeed.Entries[0]; var result = new CalendarData(); // Title result.Title = entry.Title.Text; if (entry.Locations.Count > 0 && !string.IsNullOrEmpty(entry.Locations[0].ValueString)) { result.Location = entry.Locations[0].ValueString; } else if (entry.Content != null) { result.Description = entry.Content.Content; } if (entry.Times.Count > 0) { result.BeginTime = entry.Times[0].StartTime; result.EndTime = entry.Times[0].EndTime; } return(result); } return(null); }
// TODO(obelix30): it is workaround for open issue here: https://github.com/google/google-api-dotnet-client/issues/608 /// <summary> /// Creates CalendarService with custom back-off handler. /// </summary> /// <param name="initializer">The service initializer.</param> /// <returns>Created CalendarService with custom back-off configured.</returns> public static CalendarService CreateCalendarService(BaseClientService.Initializer initializer) { CalendarService service = null; try { initializer.DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.None; service = new CalendarService(initializer); var backOffHandler = new BackoffHandler(service, new ExponentialBackOff()); service.HttpClient.MessageHandler.AddUnsuccessfulResponseHandler(backOffHandler); return(service); } catch { if (service != null) { service.Dispose(); } throw; } }
private void UpdateEvent() { CalendarService oCalendarService = GAuthenticate(); //Search for Event EventQuery oEventQuery = new EventQuery(); oEventQuery.Uri = new Uri("https://www.google.com/calendar/feeds/[email protected]/private/full"); oEventQuery.ExtraParameters = "extq=[SynchronizationID:{Your GUID Here}]"; Google.GData.Calendar.EventFeed oEventFeed = oCalendarService.Query(oEventQuery); //Update Related Events foreach (Google.GData.Calendar.EventEntry oEventEntry in oEventFeed.Entries) { //Update Event oEventEntry.Title.Text = "Updated Entry"; oCalendarService.Update(oEventEntry); break; } }
public GoogleService(IConfigurationManager configurationManager) { Check.Argument.IsNotNull(configurationManager, "configurationManager"); _configurationManager = configurationManager; calendarId = _configurationManager.AppSettings["googleCalendarId"]; applicationName = _configurationManager.AppSettings["googleApplicationName"]; private_key = _configurationManager.AppSettings["googlePrivateKey"]; client_email = _configurationManager.AppSettings["googleClientEmail"]; credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(client_email) { Scopes = scopes }.FromPrivateKey(private_key)); service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); }