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

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.

Related

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
}
}
}
}

Xamarin Forms not Debugging and ZXing freezing all the application

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.

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);

Creating a new entry in Azure mobile table

Good day
I am currently facing a weird problem with my insert command on my client side I think. I can create new entries in my other models(Tables) easily but in my person model I keep getting a bad request message each time I click create account.
Backend Model:
public class Person : EntityData
{
[StringLength(20)]
public string Name { get; set; }
[StringLength(20)]
public string Surname { get; set; }
[StringLength(150)]
public string Email { get; set; }
[StringLength(15)]
public string Mobile { get; set; }
[StringLength(15)]
public string Work { get; set; }
[StringLength(14)]
public string Password { get; set; }
[StringLength(80)]
public string Company { get; set; }
public virtual City City { get; set; }
}
Client Side Controller:
namespace azuremobile
{
public partial class PersonManager
{
static PersonManager defaultInstance = new PersonManager();
MobileServiceClient client;//Initialize Mobile SDK
IMobileServiceTable<Person> accountTable;
private PersonManager()
{
var handler = new AuthHandler();
//Create our client and pass in Authentication handler
this.client = new MobileServiceClient(
Constants.ApplicationURL, handler);
this.accountTable = client.GetTable<Person>();
}
public static PersonManager DefaultManager
{
get
{
return defaultInstance;
}
private set
{
defaultInstance = value;
}
}
public MobileServiceClient CurrentClient//Provides basic access to azure mobile services
{
get { return client; }
}
public bool IsOfflineEnabled
{
get { return accountTable is Microsoft.WindowsAzure.MobileServices.Sync.IMobileServiceSyncTable<Person>; }
}
public async Task<Person> GetTodoItemsAsync(Expression<Func<Person, bool>> linq)
//public async Task<List<Person>> GetTodoItemsAsync(bool syncItems = false)
{
try
{
// return new List<Person>(await accountTable.ReadAsync());
//List<Person> newUser = await accountTable.Where(linq).Take(1).ToListAsync();
IEnumerable<Person> items = await accountTable
.Where(c => c.Name != null)
.Take(1)
.ToListAsync();
//return newUser.First();
// return await accountTable;
// .Where(c => c.Name != null)
// .Take(1)
// .ToListAsync();
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
}
return null;
}
public async Task SaveTaskAsync(Person item)
{
// if (item.Id != null)
// await accountTable.InsertAsync(item);
// else
await accountTable.UpdateAsync(item);
}
public async Task CreateTaskAsync(Person item)
{
try
{
await accountTable.InsertAsync(item);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"INVALID {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"ERROR {0}", e.Message);
}
}
}
}
Client Side Signup Screen:
public partial class SignupScreen : ContentPage
{
PersonManager manager;
public SignupScreen()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
manager = PersonManager.DefaultManager;
LoginClicked.Clicked += async (object sender, EventArgs e) =>
{
var main = new LoginScreen();
Application.Current.MainPage = main;
Navigation.RemovePage(this);
};
}
async Task CreatedNewUser(Person items)
{
try
{
await manager.CreateTaskAsync(items);
}
catch (MobileServiceInvalidOperationException e)
{
await DisplayAlert("Info", e.Message, "Ok");
}
}
public async void OnSignUp(object sender, EventArgs e)
{
string name = this.nameEntry.Text.Trim();
string surname = this.surnameEntry.Text.Trim();
string email = this.emailEntry.Text.Trim();
string company = this.companyEntry.Text.Trim();
string work = this.workEntry.Text.Trim();
string mobile = this.mobileEntry.Text.Trim();
string password = this.passwordEntry.Text.Trim();
if (string.IsNullOrEmpty(name))
{
await DisplayAlert("Info", "Please fill in your name.", "Ok");
this.nameEntry.PlaceholderColor = this.nameEntry.TextColor = Color.FromHex("#00FF00");
nameEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(surname))
{
await DisplayAlert("Info", "Please fill in your surname.", "Ok");
this.surnameEntry.PlaceholderColor = this.surnameEntry.TextColor = Color.FromHex("#00FF00");
surnameEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(email))
{
await DisplayAlert("Info", "Please fill in your email.", "Ok");
this.emailEntry.PlaceholderColor = this.emailEntry.TextColor = Color.FromHex("#00FF00");
emailEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(company))
{
await DisplayAlert("Info", "Please fill in your company name.", "Ok");
this.companyEntry.PlaceholderColor = this.companyEntry.TextColor = Color.FromHex("#00FF00");
companyEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(mobile))
{
await DisplayAlert("Info", "Please fill in your cellphone number.", "Ok");
this.mobileEntry.PlaceholderColor = this.mobileEntry.TextColor = Color.FromHex("#00FF00");
mobileEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(work))
{
await DisplayAlert("Info", "Please fill in your office number.", "Ok");
this.workEntry.PlaceholderColor = this.workEntry.TextColor = Color.FromHex("#00FF00");
workEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(password))
{
await DisplayAlert("Info", "Please fill in your password.", "Ok");
this.passwordEntry.PlaceholderColor = this.passwordEntry.TextColor = Color.FromHex("#00FF00");
passwordEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
try
{
activityIndicator.IsRunning = true;
validationLabel.IsVisible = true;
signUpButton.IsEnabled = false;
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
{
var OnAdd = new Person
{
Name = name,
Surname = surname,
Email = email,
Mobile = mobile,
Work = work,
Company = company,
Password = password
};
await CreatedNewUser(OnAdd);
await Navigation.PushAsync(new LoginScreen());
}
else
{
await DisplayAlert("Warning", "Could not create user account.", "Ok");
}
}
catch (Exception)
{
await DisplayAlert("Warning", "Could not create user account, problem with internet connection or server.", "Ok");
activityIndicator.IsRunning = false;
validationLabel.IsVisible = false;
signUpButton.IsEnabled = true;
}
}
}
}

Resources