Esempio n. 1
0
        public bool Save()
        {
            string[] nameAndMail = Alias.Split("|".ToCharArray());
            string   name        = nameAndMail[0];
            string   email       = nameAndMail.Length > 0 ? nameAndMail[1] : "";
            string   password    = nameAndMail.Length > 1 ? nameAndMail[2] : "";
            string   loginName   = nameAndMail.Length > 2 ? nameAndMail[3] : "";

            if (cms.businesslogic.member.Member.InUmbracoMemberMode() && TypeID != -1)
            {
                cms.businesslogic.member.MemberType dt = new cms.businesslogic.member.MemberType(TypeID);
                cms.businesslogic.member.Member     m  = cms.businesslogic.member.Member.MakeNew(name, loginName, email, dt, BusinessLogic.User.GetUser(_userID));
                m.Password  = password;
                m.LoginName = loginName.Replace(" ", "").ToLower();

                NewMemberUIEventArgs e = new NewMemberUIEventArgs();
                this.OnNewMember(e, password, m);

                _returnUrl = "members/editMember.aspx?id=" + m.Id.ToString();
            }
            else
            {
                MembershipCreateStatus mc = new MembershipCreateStatus();
                Membership.CreateUser(name, password, email, "empty", "empty", true, out mc);
                if (mc != MembershipCreateStatus.Success)
                {
                    throw new Exception("Error creating Member: " + mc.ToString());
                }
                _returnUrl = "members/editMember.aspx?id=" + System.Web.HttpContext.Current.Server.UrlEncode(name);
            }

            return(true);
        }
Esempio n. 2
0
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            string statusString = createStatus.ToString();
            string resourceKey = "Exceptions.ErrorMessages.UserRegister.{0}".FormatWith(statusString);

            return ResourceManager.GetString(resourceKey);
        }
Esempio n. 3
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            MembershipCreateStatus membershipCreateStatu = MembershipCreateStatus.Success;

            if (string.IsNullOrEmpty(this.tbUsername.Text) || this.tbPass.Text != this.tbPass2.Text)
            {
                MessageBox.Show("المعلومات المزودة غير كاملة", "خطأ في الإدخال");
            }
            else
            {
                string text = this.tbUsername.Text;
                string str1 = this.tbPass2.Text;
                string str2 = this.ddlRole.SelectedItem.ToString();
                Membership.CreateUser(text, str1, "*****@*****.**", "what", "this", true, ref membershipCreateStatu);
                if (membershipCreateStatu != MembershipCreateStatus.Success)
                {
                    MessageBox.Show(membershipCreateStatu.ToString());
                }
                else
                {
                    Roles.AddUserToRole(text, str2);
                    this._AccMgr.refreshDGV();
                    MessageBox.Show("تمت الإضافة");
                    this.tbUsername.Text = "";
                    this.tbPass.Text     = "";
                    this.tbPass2.Text    = "";
                }
            }
        }
        public Blog SetupNewBlog()
        {
            const string           administratorRole = "Admin";
            const string           adminUser         = "******";
            MembershipCreateStatus createStatus      = MembershipCreateStatus.Success;

            if (Membership.GetUser(adminUser) == null)
            {
                Membership.CreateUser(adminUser, adminUser, "*****@*****.**", null, null, true, null, out createStatus);
            }

            if (createStatus == MembershipCreateStatus.Success)
            {
                if (!Roles.RoleExists(administratorRole))
                {
                    Roles.CreateRole(administratorRole);
                }
                if (!Roles.IsUserInRole(adminUser, administratorRole))
                {
                    Roles.AddUserToRole(adminUser, administratorRole);
                }

                _userRepository.Save(new User {
                    DateCreated = DateTime.Now, Username = adminUser
                });
                return(_blogRepository.Save(BlogService.InitialBlog));
            }
            throw new ApplicationException("Failed to create admin user: " + createStatus.ToString());
        }
Esempio n. 5
0
        public ActionResult AddCard(CardsModel model)
        {
            if (ModelState.IsValid)
            {
                if (client == null)
                {
                    client = new BankSystemServiceClient();
                }
                MembershipCreateStatus createStatus = client.AddCard(User.Identity.GetUserId(), model.Nazwa, model.Nr_karta);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    return(RedirectToAction("Card", "Cards"));
                }
                else
                {
                    ModelState.AddModelError("", createStatus.ToString());
                }
            }
            else
            {
                ModelState.AddModelError("", "Pola nie moga byc puste");
            }
            return(View());
        }
Esempio n. 6
0
        private void btnSaveUser_Click(object sender, EventArgs e)
        {
            try
            {
                MembershipCreateStatus status = MembershipCreateStatus.Success;

                Membership.CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtPasswordQuestion.Text, txtPasswordAnswer.Text, chkApproved.Checked, null, out status);

                if (status == MembershipCreateStatus.Success)
                {
                    MessageBox.Show("User created successfully", "Create user", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    loadUsers();
                }
                else
                {
                    MessageBox.Show("Failed to create user, " + status.ToString(), "Create user", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show("Failed to create user, " + ex.Message, "Create user", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Failed to create user, " + ex.Message, "Create user", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create user, " + ex.Message, "Create user", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Esempio n. 7
0
        public ActionResult AddNewCard(AddNewCardModel model)
        {
            if (ModelState.IsValid)
            {
                if (client == null)
                {
                    client = new BankSystemServiceClient();
                }
                MembershipCreateStatus createStatus = client.AddNewCard(model.Nr_card, model.Srodki, model.Saldo);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    return(RedirectToAction("Card", "Cards"));
                }
                else
                {
                    ModelState.AddModelError("", createStatus.ToString());

                    return(View());
                }
            }
            else
            {
                ModelState.AddModelError("", "Pola nie moga byc puste");

                return(View());
            }
        }
Esempio n. 8
0
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            string statusString = createStatus.ToString();
            string resourceKey  = "Exceptions.ErrorMessages.UserRegister.{0}".FormatWith(statusString);

            return(ResourceManager.GetString(resourceKey));
        }
Esempio n. 9
0
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes and add appropriate error handling.
            switch (createStatus)
            {
            case MembershipCreateStatus.DuplicateUserName:
                return(ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusDuplicateUserName));

            case MembershipCreateStatus.DuplicateEmail:
                return(ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusDuplicateEmail));

            case MembershipCreateStatus.ProviderError:
                return(ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusProviderError));

            case MembershipCreateStatus.UserRejected:
                return(ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusUserRejected));

            case MembershipCreateStatus.InvalidPassword:
            case MembershipCreateStatus.InvalidEmail:
            case MembershipCreateStatus.InvalidAnswer:
            case MembershipCreateStatus.InvalidQuestion:
            case MembershipCreateStatus.InvalidUserName:
                // All this errors should have been handled by the UI validation so theoretically
                // we should never get to this point
                return("Validation Error: " + createStatus.ToString());

            default:
                return("Could not register the user, please verify the provided information and try again.");
            }
        }
Esempio n. 10
0
    public string SaveMembers(DataRow drDataToSave)
    {
        MembershipCreateStatus success = new MembershipCreateStatus();

        Membership.CreateUser(drDataToSave["PROF_EMailId"].ToString(), drDataToSave["PROF_Password"].ToString(), drDataToSave["PROF_EMailId"].ToString(), "Question", "Answer", true, out success);
        return(success.ToString());
    }
Esempio n. 11
0
        public static bool CreateUser(string userName, string password, string eMail, int idEmpresa, string perfil, string nombreCompleto, string iniciales)
        {
            MembershipCreateStatus status = MembershipCreateStatus.ProviderError;

            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    Membership.CreateUser(userName, password, eMail, "uno", "dos", true, out status);
                    Logger.Debug(status.ToString());
                    if (status == MembershipCreateStatus.Success)
                    {
                        UserProfile p = UserProfile.GetUserProfile(userName);
                        p.NombreCompleto = nombreCompleto;
                        p.Iniciales      = iniciales;
                        p.Save();

                        MembershipUser mu = Membership.GetUser(userName);
                        if (mu != null && mu.ProviderUserKey != null)
                        {
                            usuarios_empresas ue = new usuarios_empresas
                            {
                                IdEmpresa = idEmpresa, UserId = mu.ProviderUserKey.ToString()
                            };
                            db.usuarios_empresas.AddObject(ue);
                        }
                        db.SaveChanges();
                        Roles.AddUserToRole(userName, perfil);
                        return(true);
                    }
                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee.Message);
            }
            if (status == MembershipCreateStatus.DuplicateEmail)
            {
                throw new FaultException("Email Duplicado");
            }
            if (status == MembershipCreateStatus.DuplicateUserName)
            {
                throw new FaultException("Usuario Duplicado");
            }
            if (status == MembershipCreateStatus.InvalidPassword)
            {
                throw new FaultException("El password no cumple con las politicas de seguridad");
            }
            return(false);
        }
Esempio n. 12
0
        /// <summary>
        /// Create a new user in the membership directory
        /// </summary>
        /// <param name="login">The user name for the new user.</param>
        /// <param name="password">The password for the new user.</param>
        /// <param name="email">The e-mail address for the new user.</param>
        /// <param name="passwordQuestion">The password-question value for the membership user.</param>
        /// <param name="passwordAnswer">The password-answer value for the membership user.</param>
        private static void CreateUser(string login, string password, string email, string passwordQuestion, string passwordAnswer)
        {
            MembershipCreateStatus userStatus = new MembershipCreateStatus();

            // Create the user in the SQL membership database
            Membership.CreateUser(login, password, email, passwordQuestion, passwordAnswer, true, out userStatus);

            // Check the Status
            if (userStatus != MembershipCreateStatus.Success)
            {
                ULS.LogError("CreateUser", "User " + login + " failed with status " + userStatus.ToString(), "SQLMembershipWS");
                throw new Exception("User " + login + " failed with status " + userStatus.ToString());
            }
        }
Esempio n. 13
0
        private void CreateRecord(string userName, string password, string email, string firstName, string lastName, int?companyID, int?functionalAreaID, Boolean?isManager, Boolean?isExecutive, Boolean?isLockedOut)
        {
            MembershipCreateStatus status = WebSecurity.Register(userName, password, email, true, firstName, lastName, companyID == 0 ? null : companyID, functionalAreaID == 0 ? null : functionalAreaID, isManager, isExecutive);

            if (status == MembershipCreateStatus.Success)
            {
                WebSecurity.LockUser(userName, (bool)isLockedOut);

                if (ddlMembershipRole.SelectedValue.Equals("0"))
                {
                    System.Web.Security.Roles.AddUserToRole(userName, "User");
                }
                else
                {
                    System.Web.Security.Roles.AddUserToRole(userName, ddlMembershipRole.SelectedItem.Text);
                }

                GridView           gv       = ProductionUnitGrid.GetGridView();
                CheckBox           selected = null;
                HiddenField        pid      = null;
                UserProductionUnit upu      = null;
                Guid userId = WebSecurity.GetUserId(userName);

                using (var db = new Models.SmizeeContext())
                {
                    foreach (GridViewRow currentRow in gv.Rows)
                    {
                        selected = currentRow.FindControl("SelectRowCheckBox") as CheckBox;
                        if (selected.Checked)
                        {
                            pid                  = currentRow.FindControl("ProductionUnitIDHidden") as HiddenField;
                            upu                  = new UserProductionUnit();
                            upu.UserID           = userId;
                            upu.ProductionUnitID = int.Parse(pid.Value);
                            db.UserProductionUnits.Add(upu);
                        }
                    }
                    db.SaveChanges();
                }

                BackPanel.Visible          = true;
                ConfirmButtonPanel.Visible = false;
                DetailPanel.Visible        = false;
                ShowInfo(MessagePanel, Resources.Resource.mUserCreateOK);
            }
            else
            {
                ShowError(ErrorPanel, status.ToString());
            }
        }
        public ActionResult Create(CreateUserModel user)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus status = MembershipCreateStatus.InvalidPassword;
                Membership.CreateUser(user.Username, user.Password, user.Email, "None?", "Answer.", user.IsApproved, out status);
                if (status != MembershipCreateStatus.Success)
                {
                    throw new Exception(status.ToString());
                }
                return(RedirectToAction("Index"));
            }

            return(View(user));
        }
Esempio n. 15
0
        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            string userName = txtUserName.Text;
            string password = txtPassword.Text;
            MembershipCreateStatus status = new MembershipCreateStatus();
            //MembershipUser newUser = Membership.CreateUser(userName, password, "", "", "", true, out  status);
            MembershipUser newUser = Membership.CreateUser(userName, password, "Default", "Default", "Default", true, out status);

            if (MembershipCreateStatus.Success.Equals(status))
            {
                lblMessage.Text = "Success";
            }
            else
            {
                lblMessage.Text = status.ToString();
            }
        }
Esempio n. 16
0
        public ActionResult Register(RegisterModel model)
        {
            ViewBag.RegionId = new SelectList(market.Regions, "Id", "Name");

            if (ModelState.IsValid)
            {
                UserModel user = new UserModel();
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Password, model.Email.ToLower());

                if (createStatus == MembershipCreateStatus.Success)
                {
                    user.ActivationId = System.Guid.NewGuid().ToString();
                    MembershipUser RegisteredUser = Membership.GetUser(model.Email.ToLower());
                    RegisteredUser.IsApproved = false;
                    Membership.UpdateUser(RegisteredUser);
                    user.Email     = model.Email.ToLower();
                    user.FirstName = model.FirstName.Substring(0, 1).ToUpper() + model.FirstName.Substring(1);
                    user.LastName  = model.LastName.Substring(0, 1).ToUpper() + model.LastName.Substring(1);
                    user.City      = model.City;
                    user.RegionId  = model.RegionId;
                    user.CountryId = 1;
                    market.Badges.SingleOrDefault(b => b.Name == "Individual").Users.Add(user);
                    market.Users.Add(user);
                    market.SaveChanges();

                    //Use MvcMailer to send welcome email to newly registered user.
                    UserMailer.Welcome(newUser: user).Send();
                    Session["REGISTERED_USER"] = true;
                    log.Info("Account - New user registered (" + model.Email.ToLower() + ")");
                    return(View());
                }
                else
                {
                    log.Error("Account - Error registering new user. " + createStatus.ToString());
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            log.Error("Account - RegisterModel Error.");
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return(View(model));
        }
Esempio n. 17
0
        protected void lvAuthUsers_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            // insert a MembershipUser here;
            // no need to go to wrapper class
            ListViewItem item        = e.Item;
            TextBox      txtUserName = item.FindControl("txtUserName") as TextBox;
            TextBox      txtPw       = item.FindControl("txtPw") as TextBox;
            TextBox      txtQ        = item.FindControl("txtSecQuestion") as TextBox;
            TextBox      txtA        = item.FindControl("txtSecAnswer") as TextBox;

            string userName = txtUserName.Text.Trim();
            string pw       = txtPw.Text.Trim();
            string q        = txtQ.Text.Trim();
            string a        = txtA.Text.Trim();
            MembershipCreateStatus status = MembershipCreateStatus.UserRejected;

            // create user
            MembershipUser newUser = Membership.CreateUser(userName, pw, userName, q, a, true, out status);

            if (status != MembershipCreateStatus.Success)
            {
                throw new Exception("CreateUser status: " + status.ToString());
            }

            // put them in client role
            Roles.AddUserToRole(userName, Settings.Default.RoleClient);

            // insert into client db
            Address address = CacheLayer.AddressFromId(Settings.Default.DefaultAddressId);
            Company company = CacheLayer.CompanyFromId(Settings.Default.DefaultCompanyId);

            Guid guid = (Guid)(newUser.ProviderUserKey);

            Client client = new Client("[First]", "[Last]", "[Phone]", guid, newUser.UserName, company, address, Settings.Default.CompanyTimeZoneId);

            CacheLayer.InsertClient(client);

            // no need to go to wrapper
            e.Cancel = true;

            this.Response.Redirect("/admin/AuthUserManage.aspx?userName=" + userName, false);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
Esempio n. 18
0
    public string GetErrorMessage(MembershipCreateStatus status)
    {
        switch (status)
        {
        case MembershipCreateStatus.DuplicateUserName:
            //return "Username already exists. Please enter a different user name.";
            return(CreateUserWizard1.DuplicateUserNameErrorMessage);

        case MembershipCreateStatus.DuplicateEmail:
            //return "A username for that e-mail address already exists. Please enter a different e-mail address.";
            return(CreateUserWizard1.DuplicateEmailErrorMessage);

        case MembershipCreateStatus.InvalidPassword:
            //return "The password provided is invalid. Please enter a valid password value.";
            return(CreateUserWizard1.InvalidPasswordErrorMessage);

        case MembershipCreateStatus.InvalidEmail:
            //return "The e-mail address provided is invalid. Please check the value and try again.";
            return(CreateUserWizard1.InvalidEmailErrorMessage);

        case MembershipCreateStatus.InvalidAnswer:
            //return "The password retrieval answer provided is invalid. Please check the value and try again.";
            return(CreateUserWizard1.InvalidAnswerErrorMessage);

        case MembershipCreateStatus.InvalidQuestion:
            //return "The password retrieval question provided is invalid. Please check the value and try again.";
            return(CreateUserWizard1.InvalidQuestionErrorMessage);

        case MembershipCreateStatus.InvalidUserName:
            return("The user name provided is invalid. Please check the value and try again.");

        case MembershipCreateStatus.ProviderError:
            return("The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.");

        case MembershipCreateStatus.UserRejected:
            return("The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.");

        default:
            //return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            return(status.ToString());
        } // End switch
    }     //End Function GetErrorMessage
Esempio n. 19
0
        public static string CreateUserStatusMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
            case MembershipCreateStatus.InvalidPassword:
                return("Password does not meet strength requirements, or does not meet the following criteria: "
                       + "<br/>minimum length: "
                       + Membership.MinRequiredPasswordLength
                       + "<br/>minimum non-alphanumeric characters: "
                       + Membership.MinRequiredNonAlphanumericCharacters);

            case MembershipCreateStatus.DuplicateEmail:
                return(" Email address is already in use.");

            case MembershipCreateStatus.DuplicateUserName:
                return(" Username is already in use.");

            default:
                return(status.ToString());
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Process Request to create user based on HTTP context
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest          request    = context.Request;
            HttpResponse         response   = context.Response;
            String               jsonString = String.Empty;
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            LoginModel.Login login = new LoginModel.Login(new User {
                UserName  = request.Form["userName"],
                Password  = request.Form["password"],
                FirstName = request.Form["firstName"],
                LastName  = request.Form["lastName"],
                Email     = request.Form["email"]
            });

            MembershipCreateStatus createStatus = login.CreateUser(new WebContentLocator());

            jsonString = serializer.Serialize(new { result = createStatus.ToString() });

            response.Write(jsonString);
            response.ContentType = "application/json";
        }
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            var culture = System.Globalization.CultureInfo.CurrentCulture;

            switch (createStatus)
            {
            case MembershipCreateStatus.DuplicateUserName:
            case MembershipCreateStatus.DuplicateEmail:
            case MembershipCreateStatus.InvalidPassword:
            case MembershipCreateStatus.InvalidEmail:
            case MembershipCreateStatus.InvalidAnswer:
            case MembershipCreateStatus.InvalidQuestion:
            case MembershipCreateStatus.InvalidUserName:
            case MembershipCreateStatus.ProviderError:
            case MembershipCreateStatus.UserRejected:
                return(MembershipResources.ResourceManager.GetString(createStatus.ToString(), culture));

            default:
                return(MembershipResources.UnknownError);
            }
        }
 public string ErrorMessage(MembershipCreateStatus status)
 {
     return status.ToString();
 }
 protected virtual string GetErrorCodeFromString(MembershipCreateStatus createStatus)
 {
     return createStatus.ToString();
 }
Esempio n. 24
0
        public Customer SaveInfo()
        {
            Customer customer = CustomerManager.GetCustomerById(this.CustomerId);

            string email            = txtEmail.Text.Trim();
            int    affiliateId      = int.Parse(this.ddlAffiliate.SelectedItem.Value);
            bool   isTaxExempt      = cbIsTaxExempt.Checked;
            bool   isAdmin          = cbIsAdmin.Checked;
            bool   isForumModerator = cbIsForumModerator.Checked;
            bool   active           = cbActive.Checked;
            string adminComment     = txtAdminComment.Text.Trim();

            if (customer != null)
            {
                customer = CustomerManager.SetEmail(customer.CustomerId, email);

                customer = CustomerManager.UpdateCustomer(customer.CustomerId, customer.CustomerGuid,
                                                          customer.Email, customer.Username, customer.PasswordHash,
                                                          customer.SaltKey, affiliateId,
                                                          customer.BillingAddressId, customer.ShippingAddressId,
                                                          customer.LastPaymentMethodId, customer.LastAppliedCouponCode,
                                                          customer.GiftCardCouponCodes, customer.CheckoutAttributes,
                                                          customer.LanguageId, customer.CurrencyId, customer.TaxDisplayType,
                                                          isTaxExempt, isAdmin, customer.IsGuest, isForumModerator,
                                                          customer.TotalForumPosts, customer.Signature, adminComment, active,
                                                          customer.Deleted, customer.RegistrationDate, customer.TimeZoneId, customer.AvatarId);
            }
            else
            {
                string username = txtUsername.Text;
                string password = txtPassword.Text;
                if (String.IsNullOrEmpty(password))
                {
                    throw new NopException(GetLocaleResourceString("Customer.PasswordIsRequired"));
                }
                MembershipCreateStatus createStatus = MembershipCreateStatus.Success;
                customer = CustomerManager.AddCustomer(Guid.NewGuid(), email, username,
                                                       password, affiliateId,
                                                       0, 0, 0, string.Empty, string.Empty, string.Empty,
                                                       NopContext.Current.WorkingLanguage.LanguageId,
                                                       NopContext.Current.WorkingCurrency.CurrencyId,
                                                       NopContext.Current.TaxDisplayType,
                                                       isTaxExempt, isAdmin,
                                                       false, isForumModerator,
                                                       0, string.Empty, adminComment, active,
                                                       false, DateTime.Now, string.Empty, 0, out createStatus);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    throw new NopException(string.Format("Could not create new customer: {0}", createStatus.ToString()));
                }
            }

            //form fields
            if (CustomerManager.FormFieldGenderEnabled)
            {
                if (rbGenderM.Checked)
                {
                    customer.Gender = "M";
                }
                else
                {
                    customer.Gender = "F";
                }
            }
            customer.FirstName = txtFirstName.Text;
            customer.LastName  = txtLastName.Text;
            if (CustomerManager.FormFieldDateOfBirthEnabled)
            {
                customer.DateOfBirth = ctrlDateOfBirthDatePicker.SelectedDate;
            }
            if (CustomerManager.FormFieldCompanyEnabled)
            {
                customer.Company = txtCompany.Text;
            }
            if (CustomerManager.FormFieldStreetAddressEnabled)
            {
                customer.StreetAddress = txtStreetAddress.Text;
            }
            if (CustomerManager.FormFieldStreetAddress2Enabled)
            {
                customer.StreetAddress2 = txtStreetAddress2.Text;
            }
            if (CustomerManager.FormFieldPostCodeEnabled)
            {
                customer.ZipPostalCode = txtZipPostalCode.Text;
            }
            if (CustomerManager.FormFieldCityEnabled)
            {
                customer.City = txtCity.Text;
            }
            if (CustomerManager.FormFieldCountryEnabled)
            {
                customer.CountryId = int.Parse(ddlCountry.SelectedItem.Value);
            }
            if (CustomerManager.FormFieldCountryEnabled &&
                CustomerManager.FormFieldStateEnabled)
            {
                customer.StateProvinceId = int.Parse(ddlStateProvince.SelectedItem.Value);
            }
            if (CustomerManager.FormFieldPhoneEnabled)
            {
                customer.PhoneNumber = txtPhoneNumber.Text;
            }
            if (CustomerManager.FormFieldFaxEnabled)
            {
                customer.FaxNumber = txtFaxNumber.Text;
            }
            customer.ReceiveNewsletter = cbNewsletter.Checked;

            if (DateTimeHelper.AllowCustomersToSetTimeZone)
            {
                if (ddlTimeZone.SelectedItem != null && !String.IsNullOrEmpty(ddlTimeZone.SelectedItem.Value))
                {
                    string       timeZoneId = ddlTimeZone.SelectedItem.Value;
                    TimeZoneInfo timeZone   = DateTimeHelper.FindTimeZoneById(timeZoneId);
                    if (timeZone != null)
                    {
                        customer = CustomerManager.SetTimeZoneId(customer.CustomerId, timeZone.Id);
                    }
                }
            }

            return(customer);
        }
Esempio n. 25
0
 public string ErrorMessage(MembershipCreateStatus status)
 {
     return(status.ToString());
 }
Esempio n. 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InvalidUserException"/> class.
 /// </summary>
 /// <param name="status">The status.</param>
 public InvalidUserException(MembershipCreateStatus status)
     : base(status.ToString())
 {
     Status = status;
 }
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes and add appropriate error handling.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusDuplicateUserName);

                case MembershipCreateStatus.DuplicateEmail:
                    return ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusDuplicateEmail);

                case MembershipCreateStatus.ProviderError:
                    return ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusProviderError);

                case MembershipCreateStatus.UserRejected:
                    return ClientCultureBasedResources.GetResource(() => ErrorResources.MembershipCreateStatusUserRejected);

                case MembershipCreateStatus.InvalidPassword:
                case MembershipCreateStatus.InvalidEmail:
                case MembershipCreateStatus.InvalidAnswer:
                case MembershipCreateStatus.InvalidQuestion:
                case MembershipCreateStatus.InvalidUserName:
                    // All this errors should have been handled by the UI validation so theoretically
                    // we should never get to this point
                    return "Validation Error: " + createStatus.ToString();

                default:
                    return "Could not register the user, please verify the provided information and try again.";
            }
        }
 public MembershipCreateUserException(MembershipCreateStatus statusCode) : base(statusCode.ToString())
 {
     this.statusCode = statusCode;
 }
Esempio n. 29
0
 protected void AP_SaveButton_Click(object sender, EventArgs e)
 {
     MembershipCreateStatus status = new MembershipCreateStatus();
     MembershipUser muser = Membership.CreateUser(AP_UsernameTextBox.Text.Trim(), AP_PasswordTextBox.Text.Trim(), AP_EmailTextBox.Text.Trim(), questionKey, answerKey, true, out status);
     if (status == MembershipCreateStatus.Success)
     {
         Roles.AddUserToRoles(AP_UsernameTextBox.Text.Trim(), GetSelectedList(AP_RoleCheckBoxList));
         ActionName = ListPanel.ID;
         InfoMessage("Yeni kullanýcý eklendi");
     }
     else
     {
         ErrorMessage(status.ToString());
     }
 }
Esempio n. 30
0
        public MembershipCreateStatus CreateUser()
        {
            int    errorNumber      = 0;
            string errorDescription = "";

            MembershipCreateStatus result = _userDao.CreateUser(_currentLogin, this, _provider.PasswordFormat, _provider.RequiresUniqueEmail,
                                                                out errorNumber, out errorDescription);

            if (errorNumber != 0 || !string.IsNullOrEmpty(errorDescription))
            {
                LogManager.WriteWarning(_currentLogin, this, "User " + this.UserName + " cannot be created.", errorDescription);
                return(result);
            }

            if (result == MembershipCreateStatus.Success)
            {
                LogManager.WriteTrace(_currentLogin, this, "User " + this.UserName + " has created.", null);
            }
            else
            {
                LogManager.WriteWarning(_currentLogin, this, "User " + this.UserName + " couldn't be created. Error: " + result.ToString(), null);
            }



            return(result);
        }
        void OnCreateUser(object sender, EventArgs e)
        {
            IMembershipManager membershipManager = UserManagerProviderFactory.CreateMembershipManager(); // new AspNetSqlProviderService(m_Url);

            string[]           users  = membershipManager.GetAllUsers(m_Application);
            Predicate <string> exists = delegate(string user)
            {
                return(user == m_UserNameTextBox.Text);
            };

            if (Array.Exists(users, exists))
            {
                m_Validator.SetError(m_UserNameTextBox, "User name already exists");
                return;
            }
            m_Validator.Clear();

            if (m_PasswordTextbox.Text == String.Empty)
            {
                m_Validator.SetError(m_PasswordTextbox, "Password cannot be empty");
                return;
            }
            m_Validator.Clear();

            if (m_PasswordTextbox.Text != m_ConfirmedPasswordTextBox.Text)
            {
                m_Validator.SetError(m_ConfirmedPasswordTextBox, "Confirmed password does not match");
                return;
            }
            m_Validator.Clear();

            if (m_UserNameTextBox.Text == String.Empty)
            {
                m_Validator.SetError(m_UserNameTextBox, "User name cannot be empty");
                return;
            }
            m_Validator.Clear();

            if (m_EmailTextBox.Text == String.Empty)
            {
                m_Validator.SetError(m_EmailTextBox, "Email cannot be empty");
                return;
            }
            m_Validator.Clear();

            if (m_SecurityQuestionTextBox.Text == String.Empty)
            {
                m_Validator.SetError(m_SecurityQuestionTextBox, "Security question cannot be empty");
                return;
            }
            m_Validator.Clear();

            if (m_SecurityAnswerTextbox.Text == String.Empty)
            {
                m_Validator.SetError(m_SecurityAnswerTextbox, "Security question cannot be empty");
                return;
            }
            m_Validator.Clear();

            MembershipCreateStatus status = membershipManager.CreateUser(m_Application, m_UserNameTextBox.Text, m_PasswordTextbox.Text, m_EmailTextBox.Text, m_SecurityQuestionTextBox.Text, m_SecurityAnswerTextbox.Text, m_ActiveUserCheckBox.Checked);

            if (status != MembershipCreateStatus.Success)
            {
                MessageBox.Show(status.ToString(), "Credentials Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                m_Users.Add(m_UserNameTextBox.Text);
                m_CreatedUsersListView.AddItem(m_UserNameTextBox.Text, true);
                m_UserNameTextBox.Text = String.Empty;
                m_UserNameTextBox.Focus();
                m_GeneratePasswordCheckBox.Checked = false;
                m_PasswordTextbox.Text             = String.Empty;
                m_ConfirmedPasswordTextBox.Text    = String.Empty;
            }
        }
Esempio n. 32
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtEmployeeCode.Text != string.Empty && txtJoiningDate.Text != string.Empty && txtUserName.Text != string.Empty && txtEmailID.Text != string.Empty)
            {
                DataSet CheckUserNameEmail = new DataSet();
                objJoinEmployeeBOL.EmailId  = Convert.ToString(txtEmailID.Text);
                objJoinEmployeeBOL.UserName = Convert.ToString(txtUserName.Text);
                CheckUserNameEmail          = objJoinEmployeeBLL.CheckUserNameEmail(objJoinEmployeeBOL);

                if (CheckUserNameEmail.Tables[0].Rows.Count != 0)
                {
                    if (CheckUserNameEmail.Tables[0].Rows[0][0].ToString() != "0")
                    {
                        lblUserNameError.ForeColor = System.Drawing.Color.Red;
                        lblUserNameError.Visible   = true;
                    }
                }
                //
                if (CheckUserNameEmail.Tables[1].Rows.Count != 0)
                {
                    if (CheckUserNameEmail.Tables[1].Rows[0][0].ToString() != "0")
                    {
                        lblEmailError.ForeColor = System.Drawing.Color.Red;
                        lblEmailError.Visible   = true;
                    }
                }

                if (CheckUserNameEmail.Tables[0].Rows[0][0].ToString() == "0" && CheckUserNameEmail.Tables[1].Rows[0][0].ToString() == "0")
                {
                    lblUserNameError.Visible        = false;
                    lblEmailError.Visible           = false;
                    objJoinEmployeeBOL.Employeecode = Convert.ToInt32(txtEmployeeCode.Text);
                    objJoinEmployeeBOL.UserName     = Convert.ToString(txtUserName.Text);
                    objJoinEmployeeBOL.EmailId      = Convert.ToString(txtEmailID.Text);
                    objJoinEmployeeBOL.CandidateId  = Convert.ToInt32(Session["CandidateID"]);
                    objJoinEmployeeBOL.JoiningDate  = Convert.ToDateTime(txtJoiningDate.Text);
                    DataSet dsEmployeeCreated = new DataSet();
                    dsEmployeeCreated = objJoinEmployeeBLL.CreaetNewEmployee(objJoinEmployeeBOL);

                    MembershipCreateStatus objMembershipCreateStatus = new MembershipCreateStatus();
                    if (dsEmployeeCreated.Tables != null)
                    {
                        if (dsEmployeeCreated.Tables[0].Rows.Count != 0)
                        {
                            if (Convert.ToString(dsEmployeeCreated.Tables[0].Rows[0][0]) == "0")
                            {
                                Membership.CreateUser(Convert.ToString(objJoinEmployeeBOL.Employeecode), "mail_123", objJoinEmployeeBOL.EmailId, "Question", "Answer", true, out objMembershipCreateStatus);
                            }
                        }
                    }
                    string strSuccess = "";
                    strSuccess = objMembershipCreateStatus.ToString();
                    if (objMembershipCreateStatus.ToString() == "Success")
                    {
                        lblSuccess.Visible   = true;
                        lblSuccess.ForeColor = System.Drawing.Color.Green;
                        lblSuccess.Text      = "Employee created successfully";
                    }
                    else
                    {
                        lblSuccess.Visible   = true;
                        lblSuccess.ForeColor = System.Drawing.Color.Red;
                        lblSuccess.Text      = "Employee not created";
                    }

                    Session["EmployeeCode"] = Convert.ToString(txtEmployeeCode.Text);
                    ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open('SendMailPopUP.aspx',null,'height=500, width=600,status= no, resizable= no, scrollbars=yes, toolbar=no,location=no,menubar=no');", true);
                }
            }
            else
            {
                lblEmailError.Visible      = true;
                lblUserNameError.Visible   = true;
                lblEmailError.ForeColor    = System.Drawing.Color.Red;
                lblUserNameError.ForeColor = System.Drawing.Color.Red;
                lblEmailError.Text         = "Please enter proper Email Id";
                lblUserNameError.Text      = "Please enter proper UserName";
            }

            //ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open('SendMailPopUP.aspx?height=250, width=1200,status= no, resizable= no, scrollbars=yes, toolbar=no,location=no,menubar=no', null, 'status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no' );", true);

            // Response.Redirect("SendMailPopUP.aspx");
        }
        public Customer SaveInfo()
        {
            Customer customer = this.CustomerService.GetCustomerById(this.CustomerId);

            string username         = txtUsername.Text;
            string email            = txtEmail.Text.Trim();
            int    affiliateId      = int.Parse(this.ddlAffiliate.SelectedItem.Value);
            bool   isTaxExempt      = cbIsTaxExempt.Checked;
            bool   isAdmin          = cbIsAdmin.Checked;
            bool   isForumModerator = cbIsForumModerator.Checked;
            bool   active           = cbActive.Checked;
            string adminComment     = txtAdminComment.Text.Trim();

            if (customer != null)
            {
                //username
                if (this.CustomerService.UsernamesEnabled &&
                    this.CustomerService.AllowCustomersToChangeUsernames)
                {
                    if (customer.Username.ToLowerInvariant() != username.ToLowerInvariant().Trim())
                    {
                        if (!customer.IsGuest)
                        {
                            customer = this.CustomerService.ChangeCustomerUsername(customer.CustomerId, username);
                        }
                    }
                }

                //email
                if (customer.Email.ToLowerInvariant() != email.ToLowerInvariant().Trim())
                {
                    if (!customer.IsGuest)
                    {
                        customer = this.CustomerService.SetEmail(customer.CustomerId, email);
                    }
                }

                customer.AffiliateId      = affiliateId;
                customer.IsTaxExempt      = isTaxExempt;
                customer.IsAdmin          = isAdmin;
                customer.IsForumModerator = isForumModerator;
                customer.AdminComment     = adminComment;
                customer.Active           = active;
                this.CustomerService.UpdateCustomer(customer);
            }
            else
            {
                string password = txtPassword.Text;
                if (String.IsNullOrEmpty(password))
                {
                    throw new NopException(GetLocaleResourceString("Customer.PasswordIsRequired"));
                }
                MembershipCreateStatus createStatus = MembershipCreateStatus.Success;

                customer = this.CustomerService.AddCustomer(Guid.NewGuid(), email, username,
                                                            password, affiliateId,
                                                            0, 0, 0, string.Empty, string.Empty, string.Empty,
                                                            NopContext.Current.WorkingLanguage.LanguageId,
                                                            NopContext.Current.WorkingCurrency.CurrencyId,
                                                            NopContext.Current.TaxDisplayType,
                                                            isTaxExempt, isAdmin,
                                                            false, isForumModerator,
                                                            0, string.Empty, adminComment, active,
                                                            false, DateTime.UtcNow, string.Empty,
                                                            0, null, out createStatus);

                if (createStatus != MembershipCreateStatus.Success)
                {
                    throw new NopException(string.Format("Could not create new customer: {0}", createStatus.ToString()));
                }
            }

            //form fields
            if (this.CustomerService.FormFieldGenderEnabled)
            {
                if (rbGenderM.Checked)
                {
                    customer.Gender = "M";
                }
                else
                {
                    customer.Gender = "F";
                }
            }

            customer.FirstName = txtFirstName.Text;
            customer.LastName  = txtLastName.Text;
            if (this.CustomerService.FormFieldDateOfBirthEnabled)
            {
                customer.DateOfBirth = ctrlDateOfBirthDatePicker.SelectedDate;
                this.CustomerService.UpdateCustomer(customer);
            }
            if (this.CustomerService.FormFieldCompanyEnabled)
            {
                customer.Company = txtCompany.Text;
            }
            if (this.CustomerService.FormFieldStreetAddressEnabled)
            {
                customer.StreetAddress = txtStreetAddress.Text;
            }
            if (this.CustomerService.FormFieldStreetAddress2Enabled)
            {
                customer.StreetAddress2 = txtStreetAddress2.Text;
            }
            if (this.CustomerService.FormFieldPostCodeEnabled)
            {
                customer.ZipPostalCode = txtZipPostalCode.Text;
            }
            if (this.CustomerService.FormFieldCityEnabled)
            {
                customer.City = txtCity.Text;
            }
            if (this.CustomerService.FormFieldCountryEnabled)
            {
                customer.CountryId = int.Parse(ddlCountry.SelectedItem.Value);
            }
            if (this.CustomerService.FormFieldCountryEnabled &&
                this.CustomerService.FormFieldStateEnabled)
            {
                customer.StateProvinceId = int.Parse(ddlStateProvince.SelectedItem.Value);
            }
            if (this.CustomerService.FormFieldPhoneEnabled)
            {
                customer.PhoneNumber = txtPhoneNumber.Text;
            }
            if (this.CustomerService.FormFieldFaxEnabled)
            {
                customer.FaxNumber = txtFaxNumber.Text;
            }
            if (this.CustomerService.FormFieldNewsletterEnabled)
            {
                customer.ReceiveNewsletter = cbNewsletter.Checked;
            }

            //set VAT number after country is saved
            if (this.TaxService.EUVatEnabled)
            {
                string prevVatNumber = customer.VatNumber;
                customer.VatNumber = txtVatNumber.Text;
                //set VAT number status
                if (!txtVatNumber.Text.Trim().Equals(prevVatNumber))
                {
                    customer.VatNumberStatus = this.TaxService.GetVatNumberStatus(this.CountryService.GetCountryById(customer.CountryId), customer.VatNumber);
                }
            }

            if (DateTimeHelper.AllowCustomersToSetTimeZone)
            {
                if (ddlTimeZone.SelectedItem != null && !String.IsNullOrEmpty(ddlTimeZone.SelectedItem.Value))
                {
                    string       timeZoneId = ddlTimeZone.SelectedItem.Value;
                    TimeZoneInfo timeZone   = DateTimeHelper.FindTimeZoneById(timeZoneId);
                    if (timeZone != null)
                    {
                        customer.TimeZoneId = timeZone.Id;
                        this.CustomerService.UpdateCustomer(customer);
                    }
                }
            }

            return(customer);
        }
        private void LogCreateUserError(MembershipCreateStatus status, string username)
        {
            string reasonText = status.ToString();

            switch (status)
            {
                case MembershipCreateStatus.DuplicateEmail:
                case MembershipCreateStatus.DuplicateProviderUserKey:
                case MembershipCreateStatus.DuplicateUserName:

                    reasonText = "The user details you entered are already registered.";
                    break;

                case MembershipCreateStatus.InvalidAnswer:
                case MembershipCreateStatus.InvalidEmail:
                case MembershipCreateStatus.InvalidProviderUserKey:
                case MembershipCreateStatus.InvalidQuestion:
                case MembershipCreateStatus.InvalidUserName:
                case MembershipCreateStatus.InvalidPassword:

                    reasonText = string.Format("The {0} provided was invalid.", status.ToString().Substring(7));
                    break;
                default:
                    reasonText = "Due to an unknown problem, we were not able to register you at this time";
                    break;

            }
        }
        public static void Import(out int count)
        {
            using (StreamWriter writer = new StreamWriter(@"C:\HCCCustomerOutput.txt"))
            {
                Console.SetOut(writer);

                count = 0;
                List <string> errorReport = new List <string>();

                try
                {
                    List <ImportedCustomer> impCusts = GetAll();

                    foreach (ImportedCustomer impCust in impCusts)
                    {
                        Console.WriteLine(count + " : ");
                        if (!impCust.IsValid)
                        {
                            impCust.Email = "admin" + count.ToString() + "@healthychefcreations.com";
                        }
                        else if (impCust.Email.Contains("info@healthychef") || impCust.Email.Contains("thehealthyassistant@earthlink"))
                        {
                            impCust.Email = "admin" + count.ToString() + "@healthychefcreations.com";
                        }

                        Console.WriteLine(impCust.Email);

                        if (impCust.IsValid)
                        {
                            count++;

                            string         userName    = impCust.Email.Trim().Split('@')[0] + DateTime.Now.ToString("yyyyMMddHHmmtt");
                            string         password    = OrderNumberGenerator.GenerateOrderNumber("?#?#?#?#");
                            string         aspUserName = Membership.GetUserNameByEmail(impCust.Email.Trim());
                            MembershipUser newUser     = null;

                            if (!string.IsNullOrWhiteSpace(aspUserName))
                            {
                                newUser = Membership.GetUser(aspUserName);
                            }

                            MembershipCreateStatus createResult = MembershipCreateStatus.UserRejected;

                            if (newUser == null)
                            {
                                newUser = Membership.CreateUser(userName, password, impCust.Email.Trim(), "import", "import", true, out createResult);

                                if (newUser != null)
                                {
                                    Console.WriteLine(newUser.UserName + "New user.");
                                }
                            }
                            else
                            {
                                Console.WriteLine(newUser.UserName + " Existing user.");
                                createResult = MembershipCreateStatus.Success;
                            }

                            if (newUser != null)
                            {
                                if (createResult == MembershipCreateStatus.Success)
                                {
                                    //Assign Customer role to newUser
                                    try
                                    {
                                        if (!Roles.IsUserInRole(newUser.UserName, "Customer"))
                                        {
                                            Roles.AddUserToRole(newUser.UserName, "Customer");
                                            Console.WriteLine(newUser.UserName + " Role assigned.");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(newUser.UserName + " =Assign role failed." + ex.Message + ex.StackTrace);
                                    }
                                    //Send E-mail notification to account user
                                    //HealthyChef.Email.EmailController ec = new HealthyChef.Email.EmailController();
                                    //ec.SendMail_NewUserConfirmation(email, password);

                                    //Create a Healthy Chef profile for this new user
                                    hccUserProfile newProfile = hccUserProfile.GetBy((Guid)newUser.ProviderUserKey).SingleOrDefault(a => !a.ParentProfileID.HasValue);

                                    if (newProfile == null)
                                    {
                                        try
                                        {
                                            newProfile = new hccUserProfile
                                            {
                                                MembershipID   = (Guid)newUser.ProviderUserKey,
                                                CreatedBy      = (Membership.GetUser() == null ? Guid.Empty : (Guid)Membership.GetUser().ProviderUserKey),
                                                CreatedDate    = DateTime.Now,
                                                AccountBalance = 0.00m,
                                                IsActive       = true,
                                                FirstName      = impCust.FirstName.Trim(),
                                                LastName       = impCust.LastName.Trim(),
                                                ProfileName    = impCust.FirstName.Trim()
                                            };

                                            //Save all hccProfile information
                                            using (var cont = new healthychefEntities())
                                            {
                                                System.Data.EntityKey key = cont.CreateEntityKey("hccUserProfiles", newProfile);
                                                object oldObj;

                                                if (cont.TryGetObjectByKey(key, out oldObj))
                                                {
                                                    cont.ApplyCurrentValues("hccUserProfiles", newProfile);
                                                }
                                                else
                                                {
                                                    cont.hccUserProfiles.AddObject(newProfile);
                                                }

                                                cont.SaveChanges();
                                            }
                                            //cont.Refresh(System.Data.Objects.RefreshMode.StoreWins, newProfile);
                                            Console.WriteLine(newUser.UserName + " New profile.");
                                        }
                                        catch (Exception)
                                        {
                                            Console.WriteLine("=" + newUser.UserName + " Save Profile failed.");
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine(newUser.UserName + " Existing profile.");
                                        createResult = MembershipCreateStatus.Success;
                                    }

                                    if (newProfile != null && newProfile.UserProfileID > 0)
                                    {
                                        if (impCust.OtherDeliveryInfo != null && !string.IsNullOrWhiteSpace(impCust.OtherDeliveryInfo))
                                        {
                                            hccUserProfileNote shipNote = new hccUserProfileNote
                                            {
                                                DateCreated   = DateTime.Now,
                                                DisplayToUser = false,
                                                UserProfileID = newProfile.UserProfileID,
                                                IsActive      = true,
                                                Note          = impCust.OtherDeliveryInfo,
                                                NoteTypeID    = (int)Enums.UserProfileNoteTypes.ShippingNote
                                            };

                                            using (var cont = new healthychefEntities())
                                            {
                                                EntityKey key          = cont.CreateEntityKey("hccUserProfileNotes", shipNote);
                                                object    originalItem = null;

                                                if (cont.TryGetObjectByKey(key, out originalItem))
                                                {
                                                    cont.ApplyCurrentValues(key.EntitySetName, shipNote);
                                                }
                                                else
                                                {
                                                    cont.hccUserProfileNotes.AddObject(shipNote);
                                                }

                                                cont.SaveChanges();
                                            }
                                        }

                                        if (impCust.HowDidYouHear != null && !string.IsNullOrWhiteSpace(impCust.HowDidYouHear))
                                        {
                                            hccUserProfileNote hearNote = new hccUserProfileNote
                                            {
                                                DateCreated   = DateTime.Now,
                                                DisplayToUser = false,
                                                UserProfileID = newProfile.UserProfileID,
                                                IsActive      = true,
                                                Note          = impCust.HowDidYouHear,
                                                NoteTypeID    = (int)Enums.UserProfileNoteTypes.GeneralNote
                                            };

                                            using (var cont = new healthychefEntities())
                                            {
                                                EntityKey key          = cont.CreateEntityKey("hccUserProfileNotes", hearNote);
                                                object    originalItem = null;

                                                if (cont.TryGetObjectByKey(key, out originalItem))
                                                {
                                                    cont.ApplyCurrentValues(key.EntitySetName, hearNote);
                                                }
                                                else
                                                {
                                                    cont.hccUserProfileNotes.AddObject(hearNote);
                                                }

                                                cont.SaveChanges();
                                            }
                                        }

                                        try
                                        {
                                            //save Shipping Address
                                            hccAddress shipAddr = null;

                                            if (newProfile.ShippingAddressID.HasValue)
                                            {
                                                shipAddr = hccAddress.GetById(newProfile.ShippingAddressID.Value);
                                            }

                                            if (shipAddr != null)
                                            {
                                                try
                                                {
                                                    newProfile.ShippingAddressID = null;
                                                    //Save all hccProfile information
                                                    using (var cont = new healthychefEntities())
                                                    {
                                                        System.Data.EntityKey key1 = cont.CreateEntityKey("hccUserProfiles", newProfile);
                                                        object oldObj1;

                                                        if (cont.TryGetObjectByKey(key1, out oldObj1))
                                                        {
                                                            cont.ApplyCurrentValues("hccUserProfiles", newProfile);
                                                        }
                                                        else
                                                        {
                                                            cont.hccUserProfiles.AddObject(newProfile);
                                                        }
                                                        cont.SaveChanges();
                                                    }
                                                    //cont.Refresh(System.Data.Objects.RefreshMode.StoreWins, newProfile);
                                                    using (var cont = new healthychefEntities())
                                                    {
                                                        EntityKey key          = cont.CreateEntityKey("hccAddresses", shipAddr);
                                                        object    originalItem = null;

                                                        if (cont.TryGetObjectByKey(key, out originalItem))
                                                        {
                                                            cont.AttachTo(shipAddr.EntityKey.EntitySetName, shipAddr);
                                                            cont.DeleteObject(shipAddr);
                                                        }
                                                        cont.SaveChanges();
                                                    }

                                                    shipAddr = null;
                                                }
                                                catch (Exception ex)
                                                {
                                                    Console.WriteLine(newUser.UserName + " =Delete old shipping address failed." + ex.Message + ex.StackTrace);
                                                }
                                            }

                                            if (shipAddr == null)
                                            {
                                                shipAddr = new hccAddress();
                                            }

                                            if (impCust.ShippingAddress1 != null)
                                            {
                                                shipAddr.Address1 = (string.IsNullOrWhiteSpace(impCust.ShippingAddress1) ? "" : impCust.ShippingAddress1.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.Address1 = "";
                                            }

                                            if (impCust.ShippingAddress2 != null)
                                            {
                                                shipAddr.Address2 = (string.IsNullOrWhiteSpace(impCust.ShippingAddress2) ? "" : impCust.ShippingAddress2.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.Address2 = "";
                                            }

                                            if (impCust.ShippingAddress3 != null)
                                            {
                                                shipAddr.Address2 += " " + (string.IsNullOrWhiteSpace(impCust.ShippingAddress3) ? "" : impCust.ShippingAddress3.Trim());
                                            }

                                            shipAddr.AddressTypeID = (int)Enums.AddressType.Shipping;

                                            if (impCust.ShippingCity != null)
                                            {
                                                shipAddr.City = (string.IsNullOrWhiteSpace(impCust.ShippingCity) ? "" : impCust.ShippingCity.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.City = "";
                                            }

                                            shipAddr.Country = "US";

                                            if (impCust.FirstName != null)
                                            {
                                                shipAddr.FirstName = (string.IsNullOrWhiteSpace(impCust.FirstName) ? "" : impCust.FirstName.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.FirstName = "";
                                            }

                                            shipAddr.IsBusiness = false;

                                            if (impCust.LastName != null)
                                            {
                                                shipAddr.LastName = (string.IsNullOrWhiteSpace(impCust.LastName) ? "" : impCust.LastName.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.LastName = "";
                                            }

                                            if (impCust.Phone1 != null)
                                            {
                                                shipAddr.Phone = (string.IsNullOrWhiteSpace(impCust.Phone1) ? "" : impCust.Phone1.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.Phone = "";
                                            }

                                            if (impCust.Phone1Ext != null)
                                            {
                                                shipAddr.Phone += (string.IsNullOrWhiteSpace(impCust.Phone1Ext.Trim()) ? "" : " x" + impCust.Phone1Ext.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.Phone = "";
                                            }

                                            if (impCust.ShippingZipCode != null)
                                            {
                                                shipAddr.PostalCode = (string.IsNullOrWhiteSpace(impCust.ShippingZipCode) ? "" : impCust.ShippingZipCode.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.PostalCode = "";
                                            }

                                            if (impCust.ShippingState != null)
                                            {
                                                shipAddr.State = (string.IsNullOrWhiteSpace(impCust.ShippingState) ? "" : impCust.ShippingState.Trim());
                                            }
                                            else
                                            {
                                                shipAddr.State = "";
                                            }

                                            if (impCust.ShipMethod == null)
                                            {
                                                shipAddr.DefaultShippingTypeID = (int)Enums.DeliveryTypes.Delivery;
                                            }
                                            else if (impCust.ShipMethod.Trim() == "F")
                                            {
                                                shipAddr.DefaultShippingTypeID = (int)Enums.DeliveryTypes.Delivery;
                                            }
                                            else if (impCust.ShipMethod.Trim() == "P")
                                            {
                                                shipAddr.DefaultShippingTypeID = (int)Enums.DeliveryTypes.LocalPickUp;
                                            }
                                            else if (impCust.ShipMethod.Trim() == "D")
                                            {
                                                shipAddr.DefaultShippingTypeID = (int)Enums.DeliveryTypes.LocalDelivery;
                                            }
                                            else
                                            {
                                                shipAddr.DefaultShippingTypeID = (int)Enums.DeliveryTypes.Delivery;
                                            }

                                            if (shipAddr != null)
                                            {
                                                try
                                                {
                                                    using (var cont = new healthychefEntities())
                                                    {
                                                        EntityKey key          = cont.CreateEntityKey("hccAddresses", shipAddr);
                                                        object    originalItem = null;

                                                        if (cont.TryGetObjectByKey(key, out originalItem))
                                                        {
                                                            cont.hccAddresses.ApplyCurrentValues((hccAddress)originalItem);
                                                        }
                                                        else
                                                        {
                                                            cont.hccAddresses.AddObject(shipAddr);
                                                        }

                                                        cont.SaveChanges();
                                                    }
                                                    //cont.Refresh(System.Data.Objects.RefreshMode.StoreWins, shipAddr);
                                                }
                                                catch (Exception ex)
                                                {
                                                    Console.WriteLine(newUser.UserName + " =Shipping address save failed." + ex.Message + ex.StackTrace);
                                                }
                                            }

                                            if (shipAddr != null && shipAddr.AddressID > 0)
                                            {
                                                newProfile.ShippingAddressID = shipAddr.AddressID;
                                            }
                                            else
                                            {
                                                newProfile.ShippingAddressID = null;
                                            }

                                            using (var cont = new healthychefEntities())
                                            {
                                                System.Data.EntityKey upkey = cont.CreateEntityKey("hccUserProfiles", newProfile);
                                                object oldObj;

                                                if (cont.TryGetObjectByKey(upkey, out oldObj))
                                                {
                                                    cont.ApplyCurrentValues("hccUserProfiles", newProfile);
                                                }
                                                else
                                                {
                                                    cont.hccUserProfiles.AddObject(newProfile);
                                                }

                                                cont.SaveChanges();
                                            }

                                            Console.WriteLine(newUser.UserName + " Shipping address saved.");
                                        }
                                        catch (Exception ex)
                                        {
                                            Console.WriteLine(newUser.UserName + " =Shipping address not created." + ex.Message + ex.StackTrace);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("User Profile for user: "******" ID not created.");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("=New user for user: "******" not created.");
                                }
                            }
                            else
                            {
                                Console.WriteLine(createResult.ToString() + " : " + impCust.Email);
                            }
                        }
                        else
                        {
                            count++; Console.WriteLine("=Customer: " + impCust.FirstName + " " + impCust.LastName + " has no email address.");
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine("=" + ex.Message + " : " + ex.StackTrace); }
            }
        }
Esempio n. 36
0
        public void CreateUser(string appName, string userName, string userPassword, string userEmail, string userPasswordQuestion, string userPasswordAnswer, bool MappedApplication)
        {
            MembershipCreateStatus userStatus = new MembershipCreateStatus();
            string oldApp = Membership.ApplicationName;

            try
            {
                if (MappedApplication)
                {
                    Membership.ApplicationName = GetMapping(appName);
                }
                else
                {
                    Membership.ApplicationName = appName;
                }

                // Create the user in the membership directory
                Membership.CreateUser(userName, userPassword, userEmail, userPasswordQuestion, userPasswordAnswer, true, out userStatus);

                // Check the Status
                if (userStatus != MembershipCreateStatus.Success)
                {
                    throw new Exception("User " + userName + " failed with status " + userStatus.ToString());
                }
            }
            finally
            {
                Membership.ApplicationName = oldApp;
            }
        }
Esempio n. 37
0
        public bool Save()
        {
            string[] nameAndMail = Alias.Split("|".ToCharArray());
            string name = nameAndMail[0];
            string email = nameAndMail.Length > 0 ? nameAndMail[1] : "";
            string password = nameAndMail.Length > 1 ? nameAndMail[2] : "";
            string loginName = nameAndMail.Length > 2 ? nameAndMail[3] : "";
            if (cms.businesslogic.member.Member.InUmbracoMemberMode() && TypeID != -1)
            {
                cms.businesslogic.member.MemberType dt = new cms.businesslogic.member.MemberType(TypeID);
                cms.businesslogic.member.Member m = cms.businesslogic.member.Member.MakeNew(name, loginName, email, dt, BusinessLogic.User.GetUser(_userID));
                m.Password = password;                
                m.LoginName = loginName.Replace(" ", "").ToLower();

                NewMemberUIEventArgs e = new NewMemberUIEventArgs();
                this.OnNewMember(e, password, m);

                _returnUrl = "members/editMember.aspx?id=" + m.Id.ToString();
            }
            else
            {
                MembershipCreateStatus mc = new MembershipCreateStatus();
                Membership.CreateUser(name, password, email, "empty", "empty", true, out mc);
                if (mc != MembershipCreateStatus.Success)
                {
                    throw new Exception("Error creating Member: " + mc.ToString());
                }
                _returnUrl = "members/editMember.aspx?id=" + System.Web.HttpContext.Current.Server.UrlEncode(name);
            }

            return true;
        }
Esempio n. 38
0
        void OnCreateUser(object sender, EventArgs e)
        {
            using (MembershipManagerProxy membershipManager = new MembershipManagerProxy(m_Url))
            {
                string[] users = membershipManager.GetAllUsers(m_Application);

                if (users.Any(user => user == m_UserNameTextBox.Text))
                {
                    m_Validator.SetError(m_UserNameTextBox, "User name already exists");
                    return;
                }
                m_Validator.Clear();

                if (m_PasswordTextbox.Text == String.Empty)
                {
                    m_Validator.SetError(m_PasswordTextbox, "Password cannot be empty");
                    return;
                }
                m_Validator.Clear();

                if (m_PasswordTextbox.Text != m_ConfirmedPasswordTextBox.Text)
                {
                    m_Validator.SetError(m_ConfirmedPasswordTextBox, "Confirmed password does not match");
                    return;
                }
                m_Validator.Clear();

                if (m_UserNameTextBox.Text == String.Empty)
                {
                    m_Validator.SetError(m_UserNameTextBox, "User name cannot be empty");
                    return;
                }
                m_Validator.Clear();

                if (m_EmailTextBox.Text == String.Empty)
                {
                    m_Validator.SetError(m_EmailTextBox, "Email cannot be empty");
                    return;
                }
                m_Validator.Clear();

                if (m_SecurityQuestionTextBox.Text == String.Empty)
                {
                    m_Validator.SetError(m_SecurityQuestionTextBox, "Security question cannot be empty");
                    return;
                }
                m_Validator.Clear();

                if (m_SecurityAnswerTextbox.Text == String.Empty)
                {
                    m_Validator.SetError(m_SecurityAnswerTextbox, "Security question cannot be empty");
                    return;
                }
                m_Validator.Clear();

                MembershipCreateStatus status = membershipManager.CreateUser(m_Application, m_UserNameTextBox.Text, m_PasswordTextbox.Text, m_EmailTextBox.Text, m_SecurityQuestionTextBox.Text, m_SecurityAnswerTextbox.Text, m_ActiveUserCheckBox.Checked);
                if (status != MembershipCreateStatus.Success)
                {
                    MessageBox.Show(status.ToString(), "Credentials Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    m_Users.Add(m_UserNameTextBox.Text);
                    m_CreatedUsersListView.AddItem(m_UserNameTextBox.Text, true);
                    m_UserNameTextBox.Text = String.Empty;
                    m_UserNameTextBox.Focus();
                    m_GeneratePasswordCheckBox.Checked = false;
                    m_PasswordTextbox.Text             = String.Empty;
                    m_ConfirmedPasswordTextBox.Text    = String.Empty;
                }
            }
        }
Esempio n. 39
0
 public SSOMembershipCreateResponse(MembershipCreateStatus status, string userName)
 {
     _status = status.ToString();
     _userName = userName;
 }
		public MembershipCreateUserException (MembershipCreateStatus statusCode) : base (statusCode.ToString ())
		{
			this.statusCode = statusCode;
		}