Xamarin Forms not Debugging and ZXing freezing all the application - debugging

I made an application to read some QR Codes using Zxing on Xamarin. Days before yesterday, it was working good, but since yesterday I have this problem:
I put a breakpoint in OnAppearing() method, but it's ignored, Ok... When I click in the Zxing button, to open the scanner, the application stops, but don't show nothing, only freeze, no errors, no messages, no debug, nothing. My code is the same as when it was working, nothing changed. If anybody could help me, I'll be grateful.
public MainPage()
{
InitializeComponent();
this.InitializeComponent();
this.BindingContext = this;
this.IsBusy = false;
}
protected override async void OnAppearing()
{
base.OnAppearing();
var dados = new AcessoDB();
if (dados.GetAlunos().Count() > 0)
{
var infopage = new Wallet();
Navigation.InsertPageBefore(infopage, Navigation.NavigationStack[0]);
await Navigation.PopToRootAsync();
codeqr.IsEnabled = false;
}
}
private async void Scan_Clicked(object sender, EventArgs e)
{
semaphoreSlim.Release();
string img;
this.IsBusy = true;
if (CrossConnectivity.Current.IsConnected)
{
var scan = new ZXingScannerPage();
await Navigation.PushAsync(scan);
scan.OnScanResult += async (result) =>
{
bool liberado = await semaphoreSlim.WaitAsync(-1);
if (!liberado)
{
return;
}
scan.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
if (CrossConnectivity.Current.IsConnected)
{
var parseResult = ResultParser.parseResult(result);
if (parseResult != null)
{
var hash = sha256_hash(result.ToString());
Aluno items = new Aluno();
try
{
scan.IsAnalyzing = false;
scan.IsScanning = false;
items = JsonConvert.DeserializeObject<Aluno>(result.ToString());
img = GetImage(items.Foto);
}
catch (Exception)
{
scan.IsScanning = false;
scan.IsAnalyzing = false;
await Navigation.PopAsync();
await DisplayAlert("Ops...", "Ocorreu algum erro com a leitura do seu código, tente de novo.", "Ok!");
return;
}
var info = new Aluno
{
Matricula = items.Matricula,
Nome = items.Nome,
RG = items.RG,
Nascimento = items.Nascimento,
Curso = items.Curso,
Campus = items.Campus,
Periodos = items.Periodos,
Modalidade = items.Modalidade,
Validade = items.Validade,
Hash = hash,
Foto = img
};
var infopage = new Wallet();
var dados = new AcessoDB();
if (!await dados.InserirAlunoAsync(info))
{
scan.IsAnalyzing = false;
scan.IsScanning = false;
await Navigation.PopAsync();
await DisplayAlert("Ops...", "Esse código não consta no nosso banco de dados, tem certeza que estuda no UGB?", "Repetir");
return;
}
try
{
scan.IsScanning = false;
scan.IsAnalyzing = false;
infopage.BindingContext = info;
Navigation.InsertPageBefore(infopage, Navigation.NavigationStack[0]);
await Navigation.PopToRootAsync();
}
catch (Exception)
{
scan.IsScanning = false;
scan.IsAnalyzing = false;
await DisplayAlert("Erro", "Não foi possível carregar a sua carteirinha.", "Ok...");
}
}
}
});
};
}
else
{
await DisplayAlert("Ops...", "Você não está conectado à internet.", "Ok!");
}
this.IsBusy = false;
}
public string GetImage(string foto)
{
if (String.IsNullOrEmpty(foto))
{
return "";
}
using (var WebClient = new WebClient())
{
var imageBytes = WebClient.DownloadData("http://portal.ugb.edu.br/upload/ImagemAluno/" + foto);
var sxtyfr = Convert.ToBase64String(imageBytes);
//var img = "data:image/jpg;base64," + sxtyfr;
return sxtyfr;
}
}
public static string sha256_hash(string value)
{
StringBuilder Sb = new StringBuilder(); using (SHA256 hash = SHA256Managed.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value)); foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
}
}

I solve my problem... I just clean, build and rebuild the solution, then magic happens. Thank you all to help me.

Related

Cant find the source to a specific image in an app using xamarin.Forms

I have tried for the last 4 days to find an illusive image in that app, I am new to xamarin forms and a client asked me to replace an image which I did, but I have left with another image that I should implement and I can't find its source, the XML code for the specific section looks like this.
<ScrollView Grid.Row="2"
HeightRequest="50"
HorizontalOptions="CenterAndExpand"
Orientation="Horizontal"
IsVisible="{Binding PhotosVisible.Value}"
x:Name="ScrollPhotos">
<StackLayout Orientation="Horizontal"
Spacing="0"
VerticalOptions="Center"
Padding="5,0"
x:Name="StackPhotos">
</StackLayout>
</ScrollView>
and the place I'm trying to implement the photo in is:
should be an image instead of the blank grey rectengle
(should be an image instead of the blank grey rectangle)
I cant find the source to the other image, and I even deleted something that was pretty similar in the drawAble folder but it changed nothing.
any help or suggestion will be helpful, Thanks. :)
edit:
The xml.cs source code:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DashboardPage : ExtPage
{
public DashboardPage()
{
InitializeComponent();
Padding = new Thickness(0, 0, 0, MashamAppForms.Helpers.Settings.NativeSetting.BottonPadding);
NavigationPage.SetHasBackButton(this, false);
}
protected override void OnAppearing() {
MessagingCenter.Subscribe<Application>(App.Current, "DashboardFillDates", FillDates);
MessagingCenter.Subscribe<Application, CPhoto[]>(App.Current, "DashboardFillPhotos", FillPhotos);
base.OnAppearing();
}
protected override void OnDisappearing() {
MessagingCenter.Unsubscribe<Application>(App.Current, "DashboardFillDates");
base.OnDisappearing();
}
void FillPhotos(Application arg1, CPhoto[] arg2) {
var bc = (DashboardViewModel)BindingContext;
StackPhotos.Children.Clear();
if (arg2 == null)
return;
foreach (var photo in arg2) {
var image = new CachedImage {
Aspect = Aspect.AspectFill,
Source = photo.Path,
BackgroundColor = Color.FromHex("#504F77AB"),
DownsampleHeight = 100,
HeightRequest = 40,
WidthRequest = 60,
Margin = new Thickness(5, 0)
};
Commands.SetTap(image, bc.ViewImageCommand);
Commands.SetTapParameter(image, photo);
StackPhotos.Children.Add(image);
}
Device.BeginInvokeOnMainThread(() => {
try {
ScrollPhotos.ScrollToAsync(StackPhotos.Children.LastOrDefault(), ScrollToPosition.End, false);
}
catch {
}
});
}
void FillDates(Application application) {
var bc = (DashboardViewModel)BindingContext;
var dates = bc.Dates;
StackDates.Children.Clear();
if (dates == null)
return;
for (var i = 0; i < dates.Length; i++) {
var t = dates[i];
var grid = new Grid {
RowDefinitions =
{
new RowDefinition {Height = GridLength.Star},
new RowDefinition {Height = GridLength.Star},
new RowDefinition {Height = GridLength.Star}
},
Padding = new Thickness(5, 0),
RowSpacing = 0,
BindingContext = t
};
grid.SetBinding(Grid.BackgroundColorProperty, "BackgroundColor.Value");
var l1 = new Label {
Text = t.HebrewDay,
TextColor = t.TextColor,
HorizontalOptions = LayoutOptions.Center,
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
l1.SetBinding(Label.TextColorProperty, "TextColor.Value");
grid.Children.Add(l1, 0, 0);
var l2 = new Label {
Text = t.HebrewDate,
TextColor = t.TextColor,
HorizontalOptions = LayoutOptions.Center,
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
l2.SetBinding(Label.TextColorProperty, "TextColor.Value");
grid.Children.Add(l2, 0, 1);
var l3 = new Label {
Text = t.Date.ToString("dd/MM/yyyy"),
TextColor = t.TextColor,
HorizontalOptions = LayoutOptions.Center,
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
l3.SetBinding(Label.TextColorProperty, "TextColor.Value");
grid.Children.Add(l3, 0, 2);
var gest = new TapGestureRecognizer {
Command = bc.ChangeDateCommand,
CommandParameter = t
};
grid.GestureRecognizers.Add(gest);
StackDates.Children.Add(grid);
if (i != dates.Length - 1)
StackDates.Children.Add(new BoxView {
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Fill,
WidthRequest = 1,
Color = (Color)Application.Current.Resources["SelectionColor"]
});
}
Device.BeginInvokeOnMainThread(() =>
{
try {
ScrollDates.ScrollToAsync(StackDates.Children.LastOrDefault(), ScrollToPosition.End, false);
}
catch {
}
});
}
}
and the viewModel.cs is:
public class DashboardViewModel : FormsBaseViewModel
{
static bool _nowAsking;
static bool _scanning;
public ICommand ChangeDateCommand { get; }
public ICommand LogoutCommand { get; }
public ICommand ListHeaderCommand { get; }
public ICommand EventCommand { get; }
public ICommand QrCommand { get; }
public ICommand ViewImageCommand { get; }
public ICommand PhotoCommand { get; }
public ICommand FeedbackCommand { get; }
public ICommand LocationCommand { get; }
public ICommand ContactsCommand { get; }
public ICommand MessagesCommand { get; }
public ICommand FileCommand { get; }
public ObservableProperty<int> CarouselPosition { get; }
public ObservableProperty<BasePageState> EventsState { get; } = new ObservableProperty<BasePageState>();
public ObservableProperty<bool> IsBusy { get; } = new ObservableProperty<bool>();
public ObservableProperty<bool> PhotosVisible { get; } = new ObservableProperty<bool>();
public SmartCollection<EventDetails> EventList { get; set; }
public Conferance Conferance { get; set; }
public bool SubtitleVisible => !string.IsNullOrEmpty(Conferance?.SubTitle);
public string Phone { get; set; }
public string Name { get; set; }
public string RealId { get; set; }
public EventDetails[] Events { get; set; }
public QrDetails[] QrDetails { get; set; }
public CPhoto[] CPhotos { get; set; }
public string FileLink { get; set; }
public string Greeting { get; set; }
public string ApiKey { get; set; }
public CParticipant[] Participants { get; set; }
public ThreeDatesItem[] Dates { get; set; }
private ThreeDatesItem _selected;
public ThreeDatesItem SelectedDate
{
get => _selected;
set
{
_selected = value;
EventList.Clear();
Task.Run(async () =>
{
await Task.Delay(100);
EventList.AddRange(GetEvents(value.Date));
});
}
}
public DashboardViewModel()
{
CarouselPosition = new ObservableProperty<int>();
EventList = new SmartCollection<EventDetails>();
ChangeDateCommand = new Command<ThreeDatesItem>(item =>
{
foreach (var tdi in Dates)
{
tdi.IsSelected = false;
}
item.IsSelected = true;
SelectedDate = item;
});
LogoutCommand = new Command(async () =>
{
Settings.Authed = false;
Settings.SavedPhone = "";
Settings.SavedId = "";
OneSignal.Current.DeleteTag("confId");
await NavigationService.Navigate<LoginViewModel>();
NavigationService.ClearNavigationStack();
});
ListHeaderCommand = new Command<EventDetails>(details =>
{
var mainColor = (Color)Application.Current.Resources["SelectionColor"];
if (details.IsOpened)
{
var del = EventList.Where(e => e.WhatMashov == details.IsMashov).ToArray();
for (var i = 0; i < del.Length; i++)
{
EventList.Remove(del[i]);
}
details.SeparatorColor.Value = mainColor;
}
else
{
var add = Events?.Where(e => e.Day == details.Day && e.WhatMashov == details.IsMashov).ToArray();
details.SeparatorColor.Value = add.Length == 0? mainColor : Color.LightGray;
var after = details;
for (var i = 0; i < add.Length; i++)
{
add[i].SeparatorColor.Value = i == add.Length - 1 ? mainColor : Color.LightGray;
add[i].GridPadding = new Thickness(10, 10, 20, 10);
EventList.Insert(EventList.IndexOf(after) + 1, add[i]);
after = add[i];
}
}
EventList.Last().SeparatorColor.Value = Color.Transparent;
details.IsOpened = !details.IsOpened;
});
EventCommand = new Command<EventDetails>(async details =>
{
await NavigationService.Navigate<EventInfoViewModel>(model =>
{
model.Participants.AddRange(Participants?.Where(e => e.EventId == details.EventId));
model.Date.Value = SelectedDate;
model.EventDetails.Value = details;
model.Phone = Phone;
model.IsVisibleDescription.Value = !string.IsNullOrEmpty(details.Description);
model.IsVisibleLecturers.Value = model.Participants.Count > 0;
model.Conferance = Conferance;
model.AllEvents = Events;
model.Name = Name;
model.SelectedEventDetails = details;
model.QrDetails = QrDetails;
});
});
QrCommand = new Command<EventDetails>(details =>
{
if (details.QrState == QrState.Normal)
NavigationService.Navigate<QrPickerViewModel>(NavigationType.Popup, m => {
m.EventDetails = Events;
m.EventId = details.EventId;
m.QrDetails = QrDetails;
m.Phone = Phone;
m.Name = Name;
m.ConfId = Conferance.Id;
});
});
ViewImageCommand = new Command<CPhoto>(p =>
{
var s = p?.Path?.Trim();
var photos = CPhotos.Select(e => new MyPhoto {
URL = e?.Path?.Trim(),
Title = string.Empty,
Link = e?.SponsorLink?.Trim()
}).ToList();
if (Device.RuntimePlatform == Device.iOS)
photos.Reverse();
var pos = photos?.FindIndex(e => e.URL == s) ?? 0;
var config = new PhotoConfig {
Photos = photos,
StartIndex = pos,
ActionButtonPressed = async (index) => {
var action = await AlertCenter.ActionSheet(Device.RuntimePlatform == Device.Android ? Localization.SelectAction : null, Localization.Cancel, null, Localization.SponsorLink);
if (action == Localization.SponsorLink) {
if (string.IsNullOrEmpty(photos[index]?.Link)) {
AlertCenter.Error(Localization.NoLink);
}
else {
Device.OpenUri(new Uri(photos[index].Link, UriKind.Absolute));
}
}
}
};
config.Show();
});
PhotoCommand = new Command(async () =>
{
await LoadingPopupService.Show();
var photos = await SimpleServerRequest.Request<CPhoto[]>(new Uri("http://app.masham.org.il/insertToConfearnce2.php?Action=getAllEvents&TableName=I_" + Conferance.Id));
await LoadingPopupService.Close();
if (photos.Item1)
await NavigationService.Navigate<PhotoGalleryViewModel>(m =>
{
m.Photos.Value = photos.Item2.Where(e => e.Type == "גלריה").ToArray();
m.ConfId = Conferance.Id;
m.ApiKey = ApiKey;
});
else
AlertCenter.Error(Localization.ErrorLoading);
});
FeedbackCommand = new Command(async () =>
{
if (string.IsNullOrEmpty(Conferance?.SurvayLink))
{
AlertCenter.Error(Localization.NoLink);
return;
}
await LoadingPopupService.Show();
var res = await SimpleServerRequest.Request(new Uri($#"http://app.masham.org.il/insertToConfearnce2.php?Action=getServerDateAndtime&CID={Conferance.Id}"));
await LoadingPopupService.Close();
try
{
if (res.Success)
{
if (res.Result.ToLower() == "true")
Device.OpenUri(new Uri(Conferance?.SurvayLink, UriKind.Absolute));
else
AlertCenter.Error(Localization.NoMashovTime);
}
else
AlertCenter.Error(Localization.ErrorLoading);
}
catch
{
AlertCenter.Error(Localization.IncorrectLink);
}
});
LocationCommand = new Command(() =>
{
Device.OpenUri(new Uri("https://waze.com/ul?q=" + Conferance?.NameOfLocation));
});
ContactsCommand = new Command(async () =>
{
await NavigationService.Navigate<ContactsViewModel>(m =>
{
m.Phone.Value = Conferance?.Phone;
m.Location.Value = Conferance?.NameOfLocation;
m.Email.Value = Conferance?.Email;
});
});
MessagesCommand = new Command(async () =>
{
await LoadingPopupService.Show();
var messages = await SimpleServerRequest.Request<CMessage[]>(new Uri(
"http://app.masham.org.il/insertToConfearnce2.php?Action=getAllEvents&TableName=" +
"Messages_" + Conferance.Id));
await LoadingPopupService.Close();
if (messages.Item1)
{
DependencyService.Get<ILocalSettings>().PushCounter = 0;
await NavigationService.Navigate<MessagesViewModel>(m =>
{
m.Messages.AddRange(messages.Item2 ?? new CMessage[0]);
m.ConfId = Conferance.Id.ToString();
});
}
else
AlertCenter.Error(Localization.ErrorLoading);
});
FileCommand = new Command(() => {
if (string.IsNullOrEmpty(FileLink)) {
AlertCenter.Error(Localization.NoLink);
return;
}
Device.OpenUri(new Uri(FileLink, UriKind.Absolute));
});
}
public async void Resumed() {
{
if (_nowAsking)
return;
_nowAsking = true;
if (NavigationService.CurrentModalPage == null && NavigationService.CurrentPage.GetType() == typeof(DashboardPage) && !LoadingPopupService.IsLoading) {
IsBusy.Value = true;
await LoadingPopupService.Show();
var users = await SimpleServerRequest.Request<UserAndConferance[]>(new Uri($"http://app.masham.org.il/apimasham.php?Action=getUser&idUsername={Phone}&realId={RealId}"));
if (users.Item1) {
var user = users.Item2.FirstOrDefault();
ApiKey = user?.ApiKey;
var conf = users.Item2.Select(e => e.Conferance).FirstOrDefault(e => e != null && e.Id == Conferance.Id);
if (conf == null) {
_nowAsking = false;
IsBusy.Value = false;
Settings.Authed = false;
Settings.SavedPhone = "";
Settings.SavedId = "";
await LoadingPopupService.Close();
await AlertCenter.ErrorAsync(Localization.ConfNotFound);
await NavigationService.Navigate<LoginViewModel>();
NavigationService.ClearNavigationStack();
return;
}
var eventContainer = await SimpleServerRequest.Request<EventContainer>(new Uri($"http://app.masham.org.il/apimasham.php?Action=getEvents&confId={Conferance.Id}&phone={Phone}"));
if (eventContainer.Item1 && eventContainer.Item2 != null) {
var dates = eventContainer.Item2.EventDetails
?.Select(e => new {
e.Day,
e.HebrewDay
})
.Distinct()
.Select(e => new ThreeDatesItem {
Date = e.Day,
HebrewDate = e.HebrewDay
})
.OrderByDescending(e => e.Date)
.ToArray();
Events = eventContainer.Item2.EventDetails ?? new EventDetails[0];
QrDetails = eventContainer.Item2.QrDetails ?? new QrDetails[0];
QrStateHelper.SetQrStatesForAll(Events, QrDetails, eventContainer.Item2.QrAnswers);
if (conf.Type == "קורס" && dates != null) {
var p = 1;
for (var i = dates.Length - 1; i >= 0; i--) {
dates[i].HebrewDate = "מפגש " + p++;
}
}
var isEqualDates = Dates != null && Dates.Length == dates?.Length && conf.Type == Conferance.Type;
if (isEqualDates)
for (var i = 0; i < dates.Length; i++) {
isEqualDates = dates[i].Date == Dates[i].Date;
if (!isEqualDates)
break;
}
if (!isEqualDates)
Dates = dates;
var photos = eventContainer.Item2.Photos?.Where(e => e.Type == "קרוסלה").ToArray();
var isEqualPhotos = CPhotos != null && CPhotos.Length == photos?.Length;
if (isEqualPhotos)
for (var i = 0; i < photos.Length; i++) {
isEqualPhotos = photos[i].Path == CPhotos[i].Path;
if (!isEqualPhotos)
break;
}
else
CPhotos = photos;
Conferance = conf;
FileLink = eventContainer.Item2.Photos?.FirstOrDefault(e => e.Type == "קובץ")?.Path;
OnPropertyChanged(nameof(Conferance));
PrepareDatesAndPhotos(!isEqualDates, !isEqualPhotos);
if (Events.Length > 0) {
EventsState.Value = BasePageState.Normal;
}
else {
EventList.Clear();
EventsState.Value = BasePageState.NoData;
}
_nowAsking = false;
IsBusy.Value = false;
await LoadingPopupService.Close();
return;
}
}
IsBusy.Value = false;
await LoadingPopupService.Close();
await AlertCenter.ErrorAsync(Localization.ErrorLoading);
}
_nowAsking = false;
}
}
public override async void FirstAppearing()
{
base.FirstAppearing();
NavigationService.ClearNavigationStack();
await Task.Delay(300);
Device.BeginInvokeOnMainThread(() => {
PrepareDatesAndPhotos();
});
}
void PrepareDatesAndPhotos(bool updDates = true, bool updPhotos = true) {
if (updPhotos)
MessagingCenter.Send(App.Current, "DashboardFillPhotos", CPhotos);
PhotosVisible.Value = CPhotos?.Any() ?? false;
if (Dates?.Any() ?? false) {
if (updDates) {
var today = Dates.FirstOrDefault(e => e.Date == DateTime.Today);
if (today != null) {
today.IsSelected = true;
SelectedDate = today;
}
else {
var date = Dates[Dates.Length - 1];
date.IsSelected = true;
SelectedDate = date;
}
MessagingCenter.Send(App.Current, "DashboardFillDates");
}
else {
SelectedDate = SelectedDate;
}
}
}
private EventDetails[] GetEvents(DateTime date)
{
var items = Events?.Where(e => e.Day == date && e.WhatMashov == "").OrderBy(e => e.StartTime).ToArray();
var mainColor = (Color)Application.Current.Resources["SelectionColor"];
if (items?.Length > 0)
{
for (var i = 0; i < items.Length; i++)
{
items[i].IsOpened = false;
if (string.IsNullOrEmpty(items[i].IsMashov) && string.IsNullOrEmpty(items[i].WhatMashov))
{
items[i].SeparatorColor.Value = mainColor;
items[i].GridPadding = new Thickness(10, 10, 10, 10);
}
else
{
items[i].GridPadding = new Thickness(10, 10, 20, 10);
if (i != items.Length - 1)
{
if (!string.IsNullOrEmpty(items[i + 1].IsMashov) ||
!string.IsNullOrEmpty(items[i + 1].WhatMashov))
{
items[i].SeparatorColor.Value = Color.LightGray;
}
else
{
items[i].SeparatorColor.Value = mainColor;
}
}
}
}
items.Last().SeparatorColor.Value = Color.Transparent;
}
return items;
}
}

When image is captured using CapturePhotoAsync() OnAppearing get called on returning to the page Xamarin Forms

I want to refresh my data whenever the app is resumed from the background. Actually, I want this functionality on only one page, not the whole app. I am using the Prism OnAppearning method in my model view. After capturing a photo with the camera when the control moves back to the app and OnApearning method is called again. How to avoid this situation? I tried OnSleep and OnResume in model view but these also have the same behavior.
I have attached my view model code below. ClockInTriggered
called when user wants to mark attendance with the face. RecognizeUser method get call for taking a picture from Camera. After taking picture method OnAppearning gets a call which is annoying.
private async void ClockInTriggered()
{
string action = await App.Current.MainPage.DisplayActionSheet(AppResources.Select_Activity, AppResources.Cancel, null, Activities.Select(x => x.Name).ToArray());
if (action == AppResources.Cancel || action == null)
return;
Activity SelectedRole = Activities.SingleOrDefault(x => x.Name == action);
ClockInVisibility = false;
LoadingIndicator = true;
LoadingText = "";
var recResult = await RecognizeUser();
if (recResult == false)
{
ClockInVisibility = true;
LoadingIndicator = false;
return;
}
var locResult = await GetCurrentLocation();
var revGeoResult = await GetReverseGeoLocation();
LoadingText = AppResources.Done_;
await Task.Delay(1000);
if (recResult && locResult && revGeoResult)
{
Attendance attendance = new Attendance()
{
DateNTime = DateTime.Now,
CheckType = "CheckIn",
ActivityId = SelectedRole.Id,
LocationInfo = ReverseGeoCoding,
Lati = Lati,
Longi = Longi
};
var result = await AddAttendanceEntry(attendance, "CheckIn");
switch (result)
{
case "true":
List<Attendance> unsortedAttendance = await GetEmployeeStoredAttendance();
Attendance = unsortedAttendance.OrderByDescending(x => x.DateNTime).ToObservableCollection();
break;
case "false":
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.We_could_not_clock_you_in__Please_try_again_,
AppResources.OK);
ClockInVisibility = true;
LoadingIndicator = false;
return;
default:
await App.Current.MainPage.DisplayAlert(AppResources.Error, result,
AppResources.OK);
await navigationService.NavigateAsync("/MasterLayout/NavigationPage/MainPage/TimeAttendance");
break;
}
}
else
{
ClockInVisibility = true;
LoadingIndicator = false;
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.We_could_not_clock_you_in__It_can_be_due_to_location_or_face_detection_problem__Please_try_again_,
AppResources.OK);
return;
}
LoadingIndicator = false;
TimeGradient1 = "#FFB75E";
TimeGradient2 = "#DA2020";
ClockOutVisibility = true;
}
private async Task<bool> RecognizeUser()
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await App.Current.MainPage.DisplayAlert(AppResources.No_Camera, AppResources.No_camera_is_available_, AppResources.OK);
return false;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Small,
CompressionQuality = 60,
Directory = "Recognition",
Name = DateTime.Now + "-Identify.jpg"
});
if (file == null)
{
return false;
}
RecognitionResult = await Identify(file.GetStream());
if (RecognitionResult.ReturnType == null)
{
await App.Current.MainPage.DisplayAlert(AppResources.Alert, RecognitionResult.Status, AppResources.OK);
return false;
}
bool result = await GetCurrentLocation();
return true;
}
private async void RefreshLogAndButtons()
{
LoadingIndicator = true;
LoadingText = AppResources.Loading___Please_Wait_;
ClockInVisibility = false;
ClockOutVisibility = false;
await Task.Delay(2000);
await GetCurrentLocation();
await GetReverseGeoLocation();
List<Attendance> unsortedAttendance = await GetEmployeeStoredAttendance();
Attendance = unsortedAttendance.OrderByDescending(x => x.DateNTime).ToObservableCollection();
if (Attendance.Count != 0 && Attendance != null)
{
ActivateButton();
try
{
TotalTime = await TimeDifferenceCalculator(Attendance);
}
catch (Exception e)
{
}
}
else
{
ClockInVisibility = true;
LoadingIndicator = false;
}
}
public void OnAppearing()
{
RefreshLogAndButtons();
}
public void OnDisappearing()
{
}

Xamarin forms monkey chat

I am using monkey chat in my mobile application(Xamrin forms based). While sending a message on IOS, on a real device, I have to click the send button 2 times. First time when I click, it minimizes the keyboard and 2nd time, it sends the message. Please suggest.
How do I send a message on one click?
Here is my send message function
namespace Budocode.ViewModels
{
public class MainChatViewModel : BaseViewModel
{
public ObservableRangeCollection Messages { get; }
ITwilioMessenger twilioMessenger;
string outgoingText = string.Empty;
public string OutGoingText
{
get { return outgoingText; }
set { SetProperty(ref outgoingText, value); }
}
public ICommand SendCommand { get; set; }
public ICommand LocationCommand { get; set; }
public MainChatViewModel()
{
// Initialize with default values
twilioMessenger = DependencyService.Get<ITwilioMessenger>();
Messages = new ObservableRangeCollection<ChatMessage>();
SendCommand = new Command(() =>
{
var message = new ChatMessage
{
Text = OutGoingText,
IsIncoming = false,
ProfileId = "profile" + GlobalSettingsDataSource.Current.SelectedProfileImageId + ".png",
MessageDateTime = DateTime.Now,
FromUser = GlobalSettingsDataSource.Current.SelectedProfile
};
if (string.IsNullOrWhiteSpace(OutGoingText))
return;
Messages.Add(message);
twilioMessenger?.SendMessage(message.Text, message.ProfileId, GlobalSettingsDataSource.Current.SelectedProfile);
OutGoingText = string.Empty;
});
LocationCommand = new Command(async () =>
{
try
{
var local = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(15));
var map = $"https://maps.googleapis.com/maps/api/staticmap?center={local.Latitude.ToString(CultureInfo.InvariantCulture)},{local.Longitude.ToString(CultureInfo.InvariantCulture)}&zoom=17&size=400x400&maptype=street&markers=color:red%7Clabel:%7C{local.Latitude.ToString(CultureInfo.InvariantCulture)},{local.Longitude.ToString(CultureInfo.InvariantCulture)}&key=";
var message = new ChatMessage
{
Text = "I am here",
AttachementUrl = map,
ProfileId = "profile" + GlobalSettingsDataSource.Current.SelectedProfileImageId + ".png",
IsIncoming = false,
MessageDateTime = DateTime.Now
};
Messages.Add(message);
twilioMessenger?.SendMessage("attach:" + message.AttachementUrl, message.ProfileId, GlobalSettingsDataSource.Current.SelectedProfile);
}
catch (Exception ex)
{
}
});
if (twilioMessenger == null)
return;
twilioMessenger.MessageAdded = (message) =>
{
//if (message.ProfileId == "Icon.png")
Device.BeginInvokeOnMainThread(() =>
{
if (message.FromUser != GlobalSettingsDataSource.Current.SelectedProfile)
{
message.IsIncoming = true;
}
else
{
message.IsIncoming = false;
}
Messages.Add(message);
});
};
}
public async void InitializeMock(string channelName)
{
try
{
var id = CrossDeviceInfo.Current.Id;
var userId = PersistantData.Current.UserAccount.Properties["user_id"];
HttpResponseMessage appResponse = CommonUtility.GetApiContent(
String.Format(ClientConfiguration.TwilioServiceChatHistory, id, GlobalSettingsDataSource.Current.SelectedProfile, channelName));
if (appResponse.IsSuccessStatusCode)
{
var chatContent = await appResponse.Content.ReadAsStringAsync();
List<ChatMessage> chatMsgs = JsonConvert.DeserializeObject<List<ChatMessage>>(chatContent);
Messages.ReplaceRange(chatMsgs);
}
}
catch
{
// ignore if there are any issues with twilio
}
}
}
}

How to i add a loop to stop multiple database entries?

When i hit my submit button it sends multiple entries to the database how can i set a loop here to stop this. I tried setting the datetime to only allow one entry at that time but the entries go in a second or two apart so that doesnt work.
I have updated this question with majority of code, i am unsure where abouts this error is coming from so any help would be appreciated.
public AddSymptom()
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
symmanager = SymptomManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
symptomfeedbackmanager = SymptomFeedbackManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
//Set Label Titles
lblTitle.Text = "Add Symptom";
lblSubtutle.Text = "What symptom are you experiencing?";
autoComplete.Keyboard = Keyboard.Create(KeyboardFlags.CapitalizeSentence | KeyboardFlags.Spellcheck);
GetCorrectiveActions();
PopulateSymptomAutoComplete();
GetSymptomHistory();
}
async Task GetUserSymptoms()
{
UserSymptoms = await usersymptommanager.getuserSymptoms();
}
async Task PopulateSymptomAutoComplete()
{
GlobalSymptoms = await symmanager.getSymptoms();
try
{
autoComplete.DataSource = GlobalSymptoms;
autoComplete.DisplayMemberPath = "Description";
autoComplete.SelectedValuePath = "ID";
}
catch (Exception ex)
{
DisplayAlert(ex.ToString(), ex.ToString(), "OK");
}
autoComplete.SelectionChanged += (sender, e) =>
{
if (e.Value != "")
{
AutoCompleteSymptomToAdd = (symptom)e.Value;
}
};
}
async void HandleHelp_Clicked(object sender, System.EventArgs e)
{
if (lblTitle.Text == "Edit Symptom")
{
await Navigation.PushAsync(new ContextHelp(HelpConstants.EditSymptomHelpTitle, HelpConstants.EditSymptomHelpContent));
}
else
{
await Navigation.PushAsync(new ContextHelp(HelpConstants.AddSymptomHelpTitle, HelpConstants.AddSymptomHelpContent));
}
}
/// <summary>
/// Rating Slider Changed Event Handler
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void Handle_ValueChanged(object sender, Xamarin.Forms.ValueChangedEventArgs e)
{
var newStep = Math.Round(e.NewValue / StepValue);
RatingSlider.Value = newStep * StepValue;
SliderValue.Text = RatingSlider.Value.ToString();
}
public AddSymptom(CorrectiveAction action)
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
//Set Label Titles
lblTitle.Text = "Add Symptom";
lblSubtutle.Text = "What symptom are you experiencing?";
GetCorrectiveActions();
//CommunitySwitch.IsVisible = false;
PopulateSymptomAutoComplete();
GetSymptomHistory();
//RemedyPicker.SelectedIndex = RemedyPicker.Items.IndexOf(action.Id);
}
void Handle_Scrolled(object sender, Xamarin.Forms.ScrolledEventArgs e)
{
autoComplete.IsDropDownOpen = false;
}
public AddSymptom(Symptoms symptom, bool isFeedback)
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
symptomfeedbackmanager = SymptomFeedbackManager.DefaultManager;
GetCorrectiveActions();
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
if (isFeedback == true)
{
this.Title = "Enter Symptom Feedback";
lblTitle.Text = "Enter Symptom Feedback";
lblSubtutle.Text = "Please enter your feedback";
SymptomLabel.IsVisible = false;
txtSymptom.IsVisible = false;
SymptomFeedbackToAdd.Usersymptomid = symptom.Id;
symptomToAdd.Id = symptom.Id;
SymptomFeedbackToAdd.Description = symptom.Description;
txtSymptom.Text = symptom.Description;
btnAdd.Text = "Add Symptom Feedback";
ProvidingFeedback = true;
//CommunitySwitch.IsVisible = true;
}
PopulateSymptomAutoComplete();
}
public AddSymptom(UserSymptomView symptom, bool isFeedback)
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
symptomfeedbackmanager = SymptomFeedbackManager.DefaultManager;
autoComplete.IsVisible = false;
lblSearchForaSymptom.IsVisible = false;
GetCorrectiveActions();
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
if (isFeedback == true)
{
this.Title = "Enter Symptom Feedback";
lblTitle.Text = "Enter Symptom Feedback";
lblSubtutle.Text = "Please enter your feedback";
SymptomLabel.IsVisible = false;
txtSymptom.IsVisible = false;
SymptomFeedbackToAdd.Usersymptomid = symptom.Usersymptomid;
SymptomFeedbackToAdd.Description = symptom.Description;
txtSymptom.Text = symptom.Description;
btnAdd.Text = "Add Symptom Feedback";
ProvidingFeedback = true;
//CommunitySwitch.IsVisible = true;
}
PopulateSymptomAutoComplete();
autoComplete.IsVisible = false;
SymptomLabel.Text = symptom.Description;
txtSymptom.IsVisible = false;
var userSymptomToEdit = UserSymptoms.Where(Item => Item.Id == symptom.Usersymptomid);
}
public AddSymptom(Symptoms symptom, bool isFeedback, bool isNotification)
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
symptomfeedbackmanager = SymptomFeedbackManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
GetCorrectiveActions();
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
if (isNotification == true)
{
this.Title = "Enter Symptom Feedback";
lblTitle.Text = "Enter Symptom Feedback";
lblSubtutle.Text = "Please enter your feedback";
GetSymptomInfo(symptom.Id);
SymptomFeedbackToAdd.Usersymptomid = symptom.Id;
symptomToAdd.Id = symptom.Id;
btnAdd.Text = "Add Symptom Feedback";
ProvidingFeedback = true;
}
PopulateSymptomAutoComplete();
}
public async Task GetSymptomInfo(string id)
{
ObservableCollection<Symptoms> SymptomToFeedback = await manager.getSymptomFromID(id);
SymptomLabel.IsVisible = false;
txtSymptom.IsVisible = false;
SymptomFeedbackToAdd.Usersymptomid = SymptomToFeedback[0].Id;
SymptomFeedbackToAdd.Description = SymptomToFeedback[0].Description;
txtSymptom.Text = SymptomToFeedback[0].Description;
}
public AddSymptom(Symptoms symptom)
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
//Set Label Titles
lblTitle.Text = "Edit Symptom";
lblSubtutle.Text = "Edit your Symptom";
GetCorrectiveActions();
symptomToAdd = symptom;
txtSymptom.Text = symptom.Description;
Symptomfeedback.Text = symptom.Symptomfeedback;
RatingSlider.Value = symptom.Intensity;
PopulateSymptomAutoComplete();
}
public AddSymptom(usersymptom symptom)
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
symptomfeedbackmanager = SymptomFeedbackManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
//Set Label Titles
lblTitle.Text = "Edit Symptom";
lblSubtutle.Text = "Edit your Symptom";
GetCorrectiveActions();
SymptomToEdit = symptom;
txtSymptom.Text = symptom.Description;
//Symptomfeedback.Text = symptom.Symptomfeedback;
//RatingSlider.Value = symptom.Rating;
PopulateSymptomAutoComplete();
}
public AddSymptom(UserSymptomView symptom)
{
InitializeComponent();
manager = SymptomsManager.DefaultManager; //intiialise the Azure Symptom class
weathermanager = WeatherManager.DefaultManager;
remedymanager = RemedyManager.DefaultManager;
imagemanager = ImagesManager.DefaultManager;
usersymptommanager = UserSymptomManager.DefaultManager;
//RemedyPicker.SelectedIndexChanged += RemedyPicker_SelectedIndexChanged;
Device.BeginInvokeOnMainThread(action: async () =>
{
Uri ImgSource = await App.GetImage("sym");
img.Source = ImgSource;
});
GetUserSymptoms();
GetUserSymptomToEdit(symptom); //Set Label Titles
lblTitle.Text = "Edit Symptom";
lblSubtutle.Text = "Edit your Symptom";
GetCorrectiveActions();
//SymptomToEdit = symptom;
txtSymptom.Text = symptom.Description;
//Symptomfeedback.Text = symptom.Symptomfeedback;
//RatingSlider.Value = symptom.Rating;
PopulateSymptomAutoComplete();
autoComplete.IsVisible = false;
SymptomLabel.Text = symptom.Description;
txtSymptom.IsVisible = false;
lblSearchForaSymptom.IsVisible = false;
}
async void GetUserSymptomToEdit(UserSymptomView symptom)
{
ObservableCollection<usersymptom> SelectedSymptom = await usersymptommanager.getuserSymptomInfo(symptom.Usersymptomid);
SymptomToEdit = SelectedSymptom[0];
}
<summary>
Gets the corrective actions.
</summary>
<returns>The corrective actions.</returns>
async public Task GetCorrectiveActions()
{
CorrectiveAction blank = new CorrectiveAction();
blank.RemedyDesc = "";
ObservableCollection<CorrectiveAction> CorrectiveActions = new ObservableCollection<CorrectiveAction>();
CorrectiveActions = await remedymanager.GetUserRemedies();
CorrectiveActions.Insert(0, blank);
//RemedyPicker.ItemsSource = CorrectiveActions;
}
async void GetSymptomHistory()
{
var usersymptoms = await usersymptommanager.CurrentClient.InvokeApiAsync<IEnumerable<UserSymptomView>>("getusersyms?userid=" + Helpers.Settings.UserKey + "&isactive=0", System.Net.Http.HttpMethod.Get, null);
foreach (var item in usersymptoms)
{
SymptomHistoryIDs.Add(item.Symptomid);
}
}
async void btnAdd_Clicked(object sender, EventArgs e)
{
// CheckSymptomInHistory(AutoCompleteSymptomToAdd.Id);
//If the autocomplete is not empty - add that symptom to the user symptom table
if (AutoCompleteSymptomToAdd != null)
{
//If the user already has symptoms, loop through them to make sure that they are not adding a duplicate
if (UserSymptoms.Count > 0)
{
foreach (usersymptom item in UserSymptoms)
{
if (item.Symptomid == AutoCompleteSymptomToAdd.Id)
{
await DisplayAlert("Duplicate Symptom", "You already have recorded this symptom - please log feedback against it if needed", "OK");
return;
}
//Check if it is not active (i.e in SYmptom History)
else
{
UserSymptomToAdd.Symptomid = AutoCompleteSymptomToAdd.Id;
UserSymptomToAdd.UserID = Helpers.Settings.UserKey;
UserSymptomToAdd.Datetimeadded = DateTime.Now.ToString();
UserSymptomToAdd.IsActive = true;
try
{
await usersymptommanager.AddUserSymptom(UserSymptomToAdd);
await AddInitialFeedback(UserSymptomToAdd.Id);
//await DisplayAlert("Symptom Added", "Your Symptom has been added", "OK");
}
catch (Exception ex)
{
Analytics.TrackEvent("App Screen: " + Title + ": " + ex);
//await DisplayAlert("Error", ex.ToString(), "OK");
}
}
}
}
//if no symptoms are present (i.e the collection has a count of 0,just add the new usersymptom)
else
{
usersymptom UserSymptomToAdd = new usersymptom();
UserSymptomToAdd.Symptomid = AutoCompleteSymptomToAdd.Id;
UserSymptomToAdd.UserID = Helpers.Settings.UserKey;
UserSymptomToAdd.Datetimeadded = DateTime.Now.ToString();
UserSymptomToAdd.IsActive = true;
try
{
await usersymptommanager.AddUserSymptom(UserSymptomToAdd);
await AddInitialFeedback(UserSymptomToAdd.Id);
//await DisplayAlert("Symptom Added", "Your Symptom has been added", "OK");
}
catch (Exception ex)
{
Analytics.TrackEvent("App Screen: " + Title + ": " + ex);
//await DisplayAlert("Error", ex.ToString(), "OK");
}
}
}
//If the textbox isn't empty - check if the symptom exists in the autocompelete data collection
else if (txtSymptom.Text !=null)
{
foreach (symptom item in GlobalSymptoms)
{
if (item.Description == txtSymptom.Text)
{
await DisplayAlert("Symptom Exists in Database", "Please search for the symptom from the autocomplete box", "OK");
}
else
{
isNewSymptom = true;
}
}
if (isNewSymptom == true)
{
NewSymptomToAdd.Description = txtSymptom.Text;
NewSymptomToAdd.Symptomstatus = "pending";
try
{
await symmanager.AddSymptom(NewSymptomToAdd);
NewUserSymptomToAdd.UserID = Helpers.Settings.UserKey;
NewUserSymptomToAdd.Datetimeadded = DateTime.Now.ToString();
NewUserSymptomToAdd.Symptomid = NewSymptomToAdd.Id;
NewUserSymptomToAdd.IsActive = true;
try
{
await usersymptommanager.AddUserSymptom(NewUserSymptomToAdd);
await DisplayAlert("Symptom Added", "Your Symptom has been added", "OK");
//Our View Symptom API depends on a feedback item to be associated with the usersymptom, so we add a dummy one
await AddInitialFeedback(NewUserSymptomToAdd.Id);
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.ToString(), "OK");
}
}
catch (Exception ex)
{
Analytics.TrackEvent("App Screen: " + Title + ": " + ex);
await DisplayAlert("Error", ex.ToString(), "OK");
}
}
}
//Determines Intensity
symptomToAdd.Rating = Convert.ToInt32(RatingSlider.Value);
SymptomFeedbackToAdd.Rating = RatingSlider.Value.ToString();
//Performs checks before adding to Azure table
if (ProvidingFeedback == true)
{
SymptomFeedbackToAdd.DateTime = DateTime.Now.ToString();
SymptomFeedbackToAdd.Description = txtSymptom.Text;
SymptomFeedbackToAdd.Symptomfeedback = Symptomfeedback.Text;
SymptomFeedbackToAdd.UserID = Helpers.Settings.UserKey;
/*if (RemedyPicker.SelectedIndex != -1)
{
var RemedyPicked = RemedyPicker.Items[RemedyPicker.SelectedIndex];
}*/
}
else
{
// symptomToAdd.Description = txtSymptom.Text;
SymptomFeedbackToAdd.Symptomfeedback = Symptomfeedback.Text;
symptomToAdd.UserID = Helpers.Settings.UserKey;
/*if (RemedyPicker.SelectedIndex != -1)
{
var RemedyPicked = RemedyPicker.Items[RemedyPicker.SelectedIndex];
}*/
}
try
{
if (ProvidingFeedback == true)
{
//if (CommunitySwitch.IsToggled == true)
//{
// SymptomFeedbackToAdd.Posttocommunity = true;
//}
//else
//{
// SymptomFeedbackToAdd.Posttocommunity = false;
//}
await symptomfeedbackmanager.AddSymptomfeedback(SymptomFeedbackToAdd);
await DisplayAlert("Symptom Feedback has been Added", "Your feedback has been added", "OK");
await Navigation.PushAsync(new newviewsymptom());
Navigation.RemovePage(this);
}
else
{
await manager.AddSymptom(symptomToAdd);
await DisplayAlert("Symptom Added", "Your symptom has been added", "OK");
await AddInitialFeedback(NewUserSymptomToAdd.Id);
await Navigation.PushAsync(new correctiveactionconfirmation());
Navigation.RemovePage(this);
}
if (ProvidingFeedback == true)
{
//Set the notification reminder period
//manager.SetSymptomReminder(TwentFourHours, Convert.ToInt32(symptomToAdd.Id), txtSymptom.Text);
manager.SetSymptomReminder(TwentFourHours, Convert.ToInt32(symptomToAdd.Id), symptomToAdd.Description);
}
//Saves the notifcation object to Azure
NotifcationToSave.Symptomid = symptomToAdd.Id;
NotifcationToSave.Userid = Helpers.Settings.UserKey;
NotifcationToSave.MessageType = notifications.MessageTypes.SymptomReminder;
NotifcationToSave.Notificationtime = DateTime.Now.Add(TwentFourHours).ToString();
GetCurrentWeather(symptomToAdd.Id);
}
catch (Exception ex)
{
Analytics.TrackEvent("App Screen: " + Title + ": " + ex);
//await DisplayAlert("Error", ex.ToString(), "OK");
}
}
async void CheckSymptomInHistory(string id)
{
foreach (string item in SymptomHistoryIDs)
{
if (id == item)
{
await DisplayAlert("Historical Symptom", "This symptom is in your history", "OK");
}
}
}
async Task AddInitialFeedback(string usersymptomid)
{
SymptomFeedback symptomFeedback = new SymptomFeedback();
symptomFeedback.Usersymptomid = usersymptomid;
symptomFeedback.Intensity = RatingSlider.Value.ToString();
symptomFeedback.UserID = Helpers.Settings.UserKey;
symptomFeedback.DateTime = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
symptomFeedback.Datetimelimit = DateTime.Now.AddMinutes(30).ToString("g");
// symptomFeedback.Symptomfeedback = Symptomfeedback.Text.ToString();
try
{
await symptomfeedbackmanager.AddSymptomfeedback(symptomFeedback);
//We have to null the id so that we are not always updating the existing feedback item
symptomFeedback.Id = null;
}
catch (Exception ex)
{
Analytics.TrackEvent(ex.ToString());
}
}
This is a wall of code so it's very hard to read. I see a lot of duplicate code and different overloads of the same function doing mostly the same thing. Anyway back to the question, from what I can see the problem in your async void btnAdd_Clicked(object sender, EventArgs e) method. You loop over the symptons the user already has to see if the AutoCompleteSymptomToAdd is already in the list of symptons, but every sympton that is not a duplicate adds the AutoCompleteSymptonToAdd by this bit of code:
else
{
UserSymptomToAdd.Symptomid = AutoCompleteSymptomToAdd.Id;
UserSymptomToAdd.UserID = Helpers.Settings.UserKey;
UserSymptomToAdd.Datetimeadded = DateTime.Now.ToString();
UserSymptomToAdd.IsActive = true;
try
{
await usersymptommanager.AddUserSymptom(UserSymptomToAdd);
await AddInitialFeedback(UserSymptomToAdd.Id);
//await DisplayAlert("Symptom Added", "Your Symptom has been added", "OK");
}
catch (Exception ex)
{
Analytics.TrackEvent("App Screen: " + Title + ": " + ex);
//await DisplayAlert("Error", ex.ToString(), "OK");
}
}
I assume the funcionality you want is to only add the new sympton if there are no duplicates. So remove the else block and paste it's content after the foreach (usersymptom item in UserSymptoms) is finished. That way you're guaranteed that there is no duplicate (since it hits return if there's a duplicate) and you're free to add it as new sympton.

WebAPI:How to read message from HttpResponseMessage class at client side

below is a sample action which is returning HttpResponseMessage and if any error occur then this way web api action returning error message and status code to client side return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);.
[HttpGet, Route("GetAll")]
public HttpResponseMessage GetAllCustomers()
{
IEnumerable<Customer> customers = repository.GetAll();
if (customers == null)
{
var message = string.Format("No customers found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, customers);
}
}
when i am invoking action by http client then i am not getting message in ReasonPhrase property. just tell me what is the right way to read message at client side which is passing like this way return Request.CreateResponse(HttpStatusCode.OK, customers);
here is my client side code
private async void btnFind_Click(object sender, EventArgs e)
{
var fullAddress = baseAddress + "api/customer/GetByID/"+txtFind.Text;
Customer _Customer = null;
using (var client = new HttpClient())
{
using (var response = client.GetAsync(fullAddress).Result)
{
if (response.IsSuccessStatusCode)
{
var customerJsonString = await response.Content.ReadAsStringAsync();
_Customer = JsonConvert.DeserializeObject<Customer>(customerJsonString);
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}
if (_Customer != null)
{
var _CustList = new List<Customer> { _Customer };
dgCustomers.DataSource = _CustList;
}
}
response.ReasonPhrase not holding the message which i am passing from action. so may be i am not doing things to read message. please tell me what to change in my code to read the message. thanks
i have the job this way.
private async void btnFind_Click(object sender, EventArgs e)
{
var fullAddress = baseAddress + "api/customer/GetByID/"+txtFind.Text;
Customer _Customer = null;
try
{
using (var client = new HttpClient())
{
using (var response = client.GetAsync(fullAddress).Result)
{
if (response.IsSuccessStatusCode)
{
var customerJsonString = await response.Content.ReadAsStringAsync();
_Customer = JsonConvert.DeserializeObject<Customer>(customerJsonString);
}
else
{
//Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
var ErrMsg = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);
MessageBox.Show(ErrMsg.Message);
}
}
}
if (_Customer != null)
{
var _CustList = new List<Customer> { _Customer };
dgCustomers.DataSource = _CustList;
}
}
catch (HttpRequestException ex)
{
// catch any exception here
}
}
read error message this way.
var ErrMsg = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);

Resources