Beispiel #1
0
 public UserController(IAuthTokenRepo authTokenRepo, IUserRepo userRepo,
                       GoogleCalendarService googleCalendarApi)
 {
     _authTokenRepo     = authTokenRepo;
     _googleCalendarApi = googleCalendarApi;
     _userRepo          = userRepo;
 }
Beispiel #2
0
        public async Task CreateCalendarWithEventsShouldReturnOperationalResultCalendarFailure()
        {
            var messages = new Dictionary <string, HttpResponseMessage>()
            {
                [this._googleCalendarSettings.CalendarsEndpoint] = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.BadRequest,
                },
                [this._googleCalendarSettings.EventsEndpoint] = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.BadRequest,
                }
            };

            using var testMessageHandler = new TestMessageHandler(messages);
            using (var httpClient = new HttpClient(testMessageHandler))
            {
                var googleCalendarService = new GoogleCalendarService(
                    httpClient,
                    this._adventSettings,
                    this._testSettings,
                    this._googleCalendarSettings);

                // Act
                var createdCalendar = await googleCalendarService.CreateNewCalendarWithEvents().ConfigureAwait(false);

                // Assert
                Assert.IsType <OperationalResult>(createdCalendar);
                Assert.Equal(OperationalResultStatus.CalendarFailure, createdCalendar.Status);
            }
        }
Beispiel #3
0
        private async Task CleanGoogleCalendarInternal()
        {
            if (SelectedProfile.GoogleSettings.GoogleAccount == null ||
                SelectedProfile.GoogleSettings.GoogleCalendar == null)
            {
                MessageService.ShowMessageAsync("Please select a Google calendar to wipe");
                return;
            }

            var task =
                await
                MessageService.ShowConfirmMessage(
                    "Are you sure you want to reset events from 10 year past and 10 year future?");

            if (task != MessageDialogResult.Affirmative)
            {
                return;
            }

            var calendarSpecificData = new Dictionary <string, object>
            {
                { "CalendarId", SelectedProfile.GoogleSettings.GoogleCalendar.Id },
                { "AccountName", SelectedProfile.GoogleSettings.GoogleAccount.Name }
            };
            var result = await GoogleCalendarService.ClearCalendar(calendarSpecificData);

            if (!result)
            {
                MessageService.ShowMessageAsync("Reset calendar failed.");
            }
        }
Beispiel #4
0
        private async Task GetGoogleCalendarInternal()
        {
            try
            {
                if (SelectedProfile.GoogleSettings.GoogleAccount == null ||
                    SelectedProfile.GoogleSettings.GoogleAccount.Name == null)
                {
                    return;
                }
                var calendars = await GoogleCalendarService.GetAvailableCalendars(
                    SelectedProfile.GoogleSettings.GoogleAccount.Name);

                if (calendars.Any())
                {
                    if (SelectedProfile.GoogleSettings.GoogleCalendar != null)
                    {
                        SelectedProfile.GoogleSettings.GoogleCalendar = calendars.FirstOrDefault(t =>
                                                                                                 t.Id.Equals(SelectedProfile.GoogleSettings.GoogleCalendar.Id));
                    }

                    if (SelectedProfile.GoogleSettings.GoogleCalendar == null)
                    {
                        SelectedProfile.GoogleSettings.GoogleCalendar = calendars.First();
                    }
                }
                SelectedProfile.GoogleSettings.GoogleCalendars = calendars;
            }
            catch (Exception exception)
            {
                MessageService.ShowMessageAsync("Unable to get Google calendars.");
                Logger.Error(exception);
            }
        }
Beispiel #5
0
 public IndexModel(ILogger <IndexModel> logger, BackgroundImageService backgroundImageService, GoogleCalendarService calendarService, WeatherService weatherService)
 {
     this._logger = logger;
     this._backgroundImageService = backgroundImageService;
     this._calendarService        = calendarService;
     this._weatherService         = weatherService;
     this.NextDays = new CalendarDay[0];
 }
Beispiel #6
0
        public static void Main(string[] args)
        {
            DesktopPlatform.Start();

            GoogleCalendarService google = new GoogleCalendarService(new TestConfig());

            DesktopPlatform.Finish();
        }
Beispiel #7
0
        public async Task DoWork() // Add new gmail account and sync with db
        {
            var service  = new GoogleCalendarService();
            var range    = (int)AppDomain.CurrentDomain.GetData("EventViewableYearRange");
            var timeMax  = new DateTime(DateTime.Today.Year + range - 1, 12, 31, 23, 59, 59);
            var accounts = _dbs.GetAvailableAccounts();

            try
            {
                var events = await service.GetEvents(timeMax);

                if (events != null && !events.Items.IsNullOrEmpty())
                {
                    var            email           = events.Items[0].Creator.Email;
                    var            foundAcc        = accounts.Find(a => a.Email == email);
                    List <GXEvent> newEvents       = null;
                    int            targetAccountId = 0;

                    // Email exists within db, add new events from last sync timestamp
                    if (foundAcc != null)
                    {
                        targetAccountId = foundAcc.AccId;
                        var fromLastSync = events.Items.Where(e => e.Updated >= foundAcc.LastSync);
                        newEvents = fromLastSync.ToGXEvents(targetAccountId);
                    }
                    // New email
                    else
                    {
                        targetAccountId = accounts.Max(a => a.AccId) + 1;
                        await _dbs.AddAccount(email);

                        newEvents = events.Items.ToGXEvents(targetAccountId);
                    }

                    // Add new events to db
                    await _dbs.AddEvents(newEvents, targetAccountId);

                    await _dbs.UpdateLastSync(targetAccountId);
                }
            }
            catch (Newtonsoft.Json.JsonException)
            {
                throw new FormatException("Incorrect oauth token file format. Restore or delete it and try again");
            }
            catch (DataException)
            {
                throw new DataException("Failed to modify database. Verify the connection and try again");
            }
            finally
            {
                if (Events.Count < viewableEventsNum)
                {
                    RefreshEvents(viewableEventsNum);
                }
            }
        }
Beispiel #8
0
 public CalendarController(ICalendarService calendarService, IAuthenticationService authenticationService, ExternalCalendarHelperService exCalHelperService, OAuthService oAuthService, GoogleCalendarService googleCalendarService, MicrosoftOAuthService msOAuthService, MicrosoftCalendarService msCalService)
 {
     this.calendarService       = calendarService;
     this.authenticationService = authenticationService;
     this.exCalHelperService    = exCalHelperService;
     this.oAuthService          = oAuthService;
     this.googleCalendarService = googleCalendarService;
     this.msOAuthService        = msOAuthService;
     this.msCalService          = msCalService;
 }
Beispiel #9
0
        private async Task <List <Appointment> > GetEqualAppointments(GoogleCalendarService googleCalenderService, OutlookCalendarService outlookCalendarService, string calenderId)
        {
            List <Appointment> googleAppointments = await googleCalenderService.GetCalendarEventsInRangeAsync(0, 2, calenderId);

            List <Appointment> outLookAppointments = await outlookCalendarService.GetOutlookAppointmentsAsync(0, 2);

            return((from lookAppointment in outLookAppointments
                    let isAvailable = googleAppointments.Any(appointment => appointment.Equals(lookAppointment))
                                      where isAvailable
                                      select lookAppointment).ToList());
        }
Beispiel #10
0
 public async Task CalendarService_SucessfullyDeleteAddedEvent(GoogleCalendarService service, string eventId)
 {
     try
     {
         await service.DeleteEvent(eventId);
     }
     catch (Exception ex)
     {
         Assert.Fail("Failed to delete event: " + ex.Message);
     }
 }
Beispiel #11
0
        private void StartAuthentication(TaskScheduler taskScheduler)
        {
            //// Authenticate Oauth2
            string clientId = "68932173233-e7nf2hlqhl9o16knj0iatg82bmgdkvom.apps.googleusercontent.com";

            string clientSecret = "QRDGYelWPnCOsCiWlXVl6Cc3";
            string redirectUri  = "urn:ietf:wg:oauth:2.0:oob";
            string userName     = "******"; //  A string used to identify a user (locally).

            var calenderService       = (new AccountAuthentication()).AuthenticateCalenderOauth(clientId, clientSecret, userName, "OutlookGoogleSyncRefresh.Auth.Store", "OutlookGoogleSyncRefresh");
            var googleCalenderService = new GoogleCalendarService(calenderService);

            googleCalenderService.GetAvailableCalendars()
            .ContinueWith(task => ContinuationActionGoogle(task, googleCalenderService, taskScheduler));
        }
Beispiel #12
0
        public async Task <string> CalendarService_SucessfullyAddEvent(GoogleCalendarService service)
        {
            var    dummyEvent = CreateDummyEvent().ToEvent();
            string dummyId    = "";

            try
            {
                dummyId = await service.AddEvent(dummyEvent);
            }
            catch (Exception ex)
            {
                Assert.Fail("Failed to add event: " + ex.Message);
            }
            return(dummyId);
        }
Beispiel #13
0
        private void ContinuationActionGoogle(Task <List <Calendar> > task, GoogleCalendarService googleCalenderService,
                                              TaskScheduler taskScheduler)
        {
            string calenderId = string.Empty;
            var    calender   = task.Result.FirstOrDefault(calendar => calendar.Name.Contains("Test"));

            if (calender != null)
            {
                calenderId = calender.Id;
            }



            googleCalenderService.GetCalendarEventsInRangeAsync(0, 1, calenderId)
            .ContinueWith(ContinuationActionGoogleAppointments, taskScheduler);
        }
Beispiel #14
0
        private void Button_Clicked(object sender, EventArgs e)
        {
            var path           = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "mycalendar_credentials.json");
            var googleCalendar = new GoogleCalendarService(path);
            var eventTitle     = EntryEventTitle.Text;
            var participants   = EntryParticipants.Text.Split(';');
            var eventDateTime  = new DateTime(DatePickerMeeting.Date.Year,
                                              DatePickerMeeting.Date.Month,
                                              DatePickerMeeting.Date.Day,
                                              TimePickerMeeting.Time.Hours,
                                              TimePickerMeeting.Time.Minutes,
                                              TimePickerMeeting.Time.Seconds
                                              );

            googleCalendar.CreateEvent(eventTitle, participants, eventDateTime, eventDateTime.AddHours(1));
        }
Beispiel #15
0
        public async Task CalendarService_SucessfullyRetrieveAddedEvent(GoogleCalendarService service, string eventId)
        {
            try
            {
                var dummyRetrieved = await service.GetEvent(eventId);

                if (dummyRetrieved == null || dummyRetrieved.Summary != "dummy event")
                {
                    Assert.Fail("Incorrect dummy event retrieved");
                }
            }
            catch (Exception ex)
            {
                Assert.Fail("Failed to get event: " + ex.Message);
            }
        }
Beispiel #16
0
        public async Task TestGoogleCalendarServiceSample()
        {
            // arrange
            var service = new GoogleCalendarService(
                googleToken: new TokenEntity()
            {
                TokenType   = "Bearer",
                AccessToken = TestContext.Parameters["GOOGLE_TEST_TOKEN"]
            },
                calendarId: TestContext.Parameters["GOOGLE_CALENDAR_ID"]
                );

            // act
            var result = await service.GetEventsSample();

            // assert
            Assert.IsNotNull(result);
        }
Beispiel #17
0
        public static async Task <System.Collections.Generic.List <Models.CalendarEntry> > GetCalendars(TokenEntity msaToken, TokenEntity googleToken,
                                                                                                        ILogger logger)
        {
            var start  = DateTime.Now.Date.AddDays(-7);
            var end    = DateTime.Now.Date.AddDays(Constants.CalendarWeeks * 7);
            var events = new System.Collections.Generic.List <CalendarEntry>();

            try
            {
                var holidays = new System.Collections.Generic.List <CalendarEntry>();

                // combine public and school holidays
                var publicHolidaysService = new PublicHolidaysService();
                var schoolHolidaysService = new SchoolHolidaysService();

                holidays.AddRange(await publicHolidaysService.GetEvents(start, end));
                holidays.AddRange(await schoolHolidaysService.GetEvents(start, end, logger));
                var deduplicatedHolidays = holidays.GroupBy(x => x.Date).Select(y => y.First()).ToList <CalendarEntry>();
                events.AddRange(deduplicatedHolidays);

                var googleCalendarService = new GoogleCalendarService(
                    googleToken,
                    calendarId: Util.GetEnvironmentVariable("GOOGLE_CALENDAR_ID"),
                    timeZone: Util.GetEnvironmentVariable("CALENDAR_TIMEZONE"));
                var googleEvents = await googleCalendarService.GetEvents(start, end, isPrimary : true);

                events.AddRange(googleEvents);

                var outlookCalendarService = new OutlookCalendarService(msaToken,
                                                                        timeZone: Util.GetEnvironmentVariable("CALENDAR_TIMEZONE"));
                var outlookEvents = await outlookCalendarService.GetEvents(start, end, isSecondary : true);

                events.AddRange(outlookEvents);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(events);
        }
Beispiel #18
0
        private void Button_Click_Selected(object sender, RoutedEventArgs e)
        {
            MyGrid.IsEnabled = false;
            //// Authenticate Oauth2
            string clientId = "68932173233-e7nf2hlqhl9o16knj0iatg82bmgdkvom.apps.googleusercontent.com";

            string clientSecret = "QRDGYelWPnCOsCiWlXVl6Cc3";
            string redirectUri  = "urn:ietf:wg:oauth:2.0:oob";
            string userName     = "******"; //  A string used to identify a user (locally).

            var calenderService = (new AccountAuthenticationService(new ApplicationLogger(), new MessageService())).AuthenticateCalenderOauth(clientId, clientSecret, userName, "OutlookGoogleSyncRefresh.Auth.Store", "OutlookGoogleSyncRefresh");

            var googleCalenderService = new GoogleCalendarService(calenderService, new ApplicationLogger());
            var scheduler             = TaskScheduler.FromCurrentSynchronizationContext();

            googleCalenderService.GetAvailableCalendars()
            .ContinueWith(
                task =>
                GetInformation(task.Result, scheduler,
                               googleCalenderService));
        }
Beispiel #19
0
        public async Task TestGoogleCalendarService1Week()
        {
            // arrange
            var service = new GoogleCalendarService(
                googleToken: new TokenEntity()
            {
                TokenType   = "Bearer",
                AccessToken = TestContext.Parameters["GOOGLE_TEST_TOKEN"]
            },
                calendarId: TestContext.Parameters["GOOGLE_CALENDAR_ID"]
                );

            var start = DateTime.Now.Date;
            var end   = DateTime.Now.Date.AddDays(7);

            // act
            var result = await service.GetEvents(start, end);

            // assert
            Assert.IsNotNull(result);
            Assert.Greater(result.Count, 0);
        }
Beispiel #20
0
        public async Task CreateCalendarWithEventsShouldReturnOperationalResultSuccess()
        {
            // Arrange
            var newCalendarId = "1";
            var eventsUrl     = this.GetEventsUrl(newCalendarId);
            var messages      = new Dictionary <string, HttpResponseMessage>()
            {
                [this._googleCalendarSettings.CalendarsEndpoint] = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content    = new StringContent(
                        JsonConvert.SerializeObject(new CalendarDto()
                    {
                        Id = newCalendarId
                    }),
                        Encoding.UTF8, MediaTypeNames.Application.Json)
                },
                [eventsUrl] = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                }
            };

            using var testMessageHandler = new TestMessageHandler(messages);
            using var httpClient         = new HttpClient(testMessageHandler);
            var googleCalendarService = new GoogleCalendarService(
                httpClient,
                this._adventSettings,
                this._testSettings,
                this._googleCalendarSettings);

            // Act
            var createdCalendar = await googleCalendarService.CreateNewCalendarWithEvents().ConfigureAwait(false);

            // Assert
            Assert.IsType <OperationalResult>(createdCalendar);
            Assert.Equal(OperationalResultStatus.Success, createdCalendar.Status);
        }
Beispiel #21
0
        public async Task CalendarService_TestAddGetDelete()
        {
            // Path for credential and token
            const string credPath   = @"auth\credentials.json";
            const string tokenPath  = @"auth\token.json";
            var          currentDir = Directory.GetCurrentDirectory();

            AppDomain.CurrentDomain.SetData("GoogleCalendarCredentialPath", Path.Combine(currentDir, credPath));
            AppDomain.CurrentDomain.SetData("GoogleCalendarTokenPath", Path.Combine(currentDir, tokenPath));

            // Actual test
            var service = new GoogleCalendarService();
            var eventId = await CalendarService_SucessfullyAddEvent(service);

            if (eventId.IsNullOrEmpty())
            {
                Assert.Fail("Empty google event id retrieved");
            }
            await CalendarService_SucessfullyRetrieveAddedEvent(service, eventId);
            await CalendarService_SucessfullyDeleteAddedEvent(service, eventId);

            // Clean up used token
            Directory.Delete(Path.Combine(currentDir, tokenPath), true);
        }
Beispiel #22
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Admin, "get", Route = null)] HttpRequest req,
            [Table(Constants.TOKEN_TABLE, partitionKey: Constants.TOKEN_PARTITIONKEY, rowKey: Constants.MSATOKEN_ROWKEY)] TokenEntity msaToken,
            [Table(Constants.TOKEN_TABLE, partitionKey: Constants.TOKEN_PARTITIONKEY, rowKey: Constants.GOOGLETOKEN_ROWKEY)] TokenEntity googleToken,
            ILogger log)
        {
            string googleCalendarResult;
            string outlookCalendarResult;
            int    statusCode = StatusCodes.Status200OK;

            // check Google calendar
            try
            {
                var calendarService = new GoogleCalendarService(
                    googleToken,
                    calendarId: Util.GetEnvironmentVariable("GOOGLE_CALENDAR_ID"),
                    timeZone: Util.GetEnvironmentVariable("CALENDAR_TIMEZONE"));
                var result = await calendarService.GetEventsSample();

                googleCalendarResult = result?.Count.ToString() ?? "empty resultset";
                log.LogInformation(googleCalendarResult);
            }
            catch (Exception ex)
            {
                googleCalendarResult = ex.Message;
                log.LogError(ex, nameof(GoogleCalendarService));
                statusCode = StatusCodes.Status424FailedDependency;
            }

            // check Outlook calender
            try
            {
                var calendarService = new OutlookCalendarService(msaToken,
                                                                 timeZone: Util.GetEnvironmentVariable("CALENDAR_TIMEZONE"));
                var result = await calendarService.GetEventsSample();

                outlookCalendarResult = result?.Count.ToString() ?? "empty resultset";
                log.LogInformation(googleCalendarResult);
            }
            catch (Exception ex)
            {
                outlookCalendarResult = ex.Message;
                log.LogError(ex, nameof(OutlookCalendarService));
                statusCode = StatusCodes.Status424FailedDependency;
            }

            // check MSA Token
            if (msaToken == null)
            {
                statusCode = StatusCodes.Status424FailedDependency;
            }

            // check Google Token
            if (googleToken == null)
            {
                statusCode = StatusCodes.Status424FailedDependency;
            }

            // assemble service info
            return(statusCode == StatusCodes.Status200OK
                 ? (ActionResult) new OkObjectResult(new
            {
                home = Environment.GetEnvironmentVariable("HOME", EnvironmentVariableTarget.Process),
                webSiteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME", EnvironmentVariableTarget.Process),
                appRoot = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase),
                staticFilesRoot = Util.GetApplicationRoot(),
                googleCalendarResult,
                outlookCalendarResult,
                msaToken,
                googleToken
            })
                 : (ActionResult) new StatusCodeResult(statusCode));
        }
 /// <summary>
 /// Get events from current user his/her google calendar
 /// </summary>
 /// <returns>A list of events in GoogleCalenderModel</returns>
 public List<GoogleCalendarModel> GetEventsUser()
 {
     var googleCalendarService = new GoogleCalendarService(_credential);
     googleCalendarService.CreateService();
     return googleCalendarService.GetData();
 }
 public async Task RequestGoogleCalendarData()
 {
     await _googleAuthenticator.LoginGoogle(_testUsername);
     var calendarService = new GoogleCalendarService(_googleAuthenticator.GetCurrentCredentials());
     calendarService.CreateService();
 }
Beispiel #25
0
        // Save received event (already validated by edit view model) to db
        // If SaveEventMsg.SaveChangeOnline true, then also save event to / delete event from google calendar
        private async void OnModifyEventReceived(ModifyEventMsg m)
        {
            var eventToModify = m.Event;
            var service       = new GoogleCalendarService();

            try
            {
                // Modify local db and possiblely google calendar based on action
                switch (m.Action)
                {
                case EventModifyAction.Add:
                    string googleCalendarEventId = null;
                    var    targetAccountId       = eventToModify.AID;
                    // Apply changes online first so any failure will prevent changes from being saved locally
                    if (LoggedIn && m.SaveChangeOnline)
                    {
                        googleCalendarEventId = await service.AddEvent(eventToModify.ToEvent());
                    }
                    // Event was successfully persisted on Google Calendar, update account and id
                    if (!googleCalendarEventId.IsNullOrEmpty())
                    {
                        var accounts        = _dbs.GetAvailableAccounts();
                        var lastSyncAccount = accounts.Where(a => a.AccId > 1)
                                              .OrderByDescending(a => a.LastSync)
                                              .FirstOrDefault();
                        if (lastSyncAccount == null)
                        {
                            throw new DataException("Couldn't find target Google Calendar account");
                        }
                        targetAccountId   = lastSyncAccount.AccId;
                        eventToModify.GID = googleCalendarEventId;
                    }
                    // Save changes locally
                    await _dbs.AddEvent(eventToModify, targetAccountId);

                    // Switch view to edit just created event
                    Messenger.Base.Send(eventToModify);
                    break;

                case EventModifyAction.Update:
                    if (LoggedIn && m.SaveChangeOnline)
                    {
                        await service.UpdateEvent(eventToModify.ToEvent());
                    }
                    await _dbs.UpdateEvent(eventToModify, eventToModify.EID);

                    break;

                case EventModifyAction.Delete:
                    if (LoggedIn && m.SaveChangeOnline)
                    {
                        await service.DeleteEvent(eventToModify.GID);
                    }
                    _dbs.DeleteEvent(eventToModify.EID);
                    break;

                default:
                    SendModifyEventStatus(success: false, msg: "Unknown action received");
                    return;
                }
            }
            catch (DataException ex)
            {
                SendModifyEventStatus(success: false, msg: ex.Message);
                return;
            }
            catch (Google.GoogleApiException)
            {
                SendModifyEventStatus(success: false, msg: "Unable to apply changes online. If error persists, consider modifying event locally");
                return;
            }
            SendModifyEventStatus(success: true, deleted: m.Action == EventModifyAction.Delete);
            RefreshEvents(viewableEventsNum);

            // Update tree view if opened
            Messenger.Base.Send(new UpdateTreeViewMsg
            {
                ModifiedEvent = m.Event,
                Action        = m.Action
            });
        }
        public CalendarViewModel()
        {
            var cs = new GoogleCalendarService();

            Events = cs.GetListedEvents(cs._googleCalendarService);
        }
Beispiel #27
0
        public static async Task Main(string[] args)
        {
            // NLog: setup the logger first to catch all errors
            LogFactory nlog = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");

#if DEBUG
            DebugLoggingConfig.ActivateDebugLogging();
#endif
            var logger = nlog.GetCurrentClassLogger();
            logger.Info("Startup...");

            try
            {
                // 1) read private config file (not on github)
                string secretsFilename = "Secrets/DashboardConfig.json";
                if (File.Exists(secretsFilename))
                {
                    using (var r = File.OpenRead(secretsFilename))
                    {
                        Config = await JsonSerializer.DeserializeAsync <DashboardConfig>(r);
                    }
                }
                else
                {
                    Config = new DashboardConfig();
                    Directory.CreateDirectory("Secrets/");
                    using (var w = File.Create(secretsFilename))
                    {
                        var options = new JsonSerializerOptions {
                            WriteIndented = true
                        };
                        await JsonSerializer.SerializeAsync(w, Config, options);
                    }
                }
#if DEBUG
                // this UNC path doesn't work on raspbian!
                Config.BackgroundImagesPath = @"\\SynologyDS218j\photo\DashboardBackgrounds";
#endif

                // 2) this one is complex, async, and long. We can't properly call this during ConfigureServices...
                GoogleService = await GoogleCalendarService.GoogleCalendarAuthAsync();

                // Want to know, which calendar IDs you have?
                // foreach (var kvp in await CalendarListService.QueryCalendarIdsAsync(GoogleService))
                // {
                //     Console.WriteLine($"CalendarID;Summary: {kvp.Key};{kvp.Value}");
                // }

#if RELEASE
                // 3) PIR sensor to control the monitor
                PirSensorService = new PirSensorService(Config, new MonitorService());
                PirSensorService.Start();
#endif

                logger.Info("Build WebHost...");
                var host = CreateWebHostBuilder(args).Build();
                logger.Info("Run WebHost!");
                await host.RunAsync();
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }
Beispiel #28
0
        private void GetInformation(IEnumerable <Calendar> list, TaskScheduler currentSynchronizationContext, GoogleCalendarService googleCalenderService)
        {
            string calenderId = string.Empty;
            var    calender   = list.FirstOrDefault(calendar => calendar.Name.Contains("Office"));

            if (calender != null)
            {
                calenderId = calender.Id;
            }
            var outlookService = new OutlookCalendarService();

            GetEqualAppointments(googleCalenderService, outlookService, calenderId).ContinueWith(ContinuationActionGoogleAppointments, currentSynchronizationContext);
        }