如何添加循环以停止多个数据库条目?

时间:2019-02-14 13:22:33

标签: xamarin xamarin.forms

当我按下我的提交按钮时,它将向数据库发送多个条目,我如何在此处设置循环以阻止此操作。我尝试将datetime设置为当时只允许一个条目,但是条目相隔一两秒,因此不起作用。

我已使用大多数代码更新了此问题,我不确定此错误来自何处,因此将不胜感激。

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

1 个答案:

答案 0 :(得分:0)

这是一堵代码墙,因此很难阅读。我看到很多重复的代码和同一功能的不同重载几乎都在做同一件事。无论如何,从我在您的async void btnAdd_Clicked(object sender, EventArgs e)方法中可以看到的问题回到问题所在。您遍历了用户已经必须查看的AutoCompleteSymptomToAdd征兆,但是不是重复的每个征兆都通过以下代码添加了AutoCompleteSymptonToAdd

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

}

我假设您想要的功能是仅在没有重复项时才添加新的症状。因此,else完成后,请删除foreach (usersymptom item in UserSymptoms)块并将其内容粘贴。这样,您可以保证没有重复项(因为如果有重复项,它会打到return),您可以自由地将其添加为新的症状。