private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                checkError();

                /*if (String.IsNullOrWhiteSpace(txtFName.Text) || String.IsNullOrWhiteSpace(txtLName.Text) || String.IsNullOrWhiteSpace(cmbSex.Text) || String.IsNullOrWhiteSpace(cmbStatus.Text))
                {
                    System.Windows.MessageBox.Show("Please input correct format and/or fill all required fields");
                    return;
                }*/
                if(error == true)
                {
                    System.Windows.MessageBox.Show("Please input correct format and/or fill all required fields", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (status == "Add")
                {
                    DialogResult dr = System.Windows.Forms.MessageBox.Show("Are you sure you want to add this record?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }

                    using (var ctx = new finalContext())
                    {
                        var ads = ctx.TempHomeAddresses.Count();
                        var con = ctx.TempClientContacts.Count();

                        if (ads == 0 || con == 0)
                        {
                            System.Windows.MessageBox.Show("Please input at least one address and one contact number", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }

                    try
                    {
                        string age = "0";
                        int years = DateTime.Now.Year - dtBDay.SelectedDate.Value.Year;
                        if (dtBDay.SelectedDate.Value.AddYears(years) > DateTime.Now) ;
                        years--;

                        age = years.ToString();
                        int iAge = Convert.ToInt32(age);
                        if (iAge < 18 || iAge > 65)
                        {
                            System.Windows.MessageBox.Show("Client's age must be between 18 and 65");
                            return;
                        }
                    }
                    catch
                    { 
                    
                    }

                    using (var ctx = new finalContext())
                    {
                        var num = ctx.Clients.Where(x => x.FirstName == txtFName.Text && x.LastName == txtLName.Text && x.MiddleName == txtMName.Text && x.Birthday == dtBDay.SelectedDate).Count();
                        if (num > 0)
                        {
                            System.Windows.MessageBox.Show("Client already exists", "Information", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                            return;
                        }
                        var result = "";
                        //if (txtEmail_Copy.Text != "")
                        //{
                            var c = ctx.Clients.Where(x => x.Email == txtEmail_Copy.Text).Count();
                            if (c > 0 && txtEmail_Copy.Text!="")
                            {
                                System.Windows.MessageBox.Show("Email has been already used", "Information", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                return;
                            }
                            
                            do
                            {
                                var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                                var random = new Random();
                                result = new string(
                                    Enumerable.Repeat(chars, 15)
                                              .Select(s => s[random.Next(s.Length)])
                                              .ToArray());
                                c = ctx.Clients.Where(x => x.TrackingNumber == result).Count();
                            } while (c > 0);
                        if (txtEmail_Copy.Text != "")
                        {
                            try
                            {
                                string email = txtEmail_Copy.Text;
                                string link = "http://*****:*****@gmail.com"); //See the note afterwards...
                                msg.Body = message;
                                SmtpClient smtp = new SmtpClient("smtp.gmail.com");
                                smtp.EnableSsl = true;
                                smtp.Port = 587;
                                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                                smtp.Credentials = new NetworkCredential("*****@*****.**", "312231212131");
                                smtp.Send(msg);
                            }
                            catch (Exception)
                            {

                            }
                        }

                        Client clt = new Client { Birthday = Convert.ToDateTime(dtBDay.SelectedDate).Date, Active = true, MiddleName = txtMName.Text, LastName = txtLName.Text, FirstName = txtFName.Text, Email = txtEmail_Copy.Text, Sex = cmbSex.Text, SSS = txtSSS.Text, Suffix = txtSuffix.Text, TIN = txtTIN.Text, Status = cmbStatus.Text, Photo = ConvertImageToByteArray(selectedFileName), isConfirmed=true, isRegistered=false, TrackingNumber = result };

                        var ads = from ad in ctx.TempHomeAddresses
                                  select ad;
                        foreach (var item in ads)
                        {
                            HomeAddress add = new HomeAddress { AddressNumber = item.AddressNumber, City = item.City, LengthOfStay = item.LengthOfStay, MonthlyFee = item.MonthlyFee, OwnershipType = item.OwnershipType, Province = item.Province, Street = item.Street };
                            ctx.HomeAddresses.Add(add);
                        }

                        var cts = from ct in ctx.TempClientContacts
                                  select ct;
                        foreach (var item in cts)
                        {
                            ClientContact con = new ClientContact { Contact = item.Contact, ContactNumber = item.ContactNumber, Primary = item.Primary };
                            ctx.ClientContacts.Add(con);
                        }

                        var dps = from dp in ctx.TempDependents
                                  select dp;
                        foreach (var item in dps)
                        {
                            Dependent dep = new Dependent { Birthday = item.Birthday, DependentNumber = item.DependentNumber, FirstName = item.FirstName, LastName = item.LastName, MiddleName = item.LastName, School = item.School, Suffix = item.Suffix };
                            ctx.Dependents.Add(dep);
                        }
                        var wks = from wk in ctx.TempWorks
                                  select wk;
                        foreach (var item in wks)
                        {
                            Work wrk = new Work { BusinessName = item.BusinessName, BusinessNumber = item.BusinessNumber, City = item.City, DTI = item.DTI, Employment = item.Employment, LengthOfStay = item.LengthOfStay, MonthlyIncome = item.MonthlyIncome, PLNumber = item.PLNumber, Position = item.Position, Province = item.Province, status = item.status, Street = item.Street, WorkNumber = item.WorkNumber };
                            ctx.Works.Add(wrk);
                        }
                        var rfs = from rf in ctx.TempReferences
                                  select rf;
                        foreach (var item in rfs)
                        {
                            Reference rfr = new Reference { City = item.City, Contact = item.Contact, FirstName = item.FirstName, LastName = item.LastName, MiddleName = item.MiddleName, Province = item.Province, ReferenceNumber = item.ReferenceNumber, Street = item.Street, Suffix = item.Suffix };
                            ctx.References.Add(rfr);
                        }

                        if (cmbStatus.Text == "Married")
                        {
                            //Spouse sps = new Spouse { Birthday = Convert.ToDateTime(dtSBday.SelectedDate).Date, BusinessName = txtSWName.Text, BusinessNumber = txtSBsNumber.Text, City = txtSCity.Text, DTI = txtSDTI.Text, Employment = cmbSEmployment.Text, FirstName = txtSFName.Text, LastName = txtSLName.Text, LengthOfStay = txtSLength.Text, MiddleName = txtSMName.Text, MonthlyIncome = Convert.ToDouble(txtSIncome.Text), PLNumber = txtSPLNumber.Text, Position = txtSPosition.Text, Province = txtSProvince.Text, status = cmbSStatus.Text, Street = txtSStreet.Text, Suffix = txtSuffix.Text };
                            Spouse sps = new Spouse { Birthday = Convert.ToDateTime(dtSBday.SelectedDate).Date, FirstName = txtSFName.Text, LastName = txtSLName.Text, MiddleName = txtSMName.Text, Suffix = txtSuffix.Text };
                            ctx.Spouses.Add(sps);
                        }

                        AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Added new Client " + txtFName.Text + " " + txtMName.Text + " " + txtLName.Text + " " + txtSuffix.Text };
                        ctx.AuditTrails.Add(at);

                        ctx.Clients.Add(clt);
                        ctx.SaveChanges();
                        System.Windows.MessageBox.Show("Client successfuly added", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                }
                else
                {
                    DialogResult dr = System.Windows.Forms.MessageBox.Show("Are you sure you want to update this record?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }

                    using (var ctx = new finalContext())
                    {
                        var ads = ctx.HomeAddresses.Where(x=> x.ClientID == cId).Count();
                        var con = ctx.ClientContacts.Where(x => x.ClientID == cId).Count();

                        if (ads == 0 || con == 0)
                        {
                            System.Windows.MessageBox.Show("Please input at least one address and one contact number", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }

                    using (var ctx = new finalContext())
                    {
                        
                        var clt = ctx.Clients.Find(cId);
                        if (txtEmail_Copy.Text != clt.Email && clt.isRegistered == false)
                        {
                            var c = ctx.Clients.Where(x => x.Email == txtEmail_Copy.Text).Count();
                            if (c > 0)
                            {
                                System.Windows.MessageBox.Show("Email has been already used", "Information", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                return;
                            }
                            else
                            {
                                try
                                {
                                    string email = txtEmail_Copy.Text;
                                    string link = "http://*****:*****@gmail.com"); //See the note afterwards...
                                    msg.Body = message;
                                    SmtpClient smtp = new SmtpClient("smtp.gmail.com");
                                    smtp.EnableSsl = true;
                                    smtp.Port = 587;
                                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                                    smtp.Credentials = new NetworkCredential("*****@*****.**", "312231212131");
                                    smtp.Send(msg);
                                }
                                catch (Exception)
                                { 
                                
                                }
                            }
                        }
                        clt.Birthday = Convert.ToDateTime(dtBDay.SelectedDate).Date;
                        clt.MiddleName = txtMName.Text;
                        clt.LastName = txtLName.Text;
                        clt.FirstName = txtFName.Text;
                        clt.Email = txtEmail_Copy.Text;
                        clt.Sex = cmbSex.Text;
                        clt.SSS = txtSSS.Text;
                        clt.Suffix = txtSuffix.Text;
                        clt.TIN = txtTIN.Text;
                        clt.Status = cmbStatus.Text;
                        if (cmbStatus.Text == "Married")
                        {
                            var sps = ctx.Spouses.Where(x => x.ClientID == clt.ClientID).First();
                            sps.Birthday = Convert.ToDateTime(dtSBday.SelectedDate).Date;
                            sps.FirstName = txtSFName.Text;
                            sps.LastName = txtSLName.Text;
                            sps.MiddleName = txtSMName.Text;
                            sps.Suffix = txtSuffix.Text;
                        }
                        if (isChanged == true)
                        {
                            clt.Photo = ConvertImageToByteArray(selectedFileName);
                        }

                        if (status2 == "Confirmation")
                        {
                            clt.isConfirmed = true;
                            AuditTrail at1 = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Confirmed Client " + txtFName.Text + " " + txtMName.Text + " " + txtLName.Text + " " + txtSuffix.Text };
                            ctx.AuditTrails.Add(at1);
                            ctx.SaveChanges();
                            System.Windows.MessageBox.Show("Client has been successfully confirmed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            this.Close();
                            return;
                        }
                        AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Updated Client " + txtFName.Text + " " + txtMName.Text + " " + txtLName.Text + " " + txtSuffix.Text };
                        ctx.AuditTrails.Add(at);
                        ctx.SaveChanges();
                        System.Windows.MessageBox.Show("Client has been successfully updated", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
        protected void btnRegister_Click1(object sender, EventArgs e)
        {
            try
            {
                if (txtCaptcha.Text == "")
                {
                    lblCaptcha.Visible = true;
                    return;
                }
                CaptchaControl1.ValidateCaptcha(txtCaptcha.Text);
                if (!CaptchaControl1.UserValidated)
                {
                    lblCaptcha.Visible = true;
                    return;
                }
                else
                {
                    lblCaptcha.Visible = !true;
                }
                DateTime bDay = Convert.ToDateTime(txtBirthday.Text);

                using (var ctx = new finalContext())
                {
                    var ctr = ctx.Clients.Where(x => x.FirstName == txtFirstName.Text && x.LastName == txtLastName.Text && x.MiddleName == txtMiddleName.Text && x.Suffix == txtSuffix.Text && x.Birthday == bDay).Count();
                    if (ctr > 0)
                    {
                        lblExists.Visible = true;
                        return;
                    }
                    else
                    {

                        string age = "0";
                        int years = DateTime.Now.Year - bDay.Year;
                        if (bDay.AddYears(years) > DateTime.Now) ;
                        years--;

                        age = years.ToString();
                        int iAge = Convert.ToInt32(age);
                        if (iAge < 18 || iAge > 65)
                        {
                            lblExists.Text = "Age must be between 18 an 65";
                            lblExists.Visible = true;
                            return;
                        }
                        if (txtPassword.Text != txtConfirm.Text)
                        {
                            lblExists.Text = "Passwords didn't match";
                            lblExists.Visible = true;
                            return;
                        }

                        if (txtPassword.Text.Length < 8)
                        {
                            lblExists.Text = "Password length must be at least 8";
                            lblExists.Visible = true;
                            return;
                        }

                        if (txtUsername.Text.Length < 8)
                        {
                            lblExists.Text = "Username length must be at least 8";
                            lblExists.Visible = true;
                            return;
                        }

                        if(txtBirthday.Text == "" || txtEmail.Text == "" || txtFirstName.Text == "" || txtLastName.Text == "" || txtUsername.Text == "")
                        {
                            lblExists.Text = "Please input all required fields";
                            lblExists.Visible = true;
                            return;
                        }

                        var c = ctx.Clients.Where(x => x.Username == txtUsername.Text).Count();
                        if (c > 0)
                        {
                            lblExists.Text = "Username has been already used";
                            lblExists.Visible = true;
                            return;
                        }

                        c = ctx.Clients.Where(x => x.Email == txtEmail.Text).Count();
                        if (c > 0)
                        {
                            lblExists.Text = "Email has been already used";
                            lblExists.Visible = true;
                            return;
                        }
                        var result = "asd";
                        do
                        {
                            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                            var random = new Random();
                            result = new string(
                                Enumerable.Repeat(chars, 15)
                                          .Select(s => s[random.Next(s.Length)])
                                          .ToArray());
                            c = ctx.Clients.Where(x => x.TrackingNumber == result).Count();
                        } while (c > 0);
                        Client clt = new Client { Active = true, Birthday = bDay, Email = txtEmail.Text, FirstName = txtFirstName.Text, isConfirmed = false, LastName = txtLastName.Text, MiddleName = txtMiddleName.Text, Password = txtPassword.Text, Sex = cmbGender.Text, SSS = txtSSS.Text, Username = txtUsername.Text, Status = cmbStatus.Text, Suffix = txtSuffix.Text, TIN = txtTIN.Text, isRegistered = false, TrackingNumber = result };
                        ClientContact con = new ClientContact { ContactNumber = 1, Primary = true, Contact = txtContact.Text };
                        iClientExpiration exp = new iClientExpiration { ExpirationDate = DateTime.Now.AddMonths(1) };

                        ctx.Clients.Add(clt);
                        ctx.ClientContacts.Add(con);
                        ctx.iClientExpirations.Add(exp);
                        ctx.SaveChanges();
                        Session["newID"] = clt.ClientID.ToString();
                        Response.Redirect("/RegistrationSuccess.aspx");

                    }
                }
            }
            catch (Exception)
            {
                //Response.Redirect("/Index.aspx");
            }
            
        }
        private void btnAddContact_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (btnAddContact.Content.ToString() != "Add")
                {
                    if (lblContact.Content == "?" || String.IsNullOrWhiteSpace(txtContact.Text))
                    {
                        System.Windows.MessageBox.Show("Please input correct format and/or fill all required fields", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }
                if (btnAddContact.Content.ToString() == "Add")
                {
                    grpContact.Visibility = Visibility.Visible;
                    btnAddContact.Content = "Save";
                    btnEdtContact.Content = "Cancel";
                    btnEdtContact.IsEnabled = true;
                    btnDelContact.Visibility = Visibility.Hidden;

                    tbAddress.IsEnabled = false;
                    tbContact.IsEnabled = false;
                    tbDep.IsEnabled = false;
                    tbInfo.IsEnabled = false;
                    tbRef.IsEnabled = false;
                    tbSps.IsEnabled = false;
                    tbWork.IsEnabled = false;
                }
                else if (btnAddContact.Content.ToString() == "Save")
                {
                    //if (txtReqName.Text == "" || txtReqDesc.Text == "")
                    //{
                    //    System.Windows.MessageBox.Show("Please complete the required information", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    //    return;
                    //}

                    //for view
                    if (status == "View")
                    {

                        using (var ctx = new finalContext())
                        {
                            var ctr = ctx.ClientContacts.Where(x => x.ClientID == cId).Count() + 1;
                            bool pr = false;
                            if (ctr == 1)
                            {
                                pr = true;
                            }

                            ClientContact tc = new ClientContact { ClientID = cId, ContactNumber = ctr, Contact = txtContact.Text, Primary = pr };
                            ctx.ClientContacts.Add(tc);
                            ctx.SaveChanges();

                            var cts = from ct in ctx.ClientContacts
                                      where ct.ClientID == cId
                                      select new { ContactNumber = ct.ContactNumber, Contact = ct.Contact, Primary = ct.Primary };
                            dgContact.ItemsSource = cts.ToList();
                            reset();

                        }
                        return;
                    }


                    using (var ctx = new finalContext())
                    {
                        var ctr = ctx.TempClientContacts.Count() + 1;
                        bool pr = false;
                        if (ctr == 1)
                        {
                            pr = true;
                        }

                        TempClientContact tc = new TempClientContact { ContactNumber = ctr, Contact = txtContact.Text, Primary = pr };
                        ctx.TempClientContacts.Add(tc);
                        ctx.SaveChanges();

                        var cts = from ct in ctx.TempClientContacts
                                  select new { ContactNumber = ct.ContactNumber, Contact = ct.Contact, Primary = ct.Primary };
                        dgContact.ItemsSource = cts.ToList();
                        reset();

                    }

                    reset();
                }
                else //for update
                {
                    //for view
                    if (status == "View")
                    {
                        using (var ctx = new finalContext())
                        {
                            int num = Convert.ToInt32(getRow(dgContact, 0));
                            var tc = ctx.ClientContacts.Where(x => x.ContactNumber == num && x.ClientID == cId).First();
                            tc.Contact = txtContact.Text;
                            ctx.SaveChanges();
                            var cts = from ct in ctx.ClientContacts
                                      where ct.ClientID == cId
                                      select new { ContactNumber = ct.ContactNumber, Contact = ct.Contact, Primary = ct.Primary };
                            dgContact.ItemsSource = cts.ToList();
                            reset();
                        }
                        return;
                    }


                    using (var ctx = new finalContext())
                    {
                        int num = Convert.ToInt32(getRow(dgContact, 0));
                        var tc = ctx.TempClientContacts.Where(x => x.ContactNumber == num).First();
                        tc.Contact = txtContact.Text;
                        ctx.SaveChanges();
                        var cts = from ct in ctx.TempClientContacts
                                  select new { ContactNumber = ct.ContactNumber, Contact = ct.Contact, Primary = ct.Primary };
                        dgContact.ItemsSource = cts.ToList();
                        reset();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }