Пример #1
0
        public void CreateUser(ContactViewModel contactModel, string contactId)
        {
            var contact = new B2BContact(CustomerContact.CreateInstance())
            {
                ContactId      = new Guid(contactId),
                FirstName      = contactModel.FirstName,
                LastName       = contactModel.LastName,
                Email          = contactModel.Email,
                UserId         = contactModel.Email,
                UserRole       = contactModel.UserRole,
                FullName       = contactModel.FullName,
                UserLocationId = (contactModel.UserRole != B2BUserRoles.Admin.ToString()) ? contactModel.Location : ""
            };

            contact.SaveChanges();

            if (contactModel.UserRole == B2BUserRoles.Admin.ToString())
            {
                AddContactToOrganization(contact);
            }
            else
            {
                AddContactToOrganization(contact, contactModel.OrganizationId);
            }
        }
        public void MapVippsContactFields()
        {
            var mapper = new VippsLoginMapper();

            var contact = CustomerContact.CreateInstance();

            var subject    = Guid.NewGuid();
            var email      = "*****@*****.**";
            var givenName  = "Test";
            var familyName = "Tester";
            var fullName   = "Test Tester";
            var birthDate  = DateTime.Now;

            mapper.MapVippsContactFields(contact, new VippsUserInfo
            {
                Sub        = subject,
                Email      = email,
                GivenName  = givenName,
                FamilyName = familyName,
                Name       = fullName,
                BirthDate  = birthDate
            });

            Assert.Equal(email, contact.Email);
            Assert.Equal(givenName, contact.FirstName);
            Assert.Equal(familyName, contact.LastName);
            Assert.Equal(fullName, contact.FullName);
            Assert.Equal(birthDate, contact.BirthDate);
        }
Пример #3
0
        /// <summary>
        /// Reads customers and their orders from an external file and creates them in the current site.
        /// </summary>
        private void CreateContactsAndOrders()
        {
            foreach (var customer in GetCustomersToImport())
            {
                var contact = CustomerContact.CreateInstance();

                contact.UserId               = customer.Email;
                contact.Email                = customer.Email;
                contact.FirstName            = customer.FirstName;
                contact.LastName             = customer.LastName;
                contact.FullName             = $"{contact.FirstName} {contact.LastName}";
                contact.RegistrationSource   = "Imported customer";
                contact.AcceptMarketingEmail = true;
                contact.ConsentUpdated       = DateTime.Now;

                contact.SaveChanges();

                MapAddressesFromCustomerToContact(customer, contact);

                contact.SaveChanges();

                foreach (var cart in customer.Carts)
                {
                    var order = CreateOrder(contact, cart);
                    _orderRepository.Service.Save(order);
                }

                foreach (var purchaseOrder in customer.PurchaseOrders)
                {
                    var order = CreateOrder(contact, purchaseOrder);
                    ProcessAndSaveAsPurchaseOrder(contact, order);
                }
            }
        }
Пример #4
0
        public B2BContact GetNewContact()
        {
            var contact = new B2BContact(CustomerContact.CreateInstance());

            contact.ContactId = BusinessManager.Create(contact.Contact);
            return(contact);
        }
Пример #5
0
        public virtual IHttpActionResult PostContact(Guid userId, [FromBody] Contact contact)
        {
            Logger.LogPost("PostContact", Request, new [] { userId.ToString() });

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var customerContact = CustomerContact.CreateInstance();

                CustomerMappings.CreateContact(customerContact, userId, contact);

                contact = customerContact.ConvertToContact();
            }
            catch (Exception exception)
            {
                Logger.Error(exception.Message, exception);
                return(InternalServerError(exception));
            }

            return(Ok(contact));
        }
Пример #6
0
        public void RegisterAccount_WhenRegisterFails_ShouldReturnModelErrorState()
        {
            _userServiceMock.Setup(
                x => x.RegisterAccount(It.IsAny <SiteUser>()))
            .Returns(Task.FromResult(new ContactIdentityResult
                                     (
                                         new IdentityResult("We have an error"),
                                         CustomerContact.CreateInstance()
                                     )));

            var model = new RegisterAccountViewModel
            {
                Email = "*****@*****.**",
                AcceptMarketingEmail = true,
                Password             = "******",
                Password2            = "Passwors@124#212",
            };

            model.Address = new AddressModel
            {
                Line1       = "Address",
                City        = "City",
                CountryName = "Country",
                FirstName   = "Fisrt Name",
                LastName    = "Last Name",
                PostalCode  = "952595",
            };

            var result = _subject.RegisterAccount(model);

            _subject.ModelState.Values.First().Errors.First().ErrorMessage.Should().Be("We have an error");
        }
Пример #7
0
        private CustomerContact CreateCustomerContact(Customer customer, MembershipUser user)
        {
            // Add user to everyone role
            // Check if such role exists
            if (user != null)
            {
                if (RoleExists(AppRoles.EveryoneRole))
                {
                    SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.EveryoneRole);
                }

                if (RoleExists(AppRoles.RegisteredRole))
                {
                    SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.RegisteredRole);
                }
            }

            // Now create an account in the ECF
            CustomerContact customerContact = CustomerContact.CreateInstance();

            customerContact.FirstName          = customer.FirstName;
            customerContact.LastName           = customer.LastName;
            customerContact.RegistrationSource = customer.RegistrationSource;
            customerContact.Email     = customer.Email;
            customerContact.FullName  = customer.FirstName + " " + customer.LastName;
            customerContact.BirthDate = customer.BirthDate;
            // customerContact.CustomerGroup
            customerContact.SaveChanges();
            return(customerContact);
        }
        public void SubjectNullIfSetToInvalidGuid()
        {
            var contact = CustomerContact.CreateInstance();

            contact[MetadataConstants.VippsSubjectGuidFieldName] = "xxx";

            Assert.Null(contact.GetVippsSubject());
        }
        public void SubjectNullIfSetToNull()
        {
            var contact = CustomerContact.CreateInstance();

            contact.SetVippsSubject(null);

            Assert.Null(contact.GetVippsSubject());
        }
        public void MapVippsContactFieldsThrowsIfVippsInfoIsNull()
        {
            var mapper = new VippsLoginMapper();

            var contact = CustomerContact.CreateInstance();

            Assert.Throws <ArgumentNullException>(() => mapper.MapVippsContactFields(contact, null));
        }
        public void CanSetAndGetSubjectGuid()
        {
            var contact = CustomerContact.CreateInstance();
            var guid    = Guid.NewGuid();

            contact.SetVippsSubject(guid);

            Assert.Equal(guid, contact.GetVippsSubject());
        }
Пример #12
0
        private CustomerContact CreateCustomerContact(ApplicationUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            CustomerContact contact = CustomerContact.CreateInstance();

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            if (!String.IsNullOrEmpty(user.FirstName) || !String.IsNullOrEmpty(user.LastName))
            {
                contact.FullName = String.Format("{0} {1}", user.FirstName, user.LastName);
            }

            contact.PrimaryKeyId       = new Mediachase.BusinessFoundation.Data.PrimaryKeyId(new Guid(user.Id));
            contact.FirstName          = user.FirstName;
            contact.LastName           = user.LastName;
            contact.Email              = user.Email;
            contact.UserId             = "String:" + user.Email; // The UserId needs to be set in the format "String:{email}". Else a duplicate CustomerContact will be created later on.
            contact.RegistrationSource = user.RegistrationSource;

            if (user.Addresses != null)
            {
                foreach (var address in user.Addresses)
                {
                    contact.AddContactAddress(address);
                }
            }

            // The contact, or more likely its related addresses, must be saved to the database before we can set the preferred
            // shipping and billing addresses. Using an address id before its saved will throw an exception because its value
            // will still be null.
            contact.SaveChanges();

            // Once the contact has been saved we can look for any existing addresses.
            CustomerAddress defaultAddress = contact.ContactAddresses.FirstOrDefault();

            if (defaultAddress != null)
            {
                // If an addresses was found, it will be used as default for shipping and billing.
                contact.PreferredShippingAddress = defaultAddress;
                contact.PreferredBillingAddress  = defaultAddress;

                // Save the address preferences also.
                contact.SaveChanges();
            }


            return(contact);
        }
        public virtual IHttpActionResult PostContact(Guid id, [FromBody] ContactModelExtended model)
        {
            var customerContact = CustomerContact.CreateInstance();

            CustomerMappings.CreateContact(customerContact, id, model);
            CreateUserIfNotExists(customerContact);
            model = customerContact.ConvertToContactModel();

            return(CreatedAtRoute("GetContact", new { contactId = model.PrimaryKeyId }, model));
        }
Пример #14
0
        public void RegisterAccount_WhenRegisterSuccessful_ShouldReturnJsonReturnUrl(bool acceptMarketingEmail)
        {
            var identityResult = new IdentityResult();

            typeof(IdentityResult).GetProperty("Succeeded").SetValue(identityResult, true, null);

            _userServiceMock.Setup(
                x => x.RegisterAccount(It.IsAny <SiteUser>()))
            .Returns(Task.FromResult(new ContactIdentityResult
                                     (
                                         identityResult,
                                         CustomerContact.CreateInstance()
                                     )));

            _optinServiceMock.Setup(
                x => x.CreateOptinTokenData(It.IsAny <string>()))
            .Returns(Task.FromResult("test token"));

            var model = new RegisterAccountViewModel
            {
                Email = "*****@*****.**",
                AcceptMarketingEmail = acceptMarketingEmail,
                Password             = "******",
                Password2            = "Passwors@124#212",
            };

            model.Address = new AddressModel
            {
                Line1       = "Address",
                City        = "City",
                CountryName = "Country",
                FirstName   = "Fisrt Name",
                LastName    = "Last Name",
                PostalCode  = "952595",
                Email       = "*****@*****.**"
            };

            var result = _subject.RegisterAccount(model).Result as JsonResult;

            var expectedResult = new JsonResult
            {
                Data = new { ReturnUrl = "/" },
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };

            result.Should().BeEquivalentTo(expectedResult);
            _subject.CallToSendMarketingEmailConfirmationMailMethod.Should().Be(acceptMarketingEmail);
        }
Пример #15
0
        public CustomerContact CreateCustomerContact(SiteUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            CustomerContact contact = _customerContext.GetContactByUsername(user.UserName);

            if (contact == null)
            {
                contact = CustomerContact.CreateInstance();
                contact.PrimaryKeyId = new PrimaryKeyId(new Guid(user.Id));
                contact.UserId       = "String:" + user.Email; // The UserId needs to be set in the format "String:{email}". Else a duplicate CustomerContact will be created later on.
            }

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
            if (!String.IsNullOrEmpty(user.FirstName) || !String.IsNullOrEmpty(user.LastName))
            {
                contact.FullName = $"{user.FirstName} {user.LastName}";
            }

            contact.FirstName          = user.FirstName;
            contact.LastName           = user.LastName;
            contact.Email              = user.Email;
            contact.RegistrationSource = user.RegistrationSource;

            if (user.Addresses != null)
            {
                foreach (var address in user.Addresses)
                {
                    contact.AddContactAddress(address);
                }
            }

            // The contact, or more likely its related addresses, must be saved to the database before we can set the preferred
            // shipping and billing addresses. Using an address id before its saved will throw an exception because its value
            // will still be null.
            contact.SaveChanges();

            SetPreferredAddresses(contact);

            return(contact);
        }
Пример #16
0
        // ToDo: Exercises in customers module
        public ActionResult CreateAccount(AccountPage currentPage, string userName, string passWord)
        {
            // The important here are the Roles and the Contact properties
            string firstName    = userName;
            string lastName     = userName;
            string emailAddress = firstName + "." + lastName + "@epi.com"; //
            string password     = passWord;

            //CustomerContext.Current.CurrentContact.

            MembershipUser membershipGuy = null;

            MembershipCreateStatus createStatus;

            membershipGuy = Membership.CreateUser(emailAddress, password, emailAddress,
                                                  null, null, true, out createStatus);
            //CustomerContext.Current.
            // Create the Contact in ECF
            CustomerContact customerContact = CustomerContact.CreateInstance(membershipGuy);

            customerContact.FirstName          = firstName;
            customerContact.LastName           = lastName;
            customerContact.RegistrationSource = String.Format("{0}, {1}"
                                                               , this.Request.Url.Host, SiteContext.Current);

            //customerContact["Email"] = emailAddress; // can do...
            customerContact.Email = emailAddress;

            // Do the "SaveChanges()" before setting ECF-"Roles"
            customerContact.SaveChanges();

            // These Roles are ECF specific ... Used by CM ... and obsolete in 9
            //SecurityContext.Current.AssignUserToGlobalRole(membershipGuy, AppRoles.EveryoneRole);
            //SecurityContext.Current.AssignUserToGlobalRole(membershipGuy, AppRoles.RegisteredRole);

            // We don't need this anymore for visitors/customers
            Roles.AddUserToRole(membershipGuy.UserName, AppRoles.EveryoneRole);
            Roles.AddUserToRole(membershipGuy.UserName, AppRoles.RegisteredRole); // could mean "ClubMember"
            // Could have other use of it...
            Roles.AddUserToRole(membershipGuy.UserName, "ClubMember");

            // Call for further properties to be set
            SetContactProperties(customerContact);

            //CustomerContext.Current.CurrentContact.e
            return(null); // for now
        }
Пример #17
0
        public Customer Insert(Customer customer)
        {
            var contact = CustomerContact.CreateInstance();

            contact.FirstName    = customer.FirstName;
            contact.LastName     = customer.LastName;
            contact.FullName     = $"{customer.FirstName} {customer.LastName}";
            contact.Email        = customer.Email;
            contact.PrimaryKeyId = new PrimaryKeyId(Guid.NewGuid());
            contact.UserId       = customer.UserId;
            var result = contact.SaveChanges();

            return(new Customer()
            {
                Email = result.Email, FirstName = result.FirstName, LastName = result.LastName
            });
        }
Пример #18
0
        public void RegisterAccount_WhenRegisterSuccessful_ShouldReturnJsonReturnUrl()
        {
            var identityResult = new IdentityResult();

            typeof(IdentityResult).GetProperty("Succeeded").SetValue(identityResult, true, null);

            _userServiceMock.Setup(
                x => x.RegisterAccount(It.IsAny <ApplicationUser>()))
            .Returns(Task.FromResult(new ContactIdentityResult
                                     (
                                         identityResult,
                                         CustomerContact.CreateInstance()
                                     )));

            var model = new RegisterAccountViewModel
            {
                Email      = "*****@*****.**",
                Newsletter = true,
                Password   = "******",
                Password2  = "Passwors@124#212",
            };

            model.Address = new AddressModel
            {
                Line1       = "Address",
                City        = "City",
                CountryName = "Country",
                FirstName   = "Fisrt Name",
                LastName    = "Last Name",
                PostalCode  = "952595",
                Email       = "*****@*****.**"
            };

            var result = _subject.RegisterAccount(model).Result as JsonResult;

            var expectedResult = new JsonResult
            {
                Data = new { ReturnUrl = "/" },
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };

            result.ShouldBeEquivalentTo(expectedResult);
        }
Пример #19
0
        public ActionResult CreateAccount(AccountPage currentPage, AccountViewModel model)
        {
            // The important here are the Roles and the Contact properties
            string firstName    = model.FirstName;
            string lastName     = model.LastName;
            string emailAddress = model.UserName; //
            string password     = model.Password;

            MembershipUser user = null;

            MembershipCreateStatus createStatus;

            user = Membership.CreateUser(emailAddress, password, emailAddress,
                                         null, null, true, out createStatus);
            //CustomerContext.Current.
            // Create the Contact in ECF
            CustomerContact customerContact = CustomerContact.CreateInstance(user);

            customerContact.FirstName          = firstName;
            customerContact.LastName           = lastName;
            customerContact.RegistrationSource = String.Format("{0}, {1}"
                                                               , this.Request.Url.Host, SiteContext.Current);

            customerContact.Email = emailAddress;

            customerContact.SaveChanges();


            // We don't need this anymore for visitors/customers
            Roles.AddUserToRole(user.UserName, AppRoles.EveryoneRole);
            Roles.AddUserToRole(user.UserName, AppRoles.RegisteredRole);

            if (Roles.RoleExists("ClubMember"))
            {
                Roles.AddUserToRole(user.UserName, "ClubMember");
            }
            // Call for further properties to be set
            SetContactProperties(customerContact);

            return(Login(currentPage, model));
        }
        public async Task <VsfUser> CreateUser(UserCreateModel newUser)
        {
            var appUser = new SiteUser
            {
                Id             = Guid.NewGuid().ToString(),
                Username       = newUser.Customer.Email,
                Email          = newUser.Customer.Email,
                EmailConfirmed = false,
                IsLockedOut    = false,
                IsApproved     = true,
                CreationDate   = DateTime.UtcNow
            };

            var result = await _appUserManager.CreateAsync(appUser, newUser.Password);

            if (!result.Succeeded)
            {
                LogDebugErrors("CreateUser failed", result.Errors);
                return(null);
            }

            var newContact = CustomerContact.CreateInstance();

            newContact.PrimaryKeyId = new PrimaryKeyId(new Guid(appUser.Id));

            /* Before it was email here, this is incorrect as epi server looks for customer contact every time the request is authorized (see BusinessFoundationInitializeModule).
             * In this module epi will look for customercontact bu user Id that is set in principal.Name. SInce we set email here before it was not found and there were concurrency exceptions
             * since when epi does not find a contactCustomer, it tries to create it and save to database in GET METHOD in every async request - WTF!!!*/
            newContact.UserId = "String:" + appUser.Id;
            newContact.AcceptMarketingEmail = false;
            newContact.FirstName            = newUser.Customer.FirstName;
            newContact.LastName             = newUser.Customer.LastName;
            newContact.Email = newUser.Customer.Email;
            newContact.SaveChanges();

            var user = await _appUserManager.FindByIdAsync(appUser.Id);

            return(QuicksilverUserModelMapper.MapToVsfModel(user));
        }
Пример #21
0
        /// <summary>
        /// Handles the click event of a new user
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void loginCreateNew_Click(object sender, EventArgs e)
        {
            string         firstName    = FirstNameId.Value;
            string         lastName     = LastNameId.Value;
            string         emailAddress = EmailAddressNewId.Value;
            string         password     = Password_NewId.Value;
            MembershipUser user         = null;

            MembershipCreateStatus createStatus;

            user = Membership.CreateUser(emailAddress, password, emailAddress,
                                         null, null, true, out createStatus);
            if (createStatus == MembershipCreateStatus.DuplicateUserName)
            {
                CreateFailureText.Text = "The supplied email address already exists. Please use a different email address";
                return;
            }
            if (createStatus != MembershipCreateStatus.Success)
            {
                CreateFailureText.Text = "Error when attempting to create the user: "******"{0}, {1}", this.Request.Url.Host, SiteContext.Current);
            customerContact["Email"]           = emailAddress;

            customerContact.SaveChanges();
            AssignDefaultRolesToUser(user);

            CreateAuthenticationCookie(emailAddress, AppContext.Current.ApplicationName, false);

            Context.RedirectFast("/Self-Service/Account-Info/");
        }
        // ToDo: Lab incustomers module
        public ActionResult CreateAccount(AccountPage currentPage, string userName, string passWord)
        {
            // The important here are the Roles and the Contact properties
            string firstName    = userName;
            string lastName     = userName;
            string emailAddress = firstName + "." + lastName + "@epi.com"; //
            string password     = passWord;

            MembershipUser membershipGuy = null;

            MembershipCreateStatus createStatus;

            membershipGuy = Membership.CreateUser(emailAddress, password, emailAddress,
                                                  null, null, true, out createStatus);

            // Create the Contact in ECF
            var customerContact = CustomerContact.CreateInstance(membershipGuy);

            customerContact.FirstName          = firstName;
            customerContact.LastName           = lastName;
            customerContact.RegistrationSource = String.Format("{0}, {1}"
                                                               , this.Request.Url.Host, SiteContext.Current);

            //customerContact["Email"] = emailAddress; // can do...
            customerContact.Email = emailAddress;

            // Do the "SaveChanges()" before setting ECF-"Roles"
            customerContact.SaveChanges();

            // These Roles are ECF specific ... saved automatically
            SecurityContext.Current.AssignUserToGlobalRole(membershipGuy, AppRoles.EveryoneRole);   // For CM
            SecurityContext.Current.AssignUserToGlobalRole(membershipGuy, AppRoles.RegisteredRole); // For CM

            SetContactProperties(customerContact);

            return(null); // for now
        }
Пример #23
0
        public bool RegisterUser(RegisterViewModel registerViewModel, out string errorMessage)
        {
            try {
                var user = Membership.CreateUser(registerViewModel.Email, registerViewModel.Password, registerViewModel.Email);

                CustomerContact customerContact = CustomerContact.CreateInstance(user);

                customerContact.FirstName      = registerViewModel.FirstName;
                customerContact.LastName       = registerViewModel.LastName;
                customerContact.Email          = registerViewModel.Email;
                customerContact["PhoneNumber"] = registerViewModel.PhoneNumber;
                customerContact["State"]       = registerViewModel.SelectedState;
                customerContact["Gender"]      = registerViewModel.Gender;

                customerContact.SaveChanges();

                errorMessage = null;
                return(true);
            }
            catch (Exception e) {
                errorMessage = e.Message;
                return(false);
            }
        }
        public void SubjectNullByDefault()
        {
            var contact = CustomerContact.CreateInstance();

            Assert.Null(contact.GetVippsSubject());
        }
		public ActionResult Register(RegisterPage currentPage, RegisterPageViewModel model, RegisterForm registerForm, int[] SelectedCategories)
		{
			model.RegisterForm.AvailableCategories = GetAvailableCategories();
			model.RegisterForm.SelectedCategories = SelectedCategories;
			if (registerForm.Password != registerForm.PasswordConfirm)
			{
				ModelState.AddModelError("RegisterForm.ValidationMessage", _localizationService.GetString("/common/validation/compare_passwords"));
			}

			if (!ModelState.IsValid)
			{
				return View("Index", model);
			}

			string emailAddress = registerForm.UserName.Trim();
			string password = registerForm.Password;

			// Account
			MembershipUser user = null;
			MembershipCreateStatus createStatus;
			user = Membership.CreateUser(emailAddress, password, emailAddress, null, null, true, out createStatus);

			bool existingUserWithoutPassword = false;

			if (createStatus == MembershipCreateStatus.DuplicateUserName)
			{
				user = Membership.GetUser(emailAddress);
				var customer1 = CustomerContext.Current.GetContactForUser(user);

                if (customer1 == null)
                {

                    customer1 = CustomerContact.CreateInstance(user);
                }


                if (customer1.GetHasPassword())
				{
					ModelState.AddModelError("RegisterForm.ValidationMessage", _localizationService.GetString("/common/account/register_error_unique_username"));
				}
				else
				{
					existingUserWithoutPassword = true;
				}
			}
			else if (user == null)
			{
				ModelState.AddModelError("RegisterForm.ValidationMessage", _localizationService.GetString("/common/account/register_error"));
			}

			if (!ModelState.IsValid)
			{
				return View("Index", model);
			}

			if (!existingUserWithoutPassword)
			{
                Roles.AddUserToRole(user.UserName, AppRoles.EveryoneRole);
                Roles.AddUserToRole(user.UserName, AppRoles.RegisteredRole);
			}
			else
			{
				// set new password
				var pass = user.ResetPassword();
				user.ChangePassword(pass, password);
			}

			var customer = CustomerContext.Current.GetContactForUser(user);

            if (customer == null)
            {

                customer = CustomerContact.CreateInstance(user);
            }

            customer.FirstName = registerForm.Address.FirstName;
			customer.LastName = registerForm.Address.LastName;
			customer.SetPhoneNumber(registerForm.Phone);
			customer.FullName = string.Format("{0} {1}", customer.FirstName, customer.LastName);
			customer.SetHasPassword(true);

			// member club
			if (registerForm.MemberClub)
			{
				customer.CustomerGroup = Constants.CustomerGroup.CustomerClub;
			}

			// categories
			customer.SetCategories(SelectedCategories);

			customer.SaveChanges();

			var CustomerAddressRepository = ServiceLocator.Current.GetInstance<ICustomerAddressRepository>();
			CustomerAddressRepository.SetCustomer(customer);

			// copy address fields to shipping address
			registerForm.Address.CheckAndSetCountryCode();

			var ShippingAddress = (Address)registerForm.Address.Clone();
			ShippingAddress.IsPreferredShippingAddress = true;
			CustomerAddressRepository.Save(ShippingAddress);

			registerForm.Address.IsPreferredBillingAddress = true;
			CustomerAddressRepository.Save(registerForm.Address);

			LoginController.CreateAuthenticationCookie(ControllerContext.HttpContext, emailAddress, Mediachase.Commerce.Core.AppContext.Current.ApplicationName, false);

			bool mail_sent = SendWelcomeEmail(registerForm.UserName, currentPage);

			return Redirect(_urlResolver.GetUrl(ContentReference.StartPage));
		}