예제 #1
0
        //todo - didnt implemented the button
        public static async Task SignoutButton_ClickAsync(object sender, EventArgs e)
        {
            UriBuilder uri   = new UriBuilder("https://login.live.com/oauth20_logout.srf");
            var        query = new StringBuilder();

            query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(redirect_uri));
            query.AppendFormat("&client_id={0}", Uri.EscapeDataString(client_id));
            uri.Query = query.ToString();

            var httpClient         = new HttpClient();
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri.Uri);
            var httpResponse       = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);

            DependencyService.Get <IClearCookies>().ClearAllCookies(); //clear cookies - sign out from microsoft user
            LiveIdCredentials.ClearCreds();                            //clear LiveIdCredentials
            SegmentSummaryTable.ClearSegmentTable();                   //clearSleepStats
        }
예제 #2
0
        private async Task GettingTokken(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new ConnectingPage()); //todo - show connecting gif

            //create URL to send
            UriBuilder uri   = new UriBuilder("https://login.live.com/oauth20_token.srf");
            var        query = new StringBuilder();

            uri.Query = query.ToString();

            //creating POST URL+body in application/x-www-form-urlencoded format
            var httpClient = new HttpClient();

            httpClient.BaseAddress = uri.Uri;
            String        urlParameters = "client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&code=" + response_code + "&grant_type=authorization_code";
            StringContent bodyParam     = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");

            //waiting to response
            var response = await httpClient.PostAsync(uri.Uri, bodyParam);

            //converting the response to JSON format
            var stringResponse = response.Content.ReadAsStringAsync().Result;
            var jsonResponse   = JObject.Parse(stringResponse);

            //reading JSON response and updating credentials
            LiveIdCredentials.AccessToken  = (string)jsonResponse["access_token"];
            LiveIdCredentials.ExpiresIn    = (long)jsonResponse["expires_in"];
            LiveIdCredentials.RefreshToken = (string)jsonResponse["refresh_token"];
            Console.WriteLine(LiveIdCredentials.RefreshToken);
            string error = (string)jsonResponse["error"];

            await Utils.GetUserProfile(sender, e);

            await Utils.GetUserId(sender, e);

            await Utils.getSleepStatsOfUser(sender, e);

            /* checking if the userId is already in the ManageUsers table in the database.
             * If not (in case it's a new user), add the user to 2 tables:
             *      1. ManageUsers
             *      2. UserDetails                                                      */
            UserDetailsRecord userDetails = new UserDetailsRecord(LiveIdCredentials.userId, LiveIdCredentials.firstName,
                                                                  LiveIdCredentials.lastName, LiveIdCredentials.gender,
                                                                  Utils.calculateUserAge(), LiveIdCredentials.height, LiveIdCredentials.weight);

            bool userInDB = dbUtils.assertUserInDB(LiveIdCredentials.userId);

            if (!userInDB)
            {
                UserRecord user = new UserRecord(LiveIdCredentials.userId, DateTime.Now);
                dbUtils.addUserToDB(user, userDetails);
            }
            else
            {
                dbUtils.addUserToUserDetailsTable(userDetails);
            }

            /* after each sign in, update the SleepQuality table in the database */
            UserSleepQualityRecord userSleepQuality = new UserSleepQualityRecord(LiveIdCredentials.userId,
                                                                                 LiveIdCredentials.mean_num_of_wakeups,
                                                                                 LiveIdCredentials.mean_sleep_efficience);

            dbUtils.updateUserSleepQualityDetails(userSleepQuality);

            /* after each sign in, update the SleepSegmentsStats table in the database */
            SegmentSummaryTable.Awake         = new SegmentSummary();
            SegmentSummaryTable.Doze          = new SegmentSummary();
            SegmentSummaryTable.Snooze        = new SegmentSummary();
            SegmentSummaryTable.RestlessSleep = new SegmentSummary();
            SegmentSummaryTable.RestfulSleep  = new SegmentSummary();
            SegmentSummaryTable.REMSleep      = new SegmentSummary();

            SleepSegmentsStatsRepository repo = new SleepSegmentsStatsRepository();
            string   UserId = LiveIdCredentials.userId;
            DateTime last_updated_time_of_segments_stats = new DateTime(1990, 1, 1);

            UserSleepSegmentsStatsRecord SleepSegmentsStatsRecord = repo.GetUserSleepSegmentsStats(UserId);

            if (SleepSegmentsStatsRecord == null) //there is no data exists on the user in SleepSegmentsStats table
            {
                await Utils.getSleepSegmentsStats(sender, e, last_updated_time_of_segments_stats);

                //bool saveSuccess = handleUserSleepSegmentsData(repo, UserId, 0); //insert user row to table
                bool saveSuccess = Utils.handleUserSleepSegmentsData(repo, UserId, 0); //insert user row to table
                if (!saveSuccess)
                {
                }                     //error
            }
            else
            {
                last_updated_time_of_segments_stats = SleepSegmentsStatsRecord.lastUpdated;
                //updateSegmentSummaryTableFromDB(SleepSegmentsStatsRecord); // update SegmentSummaryTable object from DB data
                Utils.updateSegmentSummaryTableFromDB(SleepSegmentsStatsRecord); // update SegmentSummaryTable object from DB data
                await Utils.getSleepSegmentsStats(sender, e, last_updated_time_of_segments_stats);

                //bool updateSuccess = handleUserSleepSegmentsData(repo, UserId, 1); //update user row in table
                bool updateSuccess = Utils.handleUserSleepSegmentsData(repo, UserId, 1); //update user row in table
                if (!updateSuccess)
                {
                }                       //error
            }

            /* update segment summary table by user seniority in eSleeping and avg of other same users */
            float    seniority = SegmentSummaryTable.getUserSeniority();
            TimeSpan ageTime   = DateTime.Now.Subtract(LiveIdCredentials.birthdate);
            int      age       = ageTime.Days / 365;

            List <int> weightedSleepSegmentsStats = dbUtils.defineUserSegmentsTransitionsProbabilitiesCombined(LiveIdCredentials.userId, age, LiveIdCredentials.height, LiveIdCredentials.weight, LiveIdCredentials.gender, seniority);

            SegmentSummaryTable.updateTableByList(weightedSleepSegmentsStats);

            /* updating needed values for the Statistics Pages */
            var sleepQualityRepo = new SleepQualityRepository();
            var quality          = sleepQualityRepo.checkUserSleepQualityForHisAge(LiveIdCredentials.userId, Utils.calculateUserAge());

            StatisticsPage.sleepEffAge = (int)quality.Item1;
            StatisticsPage.wakeUpAge   = (int)quality.Item2;
            StatisticsPage.userSleepQualityForHisAgeGraphValue = sleepQualityRepo.calculateQualityLevel((int)quality.Item1, (int)quality.Item2);
            quality = sleepQualityRepo.checkUserSleepQualityForHisGender(LiveIdCredentials.userId, LiveIdCredentials.gender);
            StatisticsPage.sleepEffGender = (int)quality.Item1;
            StatisticsPage.wakeUpGender   = (int)quality.Item2;
            StatisticsPage.userSleepQualityForHisGenderGraphValue = sleepQualityRepo.calculateQualityLevel((int)quality.Item1, (int)quality.Item2);
            quality = sleepQualityRepo.checkUserSleepQualityForHisGenderAndAge(LiveIdCredentials.userId, Utils.calculateUserAge(), LiveIdCredentials.gender);
            StatisticsPage.userStressLevelGraphValue = (int)quality.Item1;
            /* done updating needed values for the Statistics Pages */

            await Navigation.PushAsync(new MainPage()); //back to main

            startRefreshing(sender, e);                 //refreshing tokken
        }