private async void SubmitString(object sender, RoutedEventArgs e) { try { if (StrainChosen != null) { // Choose strain progressRing.IsActive = true; StrainList.IsEnabled = false; SubmitButton.IsEnabled = false; await SubmitStringTask(); StrainProperties.Text = UsageContext.ChosenStrain?.GetPropertiesString(); Title.Opacity = 1; Scroller.ChangeView(null, 0, null); //scroll to top Scroller.Visibility = Visibility.Visible; StrainProperties.Visibility = Visibility.Visible; } } catch (Exception ex) { AppDebug.Exception(ex, "SubmitString"); } StrainList.IsEnabled = true; SubmitButton.IsEnabled = true; progressRing.IsActive = false; }
private async void LoadStrainList(object sender, object e) { if (StrainsNamesList == null) { progressRing.IsActive = true; await Task.Run(async() => { AppDebug.Line("Loading strain list.."); try { // Get strain list from DB var res = await HttpManager.Manager.Get(Constants.MakeUrl("strains/all/")); if (res == null) { throw new Exception("Get operation failed, response is null"); } StrainsDict = HttpManager.ParseJson <Dictionary <string, string> >(res); // Parse JSON to dictionary StrainsNamesList = StrainsDict.Keys.ToList(); // Keys - strain names StrainsNamesList.Sort(); isStrainListFull = true; AppDebug.Line($"loaded {StrainsNamesList.Count} strains"); } catch (Exception exc) { AppDebug.Exception(exc, "LoadStrainList"); await new MessageDialog($"Strain list loading operation failed. Please try again or use suggested strain option.", "Error").ShowAsync(); } }); progressRing.IsActive = false; } }
public void OnPageLoaded(object sender, RoutedEventArgs e) // Import doctors list into objects { string[] data; AppDebug.Line("Loading doctors list.."); try { doctors = File.ReadAllLines("Assets/doctors.txt") // Read into dictionary, doctor name as key .Select(a => a.Split(' ')) .ToDictionary(x => x[0].Replace('-', ' ').Replace('_', ' '), x => x[1].Replace('-', ' ')); doctorNames = doctors.Keys.ToList(); foreach (string val in doctors.Values) { data = val.Split('_'); // Split into city and medical center if (!medicalCenters.Contains(data[0].Replace('-', ' '))) { medicalCenters.Add(data[0].Replace('-', ' ')); } if (!cities.Contains(data[1].Replace('-', ' '))) { cities.Add(data[1].Replace('-', ' ')); } } AppDebug.Line($"loaded {doctorNames.Count} doctors"); } catch (Exception exc) { AppDebug.Exception(exc, "LoadDoctorsList"); } }
private async void SearchStrain(object sender, RoutedEventArgs e) { // Get checked effects PagesUtilities.GetAllCheckBoxesTags(MedicalSearchGrid, out List <int> MedicalList); PagesUtilities.GetAllCheckBoxesTags(PositiveSearchGrid, out List <int> PositiveList); // Produce bitmap of effects int MedicalBitMap = StrainToInt.FromIntListToBitmap(MedicalList); int PositiveBitMap = StrainToInt.FromIntListToBitmap(PositiveList); var url = ""; if ((MedicalList.Count == 0) && (PositiveList.Count == 0) && ((StrainName.Text == "") || (StrainName.Text == "e.g. 'Alaska'"))) { // Nothing chosen Status.Text = "Invaild Search! Please enter search parameter"; } else { Status.Text = ""; if ((StrainName.Text != "") && (StrainName.Text != "e.g. 'Alaska'")) { // Search by strain name url = Constants.MakeUrl("strain/name/" + StrainName.Text); GlobalContext.searchType = 1; } else { // Search by effect url = Constants.MakeUrl($"strain/effects?medical={MedicalBitMap}&positive={PositiveBitMap}"); GlobalContext.searchType = 2; } try { // Build request for information var res = HttpManager.Manager.Get(url); if (res == null) { return; } var str = await res.Result.Content.ReadAsStringAsync(); AppDebug.Line(str); if (GlobalContext.searchType == 1) { Frame.Navigate(typeof(StrainSearchResults), str); // Search by name } else if (GlobalContext.searchType == 2) { // Search by effect GlobalContext.searchResult = str; Frame.Navigate(typeof(EffectsSearchResults)); } } catch (Exception ex) { AppDebug.Exception(ex, "SearchStrain"); await new MessageDialog("Failed get: \n" + url, "Exception in Search Strain").ShowAsync(); } } }
private void Timer_Tick(object sender, object e) { try { // Get time for usage TimeSpan timePassed = DateTime.Now.Subtract(UsageContext.Usage.StartTime); Duration.Text = $"Duration: {new DateTime(timePassed.Ticks).ToString("HH:mm:ss")}"; } catch (Exception x2) { AppDebug.Exception(x2, "Timer_Tick"); } }
private async void SubmitFeedback(object sender, TappedRoutedEventArgs e) // Send feedback to server { HttpResponseMessage res = null; UsageUpdateRequest req; double[] ranks = new double[4]; ranks = GetRanks(questionDictionary); try { // Build request for server progressRing.IsActive = true; GlobalContext.CurrentUser.UsageSessions.LastOrDefault().usageFeedback = questionDictionary; UsageData use = GlobalContext.CurrentUser.UsageSessions.LastOrDefault(); string userId = GlobalContext.CurrentUser.Data.UserID; req = new UsageUpdateRequest(use.UsageStrain.Name, use.UsageStrain.ID, userId, ((DateTimeOffset)use.StartTime).ToUnixTimeMilliseconds(), ((DateTimeOffset)use.EndTime).ToUnixTimeMilliseconds(), ranks[0], ranks[1], ranks[2], use.HeartRateMax, use.HeartRateMin, (int)use.HeartRateAverage, ranks[3], questionDictionary); res = await HttpManager.Manager.Post(Constants.MakeUrl("usage"), req); // Send request if (res != null) { // Request sent successfully if (res.IsSuccessStatusCode) { Status.Text = "Usage update Successful!"; var index = GlobalContext.CurrentUser.UsageSessions.Count - 1; GlobalContext.CurrentUser.UsageSessions[index].UsageId = res.GetContent()["body"]; PagesUtilities.SleepSeconds(0.5); Frame.Navigate(typeof(DashboardPage)); } else { Status.Text = "Usage update failed! Status = " + res.StatusCode; } } else { Status.Text = "Usage update failed!\nPost operation failed"; } Frame.Navigate(typeof(DashboardPage)); } catch (Exception x) { AppDebug.Exception(x, "UsageUpdate"); } }
public void OnPageLoaded(object sender, RoutedEventArgs e) { PagesUtilities.DontFocusOnAnythingOnLoaded(sender, e); try { EnumDescriptions positive = new EnumDescriptions("Would you use this strain again?", "Rate the quality of the treatment:"); PostQuestions.Items.Add(positive); questionDictionary[positive.q1] = "Don't know"; } catch (Exception x) { AppDebug.Exception(x, "PostTreatment2 => OnPageLoaded"); } }
private async void SendEmailAsync(object sender, RoutedEventArgs e) { HttpResponseMessage res = null; SendEmailRequest req; if (EmailAddressBox.Text.IsValidEmail()) // Check email validity { try { progressRing.IsActive = true; // Send email request req = new SendEmailRequest(EmailAddressBox.Text, FreeMessageBox.Text); // Export usages res = await HttpManager.Manager.Post(Constants.MakeUrl($"usage/export/{GlobalContext.CurrentUser.Data.UserID}"), req); progressRing.IsActive = false; if (res != null) { if (res.IsSuccessStatusCode) { // Email sent successfully await new MessageDialog($"An email was sent to {EmailAddressBox.Text} successfully", "Success").ShowAsync(); } else { await new MessageDialog($"There was an error while sending the mail (status: {res.StatusCode}, message: \"{res.GetContent()["message"]}\"", "Error").ShowAsync(); } } else { await new MessageDialog($"There was an error with the server, response is empty.", "Error").ShowAsync(); } PagesUtilities.SleepSeconds(1); Frame.Navigate(typeof(DashboardPage)); } catch (Exception x) { AppDebug.Exception(x, "UsageUpdate"); } } else { // Email address not valid await new MessageDialog("Invalid email address. Please try again").ShowAsync(); } }
private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e) { try { // Open right click menu ListView lst = sender as ListView; selectedUsage = ((FrameworkElement)e.OriginalSource).DataContext as UsageData; if (selectedUsage != null) { UsageMenu.ShowAt(lst, e.GetPosition(lst)); AppDebug.Line($"Right click usage on [{selectedUsage.StartTimeString}]"); } } catch (Exception x) { AppDebug.Exception(x, "ListView_RightTapped"); } }
private async Task SubmitStringTask() { await Task.Run(async() => { // Submit chosen strain AppDebug.Line("Submit string: " + StrainChosen); try { if (!StrainsDict.ContainsKey(StrainChosen)) { AppDebug.Line($"Strain '{StrainChosen}' not found in list"); } else { var strainId = StrainsDict[StrainChosen]; AppDebug.Line($"Strain: [{StrainChosen}], ID: {strainId}"); // Get strain properties var res = await HttpManager.Manager.Get(Constants.MakeUrl("/strain/id/" + strainId)); if (res == null) { return; } UsageContext.ChosenStrain = HttpManager.ParseJson <Strain>(res); // Parse Json to strain /* * UsageContext.ChosenStrain = new Strain(StrainChosen, int.Parse(strainId)) * { * BitmapMedicalNeeds = MedicalEnumMethods.BitmapFromStringList(values["medical"].ToList()), * BitmapPositivePreferences = PositivePreferencesEnumMethods.BitmapFromStringList(values["positive"].ToList()), * BitmapNegativePreferences = NegativePreferencesEnumMethods.BitmapFromStringList(values["negative"].ToList()) * };*/ AppDebug.Line("Finished submit"); } } catch (Exception exc) { AppDebug.Exception(exc, "SubmitString"); progressRing.IsActive = false; } }); }
public void OnPageLoaded(object sender, RoutedEventArgs e) { PagesUtilities.DontFocusOnAnythingOnLoaded(sender, e); try { // Load questions for user needs foreach (var medicalNeed in GlobalContext.CurrentUser.Data.MedicalNeeds) { var info = medicalNeed.GetAttribute <EnumDescriptions>(); PostQuestions.Items.Add(info); // Add to display questionDictionary[info.q1] = "Don't know"; } } catch (Exception x) { AppDebug.Exception(x, "PostTreatment => OnPageLoaded"); } }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var req = GlobalContext.CurrentUser.Data.NegativePreferences; if (req != null) { try { PagesUtilities.SetAllCheckBoxesTags(EditNegativeEffectsGrid, NegativePreferencesEnumMethods.FromEnumToIntList(req)); } catch (Exception exc) { AppDebug.Exception(exc, "EditPositiveEffectsPage.OnNavigatedTo"); } } }
private async void EditRegister(object sender, RoutedEventArgs e) { HttpResponseMessage res = null; var user_id = GlobalContext.CurrentUser.Data.UserID; try { progressRing.IsActive = true; PagesUtilities.GetAllCheckBoxesTags(EditNegativeEffectsGrid, out List <int> intList); GlobalContext.RegisterContext.IntNegativePreferences = intList; res = await HttpManager.Manager.Post(Constants.MakeUrl($"edit/{user_id}"), GlobalContext.RegisterContext); if (res != null) { if (res.IsSuccessStatusCode) { Status.Text = "Edit profile Successful!"; PagesUtilities.SleepSeconds(0.5); Frame.Navigate(typeof(DashboardPage), res); } else { Status.Text = "Register failed! Status = " + res.StatusCode; } } else { Status.Text = "Register failed!\nPost operation failed"; } } catch (Exception exc) { AppDebug.Exception(exc, "Register"); } finally { progressRing.IsActive = false; } }
private async void StartSession(object sender, RoutedEventArgs e) { StartAction(); bool useBand = UseBand.IsChecked.Value && isPaired && GlobalContext.Band.IsConnected(); // Enter usage details UsageContext.Usage = new UsageData(UsageContext.ChosenStrain, DateTime.Now, useBand); if (!useBand) { Frame.Navigate(typeof(ActiveSession)); } else // Use band, start acquiring heart rate { Acquiring.Visibility = Visibility.Visible; bool res = false; try { // Get heart rate res = await Task.Run(() => GlobalContext.Band.StartHeartRate(UsageContext.Usage.HeartRateChangedAsync)); } catch (Exception x) { AppDebug.Exception(x, "StartSession => StartHeartRate"); } Acquiring.Visibility = Visibility.Collapsed; EndAction(); if (res) { // Continue to active session with correct parameters ContinueButton.Content = "Success!"; PagesUtilities.SleepSeconds(1); Frame.Navigate(typeof(ActiveSession)); } else { await new MessageDialog("Try reconnecting the band, re-pairing and wear the band", "Failed!").ShowAsync(); return; } } }
private async void EndSessionAsync(object sender, RoutedEventArgs e) { try { var yesCommand = new UICommand("End Session", cmd => { AppDebug.Line("ending session..."); progressRing.IsActive = true; try { if (UsageContext.Usage.UseBandData) { // Stop band usage GlobalContext.Band.StopHeartRate(); PagesUtilities.SleepSeconds(0.5); } UsageContext.Usage.EndUsage(); } catch (Exception x) { AppDebug.Exception(x, "EndSession"); } progressRing.IsActive = false; Frame.Navigate(typeof(PostTreatment)); }); var noCommand = new UICommand("Continue Session", cmd => { AppDebug.Line("Cancel end session"); }); var dialog = new MessageDialog("Are you sure you want to end the session", "End Session") { Options = MessageDialogOptions.None }; dialog.Commands.Add(yesCommand); dialog.Commands.Add(noCommand); await dialog.ShowAsync(); } catch (Exception x) { AppDebug.Exception(x, "Remove_Click"); } }
private async void Remove_Click(object sender, RoutedEventArgs e) { // Remove usage from history AppDebug.Line($"Remove usage on [{selectedUsage.StartTimeString}]"); try { var yesCommand = new UICommand("Remove", async cmd => { AppDebug.Line("removing..."); var b = await GlobalContext.CurrentUser.RemoveUsage(selectedUsage); if (!b) { await new MessageDialog("There was an error while deleting the usage from the server.", "Error").ShowAsync(); } else { await new MessageDialog("Usage removed successfuly.", "Success").ShowAsync(); } Frame.Navigate(typeof(UsageHistory)); }); var noCommand = new UICommand("Cancel", cmd => { AppDebug.Line("Cancel remove"); }); var dialog = new MessageDialog("Are you sure you want to remove the usage from the history?", "Remove Usage") { Options = MessageDialogOptions.None }; dialog.Commands.Add(yesCommand); dialog.Commands.Add(noCommand); await dialog.ShowAsync(); } catch (Exception x) { AppDebug.Exception(x, "Remove_Click"); } }
private async void OnPageLoaded(object sender, RoutedEventArgs e) { progressRing.IsActive = true; UsageContext.ChosenStrain = null; if (GlobalContext.CurrentUser != null) { // Get recommended strains for user from server Message.Text = "Searching for matching strains based on your profile..."; var user_id = GlobalContext.CurrentUser.Data.UserID; var url = Constants.MakeUrl($"strains/recommended/{user_id}/"); // Build url for user try { // Send request to server var res = await HttpManager.Manager.Get(url); if (res == null) { progressRing.IsActive = false; return; } // Successful request PagesUtilities.SleepSeconds(0.2); // Recommended strain list strains = await Task.Run(() => HttpManager.ParseJson <SuggestedStrains>(res)); // Parsing JSON if (strains.SuggestedStrainList.Count == 0) { ErrorNoStrainFound.Visibility = Visibility.Visible; } else { switch (strains.Status) { // Status for match type case 0: // Full match Message.Text = $"Showing {strains.SuggestedStrainList.Count} exactly matched strains:"; break; case 1: // Partial match - medical match but positive dont Message.Text = $"No exact matches found!\nTry updating your positive preferences.\nShowing {strains.SuggestedStrainList.Count} partially matching strains:"; break; case 2: // Partial match - medical and positive don't match Message.Text = $"No exact matches found!\nTry updating your positive and medical preferences.\nShowing {strains.SuggestedStrainList.Count} partially matching strains:"; break; } Scroller.Height = Stack.ActualHeight - Message.ActualHeight - 20; Random rnd = new Random(); foreach (var strain in strains.SuggestedStrainList) { // **Random numbers** strain.Rank = rnd.Next(1, 100); strain.NumberOfUsages = rnd.Next(0, 1000); } if (strains.Status != 0) { // Calculate partal match rate foreach (var strain in strains.SuggestedStrainList) { strain.MatchingPercent = strain / GlobalContext.CurrentUser; } strains.SuggestedStrainList.Sort(Strain.MatchComparison); matchSortedStrains = new SuggestedStrains(strains.Status, new List <Strain>(strains.SuggestedStrainList));; } var names = $"[{string.Join(", ", from u in strains.SuggestedStrainList select $"{u.Name}")}]"; AppDebug.Line($"Status={strains.Status} Got {strains.SuggestedStrainList.Count} strains: {names}"); FillStrainList(strains); foreach (var child in ButtonsGrid.Children) { // Display buttons to choose strains if (child.GetType() == typeof(Viewbox)) { var b = (child as Viewbox).Child as RadioButton; if (!((string)b.Tag == "match" && strains.Status == 0)) { b.IsEnabled = true; } } } ButtonsGrid.Opacity = 1; //StrainList.Height = Scroller.ActualHeight; } } catch (Exception x) { AppDebug.Exception(x, "OnPageLoaded"); await new MessageDialog("Error while getting suggestions from the server", "Error").ShowAsync(); } progressRing.IsActive = false; } }