示例#1
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);
            }
        }
示例#2
0
        private void AppExitHandler(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            AppDebug.Line("Exiting app!");
            deferral.Complete();
        }
示例#3
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);
        }
示例#4
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");
            }
        }
示例#5
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;
            }
        }
示例#6
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}");
         }
     }
 }
示例#7
0
        public void StopHeartRate()
        {
            try
            {
                AppDebug.Line("Finalizing HeartRate...");

                // Heart Rate
                _hearRateModel.Stop();
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "InitHeartRate");
            }
        }
示例#8
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");
            }
        }
示例#9
0
 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}]");
     }
 }
示例#10
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;
         }
     });
 }
示例#11
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());
                }
            }
        }
示例#12
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);
     }
 }
示例#13
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);
        }
示例#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");
                    }
                }
            }
        }
示例#15
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);
                    }
                }
            }
        }
示例#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");
            }
        }
示例#17
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);
            }
        }
示例#18
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);
        }
示例#19
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);
        }
示例#20
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);
        }
示例#21
0
 private void ExitApp(object sender, TappedRoutedEventArgs e)
 {
     AppDebug.Line("Exiting app!");
     Application.Current.Exit();
 }