protected void Page_Load(object sender, EventArgs e)
    {
        currentSiteId = CMSContext.CurrentSiteID;

        customerObj = EditedObject as CustomerInfo;

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            EditedObject = null;
        }

        customerEdit.Customer = customerObj;
        customerEdit.OnSaved += new EventHandler(customerEdit_OnSaved);

        if (customerObj != null)
        {
            // Show that the customer was created or updated successfully
            if (!RequestHelper.IsPostBack() && (QueryHelper.GetString("saved", "") == "1"))
            {
                // Show message
                ShowChangesSaved();
            }
        }
    }
        public void InsertCustomer(CustomerInfo customerInfo)
        {
            using (
                var connection =
                    new SqlConnection("DataSource=(local);Initial Catalog=CustomerDatabase;Integrated Security=True"))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    var command = connection.CreateCommand();
                    command.Transaction = transaction;
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "dbo.usp_InsertCustomer";
                    command.Parameters.AddWithValue("@FirstName", customerInfo.FirstName);
                    command.Parameters.AddWithValue("@LastName", customerInfo.LastName);
                    command.Parameters.AddWithValue("@Email", customerInfo.Email);
                    command.ExecuteNonQuery();

                    transaction.Commit();
                }
                connection.Close();
            }

            _logger.LogInfo("User inserted successfully");
        }
        public bool IsCustomerValid(CustomerInfo customerInfo)
        {
            if (customerInfo.FirstName == null)
            {
                _logger.LogError("Error: First Name is required");
                return false;
            }

            if (customerInfo.LastName == null)
            {
                _logger.LogError("Error: Last Name is required");
                return false;
            }

            if (customerInfo.Email == null)
            {
                _logger.LogError("Error: Email is required");
                return false;
            }

            var isEmail = Regex.IsMatch(customerInfo.Email,
                EmailPattern,
                RegexOptions.IgnoreCase);

            if (!isEmail)
            {
                _logger.LogError("Error: Email is not valid");
                return false;
            }

            _logger.LogInfo("Validation passed successfully");

            return true;
        }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Customers.CustomFields"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Customers.CustomFields");
        }

        // Set edit mode
        customerId = QueryHelper.GetInteger("customerId", 0);
        if (customerId > 0)
        {
            customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);
            // Check if customer belongs to current site
            if (!CheckCustomerSiteID(customerObj))
            {
                customerObj = null;
            }

            EditedObject = customerObj;
            formCustomerCustomFields.Info = customerObj;
            formCustomerCustomFields.OnBeforeSave += formCustomerCustomFields_OnBeforeSave;
            formCustomerCustomFields.OnAfterSave += formCustomerCustomFields_OnAfterSave;
        }
        else
        {
            formCustomerCustomFields.Enabled = false;
        }
    }
    /// <summary>
    /// Returns true if customer is anonymous on current site or has login on current site.
    /// </summary>
    /// <param name="customer">Customer object</param>
    protected bool CheckCustomerSiteID(CustomerInfo customer)
    {
        if (customer == null)
        {
            return false;
        }

        int currentSiteId = CMSContext.CurrentSiteID;

        if (customer.CustomerSiteID == currentSiteId)
        {
            return true;
        }

        if ((customer.CustomerUserID > 0) && (UserSiteInfoProvider.GetUserSiteInfo(customer.CustomerUserID, currentSiteId) != null))
        {
            return true;
        }

        if (CurrentUser.IsGlobalAdministrator && (customer.CustomerUserID == 0) && (customer.CustomerSiteID == 0))
        {
            return true;
        }

        return false;
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Set edit mode
        customerId = QueryHelper.GetInteger("customerId", 0);
        if (customerId > 0)
        {
            customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);
            // Check if customer belongs to current site
            if (!CheckCustomerSiteID(customerObj))
            {
                customerObj = null;
            }

            EditedObject = customerObj;
            formCustomerCustomFields.Info = customerObj;
            formCustomerCustomFields.OnAfterValidate += formCustomerCustomFields_OnAfterValidate;
            formCustomerCustomFields.OnAfterSave += formCustomerCustomFields_OnAfterSave;
        }
        else
        {
            formCustomerCustomFields.Enabled = false;
        }
    }
    protected void btnOK_Click(Object sender, EventArgs e)
    {
        string strCustomer = txtCustomer.Text;
        string strPlant = txtPlant.Text;
        string strCode = txtCode.Text;
        string strDescr = txtDescr.Text;
        CustomerInfo customerInfo = new CustomerInfo();
        try
        {
            customerInfo.customer = strCustomer;
            customerInfo.Code = strCode;
            customerInfo.Plant = strPlant;
            customerInfo.Description = strDescr;


            iCustomer.AddCustomer(customerInfo);
        }
        catch (FisException ex)
        {
            showErrorMessage(ex.mErrmsg);
            return;
        }
        catch (Exception ex)
        {
            //show error
            showErrorMessage(ex.Message);
            return;
        }

        ScriptManager.RegisterStartupScript(this.updatePanel1, typeof(System.Object), "close", "onOk();", true);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Customers.Addresses"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Customers.Addresses");
        }

        customerId = QueryHelper.GetInteger("customerId", 0);
        customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            customerObj = null;
        }

        EditedObject = customerObj;

        UniGrid.OnAction += new OnActionEventHandler(uniGrid_OnAction);
        UniGrid.OnExternalDataBound += new OnExternalDataBoundEventHandler(UniGrid_OnExternalDataBound);
        UniGrid.WhereCondition = "AddressCustomerID = " + customerId;

        // Intialize the master page elements
        InitializeMasterPage();
    }
        public void CreateRegistration(
            RegistrationId i, 
            RegistrationInfo info, 
            IDomainIdentityService ids,
            IUserIndexService uniqueness, 
            PasswordGenerator generator)
        {
            var problems = new List<string>();
            // we do all the checks at registration phase 
            if (uniqueness.IsLoginRegistered(info.ContactEmail))
            {
                problems.Add(string.Format("Email '{0}' is already taken.", info.ContactEmail));
            }

            if (!string.IsNullOrEmpty(info.OptionalUserIdentity))
            {
                if (uniqueness.IsIdentityRegistered(info.OptionalUserIdentity))
                {
                    problems.Add(string.Format("Identity '{0}' is already taken.", info.OptionalUserIdentity));
                }
            }

            var userDisplay = info.OptionalUserDisplay;
            if (string.IsNullOrEmpty(userDisplay))
            {
                userDisplay = string.Format("{0}", info.CustomerName);
            }

            var password = info.OptionalUserPassword;
            if (string.IsNullOrEmpty(password))
            {
                password = generator.CreatePassword(6);
            }
            // TODO: we are checking contact uniqueness, but can use user name
            var login = info.ContactEmail;
            if (string.IsNullOrEmpty(login))
            {
                login = info.ContactEmail;
            }


            
            if (problems.Any())
            {
                Apply(new RegistrationFailed(i, info, problems.ToArray()));
                return;
            }
            var id = ids.GetId();

            var host = info.Headers.FirstOrDefault(h => h.Key == "UserHostAddress");
            

            var security = new SecurityInfo(new SecurityId(id), login, password, userDisplay, info.OptionalUserIdentity);
            var customer = new CustomerInfo(new CustomerId(id), info.CustomerName, userDisplay, info.ContactEmail,
                info.OptionalCompanyPhone, info.OptionalCompanyUrl);

            Apply(new RegistrationCreated(i, info.CreatedUtc, customer, security));
            // if no problems
        }
        public void CreateCustomer(CustomerInfo customerInfo)
        {
            //FYI: Validation check.
            if (!_customerValidation.IsCustomerValid(customerInfo)) return;

            //FYI: Insert user to db.
            _customerStorage.InsertCustomer(customerInfo);

            //FYI: Send notification.
            _notificationService.SendNotification(customerInfo);
        }
        public JsonResult CustomerList()
        {
            List<CustomerInfo> listCustomer = new List<CustomerInfo>();

            for (int i = 1; i < 280; i++)
            {
                CustomerInfo cusInfo = new CustomerInfo();
                cusInfo.Id = Guid.NewGuid().ToString("N").ToUpper();
                cusInfo.CustomerNo = string.Format("000{0}",i.ToString ());
                cusInfo.ShortName = string.Format("中天广告传媒{0}", i);
                cusInfo.CustomerType = 4;
                cusInfo.CreateTime = DateTime.Now;
                cusInfo.ReceiptType = "发票";
                cusInfo.Creator = "张三";
                cusInfo.BusinessLicNo = string.Format("N093827{0}", i);
                cusInfo.OpenBank = "中国银行";
                cusInfo.Status = "1";

                listCustomer.Add(cusInfo);
            }

            var page = GetPageIndex();
            var rows = GetPageSize();

            var data = (from u in listCustomer
                        orderby u.CreateTime
                        select new {u.Id, u.CustomerNo, u.ShortName, u.CustomerType, u.CreateTime, u.ReceiptType, u.Creator, u.BusinessLicNo, u.OpenBank, u.Status }
                       ).Skip((page - 1) * rows)
                       .Take(rows);

            //var result = new { total = listCustomer.Count(), rows = data };
            //return Json(result, JsonRequestBehavior.AllowGet);

            var a = Json(new
            {
                total = listCustomer.Count(),
                rows = data.Select(u => new
                {
                    CustomerNo = u.CustomerNo,
                    ShortName = u.ShortName,
                    CustomerType = u.CustomerType,
                    CreateTime = u.CreateTime,
                    ReceiptType = u.ReceiptType,
                    Creator = u.Creator,
                    BusinessLicNo = u.BusinessLicNo,
                    OpenBank = u.OpenBank,
                    Status = u.Status,
                    Actions = "<a href=\"javascript:checkUser('" + u.Id + "')\">查看</a>",
                })
            }, JsonRequestBehavior.AllowGet);

            return a;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Customers.Credit"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Customers.Credit");
        }

        // Get site id of credits main currency
        creditCurrencySiteId = ECommerceHelper.GetSiteID(CMSContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

        // Get currency in which credit is expressed in
        currency = CurrencyInfoProvider.GetMainCurrency(creditCurrencySiteId);

        // Get customerId from url
        customerId = QueryHelper.GetInteger("customerid", 0);

        // Load customer info
        customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            customerObj = null;
        }

        // Check, if edited customer exists
        EditedObject = customerObj;

        // Init unigrid
        UniGrid.HideControlForZeroRows = true;
        UniGrid.OnAction += new OnActionEventHandler(uniGrid_OnAction);
        UniGrid.OnExternalDataBound += new OnExternalDataBoundEventHandler(UniGrid_OnExternalDataBound);
        UniGrid.OrderBy = "EventDate DESC, EventName ASC";
        UniGrid.WhereCondition = "EventCustomerID = " + customerId + " AND ISNULL(EventSiteID, 0) = " + creditCurrencySiteId;

        if (customerObj != null)
        {
            InitializeMasterPage();

            // Configuring global records
            if (creditCurrencySiteId == 0)
            {
                // Show "using global settings" info message only if showing global store settings
                lblGlobalInfo.Visible = true;
                lblGlobalInfo.Text = GetString("com.UsingGlobalSettings");
            }

            // Display customer total credit
            lblCredit.Text = GetString("CreditEvent_List.TotalCredit");
            lblCreditValue.Text = GetFormatedTotalCredit();
        }
    }
        public ViewResult Customer(CustomerInfo model, string next)
        {
            if (next != null)
                if (ModelState.IsValid)
                {
                    var cacheInfo = GetUserInfo();
                    cacheInfo.CustomerInfo = model;

                    return View("~/Views/Wizards/EditUserInfo/Address.cshtml", cacheInfo.AddressInfo);
                }

            return View("~/Views/Wizards/EditUserInfo/Customer.cshtml");
        }
 public void Apply(TimeAndMaterialJobOrderRegisteredEvent evt)
 {
     Id = evt.JobOrderId;
     Customer = new CustomerInfo(evt.CustomerId, evt.CustomerName);
     Manager = new ManagerInfo(evt.ManagerId, evt.ManagerName);
     Value = new PositiveMoney(evt.Value, evt.Currency);
     DateOfStart = evt.DateOfStart;
     DateOfExpiration = evt.DateOfExpiration;
     Name = evt.JobOrderName;
     Number = evt.JobOrderNumber; 
     IsCompleted = false;
     PurchaseOrderNumber = evt.PurchaseOrderNumber;
     Description = evt.Description;
 }
Beispiel #15
0
 public void Apply(FixedPriceJobOrderRegisteredEvent evt)
 {
     Id = evt.JobOrderId;
     Customer = new CustomerInfo(evt.CustomerId, evt.CustomerName);
     Manager = new ManagerInfo(evt.ManagerId, evt.ManagerName);
     Price = new PositiveMoney(evt.Price, evt.Currency);
     DateOfStart= evt.DateOfStart;
     DueDate=evt.DueDate;
     Name = evt.JobOrderName;
     Number = evt.JobOrderNumber; 
     IsCompleted = false;
     PurchaseOrderNumber = evt.PurchaseOrderNumber;
     Description = evt.Description;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get site id of credits main currency
        creditCurrencySiteId = ECommerceHelper.GetSiteID(SiteContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

        // Get currency in which credit is expressed in
        currency = CurrencyInfoProvider.GetMainCurrency(creditCurrencySiteId);

        // Get customerId from url
        customerId = QueryHelper.GetInteger("customerid", 0);

        // Load customer info
        customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            customerObj = null;
        }

        // Check, if edited customer exists
        EditedObject = customerObj;

        // Init unigrid
        UniGrid.HideControlForZeroRows = true;
        UniGrid.OnAction += uniGrid_OnAction;
        UniGrid.OnExternalDataBound += UniGrid_OnExternalDataBound;
        UniGrid.OrderBy = "EventDate DESC, EventName ASC";
        UniGrid.WhereCondition = "EventCustomerID = " + customerId + " AND ISNULL(EventSiteID, 0) = " + creditCurrencySiteId;

        if (customerObj != null)
        {
            InitializeMasterPage();

            // Configuring global credit
            if (creditCurrencySiteId == 0)
            {
                var site = SiteContext.CurrentSite;
                if (site != null)
                {
                    // Show "using global credit" info message
                    ShowInformation(string.Format(GetString("com.UsingGlobalSettings"), site.DisplayName, GetString("com.ui.creditevents")));
                }
            }

            // Display customer total credit
            headTotalCredit.Text = string.Format(GetString("CreditEvent_List.TotalCredit"), GetFormattedTotalCredit());
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        customerObj = EditedObject as CustomerInfo;

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            EditedObject = null;
        }

        if (customerObj != null)
        {
            UniGrid.OnAction += uniGrid_OnAction;
            UniGrid.WhereCondition = "AddressCustomerID = " + customerObj.CustomerID;
        }
    }
    /// <summary>
    /// Load data.
    /// </summary>
    public void LoadDataSelectors(CustomerInfo customerObj)
    {
        // Set site id of the edited object to selectors
        drpCurrency.SiteID = currentSiteId;
        drpPayment.SiteID = currentSiteId;
        drpShipping.SiteID = currentSiteId;
        drpGlobalDiscountLevel.SiteID = 0;
        drpDiscountLevel.SiteID = currentSiteId;

        if (!URLHelper.IsPostback())
        {
            int currencyId = (customerObj.CustomerUser != null) ? customerObj.CustomerUser.GetUserPreferredCurrencyID(CurrentSiteName) : 0;
            currencyId = (currencyId > 0) ? currencyId : customerObj.CustomerPreferredCurrencyID;
            if (currencyId > 0)
            {
                drpCurrency.CurrencyID = currencyId;
            }

            int paymentId = (customerObj.CustomerUser != null) ? customerObj.CustomerUser.GetUserPreferredPaymentOptionID(CurrentSiteName) : 0;
            paymentId = (paymentId > 0) ? paymentId : customerObj.CustomerPreferredPaymentOptionID;
            if (paymentId > 0)
            {
                drpPayment.PaymentID = paymentId;
            }

            int shippingId = (customerObj.CustomerUser != null) ? customerObj.CustomerUser.GetUserPreferredShippingOptionID(CurrentSiteName) : 0;
            shippingId = (shippingId > 0) ? shippingId : customerObj.CustomerPreferredShippingOptionID;
            if (shippingId > 0)
            {
                drpShipping.ShippingID = shippingId;
            }

            if (customerObj.CustomerDiscountLevelID > 0)
            {
                drpGlobalDiscountLevel.DiscountLevel = customerObj.CustomerDiscountLevelID;
            }
            int siteDiscountId = (customerObj.CustomerUser != null) ? customerObj.CustomerUser.GetUserDiscountLevelID(CurrentSiteName) : 0;
            if (siteDiscountId > 0)
            {
                drpDiscountLevel.DiscountLevel = siteDiscountId;
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        customerId = QueryHelper.GetInteger("customerId", 0);
        customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            customerObj = null;
        }

        EditedObject = customerObj;

        UniGrid.OnAction += new OnActionEventHandler(uniGrid_OnAction);
        UniGrid.OnExternalDataBound += new OnExternalDataBoundEventHandler(UniGrid_OnExternalDataBound);
        UniGrid.WhereCondition = "AddressCustomerID = " + customerId;

        // Intialize the master page elements
        InitializeMasterPage();
    }
Beispiel #20
0
 public IssueInvoiceCommand(DateTime invoiceDate, decimal amount, decimal taxes, decimal totalPrice, string description, string paymentTerms, string purchaseOrderNumber, Guid customerId, string customerName, string streetName, string city, string postalCode, string country, string vatIndex, string nationalIdentificationNumber)
 {
     var customer = new CustomerInfo(
         city: city,
         customerName: customerName,
         country: country,
         customerId: customerId,
         nationalIdentificationNumber: nationalIdentificationNumber,
         postalCode: postalCode,
         streetName: streetName,
         vatIndex: vatIndex
     );
     Customer = customer;
     InvoiceDate = invoiceDate;
     Amount = amount;
     Taxes = taxes;
     TotalPrice = totalPrice;
     Description = description;
     PaymentTerms = paymentTerms;
     PurchaseOrderNumber = purchaseOrderNumber;
 }
Beispiel #21
0
        /// <summary>
        /// 新增开户记录
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="device"></param>
        /// <param name="recordId"></param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public bool AddOpenAccountRecord(CustomerInfo customer, DeviceInfo device, out int recordId, SqlConnection conn, SqlTransaction tran)
        {
            recordId = 0;
            OpenAccountRecord model = new OpenAccountRecord
            {
                customerNo   = customer.customerNo,
                customerType = customer.customerType,
                customerName = customer.customerName,
                estateNo     = customer.estateNo,
                address      = customer.address,

                meterNo     = device.meterNo.ToString(),
                meterTypeNo = device.meterTypeNo,
                factoryNo   = device.factoryNo,

                Opentime = DateTime.Now,
                OpenType = 0
            };

            recordId = Add(model, conn, tran);
            return(true);
        }
Beispiel #22
0
        private void SetCustomerInfo()
        {
            Android.Telephony.TelephonyManager mTelephonyMgr;
            mTelephonyMgr = (Android.Telephony.TelephonyManager)GetSystemService(TelephonyService);
            CustomerDeviceInfo deviceInfo = new CustomerDeviceInfo()
            {
                DeviceSetPhoneNumber = Decimal.TryParse(mTelephonyMgr.Line1Number, out decimal num) ? num : 0,
                DeviceNumber         = mTelephonyMgr.DeviceId,
                DeviceModel          = Xamarin.Essentials.DeviceInfo.Model,
                DeviceName           = Xamarin.Essentials.DeviceInfo.Name,
                DeviceVersion        = Xamarin.Essentials.DeviceInfo.VersionString,
                DeviceType           = Convert.ToInt16(Xamarin.Essentials.DeviceInfo.DeviceType)
            };

            customerInfo = new CustomerInfo()
            {
                CustomerMobileNumber = Convert.ToDecimal(phoneText.EditText.Text),
                CustomerName         = fullNameText.EditText.Text,
                CustomerEmail        = emailText.EditText.Text,
                DeviceInfo           = deviceInfo
            };
        }
        protected virtual IMutablePagedList <CustomerOrder> GetCustomerOrders(CustomerInfo customer)
        {
            var workContext         = _workContextFactory();
            var orderSearchcriteria = new orderDto.CustomerOrderSearchCriteria
            {
                CustomerId    = customer.Id,
                ResponseGroup = "full"
            };

            Func <int, int, IEnumerable <SortInfo>, IPagedList <CustomerOrder> > ordersGetter = (pageNumber, pageSize, sortInfos) =>
            {
                //TODO: add caching
                orderSearchcriteria.Skip = (pageNumber - 1) * pageSize;
                orderSearchcriteria.Take = pageSize;
                var cacheKey       = "GetCustomerOrders-" + orderSearchcriteria.GetHashCode();
                var ordersResponse = _cacheManager.Get(cacheKey, string.Format(_customerOrdersCacheRegionFormat, customer.Id), () => _orderApi.OrderModule.Search(orderSearchcriteria));
                return(new StaticPagedList <CustomerOrder>(ordersResponse.CustomerOrders.Select(x => x.ToCustomerOrder(workContext.AllCurrencies, workContext.CurrentLanguage)), pageNumber, pageSize,
                                                           ordersResponse.TotalCount.Value));
            };

            return(new MutablePagedList <CustomerOrder>(ordersGetter, 1, OrderSearchCriteria.DefaultPageSize));
        }
Beispiel #24
0
        public IList <CustomerInfo> GetList()
        {
            StringBuilder sb = new StringBuilder(300);

            sb.Append(@"select Id,UserId,Coded,Named,ShortName,ContactMan,Email,Phone,TelPhone,Fax,Postcode,Address,Remark,LastUpdatedDate 
			            from Customer
					    order by LastUpdatedDate desc "                    );

            IList <CustomerInfo> list = new List <CustomerInfo>();

            using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString()))
            {
                if (reader != null && reader.HasRows)
                {
                    while (reader.Read())
                    {
                        CustomerInfo model = new CustomerInfo();
                        model.Id              = reader.GetGuid(0);
                        model.UserId          = reader.GetGuid(1);
                        model.Coded           = reader.GetString(2);
                        model.Named           = reader.GetString(3);
                        model.ShortName       = reader.GetString(4);
                        model.ContactMan      = reader.GetString(5);
                        model.Email           = reader.GetString(6);
                        model.Phone           = reader.GetString(7);
                        model.TelPhone        = reader.GetString(8);
                        model.Fax             = reader.GetString(9);
                        model.Postcode        = reader.GetString(10);
                        model.Address         = reader.GetString(11);
                        model.Remark          = reader.GetString(12);
                        model.LastUpdatedDate = reader.GetDateTime(13);

                        list.Add(model);
                    }
                }
            }

            return(list);
        }
        public UserInformation GetUserDetail(LoginForm loginForm)
        {
            UserInformation userInformation = null;

            CustomerInfo customerInfo = context.CustomerInfo.FirstOrDefault(
                x => x.Phone.Equals(loginForm.UserName, StringComparison.OrdinalIgnoreCase) &&
                x.Password.Equals(loginForm.Password));

            if (customerInfo != null)
            {
                userInformation = new UserInformation()
                {
                    UserId       = customerInfo.Id,
                    City         = customerInfo.City,
                    CustomerName = customerInfo.CustomerName,
                    FirstName    = customerInfo.FirstName,
                    LastName     = customerInfo.LastName,
                    Phone        = customerInfo.Phone
                };
            }
            return(userInformation);
        }
Beispiel #26
0
        public virtual coreDto.Contact ToCoreContactDto(CustomerInfo customer)
        {
            var retVal = new coreDto.Contact();

            retVal.InjectFrom <NullableAndEnumValueInjecter>(customer);

            if (customer.UserGroups != null)
            {
                retVal.Groups = customer.UserGroups.ToArray();
            }
            if (customer.Addresses != null)
            {
                retVal.Addresses = customer.Addresses.Select(x => x.ToCoreAddressDto()).ToList();
            }
            if (!string.IsNullOrEmpty(customer.Email))
            {
                retVal.Emails = new[] { customer.Email }.ToList();
            }
            retVal.FullName = customer.FullName;

            return(retVal);
        }
        public CustomerInfo getCustomerInfo(string customerId)
        {
            CustomerInfo customerInfo = new CustomerInfo();

            if (customerId != string.Empty)
            {
                MySqlParameter  paraId          = new MySqlParameter("@paraId", customerId);
                string          sql             = "select unit_name,address,responsible_user_name,tel,fax,email from customer where id = @paraId";
                MySqlDataReader mySqlDataReader = MySqlHelper.ExecuteReader(MySqlHelper.conn, CommandType.Text, sql, paraId);
                if (mySqlDataReader.Read())
                {
                    customerInfo.unitName            = (string)mySqlDataReader["unit_name"];
                    customerInfo.address             = (string)mySqlDataReader["address"];
                    customerInfo.responsibleUserName = (string)mySqlDataReader["responsible_user_name"];
                    customerInfo.tel   = (string)mySqlDataReader["tel"];
                    customerInfo.fax   = (string)mySqlDataReader["fax"];
                    customerInfo.email = (string)mySqlDataReader["email"];
                }
                mySqlDataReader.Close();
            }
            return(customerInfo);
        }
Beispiel #28
0
        public ActionResult SearchResults(string id, string firstName, string lastName)
        {
            Int32 idStrong            = id.TryParseInt32();
            CustomerSearchModel model = new CustomerSearchModel()
            {
                ID = idStrong, FirstName = firstName, LastName = lastName
            };
            IQueryable <CustomerInfo> searchResults;

            ModelState.Clear();
            searchResults = CustomerInfo.GetByAny(model).Take(25);
            if (searchResults.Any() == true)
            {
                model.Results.FillRange(searchResults);
            }
            else
            {
                ModelState.AddModelError("Result", "0 matches found");
            }

            return(PartialView(CustomerSearchController.SearchResultsView, model.Results)); // Return partial view for client-side to render
        }
Beispiel #29
0
        public ActionResult Submit(CustomerInfo model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.Serialized = null;
                    CustInfoSerializerFactory serializationFactory = new ConcreteCustInfoSerializerFactory();
                    string      serializeTo = model.SerializeDirection.ToString();
                    ISerializer direction   = serializationFactory.GetSerializer(serializeTo);
                    string      result      = direction.Serialize(model);
                    model.Serialized = result;
                    ModelState.Clear();
                }
                catch (Exception ex)
                {
                    TempData["ErrorMsg"] = ex.Message;
                }
            }

            return(View("Index", model));
        }
    private void addressForm_OnAfterDataLoad(object sender, EventArgs e)
    {
        if (!ViewMode.IsLiveSite())
        {
            // Suppress form validation on Check-in/Check-out actions
            addressForm.StopProcessing = true;

            return;
        }

        CustomerInfo customer = ShoppingCart.Customer;
        AddressInfo  address  = addressForm.EditedObject as AddressInfo;

        // Preset personal name filed for new address and logged in user
        if ((customer != null) && (address != null) && (address.AddressID == 0) && string.IsNullOrEmpty(address.AddressPersonalName))
        {
            address.AddressPersonalName = $"{customer.CustomerFirstName} {customer.CustomerLastName}".Trim();
        }

        if (PropagateChangesOnPostback)
        {
            // Propagate changes on postback if there is address info in UIForm
            if (((CurrentCartAddress != null) || (address != null)) &&
                RequestHelper.IsPostBack())
            {
                // Set first time user current address for postback tax recalculation
                if (CurrentCartAddress == null)
                {
                    CurrentCartAddress = address;
                }

                var formControl = addressForm.FieldControls["AddressCountryID"];
                if (formControl != null)
                {
                    formControl.Changed += CountrySelector_Changed;
                }
            }
        }
    }
Beispiel #31
0
        public async Task GetOrderDetailsByCustomerInfoAsync_ShouldThrow_ECommerceValidationException_404_When_UserService_ReturnsNull()
        {
            var customerInfo = new CustomerInfo()
            {
                CustomerId = "Customer123", User = "******"
            };

            _userServiceMock.Setup(u => u.GetCustomerAsync(customerInfo.User))
            .Returns(Task.FromResult <Customer>(null));

            _orderRepositoryMock.Setup(o => o.GetOrderByCustomerIdAsync(customerInfo.CustomerId)).Returns(Task.FromResult(new Order()));

            try
            {
                var response = _orderService.GetOrderDetailsByCustomerInfoAsync(customerInfo).Result;
                Assert.Fail("Test Should Fail");
            }
            catch (System.Exception e)
            {
                e.InnerException.Message.Should().Be("Customer does not exists " + customerInfo.User);
            }
        }
Beispiel #32
0
        //Substring here to match HDBs requirements
        public static HDSSRequest ToHDSSRequest(Request rq, CustomerInfo customerInfo)
        {
            var hdssRq = new HDSSRequest()
            {
                //TODO:
                //Home or Contact address is must?
                //interchangeable?
                requestId        = Guid.NewGuid().ToString(),                //Hardcoded as HDB requested TODO: store this
                requestTime      = DateTime.Now.ToString(RequestTimeFormat), //Hardcoded as HDB requested
                requestType      = rq.RequestType,
                identityCard     = customerInfo.IdentityCard,
                gender           = customerInfo.Gender,
                address          = customerInfo.HomeAddress,
                birthDate        = customerInfo.Dob.ToString(DOBDateFormat),
                identityCardName = customerInfo.FullName,
                issuePlace       = customerInfo.Issuer,
                issueDate        = customerInfo.IssueDate.ToString(DOBDateFormat),
                phone            = customerInfo.Phone,
                loanNo           = rq.LoanNo,
                branch           = rq.UsernameNavigation.DivisionNameNavigation.BranchId.ToString(),
                amount           = customerInfo.LoanAmount.ToString()
            };

            hdssRq.signature = CreateSignature(hdssRq);;
            //logger.Info(hdssRq.requestId);
            //logger.Info(hdssRq.requestTime);
            //logger.Info(hdssRq.requestType);
            //logger.Info(hdssRq.identityCard);
            //logger.Info(hdssRq.gender);
            //logger.Info(hdssRq.address);
            //logger.Info(hdssRq.birthDate);
            //logger.Info(hdssRq.identityCardName);
            //logger.Info(hdssRq.issuePlace);
            //logger.Info(hdssRq.issueDate);
            //logger.Info(hdssRq.phone);
            //logger.Info(hdssRq.loanNo);
            //logger.Info(hdssRq.signature);
            return(hdssRq);
        }
Beispiel #33
0
        public void PutItemBack(CustomerInfo customer)
        {
            bool storedBack = false;

            _LoggerService.Log($"Put item back because of trade failed with customer {customer.Nickname} trading {customer.Product}");
            if (customer != null)
            {
                if (!OpenStash())
                {
                    throw new Exception("Stash not found");
                }
                if (!OpenTab(customer.Stash_Tab))
                {
                    throw new Exception("Tab not found");
                }
                if (!MoveItemBack(customer.Product))
                {
                    ClearInventory();
                }
                Win32.SendKeyInPoE("ESC");
            }
        }
        private IMutablePagedList <CustomerOrder> GetCustomerOrders(CustomerInfo customer)
        {
            var workContext         = _workContextFactory();
            var orderSearchcriteria = new OrderModule.Client.Model.SearchCriteria
            {
                CustomerId    = customer.Id,
                ResponseGroup = "full"
            };

            Func <int, int, IPagedList <CustomerOrder> > ordersGetter = (pageNumber, pageSize) =>
            {
                //TODO: add caching
                orderSearchcriteria.Start = (pageNumber - 1) * pageSize;
                orderSearchcriteria.Count = pageSize;
                var cacheKey       = "GetCustomerOrders-" + orderSearchcriteria.GetHashCode();
                var ordersResponse = _cacheManager.Get(cacheKey, string.Format(_customerOrdersCacheRegionFormat, customer.Id), () => _orderApi.OrderModuleSearch(orderSearchcriteria));
                return(new StaticPagedList <CustomerOrder>(ordersResponse.CustomerOrders.Select(x => x.ToWebModel(workContext.AllCurrencies, workContext.CurrentLanguage)), pageNumber, pageSize,
                                                           ordersResponse.TotalCount.Value));
            };

            return(new MutablePagedList <CustomerOrder>(ordersGetter));
        }
        /// <summary>
        /// Load a list of purchase orders by filtering by the order date and the customer info passed in
        /// </summary>
        /// <param name="paymentCaptured">if the payment from paypal has been captured</param>
        /// <param name="orderShipped">if the order has been shipped</param>
        /// <param name="orderPlacedFrom"></param>
        /// <param name="orderPlaceTo"></param>
        /// <param name="customerInfo">Relevant customer info to search by</param>
        /// <returns>list of purchase orders</returns>
        public static List<PurchaseOrderDetails> Search(string paymentCaptured, string orderShipped, DateTime orderPlacedFrom, DateTime orderPlaceTo, CustomerInfo customerInfo, int numberToQuery)
        {
            paymentCaptured = paymentCaptured.ToUpper();
            orderShipped = orderShipped.ToUpper();

            MongoCollection<PurchaseOrderDetails> Collection = Execute.GetCollection<PurchaseOrderDetails>(COLLECTION_NAME);

            return (from e in Collection.AsQueryable<PurchaseOrderDetails>()

                    where e.PayPalOrderDetails.OrderPlacedDateUtc >= orderPlacedFrom

                    && (orderPlaceTo == DateTime.MinValue || e.PayPalOrderDetails.OrderPlacedDateUtc <= orderPlaceTo)
                    && (string.IsNullOrWhiteSpace(orderShipped) || ("FALSE" == orderShipped && e.PayPalOrderDetails.OrderShippedDateUtc == DateTime.MinValue) || ("TRUE" == orderShipped && e.PayPalOrderDetails.OrderShippedDateUtc != DateTime.MinValue))
                    && (string.IsNullOrWhiteSpace(paymentCaptured) || ("FALSE" == paymentCaptured && e.PayPalOrderDetails.PaymentCapturedDateUtc == DateTime.MinValue) || ("TRUE" == paymentCaptured && e.PayPalOrderDetails.PaymentCapturedDateUtc != DateTime.MinValue))
                    && ("" == customerInfo.Email || e.PayPalOrderDetails.CustomerInfo.Email.Contains(customerInfo.Email))
                    && ("" == customerInfo.FirstName || e.PayPalOrderDetails.CustomerInfo.FirstName.Contains(customerInfo.FirstName))
                    && ("" == customerInfo.LastName || e.PayPalOrderDetails.CustomerInfo.LastName.Contains(customerInfo.LastName))

                    orderby e.PayPalOrderDetails.OrderPlacedDateUtc descending

                    select e).Take(numberToQuery).ToList();
        }
Beispiel #36
0
        public async Task <ActionResult> UpdateAccount(CustomerInfo customer)
        {
            customer.Id = WorkContext.CurrentCustomer.Id;

            var fullName = string.Join(" ", customer.FirstName, customer.LastName).Trim();

            if (string.IsNullOrEmpty(fullName))
            {
                fullName = customer.Email;
            }

            if (!string.IsNullOrWhiteSpace(fullName))
            {
                customer.FullName = fullName;
            }

            await _customerService.UpdateCustomerAsync(customer);

            WorkContext.CurrentCustomer = await _customerService.GetCustomerByIdAsync(customer.Id);

            return(View("customers/account", WorkContext));
        }
        /// <summary>
        /// 将用户所有数据刷到Redis中
        /// </summary>
        //public void UpdateAllUserToRedis()
        //{
        //    CustomerRedisDal custRedisDal = new CustomerRedisDal();
        //    List<long> allCustomerId = _customerDbDal.GetAllCustomerId();
        //    TokenRedisDal tokenDal = new TokenRedisDal();
        //    allCustomerId.ForEach(x =>
        //    {
        //        var info = _customerDbDal.GetCustomerDetail(x);
        //        long customerId = info.CustomerID;
        //        custRedisDal.UpdateUserInfoInRedis(info);

        //        //刷备注名
        //        var nickNameList = custDbDal.GetCustomerNickName(customerId);
        //        custRedisDal.UpdateCustomerNickNameToRedis(customerId, nickNameList);

        //        //刷设备号
        //        if (!string.IsNullOrEmpty(info.DeviceTokensIos))
        //        {
        //            custRedisDal.UpdateCustomerDeviceToRedis(customerId, true, info.DeviceTokensIos);
        //        }
        //        else if (!string.IsNullOrEmpty(info.DeviceTokensAndroid))
        //        {
        //            custRedisDal.UpdateCustomerDeviceToRedis(customerId, false, info.DeviceTokensAndroid);
        //        }
        //        //将旧Redis用户token表更新
        //        tokenDal.UpdateTokenUser(info.CustomerTel, customerId);
        //    });
        //}

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="result">注册响应信息</param>
        /// <param name="user">用户信息</param>
        /// <param name="appType">注册来源</param>
        /// <param name="isFromShare">是否分享页面注册</param>
        /// <returns></returns>
        public CustomerInfo Register(out LoginResponseInfo result, RegisterInfo customer, int appType, bool isFromShare)
        {
            //if (!StringConvert.IsChinese(customer.CustomerName) || customer.CustomerName.Length < 2 || customer.CustomerName.Length > 6)
            //    ThrowResponseContextException(ErrCode.NameIsWrong);
            //SmsSendLogSrv smsSendSrv = new SmsSendLogSrv();
            //if (!smsSendSrv.IsRegSmsAuthenticated(customer.CustomerTel))
            //{
            //    //方便测试屏蔽
            //    //ThrowResponseContextException(ErrCode.InvalidCheckCode, "您没有通过短信验证,请先填写手机号进行短信验证");
            //}
            if (_customerDbDal.IsCustomerNameExists(customer.CustomerName))
            {
                ThrowResponseContextException(ErrCode.customerNameAlreadyExist);
            }

            DateTime     now          = DateTime.Now;
            CustomerInfo customerInfo = new CustomerInfo
            {
                Email        = customer.Email,
                CustomerName = customer.CustomerName,
                PassWord     = Md5.Encrypt(customer.PassWord),
                CreateTime   = now,
                UpdateTime   = now
            };

            customerInfo.CustomerId = _customerDbDal.AddCustomerInfo(customerInfo);

            CustomerDetail redisCustomerInfo = JsonHelper.ObjectToObject <CustomerDetail>(customerInfo);

            _customerRedisDal.AddCustomerInfo(redisCustomerInfo);

            result = new LoginResponseInfo
            {
                CustomerId   = customerInfo.CustomerId,
                CustomerName = customerInfo.CustomerName,
            };

            return(customerInfo);
        }
        public async Task <ResponseData> RegisterCustomer(CustomerInfo customerInfo)
        {
            ResponseData response = new ResponseData();
            var          client   = new HttpClient();
            var          content  = new StringContent(
                JsonConvert.SerializeObject(customerInfo));
            HttpContent cont = content;

            cont.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var result = await client.PostAsync(LetsRideCredentials.WebUrl + "api/Login/CustomerRegistration", cont).ConfigureAwait(false);

            if (result.IsSuccessStatusCode)
            {
                response = JsonConvert.DeserializeObject <ResponseData>(await result.Content.ReadAsStringAsync());
            }
            else
            {
                response.IsSuccess = false;
                response.Message   = "Problem to establish connection with server";
            }
            return(response);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string currentCustomer = "";

        customerId = QueryHelper.GetInteger("customerid", 0);
        if (customerId > 0)
        {
            customerInfoObj = CustomerInfoProvider.GetCustomerInfo(customerId);

            // Prepare customer name string
            if (customerInfoObj != null)
            {
                if (ValidationHelper.GetString(customerInfoObj.CustomerCompany, "") != "")
                {
                    currentCustomer = customerInfoObj.CustomerCompany;
                }
                else
                {
                    currentCustomer = customerInfoObj.CustomerLastName + " " + customerInfoObj.CustomerFirstName;
                }
            }
        }

        // Initialize breadcrumbs when visible
        if (!hideBreadcrumbs)
        {
            InitializeBreadcrumbs(currentCustomer);
        }

        // Ensure page with changes saved message is loaded initially if required
        if (QueryHelper.GetInteger("saved", 0) == 1)
        {
            this.CurrentMaster.Tabs.StartPageURL = "Customer_Edit_General.aspx" + URLHelper.Url.Query;
        }

        InitializeMasterPage(customerId);

        AddMenuButtonSelectScript("Customers", "");
    }
Beispiel #40
0
        /// <summary>
        /// 修改客户
        /// </summary>
        /// <param name="customer">修改信息</param>
        /// <param name="ProfessionaId"></param>
        /// <param name="AccountId"></param>
        /// <param name="UserStatusID"></param>
        /// <param name="SourceID"></param>
        /// <param name="SchoolId"></param>
        /// <returns></returns>
        public ActionResult EditCustomer(CustomerInfo customer, string ProfessionaId, string AccountId, string UserStatusID, string SourceID, string SchoolId)
        {
            customer.Id   = Convert.ToInt32(CusId);
            customer.Lock = 1;
            try
            {
                if (AccountId != null && ProfessionaId != null && UserStatusID != null && SourceID != null && SchoolId != null)
                {
                    int actId = Convert.ToInt32(AccountId);
                    int proId = Convert.ToInt32(ProfessionaId);
                    int ustId = Convert.ToInt32(UserStatusID);
                    int souId = Convert.ToInt32(SourceID);
                    int schId = Convert.ToInt32(SchoolId);

                    UserInfo    user        = unit.UserInfo.GetAll(m => m.Id == actId).FirstOrDefault();
                    Professiona professiona = unit.Professiona.GetAll(m => m.Id == proId).FirstOrDefault();
                    UserStatus  status      = unit.UserStatus.GetAll(m => m.Id == ustId).FirstOrDefault();
                    SourceInfo  source      = unit.SourceInfo.GetAll(m => m.Id == souId).FirstOrDefault();
                    SchoolInfo  school      = unit.SchoolInfo.GetAll(m => m.Id == schId).FirstOrDefault();

                    customer.AccountId     = user;
                    customer.ProfessionaId = professiona;
                    customer.UserStatusID  = status;
                    customer.SourceID      = source;
                    customer.SchoolId      = school;

                    unit.CustomerInfo.Update(customer);
                    unit.Save();
                    return(Json(new { suses = true }));
                }
                return(Json(new { suses = false }));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("CustomerEditPage", "Customer"));

                throw ex;
            }
        }
Beispiel #41
0
        private void SetCustomerRelationAndUpdateContact(CustomerInfo customerInfo)
        {
            if (mCurrentContactProvider == null || mContactProcessingChecker == null)
            {
                return;
            }

            if (!mContactProcessingChecker.CanProcessContactInCurrentContext())
            {
                return;
            }

            var currentContact = mCurrentContactProvider.GetCurrentContact(MembershipContext.AuthenticatedUser, false);

            mCurrentContactProvider.SetCurrentContact(currentContact);

            Service.Resolve <IContactRelationAssigner>().Assign(MemberTypeEnum.EcommerceCustomer, customerInfo, currentContact);
            ContactInfoProvider.UpdateContactFromExternalData(
                customerInfo,
                DataClassInfoProvider.GetDataClassInfo(CustomerInfo.TYPEINFO.ObjectClassName).ClassContactOverwriteEnabled,
                currentContact.ContactID);
        }
Beispiel #42
0
        public ChatResult RemoveCustomerFromGroup(string groupId, string customerId)
        {
            GroupInfo     group        = GetGroupByGroupId(groupId);
            List <string> memberIdList = new List <string>();

            if (group != null)
            {
                memberIdList = new List <string>(group.CustomerList);
            }

            ChatResult result = Manager.Instance.RemoveCustomerFromGroup(Context.ConnectionId, groupId, customerId);

            if (result.Success)
            {
                foreach (string memberId in memberIdList)
                {
                    CustomerInfo cus = Manager.Instance.GetCustomerByCustomerId(memberId);
                    Clients.Clients(cus.ConnectionList).OnRemoveCustomerFromGroup(groupId, customerId);
                }
            }
            return(result);
        }
Beispiel #43
0
        /// <summary>
        /// 搜索客户列表
        /// </summary>
        /// <param name="name">客户名称</param>
        /// <param name="type">客户类型</param>
        /// <param name="salesman">业务员</param>
        /// <returns></returns>
        public JsonResult Customer_search(string name, string type, string salesman)
        {
            CustomerInfo en = new CustomerInfo();

            en.name = name;

            if (type.Trim() != "")
            {
                en.channelTypeID = Convert.ToInt32(type);
            }

            if (salesman.Trim() != "")
            {
                en.salesmanID = Convert.ToInt32(salesman);
            }

            DaCustomerInfo dal    = new DaCustomerInfo();
            var            result = new CustomJsonResult();

            result.Data = dal.getList(en, BaseHelper.getCookie().id.ToString());
            return(result);
        }
Beispiel #44
0
        public void GetValidationErrors_ShouldReturnAgeTooSmallAgeTooBigIncomeTooSmallIncomeTooBigPersonMustBeDifferent()
        {
            Mock <IRange> FakeAgeRange = new Mock <IRange>(MockBehavior.Strict);

            FakeAgeRange.Setup(x => x.WithinLowerBounds(It.IsAny <int>())).Returns(false);
            FakeAgeRange.Setup(x => x.WithinUpperBounds(It.IsAny <int>())).Returns(false);

            Mock <IRange> FakeIncomeRange = new Mock <IRange>(MockBehavior.Strict);

            FakeIncomeRange.Setup(x => x.WithinLowerBounds(It.IsAny <int>())).Returns(false);
            FakeIncomeRange.Setup(x => x.WithinUpperBounds(It.IsAny <int>())).Returns(false);

            CustomerInfo sut = new CustomerInfo
            {
                Age    = FakeAgeRange.Object,
                Income = FakeIncomeRange.Object,
                Status = CustomerInfo.PersonStatus.STUDENT,
            };

            CustomerInfo test = new CustomerInfo
            {
                Age = new BusinessLogic.Range {
                    From = 18, To = int.MaxValue
                },
                Income = new BusinessLogic.Range {
                    From = 40001, To = int.MaxValue
                },
                Status = CustomerInfo.PersonStatus.OTHER,
            };

            List <string> errors = sut.GetValidationErrors(test);

            Assert.AreEqual(errors.Count, 5);
            Assert.IsTrue(errors.Contains(CustomerInfo.AgeMustBeGreaterThan));
            Assert.IsTrue(errors.Contains(CustomerInfo.AgeMustBeLessThan));
            Assert.IsTrue(errors.Contains(CustomerInfo.IncomeMustBeGreaterThan));
            Assert.IsTrue(errors.Contains(CustomerInfo.IncomeMustBeLessThan));
            Assert.IsTrue(errors.Contains(CustomerInfo.PersonMustBe + sut.Status));
        }
Beispiel #45
0
        public void GetUuidAddToCustomerList(SqlConnection connection, string uuid, List <CustomerInfo> customers)
        {
            SqlCommand selectCustomers = new SqlCommand(
                "SELECT * FROM [CustomerInfo] WHERE (Uuid) LIKE (@Uuid)",
                connection);

            selectCustomers.Parameters.AddWithValue("Uuid", uuid);
            using (SqlDataReader customerReader = selectCustomers.ExecuteReader())
            {
                DataTable dataTable = new DataTable();
                dataTable.Load(customerReader);
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    CustomerInfo customer = new CustomerInfo(
                        (dataRow["Uuid"].ToString() != "") ? dataRow["Uuid"].ToString() : "-",
                        (dataRow["Email"].ToString() != "") ? dataRow["Email"].ToString() : "-",
                        (dataRow["FirstName"].ToString() != "") ? dataRow["FirstName"].ToString() : "-",
                        (dataRow["Address"].ToString() != "") ? dataRow["Address"].ToString() : "-");
                    customers.Add(customer);
                }
            }
        }
Beispiel #46
0
    private string GetHotelResBodyRQ(CustomerInfo ci, string rph)
    {
        int rphl = rph.ToString().Length;

        if (rphl == 1)
        {
            rph = "00" + rph.ToString();
        }
        if (rphl == 2)
        {
            rph = "0" + rph.ToString();
        }

        string expdate = "";

        string[] expdatepart = ci.CCExpDate.Split('-');
        expdate = "20" + expdatepart[1] + "-" + expdatepart[0];

        string rq = "";

        rq += "<SOAP-ENV:Body>";
        rq += "<OTA_HotelResRQ xmlns='http://webservices.sabre.com/sabreXML/2011/10' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ReturnHostCommand='false' TimeStamp='2013-11-22T17:15:00-06:00' Version='2.2.0'>";
        rq += "<Hotel>";
        rq += "<BasicPropertyInfo RPH='" + rph + "' />";
        rq += "<Guarantee Type='G'>";
        rq += "<CC_Info>";
        rq += "<PaymentCard Code='" + ci.PayMethod + "' ExpireDate='" + expdate + "' Number='" + ci.CCNumber + "'/>";
        rq += "<PersonName>";
        rq += "<Surname>" + ci.CCHName + "</Surname>";
        rq += "</PersonName>";
        rq += "</CC_Info>";
        rq += "</Guarantee>";
        rq += "<RoomType NumberOfUnits='1'/>";
        rq += "</Hotel>";
        rq += "</OTA_HotelResRQ>";
        rq += "</SOAP-ENV:Body>";
        return(rq);
    }
        public void Data_DatabaseWriter_Insert()
        {
            var dataStore = DatabaseWriter <CustomerInfo> .Construct();

            var testEntity   = new CustomerInfo();
            var resultEntity = new CustomerInfo();
            var oldID        = TypeExtension.DefaultInteger;
            var oldKey       = TypeExtension.DefaultGuid;
            var newID        = TypeExtension.DefaultInteger;
            var newKey       = TypeExtension.DefaultGuid;

            // Create and insert record
            testEntity.Fill(testEntities[Arithmetic.Random(1, 5)]);
            oldID  = testEntity.ID;
            oldKey = testEntity.Key;
            Assert.IsTrue(testEntity.IsNew);
            Assert.IsTrue(testEntity.IsNew);
            Assert.IsTrue(testEntity.Key == TypeExtension.DefaultGuid);

            // Do Insert and check passed entity and returned entity
            dataStore = DatabaseWriter <CustomerInfo> .Construct(testEntity);

            resultEntity = dataStore.Save(SaveBehaviors.InsertOnly);
            Assert.IsTrue(testEntity.ID != TypeExtension.DefaultInteger);
            Assert.IsTrue(resultEntity.ID != TypeExtension.DefaultInteger);
            Assert.IsTrue(resultEntity.Key != TypeExtension.DefaultGuid);

            // Pull from DB and retest
            testEntity = dataStore.GetByID(resultEntity.ID);
            Assert.IsTrue(testEntity.IsNew == false);
            Assert.IsTrue(testEntity.ID != oldID);
            Assert.IsTrue(testEntity.Key != oldKey);
            Assert.IsTrue(testEntity.ID != TypeExtension.DefaultInteger);
            Assert.IsTrue(testEntity.Key != TypeExtension.DefaultGuid);

            // Cleanup
            DatabaseWriterTests.RecycleBin.Add(testEntity.ID);
        }
Beispiel #48
0
        public CustomerInfo getCustomerByBidPlanCode(SqlConnection connection, string bidPlanCode)
        {
            CustomerInfo info = null;

            using (var command = new SqlCommand("Select C.* from " +
                                                " (select BP.AuditID from tbl_BidPlan BP where BP.BidPlanCode = @BidPlanCode) BP " +
                                                " left join tbl_Audit A on A.AuditID = BP.AuditID" +
                                                " left join tbl_Quote Q on Q.QuoteID = A.QuoteID" +
                                                " left join tbl_Customer C on C.CustomerID = Q.CustomerID ", connection))
            {
                AddSqlParameter(command, "@BidPlanCode", bidPlanCode, System.Data.SqlDbType.NVarChar);
                WriteLogExecutingCommand(command);
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        info              = new CustomerInfo();
                        info.CustomerID   = GetDbReaderValue <int>(reader["CustomerID"]);
                        info.CustomerCode = GetDbReaderValue <string>(reader["CustomerCode"]);
                        info.CustomerName = GetDbReaderValue <string>(reader["CustomerName"]);
                        info.Address      = GetDbReaderValue <string>(reader["Address"]);
                        info.Phone        = GetDbReaderValue <string>(reader["Phone"]);
                        info.Fax          = GetDbReaderValue <string>(reader["Fax"]);
                        info.Email        = GetDbReaderValue <string>(reader["Email"]);
                        info.TaxCode      = GetDbReaderValue <string>(reader["TaxCode"]);
                        info.BankNumber   = GetDbReaderValue <string>(reader["BankNumber"]);
                        info.BankName     = GetDbReaderValue <string>(reader["BankName"]);
                        info.Surrogate    = GetDbReaderValue <string>(reader["Surrogate"]);
                        info.Position     = GetDbReaderValue <string>(reader["Position"]);
                        info.UserI        = GetDbReaderValue <string>(reader["UserI"]);
                        info.InTime       = GetDbReaderValue <DateTime?>(reader["InTime"]);
                        info.UserU        = GetDbReaderValue <string>(reader["UserU"]);
                        info.UpdateTime   = GetDbReaderValue <DateTime>(reader["UpdateTime"]);
                    }
                }
                return(info);
            }
        }
        public static CustomerInfo ToWebModel(this VirtoCommerceCustomerModuleWebModelContact contact)
        {
            var retVal = new CustomerInfo();

            retVal.InjectFrom(contact);

            retVal.IsRegisteredUser = true;
            if (contact.Addresses != null)
            {
                retVal.Addresses = contact.Addresses.Select(a => a.ToWebModel()).ToList();
            }

            retVal.DefaultBillingAddress  = retVal.Addresses.FirstOrDefault(a => (a.Type & AddressType.Billing) == AddressType.Billing);
            retVal.DefaultShippingAddress = retVal.Addresses.FirstOrDefault(a => (a.Type & AddressType.Shipping) == AddressType.Shipping);

            // TODO: Need separate properties for first, middle and last name
            if (!string.IsNullOrEmpty(contact.FullName))
            {
                var nameParts = contact.FullName.Split(_nameSeparator, 2);

                if (nameParts.Length > 0)
                {
                    retVal.FirstName = nameParts[0];
                }

                if (nameParts.Length > 1)
                {
                    retVal.LastName = nameParts[1];
                }
            }

            if (contact.Emails != null)
            {
                retVal.Email = contact.Emails.FirstOrDefault();
            }

            return(retVal);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string currentCustomer = "";
        int customerId = QueryHelper.GetInteger("customerid", 0);
        if (customerId > 0)
        {
            customerInfoObj = CustomerInfoProvider.GetCustomerInfo(customerId);

            // Prepare customer name string
            if (customerInfoObj != null)
            {
                if (ValidationHelper.GetString(customerInfoObj.CustomerCompany, "") != "")
                {
                    currentCustomer = customerInfoObj.CustomerCompany;
                }
                else
                {
                    currentCustomer = customerInfoObj.CustomerLastName + " " + customerInfoObj.CustomerFirstName;
                }
            }
        }

        // Initialize breadcrumbs when visible
        if (!hideBreadcrumbs)
        {
            InitializeBreadcrumbs(currentCustomer);
        }

        // Ensure page with changes saved message is loaded initially if required
        if (QueryHelper.GetInteger("saved", 0) == 1)
        {
            CurrentMaster.Tabs.StartPageURL = "Customer_Edit_General.aspx" + URLHelper.Url.Query;
        }

        InitializeMasterPage();

        AddMenuButtonSelectScript("Customers", "");
    }
Beispiel #51
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get order
        OrderInfo oi = OrderInfoProvider.GetOrderInfo(this.orderId);

        if (oi != null)
        {
            // Get customer for current user
            CustomerInfo customer = CustomerInfoProvider.GetCustomerInfoByUserID(CMSContext.CurrentUser.UserID);

            // If order does not belong to current user
            if ((customer == null) || ((customer != null) && (oi.OrderCustomerID != customer.CustomerID)))
            {
                // Redirect to access denied page
                URLHelper.Redirect("~/CMSMessages/AccessDeniedToPage.aspx");
            }
        }
        else
        {
            string title = this.GetString("com.downloadsdialog.ordernotfoundtitle");
            string text  = this.GetString("com.downloadsdialog.ordernotfoundtext");

            // Redirect to error page
            URLHelper.Redirect(String.Format("~/CMSMessages/Error.aspx?title={0}&text={1}", title, text));
        }

        // Initialize dialog title
        this.CurrentMaster.Title.TitleText  = this.GetString("com.downloadsdialog.title");
        this.CurrentMaster.Title.TitleImage = this.GetImageUrl("Objects/Ecommerce_Order/download.png");

        // Initialize close button
        btnClose.Text = GetString("general.close");

        // Initialize unigrid
        this.downloadsGridElem.ZeroRowsText         = this.GetString("com.downloadsdialog.nodownloadsfound");
        this.downloadsGridElem.OnDataReload        += new OnDataReloadEventHandler(downloadsGridElem_OnDataReload);
        this.downloadsGridElem.OnExternalDataBound += new OnExternalDataBoundEventHandler(downloadsGridElem_OnExternalDataBound);
    }
Beispiel #52
0
        public static void SaveCustomer(CustomerInfo objCustomerInfo)
        {
            Dictionary <string, object> ParamDict = new Dictionary <string, object>();

            ParamDict.Add("@CompanyName", objCustomerInfo.CompanyName);
            ParamDict.Add("@CompanyOwnerName", objCustomerInfo.CompanyOwnerName);
            ParamDict.Add("@Address", objCustomerInfo.Address);
            ParamDict.Add("@Contact", objCustomerInfo.Contact);
            ParamDict.Add("@Gst", objCustomerInfo.GST);
            ParamDict.Add("@Cin", objCustomerInfo.CIN);
            ParamDict.Add("@Pan", objCustomerInfo.PAN);
            ParamDict.Add("@StateName", objCustomerInfo.StateName);
            ParamDict.Add("@StateCode", objCustomerInfo.StateCode);

            DataAccess.ExecuteNonQuery(@"
                        INSERT INTO MastersCustomer (
                                CompanyName,
                                CompanyOwnerName,
                                Address,
                                Contact,
                                GST,
                                CIN,
                                PAN,
                                StateName,
                                StateCode)
                                    VALUES (
                                        @CompanyName,
                                        @CompanyOwnerName,
                                        @Address,
                                        @Contact,
                                        @Gst,
                                        @Cin,
                                        @Pan,
                                        @StateName,
                                        @StateCode)
                        "
                                       , ParamDict, CommandType.Text);
        }
        public void SendNotification(CustomerInfo customerInfo)
        {
            var client = new SmtpClient
            {
                Port = 587,
                Host = "smtp.gmail.com",
                EnableSsl = true,
                Timeout = 10000,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential("*****@*****.**", "password")
            };

            var mm = new MailMessage("*****@*****.**", customerInfo.Email, "New Account", "Congratulations!")
            {
                BodyEncoding = Encoding.UTF8,
                DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
            };

            client.Send(mm);

            _logger.LogInfo("Email sent successfully");
        }
Beispiel #54
0
        public ChatResult AddFriendRespond(string requestId, bool agree)
        {
            AddFriendRequest request = Manager.Instance.GetFriendRequestById(requestId);
            if (request == null)
                return new ChatResult(false, "Request not found");
            CustomerInfo myCustomer = Manager.Instance.GetCustomerByCustomerId(request.Receiver);
            CustomerInfo friendCustomer = Manager.Instance.GetCustomerByCustomerId(request.Sender);
            CustomerInfo returnMyCustomer = new CustomerInfo(myCustomer.CustomerId, myCustomer.CustomerName, myCustomer.Status);
            CustomerInfo returnFriendCustomer = new CustomerInfo(friendCustomer.CustomerId, friendCustomer.CustomerName, friendCustomer.Status);

            ChatResult result = Manager.Instance.AddFriendRespond(Context.ConnectionId, requestId, agree);
            if (result.Success)
            {
                //send to request customer
                Clients.Clients(friendCustomer.ConnectionList).OnAddFriendRespond(returnMyCustomer, agree);
                if (agree)
                {
                    //send to respond customer
                    Clients.Clients(myCustomer.ConnectionList).OnAddFriendRespond(returnFriendCustomer, agree);
                }
            }
            return result;
        }
Beispiel #55
0
		public Order(OrderInfo orderInfo)
		{
			Name = orderInfo.Name;
			TermsAccepted = orderInfo.TermsAccepted;
			PaidDate = orderInfo.PaidDate;
		    FulfillDate = orderInfo.FulfillDate;
			ConfirmDate = orderInfo.ConfirmDate;
			OrderLines = orderInfo.OrderLines.Select(line => new OrderLine(line)).ToList();
			CouponCodes = orderInfo.CouponCodesData;
			CustomerInfo = orderInfo.CustomerInfo;
			ShippingInfo = orderInfo.ShippingInfo;
			PaymentInfo = orderInfo.PaymentInfo;
			StoreInfo = orderInfo.StoreInfo;
			CurrencyCode = orderInfo.Localization.CurrencyCode;
			// todo: onderstaand kan waarschijnlijk anders (geen check = dubbel)
			Discounts = orderInfo.Discounts.Select(discount => new OrderDiscount(orderInfo.Localization, discount, orderInfo)).ToList(); // todo: add/save used coupon code
			IncludingVAT = orderInfo.PricesAreIncludingVAT;

			VatCalculatedOverParts = orderInfo.VatCalculationStrategy is OverSmallestPartsVatCalculationStrategy;

			PaymentProviderPrice = orderInfo.PaymentProviderAmount;
			PaymentProviderOrderPercentage = orderInfo.PaymentProviderOrderPercentage;

			ShippingProviderPrice = orderInfo.ShippingProviderAmountInCents;
			RegionalVatAmount = orderInfo.RegionalVatInCents;

			VATCharged = orderInfo.VATCharged;
			ChargedAmount = orderInfo.ChargedAmountInCents;

			CorrespondingOrderDocumentId = orderInfo.OrderNodeId;

			RevalidateOrderOnLoad = orderInfo.RevalidateOrderOnLoad; // version 2.1 hack
			ReValidateSaveAction = orderInfo.ReValidateSaveAction; // version 2.1 hack

			StockUpdated = orderInfo.StockUpdated;
			CreatedInTestMode = orderInfo.CreatedInTestMode;
		}
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (plcAccount.Visible)
        {
            string siteName = SiteContext.CurrentSiteName;

            // Existing account
            if (radSignIn.Checked)
            {
                // Authenticate user
                UserInfo ui = AuthenticationHelper.AuthenticateUser(txtUsername.Text.Trim(), txtPsswd1.Text, SiteContext.CurrentSiteName, false);
                if (ui == null)
                {
                    lblError.Text = GetString("ShoppingCartCheckRegistration.LoginFailed");
                    lblError.Visible = true;
                    return false;
                }

                // Sign in customer with existing account
                AuthenticationHelper.AuthenticateUser(ui.UserName, false);

                // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
                ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

                // Assign current user to the current shopping cart
                ShoppingCart.User = ui;

                // Save changes to database
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                // Log "login" activity
                ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();

                LoadStep(true);

                // Return false to get to Edit customer page
                return false;
            }
            // New registration
            else if (radNewReg.Checked)
            {
                txtEmail2.Text = txtEmail2.Text.Trim();
                pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

                string[] siteList = { siteName };

                // If AssignToSites field set
                if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                {
                    siteList = ShoppingCartControl.AssignToSites.Split(';');
                }

                // Check if user exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
                if (ui != null)
                {
                    lblError.Visible = true;
                    lblError.Text = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                    return false;
                }

                // Check all sites where user will be assigned
                if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text = GetString("UserInfo.EmailAlreadyExist");
                    return false;
                }

                // Create new customer and user account and sign in
                // User
                ui = new UserInfo();
                ui.UserName = txtEmail2.Text.Trim();
                ui.Email = txtEmail2.Text.Trim();
                ui.FirstName = txtFirstName1.Text.Trim();
                ui.LastName = txtLastName1.Text.Trim();
                ui.FullName = ui.FirstName + " " + ui.LastName;
                ui.Enabled = true;
                ui.UserIsGlobalAdministrator = false;
                ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
                ui.UserCampaign = AnalyticsHelper.Campaign;
                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent;

                try
                {
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    foreach (string site in siteList)
                    {
                        UserInfoProvider.AddUserToSite(ui.UserName, site);

                        // Add user to roles
                        if (ShoppingCartControl.AssignToRoles != "")
                        {
                            AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                        }
                    }

                    // Log registered user
                    AnalyticsHelper.LogRegisteredUser(siteName, ui);

                    Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text = ex.Message;
                    return false;
                }

                // Customer
                CustomerInfo ci = new CustomerInfo();
                ci.CustomerFirstName = txtFirstName1.Text.Trim();
                ci.CustomerLastName = txtLastName1.Text.Trim();
                ci.CustomerEmail = txtEmail2.Text.Trim();

                ci.CustomerCompany = "";
                ci.CustomerOrganizationID = "";
                ci.CustomerTaxRegistrationID = "";
                if (chkCorporateBody.Checked)
                {
                    ci.CustomerCompany = txtCompany1.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                    }
                }

                ci.CustomerUserID = ui.UserID;
                ci.CustomerSiteID = 0;
                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Track successful registration conversion
                string name = ShoppingCartControl.RegistrationTrackConversionName;
                ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

                // Log "customer registration" activity and update profile
                var activityCustomerRegistration = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                if (activityCustomerRegistration.Data != null)
                {
                    if (ContactID <= 0)
                    {
                        activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    }
                    activityCustomerRegistration.Log();
                }

                // Sign in
                if (ui.UserEnabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, false);
                    ShoppingCart.User = ui;

                    ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activity.Log();
                }

                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

                // Send new registration notification email
                if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
                {
                    SendRegistrationNotification(ui);
                }
            }
            // Anonymous customer
            else if (radAnonymous.Checked)
            {
                CustomerInfo ci = null;
                if (ShoppingCart.ShoppingCartCustomerID > 0)
                {
                    // Update existing customer account
                    ci = CustomerInfoProvider.GetCustomerInfo(ShoppingCart.ShoppingCartCustomerID);
                }
                if (ci == null)
                {
                    // Create new customer account
                    ci = new CustomerInfo();
                }

                ci.CustomerFirstName = txtFirstName2.Text.Trim();
                ci.CustomerLastName = txtLastName2.Text.Trim();
                ci.CustomerEmail = txtEmail3.Text.Trim();

                ci.CustomerCompany = "";
                ci.CustomerOrganizationID = "";
                ci.CustomerTaxRegistrationID = "";

                if (chkCorporateBody2.Checked)
                {
                    ci.CustomerCompany = txtCompany2.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID2.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID2.Text.Trim();
                    }
                }

                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                ci.CustomerSiteID = SiteContext.CurrentSiteID;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Log "customer registration" activity
                var activity = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID();
                    activity.Data.ContactID = ContactID;
                    activity.Log();
                }

                // Assign customer to shoppingcart
                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
            }
            else
            {
                return false;
            }
        }
        else
        {
            // Save the customer data
            bool newCustomer = false;
            CustomerInfo ci = CustomerInfoProvider.GetCustomerInfoByUserID(ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID = ShoppingCartControl.UserInfo.UserID;
                ci.CustomerSiteID = 0;
                ci.CustomerEnabled = true;
                newCustomer = true;
            }

            // Old email address
            string oldEmail = ci.CustomerEmail.ToLowerCSafe();

            ci.CustomerFirstName = txtEditFirst.Text.Trim();
            ci.CustomerLastName = txtEditLast.Text.Trim();
            ci.CustomerEmail = txtEditEmail.Text.Trim();

            pnlCompanyAccount2.Visible = chkEditCorpBody.Checked;

            ci.CustomerCompany = "";
            ci.CustomerOrganizationID = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkEditCorpBody.Checked)
            {
                ci.CustomerCompany = txtEditCompany.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtEditOrgID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtEditTaxRegID.Text.Trim();
                }
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Update corresponding user email when required
            if (oldEmail != ci.CustomerEmail.ToLowerCSafe())
            {
                UserInfo user = UserInfoProvider.GetUserInfo(ci.CustomerUserID);
                if (user != null)
                {
                    user.Email = ci.CustomerEmail;
                    UserInfoProvider.SetUserInfo(user);
                }
            }

            // Log "customer registration" activity and update contact profile
            if (newCustomer)
            {
                var activity = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();
            }

            // Set the shopping cart customer ID
            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }

        try
        {
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            ShoppingCart.InvalidateCalculations();
            return true;
        }
        catch
        {
            return false;
        }
    }
    /// <summary>
    /// Adds product to wishlist. Called when the "Assign discount level to customer" button is pressed.
    /// Expects the CreateProduct and CreateRegisteredCustomer methods to be run first.
    /// </summary>
    private bool AddProductToWishlist()
    {
        // Prepare the parameters
        string whereCustomer = "CustomerLastName LIKE N'My New Registered%'";
        string whereProduct = "SKUName LIKE N'MyNewProduct%'";
        CustomerInfo customer = null;
        SKUInfo product = null;

        // Get the product
        DataSet products = SKUInfoProvider.GetSKUs(whereProduct, null);
        if (!DataHelper.DataSourceIsEmpty(products))
        {
            // Create object from DataRow
            product = new SKUInfo(products.Tables[0].Rows[0]);
        }

        // Get the customer
        DataSet customers = CustomerInfoProvider.GetCustomers(whereCustomer, null);
        if (!DataHelper.DataSourceIsEmpty(customers))
        {
            // Create object from DataRow
            customer = new CustomerInfo(customers.Tables[0].Rows[0]);
        }

        if ((customer != null) && (product != null))
        {
            // Add product to wishlist
            WishlistItemInfoProvider.AddSKUToWishlist(customer.CustomerUserID, product.SKUID, CMSContext.CurrentSiteID);

            return true;
        }

        return false;
    }
    /// <summary>
    /// Assigns discount level to customer. Called when the "Assign discount level to customer" button is pressed.
    /// Expects the CreateRegisteredCustomer method to be run first.
    /// </summary>
    private bool AssignDiscountLevelToCustomer()
    {
        // Prepare the parameters
        string where = "CustomerLastName LIKE N'My New Registered%'";
        CustomerInfo customer = null;

        // Get the discount level
        DiscountLevelInfo discountLevel = DiscountLevelInfoProvider.GetDiscountLevelInfo("MyNewDiscountLevel", CMSContext.CurrentSiteName);

        // Get the data
        DataSet customers = CustomerInfoProvider.GetCustomers(where, null);
        if (!DataHelper.DataSourceIsEmpty(customers))
        {
            // Create object from DataRow
            customer = new CustomerInfo(customers.Tables[0].Rows[0]);
        }

        if ((customer != null) && (discountLevel != null))
        {
            // Assign discount level to customer
            customer.CustomerDiscountLevelID = discountLevel.DiscountLevelID;

            // Assign discount level to customer
            CustomerInfoProvider.SetCustomerInfo(customer);

            return true;
        }

        return false;
    }
    /// <summary>
    /// Changes order status. Called when the "Change order status" button is pressed.
    /// Expects the CreateOrder method to be run first.
    /// </summary>
    private bool ChangeOrderStatus()
    {
        // Prepare the parameters
        string where = "CustomerLastName LIKE N'My New Registered%'";
        CustomerInfo customer = null;
        OrderInfo order = null;

        // Get the customer
        DataSet customers = CustomerInfoProvider.GetCustomers(where, null);
        if (!DataHelper.DataSourceIsEmpty(customers))
        {
            // Create object from DataRow
            customer = new CustomerInfo(customers.Tables[0].Rows[0]);
        }

        if (customer != null)
        {
            string whereOrder = "OrderCustomerID = " + customer.CustomerID;

            // Get the order
            DataSet orders = OrderInfoProvider.GetOrders(whereOrder, null);
            if (!DataHelper.DataSourceIsEmpty(orders))
            {
                // Create object from DataRow
                order = new OrderInfo(orders.Tables[0].Rows[0]);
            }

            if (order != null)
            {
                // Get next enabled order status
                OrderStatusInfo nextOrderStatus = OrderStatusInfoProvider.GetNextEnabledStatus(order.OrderStatusID);

                if (nextOrderStatus != null)
                {
                    // Create new order status user object
                    OrderStatusUserInfo newUserStatus = new OrderStatusUserInfo();

                    // Set the properties
                    newUserStatus.OrderID = order.OrderID;
                    newUserStatus.ChangedByUserID = CMSContext.CurrentUser.UserID;
                    newUserStatus.FromStatusID = order.OrderStatusID;
                    newUserStatus.ToStatusID = nextOrderStatus.StatusID;
                    newUserStatus.Date = DateTime.Now;

                    // Set the order status user
                    OrderStatusUserInfoProvider.SetOrderStatusUserInfo(newUserStatus);

                    // Set next order status to order
                    order.OrderStatusID = nextOrderStatus.StatusID;

                    // Change the order status
                    OrderInfoProvider.SetOrderInfo(order);

                    return true;
                }
            }
        }

        return false;
    }
    /// <summary>
    /// Creates address. Called when the "Create address" button is pressed.
    /// Expects the CreateRegisteredCustomer method to be run first.
    /// </summary>
    private bool CreateAddress()
    {
        // Prepare the parameters
        string where = "CustomerLastName LIKE N'My New Registered%'";
        CustomerInfo customer = null;

        // Get the customer
        DataSet customers = CustomerInfoProvider.GetCustomers(where, null);
        if (!DataHelper.DataSourceIsEmpty(customers))
        {
            // Create object from DataRow
            customer = new CustomerInfo(customers.Tables[0].Rows[0]);
        }

        // Get the country
        CountryInfo country = CountryInfoProvider.GetCountryInfo("USA");

        // Get the state
        StateInfo state = StateInfoProvider.GetStateInfo("Alabama");

        if ((customer != null) && (country != null))
        {
            // Create new address object
            AddressInfo newAddress = new AddressInfo();

            // Set the properties
            newAddress.AddressName = "My new address";
            newAddress.AddressLine1 = "Address line 1";
            newAddress.AddressLine2 = "Address line 2";
            newAddress.AddressCity = "Address city";
            newAddress.AddressZip = "Address ZIP code";
            newAddress.AddressIsBilling = true;
            newAddress.AddressIsShipping = false;
            newAddress.AddressEnabled = true;
            newAddress.AddressPersonalName = "";
            newAddress.AddressCustomerID = customer.CustomerID;
            newAddress.AddressCountryID = country.CountryID;
            newAddress.AddressStateID = state.StateID;

            // Create the address
            AddressInfoProvider.SetAddressInfo(newAddress);

            return true;
        }

        return false;
    }