Ejemplo n.º 1
0
        public async Task <bool> RemoveUsage(UsageData usage)
        {
            bool status = false;

            try
            {
                UsageSessions.Remove(usage);

                var res = await HttpManager.Manager.Delete(Constants.MakeUrl($"usage/{Data.UserID}/{usage.UsageId}"));

                if (res == null)
                {
                    throw new Exception("Delete response is null");
                }

                if (res.IsSuccessStatusCode)
                {
                    status = true;
                }
                else
                {
                    AppDebug.Line("Error while removing usage");
                }
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "RemoveUsage");
            }

            return(status);
        }
Ejemplo n.º 2
0
        public static async Task InitAsync()
        {
            AppDebug.Line("In InitAsync");
            try
            {
                if (IsConnected)
                {
                    return;
                }

                await FindDevicesAsync();

                if (SelectedBand != null)
                {
                    AppDebug.Line("connecting to band");

                    BandClient = await BandClientManager.Instance.ConnectAsync(SelectedBand);

                    AppDebug.Line("connected to band");
                }
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "InitAsync");
            }
        }
Ejemplo n.º 3
0
        public async Task <HttpResponseMessage> Post(string URL, HttpContent content)
        { // Post to server
            try
            {
                bool isInternetConnected = NetworkInterface.GetIsNetworkAvailable();
                if (!isInternetConnected)
                {
                    AppDebug.Line("Error - No Internet connection!");

                    await new MessageDialog("No internet connection!", "Error!").ShowAsync();
                    return(null);
                }
                var response = await client.PostAsync(URL, content);

                var responseString = await response.Content.ReadAsStringAsync();

                AppDebug.Line("response from post: [" + responseString + "]");
                return(response);
            }
            catch (Exception e)
            {
                AppDebug.Exception(e, "Post");
                return(null);
            }
        }
Ejemplo n.º 4
0
        public static void SetAllCheckBoxesTags(Grid gridWithCheckBoxes, List <int> listOfTags)
        { // Set checkbox tags in grid from list of tags
            if (listOfTags == null)
            {
                return;
            }

            if (listOfTags.Count == 0)
            {
                return;
            }

            try
            {
                foreach (var ctrl in gridWithCheckBoxes.Children)
                {
                    if (ctrl is CheckBox)
                    {
                        var chk = ctrl as CheckBox;

                        if (listOfTags.Contains(System.Int32.Parse(chk.Tag as string)))
                        {
                            chk.IsChecked = true;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                AppDebug.Exception(e, "SetAllCheckBoxesTags");
            }
        }
        private async void Register(object sender, RoutedEventArgs e)
        {
            HttpResponseMessage res = null;

            try
            { // Build register request
                progressRing.IsActive = true;

                // Get negative checkboxes
                PagesUtilities.GetAllCheckBoxesTags(RegisterNegativeEffectsGrid,
                                                    out List <int> intList);

                GlobalContext.RegisterContext.IntNegativePreferences = intList;

                // Send request with register information
                res = await HttpManager.Manager.Post(Constants.MakeUrl("register"), GlobalContext.RegisterContext);


                if (res != null)
                { // Request succeeded
                    var content = res.GetContent();

                    switch (res.StatusCode)
                    { // Register succeeded
                    case HttpStatusCode.Created:
                    case HttpStatusCode.OK:
                        Status.Text = "Register Successful!";
                        PagesUtilities.SleepSeconds(1);
                        Frame.Navigate(typeof(DashboardPage), res);
                        break;

                    // Register failed
                    case HttpStatusCode.BadRequest:
                        Status.Text = "Register failed!\n" + content["message"];
                        break;

                    default:
                        Status.Text = "Error!\n" + content["message"];
                        break;
                    }
                }
                else
                {
                    Status.Text = "Register failed!\nPost operation failed";
                }
            }
            catch (Exception exc)
            {
                AppDebug.Exception(exc, "Register");
            }
            finally
            {
                progressRing.IsActive = false;
            }
        }
Ejemplo n.º 6
0
 public static void AddUserToContext(NavigationEventArgs e)
 { // Add user to context after login
     try
     {
         CurrentUser = new UserData(LoginResponse.CreateFromHttpResponse(e.Parameter));
     }
     catch (System.Exception exc)
     {
         AppDebug.Exception(exc, "AddUserToContext");
         CurrentUser = null;
     }
 }
Ejemplo n.º 7
0
        private async void PostLogin(object sender, RoutedEventArgs e)
        {
            AppDebug.Line("PostLogin");
            HttpResponseMessage res = null;

            progressRing.IsActive = true;

            try
            { // Create login request
                var req = new LoginRequest(Username.Text, Password.Password);

                res = await Task.Run(async() => await HttpManager.Manager.Post(Constants.MakeUrl("login"), req));

                if (res != null)
                { // Request succeeded
                    var content = res.GetContent();

                    switch (res.StatusCode)
                    { // Login successfull
                    case HttpStatusCode.OK:
                        AppDebug.Line("Login success!");
                        PagesUtilities.SleepSeconds(1);
                        progressRing.IsActive = false;
                        Frame.Navigate(typeof(DashboardPage), res);
                        break;

                    // Login failed
                    case HttpStatusCode.BadRequest:
                        Status.Text = "Login failed!\n" + content["message"];
                        break;

                    default:
                        Status.Text = "Error!\n" + content["message"];
                        break;
                    }
                }
                else
                {
                    Status.Text = "Login failed!\nPost operation failed";
                }
            }
            catch (Exception exc)
            {
                Status.Text = "Exception during login";

                AppDebug.Exception(exc, "PostLogin");
            }
            finally
            {
                progressRing.IsActive = false;
            }
        }
Ejemplo n.º 8
0
        public void StopHeartRate()
        {
            try
            {
                AppDebug.Line("Finalizing HeartRate...");

                // Heart Rate
                _hearRateModel.Stop();
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "InitHeartRate");
            }
        }
Ejemplo n.º 9
0
 public void Stop()
 {
     try
     {
         if (BandModel.IsConnected)
         {
             BandModel.BandClient.SensorManager.HeartRate.StopReadingsAsync().GetAwaiter().GetResult();
         }
     }
     catch (Exception x)
     {
         AppDebug.Exception(x, "HeartRateModel.Stop");
     }
 }
Ejemplo n.º 10
0
        private static List <UsageData> GetUsagesFromServer()
        { // Get usages for user from DB
            try
            {
                var res = HttpManager.Manager.Get(Constants.MakeUrl("usage/" + GlobalContext.CurrentUser.Data.UserID));
                var str = res.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                return(JsonConvert.DeserializeObject <UsageUpdateRequest[]>(str).ToUsageList());
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "GetUsagesFromServer");

                return(null);
            }
        }
Ejemplo n.º 11
0
 public static int ToAge(this DateTime dob)
 {
     try
     {
         //taken from here: stackoverflow.com/a/11942
         int now    = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
         int dobInt = int.Parse(dob.ToString("yyyyMMdd"));
         return((now - dobInt) / 10000);
     }
     catch (Exception x)
     {
         AppDebug.Exception(x, "GetAgeFromDob");
         return(0);
     }
 }
Ejemplo n.º 12
0
 public static SolidColorBrush GetColor(this string hex)
 {
     try
     {
         hex = hex.Replace("#", string.Empty);
         byte a = (byte)(Convert.ToUInt32(hex.Substring(0, 2), 16));
         byte r = (byte)(Convert.ToUInt32(hex.Substring(2, 2), 16));
         byte g = (byte)(Convert.ToUInt32(hex.Substring(4, 2), 16));
         byte b = (byte)(Convert.ToUInt32(hex.Substring(6, 2), 16));
         return(new SolidColorBrush(Color.FromArgb(a, r, g, b)));;
     }
     catch (Exception x)
     {
         AppDebug.Exception(x, "GetColor");
         return(new SolidColorBrush(Colors.Transparent));
     }
 }
Ejemplo n.º 13
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var req = GlobalContext.RegisterContext;

            if (req != null)
            {
                try
                { // If checkboxes were chosen before, update them again
                    PagesUtilities.SetAllCheckBoxesTags(RegisterMedicalGrid,
                                                        req.IntListMedicalNeeds);
                }
                catch (Exception exc)
                {
                    AppDebug.Exception(exc, "RegisterMedicalPage.OnNavigatedTo");
                }
            }
        }
Ejemplo n.º 14
0
        public void HeartRateChangedAsync(int rate, double accuracy)
        { // Compute heart rate - min, max and average
            if (accuracy == 1)
            {
                HeartRateReadings++;

                if (HeartRateReadings < 5)
                {
                    return;
                }

                //from: math.stackexchange.com/questions/106700/incremental-averageing
                HeartRateAverage += (rate - HeartRateAverage) / (HeartRateReadings - 4);

                HeartRateMin = Math.Min(HeartRateMin, rate);
                HeartRateMax = Math.Max(HeartRateMax, rate);

                //AppDebug.Line($"HeartRate: cur<{rate}> min<{HeartRateMin}> avg<{Math.Round(HeartRateAverage, 0)}> max<{HeartRateMax}>");

                if (HeartRateReadings % 5 == 0)
                {
                    AppDebug.Line($"HeartRate: cur<{rate}> min<{HeartRateMin}> avg<{Math.Round(HeartRateAverage, 0)}> max<{HeartRateMax}>");
                    try
                    {
                        //Run code on main thread for UI change, preventing exception
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            try
                            {
                                Handler?.Invoke(HeartRateAverage, HeartRateMin, HeartRateMax);
                            }
                            catch (Exception x)
                            {
                                AppDebug.Exception(x, "HeartRateChangedAsync => Handler?.Invoke");
                            }
                        }).AsTask().GetAwaiter().GetResult();
                    }
                    catch (Exception e)
                    {
                        AppDebug.Exception(e, "HeartRateChanged");
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public static List <TEnum> FromBitmapToEnumList <TEnum>(this int bitmap)
        {
            List <TEnum> lst = new List <TEnum>();

            try
            {
                foreach (TEnum val in Enum.GetValues(typeof(TEnum)))
                {
                    if ((bitmap & (1 << (Convert.ToInt32(val) - 1))) != 0)
                    {
                        lst.Add(val);
                    }
                }
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, $"FromBitmapToEnumList Type:{typeof(TEnum).Name}");
            }

            return(lst);
        }
Ejemplo n.º 16
0
        public async Task InitAsync()
        {
            AppDebug.Line("HeartRateModel Starting...");

            if (BandModel.IsConnected)
            {
                AppDebug.Line("HeartRateModel Is connected...");

                var consent = UserConsent.Declined;
                try
                {
                    consent = BandModel.BandClient.SensorManager.HeartRate.GetCurrentUserConsent();
                }
                catch (Exception x)
                {
                    AppDebug.Exception(x, "InitAsync");
                }

                if (consent != UserConsent.Granted)
                {
                    AppDebug.Line("HeartRateModel requesting user access");
                    try
                    {
                        AppDebug.Line("HeartRateModel inside CoreDispatcher");

                        var r = await BandModel.BandClient.SensorManager.HeartRate.RequestUserConsentAsync();

                        AppDebug.Line($"HeartRateModel RequestUserConsentAsync returned {r}");
                    }
                    catch (Exception x)
                    {
                        AppDebug.Exception(x, "HeartRate.RequestUserConsentAsync");
                    }
                    AppDebug.Line("HeartRateModel user access success");
                }

                BandModel.BandClient.SensorManager.HeartRate.ReadingChanged += HeartRate_ReadingChanged;
                AppDebug.Line("HeartRateModel InitAsync");
            }
        }
Ejemplo n.º 17
0
        public void OnPageLoaded(object sender, RoutedEventArgs e)
        {
            PagesUtilities.DontFocusOnAnythingOnLoaded(sender, e);

            var req = GlobalContext.RegisterContext;

            if (req != null)
            {
                try
                { // Load previously entered details, or empty if none exist
                    Username.Text     = req.Username ?? "";
                    Password.Password = "";
                    Country.Text      = req.Country ?? "";
                    City.Text         = req.City ?? "";
                    Email.Text        = req.Email ?? "";

                    if (req.Gender != null)
                    {
                        if (req.Gender == "Male")
                        {
                            Gender.SelectedIndex = 1;
                        }
                        else if (req.Gender == "Female")
                        {
                            Gender.SelectedIndex = 2;
                        }
                        else
                        {
                            Gender.SelectedIndex = 0;
                        }
                    }
                }
                catch (Exception exc)
                {
                    AppDebug.Exception(exc, "RegisterPage.OnPageLoaded");
                }
            }
        }
Ejemplo n.º 18
0
        public async Task <HttpResponseMessage> Get(string URL)
        { // Get from server
            AppDebug.Line("In Get: " + URL);

            try
            {
                bool isInternetConnected = NetworkInterface.GetIsNetworkAvailable();
                if (!isInternetConnected)
                {
                    AppDebug.Line("Error - No Internet connection!");

                    await new MessageDialog("No internet connection!", "Error!").ShowAsync();
                    return(null);
                }

                var response = await client.GetAsync(URL).ConfigureAwait(false);

                AppDebug.Line("finished get");

                var responseString = await response.Content.ReadAsStringAsync();

                if (responseString.Length < 2000)
                {
                    AppDebug.Line("response from get: [" + responseString + "]");
                }
                else
                {
                    AppDebug.Line("response from get (first 2000 chars): [" + responseString.Substring(0, 500) + "]");
                }
                return(response);
            }
            catch (Exception e)
            {
                AppDebug.Exception(e, "Get");
                return(null);
            }
        }
Ejemplo n.º 19
0
        public static async Task EnableBluetoothAsync()
        {
            try
            {
                var access = await Radio.RequestAccessAsync();

                if (access != RadioAccessStatus.Allowed)
                {
                    return;
                }
                BluetoothAdapter adapter = await BluetoothAdapter.GetDefaultAsync();

                if (null != adapter)
                {
                    var btRadio = await adapter.GetRadioAsync();

                    await btRadio.SetStateAsync(RadioState.On);
                }
            }
            catch (Exception c)
            {
                AppDebug.Exception(c, "EnableBluetoothAsync");
            }
        }
Ejemplo n.º 20
0
        public async Task <bool> StartHeartRate(HeartRateModel.ChangedHandler handler)
        {
            bool ret = false;

            try
            {
                AppDebug.Line("Initializing HeartRate...");

                // Heart Rate
                await _hearRateModel.InitAsync();

                if (handler != null)
                {
                    _hearRateModel.Changed += handler;
                }
                ret = await _hearRateModel.Start();
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "InitHeartRate");
            }

            return(ret);
        }
Ejemplo n.º 21
0
        public async Task <bool> Start()
        {
            bool ret = false;

            try
            {
                AppDebug.Line("HeartRateModel Start");

                if (BandModel.IsConnected)
                {
                    AppDebug.Line("HeartRateModel reading..");

                    ret = await BandModel.BandClient.SensorManager.HeartRate.StartReadingsAsync();

                    AppDebug.Line("HeartRateModel read..");
                }
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "HeartRateModel.Start");
            }

            return(ret);
        }