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;
            }
        }
Exemple #2
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;
     }
 }
        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;
            }
        }
Exemple #4
0
 public void Stop()
 {
     try
     {
         if (BandModel.IsConnected)
         {
             BandModel.BandClient.SensorManager.HeartRate.StopReadingsAsync().GetAwaiter().GetResult();
         }
     }
     catch (Exception x)
     {
         AppDebug.Exception(x, "HeartRateModel.Stop");
     }
 }
Exemple #5
0
 public static void UpdateUsagesContextIfEmptyAsync()
 { // Update user usages in current context
     if (CurrentUser.UsageSessions.Count == 0)
     {
         AppDebug.Line("Updating usage history from server for user " + CurrentUser.Data.Username);
         var usages = Task.Run(() => GetUsagesFromServer()).GetAwaiter().GetResult();
         if (usages != null)
         { // Usages exist
             CurrentUser.UsageSessions = usages;
             var names = $"[{string.Join(", ", from u in usages select $"{u.UsageStrain.Name}-{u.StartTime.ToString("dd.MM.yy-HH:mm")}")}]";
             AppDebug.Line($"Got {usages.Count} usages: {names}");
         }
     }
 }
Exemple #6
0
        public void StopHeartRate()
        {
            try
            {
                AppDebug.Line("Finalizing HeartRate...");

                // Heart Rate
                _hearRateModel.Stop();
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "InitHeartRate");
            }
        }
Exemple #7
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);
            }
        }
 public void OnPageLoaded(object sender, RoutedEventArgs e)
 {
     PagesUtilities.DontFocusOnAnythingOnLoaded(sender, e);
     if (GlobalContext.CurrentUser == null)
     {
         UsageHistoryButton.IsEnabled = false;
         MyProfileButton.IsEnabled    = false;
         Welcome.Text = "Debug Session, no user";
     }
     else
     { // Login successfull
         Welcome.Text = $"Welcome, {GlobalContext.CurrentUser.Data.Username}!";
         AppDebug.Line($"Wrote welocme text: [{Welcome.Text}]");
     }
 }
Exemple #9
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);
     }
 }
Exemple #10
0
        public static async Task FindDevicesAsync()
        {
            AppDebug.Line("In FindDevicesAsync");
            var bands = await BandClientManager.Instance.GetBandsAsync();

            if (bands != null && bands.Length > 0)
            {
                SelectedBand = bands[0]; // take the first band
                AppDebug.Line($"Found Band [{SelectedBand.Name}]");
            }
            else
            {
                AppDebug.Line("Did not find Band");
            }
        }
Exemple #11
0
        public static HttpContent CreateJson(object obj)
        {
            //from: https://stackoverflow.com/questions/23585919/send-json-via-post-in-c-sharp-and-receive-the-json-returned
            AppDebug.Line("Creating json");
            // Serialize our concrete class into a JSON String
            var stringPayload = JsonConvert.SerializeObject(obj, Formatting.Indented);

            AppDebug.Line("created json");

            // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

            AppDebug.Line("created content");

            return(httpContent);
        }
Exemple #12
0
        public static void GetAllComboBoxesTags(Grid gridWithComboBoxes, out List <string> listToAddTo)
        { // Get all values from comboxes in grid
            var pageName = gridWithComboBoxes.Parent.GetType().Name;

            listToAddTo = new List <string>();

            foreach (var ctrl in gridWithComboBoxes.Children)
            {
                if (ctrl is ComboBox)
                {
                    var chk = ctrl as ComboBox;
                    listToAddTo.Add(chk.SelectedValue.ToString());
                    AppDebug.Line(chk.Name.ToString());
                }
            }
        }
Exemple #13
0
 async void Contact_ReadingChanged(object sender, BandSensorReadingEventArgs <IBandContactReading> e)
 {
     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                   () =>
     {
         ContactSensorReading reading = new ContactSensorReading {
             Contact = e.SensorReading.State
         };
         if (Changed != null)
         {
             AppDebug.Line("Contact_ReadingChanged value<" + reading.Value.ToString() + ">");
             Changed(reading.Value);
             State = reading.Value;
         }
     });
 }
Exemple #14
0
 public void Start()
 {
     try
     {
         if (BandModel.IsConnected)
         {
             BandModel.BandClient.SensorManager.Contact.StartReadingsAsync();
         }
     }
     catch (Exception x)
     {
         AppDebug.Line("Exception caught in Start");
         AppDebug.Line(x.Message);
         AppDebug.Line(x.StackTrace);
     }
 }
Exemple #15
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));
     }
 }
        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");
                }
            }
        }
Exemple #17
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");
                    }
                }
            }
        }
Exemple #18
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);
        }
Exemple #19
0
        public static void GetAllCheckBoxesTags(Grid gridWithCheckBoxes, out List <int> listToAddTo)
        { // Get all check box that are selected in grid
            var pageName = gridWithCheckBoxes.Parent.GetType().Name;

            listToAddTo = new List <int>();

            foreach (var ctrl in gridWithCheckBoxes.Children)
            { // For each checkbox existing
                if (ctrl is CheckBox)
                {
                    var chk = ctrl as CheckBox;

                    if (chk.IsChecked == true)
                    {
                        System.Int32.TryParse(chk.Tag.ToString(), out int tag);
                        listToAddTo.Add(tag);
                        AppDebug.Line(pageName + "." + tag);
                    }
                }
            }
        }
Exemple #20
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");
            }
        }
Exemple #21
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");
                }
            }
        }
Exemple #22
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);
            }
        }
Exemple #23
0
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // Ensure the current window is active
                Window.Current.Activate();
            }
            AppDebug.Init();
        }
Exemple #24
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);
        }
Exemple #25
0
        public async Task <bool> PairBand()
        {
            bool ret = false;

            do
            {
                await BandModel.InitAsync();

                if (!BandModel.IsConnected)
                {
                    AppDebug.Line("Band NOT CONNECTED");
                    break;
                }

                AppDebug.Line("Band CONNECTED");

                _hearRateModel = new HeartRateModel();
                _contactModel  = new ContactModel();

                ret = true;
            } while (false);

            return(ret);
        }
Exemple #26
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");
            }
        }
Exemple #27
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);
        }
Exemple #28
0
 private void ExitApp(object sender, TappedRoutedEventArgs e)
 {
     AppDebug.Line("Exiting app!");
     Application.Current.Exit();
 }