private void UpdateAddress(int Id, AddressModel address)
		{
			AddressModel originalAddress = this.GetAddressById(Id);
			originalAddress.FirstName = address.FirstName;
			originalAddress.LastName = address.LastName;
			originalAddress.Address = address.Address;
		}
		public ActionResult Index ()
		{
			
			if(this.AddressStore.Count == 0)
			{
				//* Populate AddressStore with seed data
				AddressModel johnWayne = new AddressModel();
				
				johnWayne.FirstName = "John";
				johnWayne.LastName = "Wayne";
				johnWayne.Address = "123 Test St.";
				johnWayne.Id = 1;
				
				AddressModel tomCruise = new AddressModel();
				
				tomCruise.FirstName = "Tom";
				tomCruise.LastName = "Cruise";
				tomCruise.Address = "123 Test St.";
				tomCruise.Id = 2;
				
				this.AddressStore.Add(johnWayne);
				this.AddressStore.Add(tomCruise);
			}
			
			this.ViewData["Addresses"] = this.AddressStore;
			
			return View ();
		}
		private void SaveModel(AddressModel address)
		{
			int maxCurrentId = this.AddressStore.Max(x => x.Id);
			int newId = maxCurrentId + 1;
			address.Id = newId;
			this.AddressStore.Add(address);
		}
 public void BeforeEach()
 {
     _notification = new Notification();
     _model = new AddressModel();
     _strategy = new MaximumStringLengthFieldStrategy() { Length = 10 };
     _accessor = AccessorFactory.Create<AddressModel>(m => m.Address1);
     _rule = new FieldRule(_accessor, new TypeResolver(), _strategy);
 }
 public ActionResult GoogleMaps(AddressModel model)
 {
     if (ModelState.IsValid)
     {
         TempData.AddSuccessMessage("Location was successfully submitted");
     }
     return View(model);
 }
        public ActionResult GoogleMaps()
        {
            var model = new AddressModel
            {
                Address = "301 15th Street, Hood River",
                Location = GeographyHelpers.CreatePoint(45.7120903, -121.5272902)
            };

            return View(model);
        }
        protected Boolean SubmitForm()
        {
            StringBuilder formattedHtml = new StringBuilder();
            StringBuilder formattedInternalHtml = new StringBuilder();
            string seasonalMonths = "";

            try
            {
                foreach (ListItem item in cblSeasonal.Items)
                {
                    if (item.Selected)
                    {
                        seasonalMonths += item.Value + " - ";
                    }
                }

                if (seasonalMonths.Length > 3)
                {
                    seasonalMonths = seasonalMonths.Substring(0, seasonalMonths.Length - 3);
                }
            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "AdminSubmitForm - Get Seasonal Months");
            }

            try
            {
                //Instanciate new model objects for each piece of data to be created
                MerchantModel newMerchant = new MerchantModel();
                MerchantPrincipalModel newMerchantPrincipal = new MerchantPrincipalModel();
                ContactModel newMerchantPrincipalContact = new ContactModel();
                AddressModel newMerchantPrincipalContactAddress = new AddressModel();
                ContactModel newContact = new ContactModel();
                ContactModel newBusiness = new ContactModel();
                AddressModel newBusinessAddress = new AddressModel();
                ProcessorModel newProcessor = new ProcessorModel();
                DebitCardModel newDebitCard = new DebitCardModel();
                BankModel newBankModel = new BankModel();
                BankAccountModel newBankAccountModel = new BankAccountModel();

                //Set base merchant information in newMerchant object
                if (txtMerchantId.Text != "") { newMerchant.MerchantId = txtMerchantId.Text; }
                if (txtCorpName.Text != "") { newMerchant.CorpName = txtCorpName.Text; }
                if (txtDBAName.Text != "") { newMerchant.DbaName = txtDBAName.Text; }
                if (txtBusLicNumber.Text != "") { newMerchant.BusLicNumber = txtBusLicNumber.Text; }
                if (txtBusLicType.Text != "") { newMerchant.BusLicType = txtBusLicType.Text; }
                if (txtBusLicIssuer.Text != "") { newMerchant.BusLicIssuer = txtBusLicIssuer.Text; }
                if (radBusLicDate.SelectedDate.HasValue) { newMerchant.BusLicDate = Convert.ToDateTime(radBusLicDate.SelectedDate); }
                if (txtFedTaxId.Text != "") { newMerchant.FedTaxId = txtFedTaxId.Text; }
                if (txtMerchandiseSold.Text != "") { newMerchant.MerchandiseSold = txtMerchandiseSold.Text; }
                if (txtYearsInBus.Text != "") { newMerchant.YearsInBusiness = Convert.ToInt32(txtYearsInBus.Text); }
                if (txtMonthsInBus.Text != "") { newMerchant.MonthsInBusiness = Convert.ToInt32(txtMonthsInBus.Text); }
                if (rblSeasonal.SelectedValue != "") { newMerchant.SeasonalSales = Convert.ToBoolean(rblSeasonal.SelectedValue); }
                if (seasonalMonths != "") { newMerchant.SeasonalMonths = seasonalMonths; }
                if (txtSwipedPct.Text != "") { newMerchant.SwipedPct = Convert.ToInt32(txtSwipedPct.Text); }
                if (txtAvgMonthlySales.Text != "") { newMerchant.AvgMonthlySales = Convert.ToDecimal(txtAvgMonthlySales.Text); }
                if (txtHighestMonthlySales.Text != "") { newMerchant.HighestMonthlySales = Convert.ToDecimal(txtHighestMonthlySales.Text); }
                if (txtAvgWeeklySales.Text != "") { newMerchant.AvgWeeklySales = Convert.ToDecimal(txtAvgWeeklySales.Text); }
                if (rblHighRisk.SelectedValue != "") { newMerchant.HighRisk = Convert.ToBoolean(rblHighRisk.SelectedValue); }
                if (txtHighRiskWho.Text != "") { newMerchant.HighRiskWho = txtHighRiskWho.Text; }
                if (radHighRiskDate.SelectedDate.HasValue) { newMerchant.HighRiskDate = Convert.ToDateTime(radHighRiskDate.SelectedDate); }
                if (rblBankruptcy.SelectedValue != "") { newMerchant.Bankruptcy = Convert.ToBoolean(rblBankruptcy.SelectedValue); }
                if (radBankruptcyDate.SelectedDate.HasValue) { newMerchant.BankruptcyDate = Convert.ToDateTime(radBankruptcyDate.SelectedDate); }

                //Add Legal Org State to merchant
                if (ddlLegalOrgState.SelectedValue != "")
                {
                    Int32 legalOrgStateId = Convert.ToInt32(ddlLegalOrgState.SelectedValue);
                    newMerchant.LegalOrgState = _globalCtx.GeoStates.Where(gs => gs.RecordId == legalOrgStateId).FirstOrDefault();
                }

                //Add Legal Org Type to merchant
                if (ddlLegalOrgType.SelectedValue != "")
                {
                    Int32 legalOrgTypeId = Convert.ToInt32(ddlLegalOrgType.SelectedValue);
                    newMerchant.LegalOrgType = _globalCtx.LegalOrgTypes.Where(lot => lot.RecordId == legalOrgTypeId).FirstOrDefault();
                }

                //Add Merchant Type to Merchant
                if (rblMerchantType.SelectedValue != "") { newMerchant.MerchantType = _globalCtx.MerchantTypes.Where(mt => mt.MerchantTypeName == rblMerchantType.SelectedValue).FirstOrDefault(); }

                //Add MCC to merchant
                if (ddlMCC.SelectedValue != "")
                {
                    Int32 mccId = Convert.ToInt32(ddlMCC.SelectedValue);
                    newMerchant.Mcc = _globalCtx.MerchantCategoryCodes.Where(mcc => mcc.RecordId == mccId).FirstOrDefault();
                }

                //Add Business Contact info - Email, Phone, Fax
                if (txtBusEmail.Text != "") { newBusiness.Email = txtBusEmail.Text; }
                if (txtBusFax.Text != "") { newBusiness.Fax = txtBusFax.Text; }
                if (txtBusPhone.Text != "") { newBusiness.HomePhone = txtBusPhone.Text; }

                _globalCtx.Contacts.Add(newBusiness);

                //Add Business Contact Addess
                if (txtCorpAddress.Text != "") { newBusinessAddress.Address = txtCorpAddress.Text; }
                if (txtCorpCity.Text != "") { newBusinessAddress.City = txtCorpCity.Text; }
                if (ddlCorpState.SelectedValue != "")
                {
                    Int32 businessAddressStateId = Convert.ToInt32(ddlCorpState.SelectedValue);
                    newBusinessAddress.State = _globalCtx.GeoStates.Where(gs => gs.RecordId == businessAddressStateId).FirstOrDefault();
                }
                if (txtCorpZip.Text != "") { newBusinessAddress.Zip = txtCorpZip.Text; }

                _globalCtx.Addresses.Add(newBusinessAddress);

                //Add new Business Contact Address to new Business
                newBusiness.Address = newBusinessAddress;

                //Add new Contact to new Merchant
                newMerchant.Business = newBusiness;

                //Add new Contact
                if (txtContactFirstName.Text != "") { newContact.FirstName = txtContactFirstName.Text; }
                if (txtContactLastName.Text != "") { newContact.LastName = txtContactLastName.Text; }
                if (txtContactEmail.Text != "") { newContact.Email = txtContactEmail.Text; }
                if (txtContactPhone.Text != "") { newContact.HomePhone = txtContactPhone.Text; }
                if (txtContactFax.Text != "") { newContact.Fax = txtContactFax.Text; }

                _globalCtx.Contacts.Add(newContact);

                //Add new contact to new Merchant
                newMerchant.Contact = newContact;

                //Add new Merchant Principal
                if (txtPrincipalDLNumber.Text != "") { newMerchantPrincipal.PrincipalDLNumber = PWDTK.StringToUtf8Bytes(txtPrincipalDLNumber.Text); }
                if (ddlPrincipalDLState.SelectedValue != "")
                {
                    Int32 dlStateId = Convert.ToInt32(ddlPrincipalDLState.SelectedValue);
                    newMerchantPrincipal.PrincipalDLState = _globalCtx.GeoStates.Where(gs => gs.RecordId == dlStateId).FirstOrDefault();
                }
                if (radPrincipalDoB.SelectedDate.HasValue) { newMerchantPrincipal.PrincipalDoB = Convert.ToDateTime(radPrincipalDoB.SelectedDate); }
                if (txtPrincipalPctOwn.Text != "") { newMerchantPrincipal.PrincipalPctOwn = Convert.ToInt32(txtPrincipalPctOwn.Text); }

                _globalCtx.MerchantPrincipal.Add(newMerchantPrincipal);

                //Create new contact for Merchant Principal
                if (txtPrincipalFirstName.Text != "") { newMerchantPrincipalContact.FirstName = txtPrincipalFirstName.Text; }
                if (txtPrincipalLastName.Text != "") { newMerchantPrincipalContact.LastName = txtPrincipalLastName.Text; }
                if (txtPrincipalMI.Text != "") { newMerchantPrincipalContact.MiddleInitial = txtPrincipalMI.Text; }
                if (txtPrincipalTitle.Text != "") { newMerchantPrincipalContact.Title = txtPrincipalTitle.Text; }
                if (txtPrincipalCellPhone.Text != "") { newMerchantPrincipalContact.CellPhone = txtPrincipalCellPhone.Text; }
                if (txtPrincipalHomePhone.Text != "") { newMerchantPrincipalContact.HomePhone = txtPrincipalHomePhone.Text; }

                _globalCtx.Contacts.Add(newMerchantPrincipalContact);

                //Create new address for Merchant principal Contact
                if (txtPrincipalAddress.Text != "") { newMerchantPrincipalContactAddress.Address = txtPrincipalAddress.Text; }
                if (txtPrincipalCity.Text != "") { newMerchantPrincipalContactAddress.City = txtPrincipalCity.Text; }
                if (ddlPrincipalState.SelectedValue != "")
                {
                    Int32 mpcStateId = Convert.ToInt32(ddlPrincipalState.SelectedValue);
                    newMerchantPrincipalContactAddress.State = _globalCtx.GeoStates.Where(gs => gs.RecordId == mpcStateId).FirstOrDefault();
                }
                if (txtPrincipalZip.Text != "") { newMerchantPrincipalContactAddress.Zip = txtPrincipalZip.Text; }

                _globalCtx.Addresses.Add(newMerchantPrincipalContactAddress);

                //Add new address to Merchant Principal Contact
                newMerchantPrincipalContact.Address = newMerchantPrincipalContactAddress;

                //Add new Contact to Merchant Principal
                newMerchantPrincipal.Contact = newMerchantPrincipalContact;

                //Add new Principal to the new merchant
                newMerchant.MerchantPrincipal = newMerchantPrincipal;

                //Check if merchant processor already exists, if so link to merchant.  If not, create it and add to merchant.
                if (txtCardProcessor.Text != "")
                {
                    if (_globalCtx.Processor.Where(p => p.ProcessorName == txtCardProcessor.Text.Trim()).ToList().Count > 0)
                    {
                        newMerchant.Processor = _globalCtx.Processor.First(p => p.ProcessorName == txtCardProcessor.Text.Trim());
                    }
                    else
                    {
                        newProcessor.ProcessorName = txtCardProcessor.Text.Trim();
                        _globalCtx.Processor.Add(newProcessor);
                        newMerchant.Processor = newProcessor;
                    }
                }

                _globalCtx.Banks.Add(newBankModel);

                newBankAccountModel.Bank = newBankModel;
                newDebitCard.Bank = newBankModel;

                _globalCtx.BankAccounts.Add(newBankAccountModel);
                _globalCtx.DebitCards.Add(newDebitCard);

                newMerchant.BankAccount = newBankAccountModel;
                newMerchant.DebitCard = newDebitCard;

                //Set Merchant Status to "Admin Registered"
                newMerchant.MerchantStatus = _globalCtx.MerchantStatuses.FirstOrDefault(ms => ms.StatusDescription == "Pre-Enrolled");

                //Set Underwriting Status to "Pending"
                newMerchant.UnderwritingStatus = _globalCtx.UnderwritingStatuses.FirstOrDefault(ms => ms.StatusDescription == "Pending");

                newMerchant.AdvancePlan = _globalCtx.AdvancePlans.First(ap => ap.DefaultPlan == true);

                //Add new Merchant to context
                _globalCtx.Merchants.Add(newMerchant);

                //Add new merchant to selected User
                if (txtSelectedUserName.Text != "")
                {
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_globalCtx));
                    ApplicationUser selectedUser = manager.FindByName(txtSelectedUserName.Text);
                    if (selectedUser != null)
                    {
                        selectedUser.Merchant = newMerchant;

                        //Save Context and Update DB
                        _globalCtx.SaveChanges();
                    }
                }
                else
                {
                    lblSubmissionMessage.Text = "Please select a User to join with this merchant.";
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "AdminSubmitForm - Add Data to DB");
                return false;
            }

            return true;
        }
Beispiel #8
0
 public ProfileModel()
 {
     PersonalInfo = new PersonalInfoModel();
     AddressInfo = new AddressModel();
 }
		public ActionResult SaveAddress()
		{
			//* TODO: Query up Address to save 
			AddressModel address = new AddressModel();
			
			address.FirstName = Request.Form["FirstName"];
			address.LastName = Request.Form["LastName"];
			address.Address = Request.Form["Address"];
			
			if(Request.Form["Id"] != "-1")
			{
				//* this is an update rather than a save
				int Id = int.Parse(Request.Form["Id"]);
				this.UpdateAddress(Id, address);
			}
			else
				this.SaveModel(address);
			
			return this.RedirectToAction("Index");
		}
Beispiel #10
0
 public Insured()
 {
     InfosAdresse = new AddressModel(false);
 }
        private void SavePrincipalChanges(MerchantModel editMerchant, ApplicationDbContext ctx)
        {
            try
            {
                foreach (RepeaterItem rItem in rptrPrincipalChanges.Items)
                {
                    Label lblFieldName = (Label)rItem.FindControl("lblFieldName1");
                    Label lblNewValue = (Label)rItem.FindControl("lblNewValue1");
                    CheckBox cbConfirmed = (CheckBox)rItem.FindControl("cbConfirmed1");

                    if (lblFieldName != null && lblNewValue != null && cbConfirmed != null)
                    {
                        if (lblFieldName.Text == "First Name")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.FirstName, lblNewValue.Text);

                                editMerchant.MerchantPrincipal.Contact.FirstName = lblNewValue.Text;
                            }
                            else
                            {
                                txtPrincipalFirstName.Text = editMerchant.MerchantPrincipal.Contact.FirstName;
                            }
                        }

                        if (lblFieldName.Text == "Last Name")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.LastName, lblNewValue.Text);

                                editMerchant.MerchantPrincipal.Contact.LastName = lblNewValue.Text;
                            }
                            else
                            {
                                txtPrincipalLastName.Text = editMerchant.MerchantPrincipal.Contact.LastName;
                            }
                        }

                        if (lblFieldName.Text == "M.I.")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.MiddleInitial, lblNewValue.Text);

                                editMerchant.MerchantPrincipal.Contact.MiddleInitial = lblNewValue.Text;
                            }
                            else
                            {
                                txtPrincipalMI.Text = editMerchant.MerchantPrincipal.Contact.MiddleInitial;
                            }
                        }

                        if (lblFieldName.Text == "D.O.B.")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.PrincipalDoB.ToString(), lblNewValue.Text);

                                editMerchant.MerchantPrincipal.PrincipalDoB = Convert.ToDateTime(lblNewValue.Text);
                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.PrincipalDoB.HasValue)
                                {
                                    ddlBirthYear.SelectedValue = editMerchant.MerchantPrincipal.PrincipalDoB.Value.Year.ToString();
                                    ddlBirthMonth.SelectedValue = editMerchant.MerchantPrincipal.PrincipalDoB.Value.Month.ToString();
                                    ddlBirthDay.SelectedValue = editMerchant.MerchantPrincipal.PrincipalDoB.Value.Day.ToString();
                                }
                                else
                                {
                                    ddlBirthYear.SelectedIndex = -1;
                                    ddlBirthMonth.SelectedIndex = -1;
                                    ddlBirthDay.SelectedIndex = -1;
                                }
                            }
                        }

                        if (lblFieldName.Text == "S.S.N.")
                        {
                            if (cbConfirmed.Checked)
                            {
                                String maskedOldSsn = MaskSsn(editMerchant.MerchantPrincipal.PrincipalSsn, editMerchant.MerchantPrincipal.RecordId);

                                Logic.Crypt crypto1 = new Logic.Crypt();
                                crypto1.CryptType = "SSN";
                                crypto1.CryptData = Convert.ToBase64String(PWDTK.StringToUtf8Bytes(lblNewValue.Text));
                                crypto1.Purpose = "86d4b5b2-b34a-4968-9fde-f8ed677bca8b";
                                crypto1.AdditionalData = editMerchant.MerchantPrincipal.RecordId.ToString();

                                byte[] newSsn = crypto1.Protect();

                                editMerchant.MerchantPrincipal.PrincipalSsn = newSsn;

                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, maskedOldSsn, MaskSsn(newSsn, editMerchant.MerchantPrincipal.RecordId));

                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.PrincipalSsn != null)
                                {
                                    txtPrincipalSSN.Text = MaskSsn(editMerchant.MerchantPrincipal.PrincipalSsn, editMerchant.MerchantPrincipal.RecordId);
                                }
                                else
                                {
                                    txtPrincipalSSN.Text = "";
                                }
                            }

                            txtPrincipalSSN.Enabled = false;
                        }

                        if (lblFieldName.Text == "% Ownership")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.PrincipalPctOwn.ToString(), lblNewValue.Text);

                                editMerchant.MerchantPrincipal.PrincipalPctOwn = Convert.ToDecimal(lblNewValue.Text.Substring(0, lblNewValue.Text.Length - 2));
                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.PrincipalPctOwn.HasValue)
                                {
                                    txtPrincipalPctOwn.Text = editMerchant.MerchantPrincipal.PrincipalPctOwn.ToString();
                                }
                                else
                                {
                                    txtPrincipalPctOwn.Text = "";
                                }
                            }
                        }

                        if (lblFieldName.Text == "Title")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.Title, lblNewValue.Text);

                                editMerchant.MerchantPrincipal.Contact.Title = lblNewValue.Text;
                            }
                            else
                            {
                                txtPrincipalTitle.Text = editMerchant.MerchantPrincipal.Contact.Title;
                            }
                        }

                        if (lblFieldName.Text == "DL Number")
                        {
                            if (cbConfirmed.Checked)
                            {
                                String maskedOldDL = MaskDLNumber(editMerchant.MerchantPrincipal.PrincipalDLNumber, editMerchant.MerchantPrincipal.RecordId);

                                Logic.Crypt crypto2 = new Logic.Crypt();
                                crypto2.CryptType = "DL";
                                crypto2.CryptData = Convert.ToBase64String(PWDTK.StringToUtf8Bytes(lblNewValue.Text));
                                crypto2.Purpose = "29dc7202-ae1f-4d38-9694-9d700a94897b";
                                crypto2.AdditionalData = editMerchant.MerchantPrincipal.RecordId.ToString();

                                byte[] newDl = crypto2.Protect();

                                editMerchant.MerchantPrincipal.PrincipalDLNumber = newDl;

                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, maskedOldDL, MaskDLNumber(newDl, editMerchant.MerchantPrincipal.RecordId));

                            }
                            else
                            {
                                txtPrincipalDLNumber.Text = MaskDLNumber(editMerchant.MerchantPrincipal.PrincipalDLNumber, editMerchant.MerchantPrincipal.RecordId);
                            }

                            txtPrincipalDLNumber.Enabled = false;
                        }

                        if (lblFieldName.Text == "DL State")
                        {
                            if (cbConfirmed.Checked)
                            {
                                string stateName = editMerchant.MerchantPrincipal.PrincipalDLState == null ? "" : editMerchant.MerchantPrincipal.PrincipalDLState.Name;

                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, stateName, lblNewValue.Text);

                                editMerchant.MerchantPrincipal.PrincipalDLState = ctx.GeoStates.First(gs => gs.Name == lblNewValue.Text);
                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.PrincipalDLState != null)
                                {
                                    ddlPrincipalDLState.SelectedValue = editMerchant.MerchantPrincipal.PrincipalDLState.RecordId.ToString();
                                }
                                else
                                {
                                    ddlPrincipalDLState.SelectedIndex = -1;
                                }
                            }
                        }

                        if (lblFieldName.Text == "Address")
                        {
                            if (cbConfirmed.Checked)
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address != null)
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.Address.Address, lblNewValue.Text);

                                    editMerchant.MerchantPrincipal.Contact.Address.Address = lblNewValue.Text;
                                }
                                else
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, "", lblNewValue.Text);

                                    AddressModel newContactAddress = new AddressModel();
                                    newContactAddress.Address = lblNewValue.Text;
                                    ctx.Addresses.Add(newContactAddress);
                                    editMerchant.MerchantPrincipal.Contact.Address = newContactAddress;
                                }
                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address != null)
                                {
                                    txtPrincipalAddress.Text = editMerchant.MerchantPrincipal.Contact.Address.Address;
                                }
                                else
                                {
                                    txtPrincipalAddress.Text = "";
                                }
                            }
                        }

                        if (lblFieldName.Text == "City")
                        {
                            if (cbConfirmed.Checked)
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address != null)
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.Address.City, lblNewValue.Text);

                                    editMerchant.MerchantPrincipal.Contact.Address.City = lblNewValue.Text;
                                }
                                else
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, "", lblNewValue.Text);

                                    AddressModel newContactAddress = new AddressModel();
                                    newContactAddress.City = lblNewValue.Text;
                                    ctx.Addresses.Add(newContactAddress);
                                    editMerchant.MerchantPrincipal.Contact.Address = newContactAddress;
                                }
                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address != null)
                                {
                                    txtPrincipalCity.Text = editMerchant.MerchantPrincipal.Contact.Address.City;
                                }
                                else
                                {
                                    txtPrincipalCity.Text = "";
                                }
                            }
                        }

                        if (lblFieldName.Text == "Zip")
                        {
                            if (cbConfirmed.Checked)
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address != null)
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.Address.Zip, lblNewValue.Text);

                                    editMerchant.MerchantPrincipal.Contact.Address.Zip = lblNewValue.Text;
                                }
                                else
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, "", lblNewValue.Text);

                                    AddressModel newContactAddress = new AddressModel();
                                    newContactAddress.Zip = lblNewValue.Text;
                                    ctx.Addresses.Add(newContactAddress);
                                    editMerchant.MerchantPrincipal.Contact.Address = newContactAddress;
                                }
                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address != null)
                                {
                                    txtPrincipalZip.Text = editMerchant.MerchantPrincipal.Contact.Address.Zip;
                                }
                                else
                                {
                                    txtPrincipalZip.Text = "";
                                }
                            }
                        }

                        if (lblFieldName.Text == "State")
                        {
                            if (cbConfirmed.Checked)
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address != null && editMerchant.MerchantPrincipal.Contact.Address.State != null)
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.Address.State.Name, lblNewValue.Text);

                                    editMerchant.MerchantPrincipal.Contact.Address.State = ctx.GeoStates.First(gs => gs.Name == lblNewValue.Text);
                                }
                                else
                                {
                                    AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, "", lblNewValue.Text);

                                    AddressModel newContactAddress = new AddressModel();
                                    newContactAddress.State = ctx.GeoStates.First(x => x.Name == lblNewValue.Text);
                                    ctx.Addresses.Add(newContactAddress);
                                    editMerchant.MerchantPrincipal.Contact.Address = newContactAddress;
                                }
                            }
                            else
                            {
                                if (editMerchant.MerchantPrincipal.Contact.Address.State != null)
                                {
                                    ddlPrincipalState.SelectedValue = editMerchant.MerchantPrincipal.Contact.Address.State.RecordId.ToString();
                                }
                                else
                                {
                                    ddlPrincipalState.SelectedIndex = -1;
                                }
                            }
                        }

                        if (lblFieldName.Text == "Home Phone")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.HomePhone, lblNewValue.Text);

                                editMerchant.MerchantPrincipal.Contact.HomePhone = lblNewValue.Text;
                            }
                            else
                            {
                                txtPrincipalHomePhone.Text = editMerchant.MerchantPrincipal.Contact.HomePhone;
                            }
                        }

                        if (lblFieldName.Text == "Cell Phone")
                        {
                            if (cbConfirmed.Checked)
                            {
                                AddChangeToAudit(editMerchant.RecordId, lblFieldName.Text, editMerchant.MerchantPrincipal.Contact.CellPhone, lblNewValue.Text);

                                editMerchant.MerchantPrincipal.Contact.CellPhone = lblNewValue.Text;
                            }
                            else
                            {
                                txtPrincipalCellPhone.Text = editMerchant.MerchantPrincipal.Contact.CellPhone;
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                string userId = "";

                if (Request.IsAuthenticated)
                {
                    userId = Page.User.Identity.GetUserId();
                }
                _newLogic.WriteExceptionToDB(ex, "SavePrincipalChanges", 0, editMerchant.RecordId, userId);
            }
        }
 /// <summary>
 /// 监控一个地址。
 /// </summary>
 /// <param name="address">地址模型。</param>
 /// <returns>一个任务。</returns>
 public Task Monitor(AddressModel address)
 {
     return(Task.Run(() => { _dictionary.GetOrAdd(address.ToString(), k => new MonitorEntry(address)); }));
 }
 public MonitorEntry(AddressModel addressModel, bool health = true)
 {
     EndPoint = addressModel.CreateEndPoint();
     Health   = health;
 }
        public async Task <PvaPropertyInfo> GetPropertyInfo(string address)
        {
            address = Regex.Replace(address, " pky", " pkwy", RegexOptions.IgnoreCase);

            var propertyInfo = new PvaPropertyInfo {
                Address = new AddressModel()
            };

            var addressParsings = (await _addressParser.Parse(address)).ToList();

            if (!addressParsings.Any())
            {
                propertyInfo.Error = "Could not parse address.";
                return(propertyInfo);
            }

            var maxScore    = addressParsings.Max(p => p.Score);
            var bestParsing = addressParsings.First(p => p.Score == maxScore);

            propertyInfo.Address = bestParsing.Address;

            // See if the address exists in the database...
            var savedAddress = await _addressRepository.Get(bestParsing.Address.Number, bestParsing.Address.Direction, bestParsing.Address.Street, bestParsing.Address.Tag);

            // If found, and owner, assessed value, and acreage exist, return this instead of asking PVA. The AddressRepository deals with determining
            // whether these attributes are expired.
            if (savedAddress != null && !string.IsNullOrEmpty(savedAddress.Owner) && savedAddress.AssessedValue != null && savedAddress.Acreage != null)
            {
                propertyInfo.Address = savedAddress;
                return(propertyInfo);
            }

            try
            {
                var          webGet    = new HtmlWeb();
                var          document1 = webGet.Load(_settings.Url + string.Format(_settings.SearchUrl, HttpUtility.UrlEncode(bestParsing.Address.BaseAddressDisplay)));
                HtmlDocument document2 = null;

                // If the search returned only one result, the first web page that the PVA site returns will contain javascript redirect to another URL. Get the script tag.
                var redirectScriptTag = document1.DocumentNode.Descendants("script").Where(tag => tag.InnerHtml.Contains("window.location.href=")).ToList();

                var redirectUrl = "";

                if (webGet.ResponseUri.LocalPath.StartsWith("/property-search/property-details")) //  301 redirect
                {
                    document2 = document1;
                }
                else if (redirectScriptTag.Any())
                {
                    // Get the redirect script out of the script tag.
                    var redirectScript = redirectScriptTag.First().InnerHtml;

                    // Remove the javascript and the quotation marks. The remainder is the actual URL.
                    redirectUrl = redirectScript.Replace("window.location.href=", "").Replace("\"", "");
                }
                else if (!redirectScriptTag.Any() && !string.IsNullOrEmpty(bestParsing.Address.Tag))
                {
                    var resultsTable = document1.DocumentNode.Descendants("table").FirstOrDefault(tag => tag.Attributes["class"] != null && tag.Attributes["class"].Value.Contains("searchResultsTable"));

                    if (resultsTable != null)
                    {
                        var resultsRows = resultsTable.Descendants("tr").ToList();

                        // The first row is the table header. Skip this row.
                        foreach (var resultRow in resultsRows.Skip(1))
                        {
                            var resultRowLink = resultRow.ChildNodes.Where(tag => tag.Name == "td").ElementAt(1).ChildNodes.First(tag => tag.Name == "a");
                            if (resultRowLink == null)
                            {
                                continue;
                            }
                            if (!await _addressParser.AreEqual(resultRowLink.InnerHtml, address))
                            {
                                continue;
                            }
                            redirectUrl = resultRowLink.Attributes["href"].Value;
                            break;
                        }
                    }
                }

                if (document2 == null && string.IsNullOrEmpty(redirectUrl))
                {
                    _logger.LogError("Did not find expected redirect URL or was not automatically redirected: {address}", address);
                    propertyInfo.Error = "Did not find expected redirect URL.";
                    return(propertyInfo);
                }

                // The redurectUrl is a relative path, so we have to add the rootUrl to it before making another request.
                document2 = document2 ?? webGet.Load(string.Concat(_settings.Url, redirectUrl.Replace("#038;", "&")));

                var returnedAddressTag = document2.DocumentNode.SelectSingleNode("// div[@id='primary']/div/h1");
                if (returnedAddressTag == null)
                {
                    _logger.LogError("Could not find <h1> tag containing address: {address}", address);
                    propertyInfo.Error = "Could not find <h1> tag containing address.";
                    return(propertyInfo);
                }

                var returnedAddress = returnedAddressTag.InnerHtml;

                if (!await _addressParser.AreEqual(returnedAddress, address))
                {
                    _logger.LogInformation("PVA returned differenct address than searched: (original) {address} (returned) {returnedAddress}", address, returnedAddress);
                    propertyInfo.Error = "PVA returned different address than searched.";
                    return(propertyInfo);
                }

                var ownerLabelDt = document2.DocumentNode.Descendants().FirstOrDefault(tag => tag.Name == "dt" && tag.InnerHtml == "Owner");

                if (ownerLabelDt == null)
                {
                    _logger.LogError("Could not find <dt> tag containing string \"Owner\": {address}", address);
                    propertyInfo.Error = "Could not find <dt> tag containing string \"Owner\".";
                    return(propertyInfo);
                }

                var ownerNames = ownerLabelDt.NextSibling.NextSibling.InnerHtml.Trim();

                if (string.IsNullOrEmpty(ownerNames))
                {
                    _logger.LogInformation("Could not find owner in document or owner was empty: {address}", address);
                    propertyInfo.Error = "Could not find owner in document or owner was empty.";
                    return(propertyInfo);
                }

                propertyInfo.Address.Owner = HttpUtility.HtmlDecode(ownerNames);

                var assessedValueLabelDt = document2.DocumentNode.Descendants().FirstOrDefault(tag => tag.Name == "dt" && tag.InnerHtml == "Assessed Value");

                if (assessedValueLabelDt == null)
                {
                    _logger.LogError("Could not find <dt> tag containing string \"Assessed Value\": {address}", address);
                }
                else
                {
                    if (int.TryParse(HttpUtility.HtmlDecode(assessedValueLabelDt.NextSibling.NextSibling.InnerHtml.Trim().Replace(",", "")), out var iAssessedValue))
                    {
                        propertyInfo.Address.AssessedValue = iAssessedValue;
                    }
                }

                var acreageLabelDt = document2.DocumentNode.Descendants().FirstOrDefault(tag => tag.Name == "dt" && tag.InnerHtml == "Acres");

                if (acreageLabelDt == null)
                {
                    _logger.LogError("Could not find <dt> tag containing string \"Acres\": {address}", address);
                }
                else
                {
                    if (double.TryParse(HttpUtility.HtmlDecode(acreageLabelDt.NextSibling.NextSibling.InnerHtml.Trim()), out var dAcres))
                    {
                        propertyInfo.Address.Acreage = dAcres;
                    }
                }
            }
            catch (Exception ex)
            {
                propertyInfo.Error = ex.ToString();
            }

            if (savedAddress == null)
            {
                savedAddress = new AddressModel
                {
                    Id = await _addressRepository.Add(bestParsing.Address.Number, bestParsing.Address.Direction, bestParsing.Address.Street, bestParsing.Address.Tag)
                };
            }

            await _addressRepository.AddAttributes(savedAddress.Id.Value, new List <AddressAttributeModel> {
                new AddressAttributeModel {
                    Source = "PVA", Name = "owner", Value = propertyInfo.Address.Owner
                },
                new AddressAttributeModel {
                    Source = "PVA", Name = "assessedvalue", Value = propertyInfo.Address.AssessedValue.ToString()
                },
                new AddressAttributeModel {
                    Source = "PVA", Name = "acreage", Value = propertyInfo.Address.Acreage.ToString()
                }
            });

            return(propertyInfo);
        }
        /// <summary>
        /// Prepare shipping address model
        /// </summary>
        /// <param name="selectedCountryId">Selected country identifier</param>
        /// <param name="prePopulateNewAddressWithCustomerFields">Pre populate new address with customer fields</param>
        /// <param name="overrideAttributesXml">Override attributes xml</param>
        /// <returns>Shipping address model</returns>
        public virtual CheckoutShippingAddressModel PrepareShippingAddressModel(int?selectedCountryId = null,
                                                                                bool prePopulateNewAddressWithCustomerFields = false, string overrideAttributesXml = "")
        {
            var model = new CheckoutShippingAddressModel
            {
                //allow pickup in store?
                AllowPickUpInStore = _shippingSettings.AllowPickUpInStore
            };

            if (model.AllowPickUpInStore)
            {
                model.DisplayPickupPointsOnMap = _shippingSettings.DisplayPickupPointsOnMap;
                model.GoogleMapsApiKey         = _shippingSettings.GoogleMapsApiKey;
                var pickupPointProviders = _shippingService.LoadActivePickupPointProviders(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id);
                if (pickupPointProviders.Any())
                {
                    var languageId           = _workContext.WorkingLanguage.Id;
                    var pickupPointsResponse = _shippingService.GetPickupPoints(_workContext.CurrentCustomer.BillingAddress,
                                                                                _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id);
                    if (pickupPointsResponse.Success)
                    {
                        model.PickupPoints = pickupPointsResponse.PickupPoints.Select(point =>
                        {
                            var country = _countryService.GetCountryByTwoLetterIsoCode(point.CountryCode);
                            var state   = _stateProvinceService.GetStateProvinceByAbbreviation(point.StateAbbreviation, country?.Id);

                            var pickupPointModel = new CheckoutPickupPointModel
                            {
                                Id                 = point.Id,
                                Name               = point.Name,
                                Description        = point.Description,
                                ProviderSystemName = point.ProviderSystemName,
                                Address            = point.Address,
                                City               = point.City,
                                County             = point.County,
                                StateName          = state != null ? _localizationService.GetLocalized(state, x => x.Name, languageId) : string.Empty,
                                CountryName        = country != null ? _localizationService.GetLocalized(country, x => x.Name, languageId) : string.Empty,
                                ZipPostalCode      = point.ZipPostalCode,
                                Latitude           = point.Latitude,
                                Longitude          = point.Longitude,
                                OpeningHours       = point.OpeningHours
                            };
                            if (point.PickupFee > 0)
                            {
                                var amount = _taxService.GetShippingPrice(point.PickupFee, _workContext.CurrentCustomer);
                                amount     = _currencyService.ConvertFromPrimaryStoreCurrency(amount, _workContext.WorkingCurrency);
                                pickupPointModel.PickupFee = _priceFormatter.FormatShippingPrice(amount, true);
                            }

                            return(pickupPointModel);
                        }).ToList();
                    }
                    else
                    {
                        foreach (var error in pickupPointsResponse.Errors)
                        {
                            model.Warnings.Add(error);
                        }
                    }
                }

                //only available pickup points
                if (!_shippingService.LoadActiveShippingRateComputationMethods(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id).Any())
                {
                    if (!pickupPointProviders.Any())
                    {
                        model.Warnings.Add(_localizationService.GetResource("Checkout.ShippingIsNotAllowed"));
                        model.Warnings.Add(_localizationService.GetResource("Checkout.PickupPoints.NotAvailable"));
                    }
                    model.PickUpInStoreOnly = true;
                    model.PickUpInStore     = true;
                    return(model);
                }
            }

            //existing addresses
            var addresses = _workContext.CurrentCustomer.Addresses
                            .Where(a => a.Country == null ||
                                   (//published
                                       a.Country.Published &&
                                       //allow shipping
                                       a.Country.AllowsShipping &&
                                       //enabled for the current store
                                       _storeMappingService.Authorize(a.Country)))
                            .ToList();

            foreach (var address in addresses)
            {
                var addressModel = new AddressModel();
                _addressModelFactory.PrepareAddressModel(addressModel,
                                                         address: address,
                                                         excludeProperties: false,
                                                         addressSettings: _addressSettings);
                model.ExistingAddresses.Add(addressModel);
            }

            //new address
            model.ShippingNewAddress.CountryId = selectedCountryId;
            _addressModelFactory.PrepareAddressModel(model.ShippingNewAddress,
                                                     address: null,
                                                     excludeProperties: false,
                                                     addressSettings: _addressSettings,
                                                     loadCountries: () => _countryService.GetAllCountriesForShipping(_workContext.WorkingLanguage.Id),
                                                     prePopulateWithCustomerFields: prePopulateNewAddressWithCustomerFields,
                                                     customer: _workContext.CurrentCustomer,
                                                     overrideAttributesXml: overrideAttributesXml);

            return(model);
        }
        ///// <summary>
        ///// Sets the home h link.
        ///// </summary>
        ///// <param name="argBaseHLink">
        ///// The home image h link.
        ///// </param>
        ///// <param name="argNewHLink">
        ///// The hlink.
        ///// </param>
        ///// <returns>
        ///// Updatded HomeImageLink
        ///// </returns>
        //private static HLinkHomeImageModel SetHomeHLink(HLinkHomeImageModel argBaseHLink, HLinkHomeImageModel argNewHLink)
        //{
        //    HLinkHomeImageModel returnHLink = argBaseHLink;

        // returnHLink.HLinkKey = argNewHLink.HLinkKey; returnHLink.HomeImageType =
        // argNewHLink.HomeImageType; returnHLink.HomeSymbol = argNewHLink.HomeSymbol;

        //    return returnHLink;
        //}

        private OCAddressModelCollection GetAddressCollection(XElement xmlData)
        {
            OCAddressModelCollection t = new OCAddressModelCollection();

            // Get colour
            Application.Current.Resources.TryGetValue("CardBackGroundAddress", out var varCardColour);
            Color cardColour = (Color)varCardColour;

            // Run query
            var theERElement =
                from orElementEl
                in xmlData.Elements(ns + "address")
                select orElementEl;

            if (theERElement.Any())
            {
                // Load address object references
                foreach (XElement theLoadORElement in theERElement)
                {
                    AddressModel newAddressModel = new AddressModel
                    {
                        Handle = "AddressCollection",

                        GCitationRefCollection = GetCitationCollection(theLoadORElement),

                        GCity = GetElement(theLoadORElement, "city"),

                        GCountry = GetElement(theLoadORElement, "country"),

                        GCounty = GetElement(theLoadORElement, "county"),

                        GDate = GetDate(theLoadORElement),

                        GLocality = GetElement(theLoadORElement, "locality"),

                        GPhone = GetElement(theLoadORElement, "phone"),

                        GPostal = GetElement(theLoadORElement, "postal"),

                        GState = GetElement(theLoadORElement, "state"),

                        GStreet = GetElement(theLoadORElement, "street"),

                        Priv = SetPrivateObject(GetAttribute(theLoadORElement.Attribute("priv"))),

                        GNoteRefCollection = GetNoteCollection(theLoadORElement),
                    };

                    // set the Home image or symbol
                    newAddressModel.HomeImageHLink.HomeImageType    = CommonConstants.HomeImageTypeSymbol;
                    newAddressModel.HomeImageHLink.HomeSymbol       = CommonConstants.IconAddress;
                    newAddressModel.HomeImageHLink.HomeSymbolColour = cardColour;

                    t.Add(newAddressModel);
                }

                t.Sort(x => x.GDate.SortDate);
            }

            return(t);
        }