public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }


                    if (!WebSecurity.Initialized)
                    {
                        WebSecurity.InitializeDatabaseConnection("PortugalVillasContext", "UserProfile", "UserId", "UserName",
                            true);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public List<EmailAddress> GetAllCustomerAndLoginEmailAddresses()
        {
            List<EmailAddress> emailList = new List<EmailAddress>();

            var customers = db.Customers.Select(x => x.EmailAddress).ToList();

            using (var userdb = new UsersContext())
            {
                var users = userdb.UserProfiles.Select(x => x.UserName).ToList();

                foreach (var item in users)
                {
                    emailList.Add(new EmailAddress
                    {
                        Email = item.ToLower().Trim()
                    });
                }

                foreach (var item in customers)
                {

                    if (item != null)
                    {
                        emailList.Add(new EmailAddress
                        {
                            Email = item.ToLower().Trim()
                        });
                    }
                }
            }


            return emailList;

        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public ActionResult ManageCustomerPassword()
        {
            PortugalVillasContext _dbContext = new PortugalVillasContext();
            UsersContext _usersContext = new UsersContext();

            //get the customer from the db according to who's logged in

            //Show the customer to the suer

            //update the customer

            //update the SIMPLEMEMBERSHIPPROVDER CORRESPONDING RECORD!! (if they change the email!!)

            //update the 
            return View();

        }
        //  [Authorize(Roles = "Administrator, User")]
        public ActionResult ManageCustomer(Customer customer)
        {


            Customer previousCustomer = (Customer)Session["prc_previouscustomer"];
            customer.CustomerID = previousCustomer.CustomerID;


            if ((!CheckIfCustomerEmailAlreadyExists(customer.EmailAddress) &&
                !CheckIfUserExistsInSimpleMemberProvider(customer.EmailAddress)) || (previousCustomer.EmailAddress.ToLower().Trim() == customer.EmailAddress.ToLower().Trim()))
            {

                PortugalVillasContext _dbContext = new PortugalVillasContext();
                UsersContext _usersContext = new UsersContext();

                //get the old customer detailf from the session



                //update simplemembership provider too
                var user =
                    _usersContext.UserProfiles.Where(
                        x => x.UserName.ToLower().Trim() == previousCustomer.EmailAddress.ToLower().Trim())
                        .FirstOrDefault();

                user.UserName = customer.EmailAddress;

                //update customer and user
                try
                {
                    if (ModelState.IsValid)
                    {
                        _dbContext.Entry(customer).State = EntityState.Modified;
                        var objContext = ((IObjectContextAdapter)_dbContext).ObjectContext;

                        var refreshableObjects = (from entry in objContext.ObjectStateManager.GetObjectStateEntries(
                            EntityState.Added
                            | EntityState.Deleted
                            | EntityState.Modified
                            | EntityState.Unchanged)
                                                  where entry.EntityKey != null
                                                  select entry.Entity);

                        objContext.Refresh(RefreshMode.ClientWins, refreshableObjects);

                        //if it works, do the update for the userContext, else, don't as it failed
                        if (objContext.SaveChanges() > 0)
                        {
                            _usersContext.Entry(user).State = EntityState.Modified;
                            _usersContext.SaveChanges();

                            WebSecurity.Logout();

                            Session["prc_customer"] = customer;
                            //update the customer
                            return View("CustomerUpdateSuccess");
                        }

                    }
                }

                catch
            (DbUpdateConcurrencyException ex)
                {
                    var objContext = ((IObjectContextAdapter)_dbContext).ObjectContext;
                    var entry = ex.Entries.Single();

                    objContext.Refresh(RefreshMode.ClientWins, entry.Entity);
                    _dbContext.SaveChanges();


                }

            }


            //update the customer on result
            ViewBag.Title = "Manage Portugal Holiday Rentals Customer";
            return View("CustomerUpdateFailed");


        }
        private bool CheckIfUserExistsInSimpleMemberProvider(string userEmail)
        {
            try
            {
                UsersContext userContext = new UsersContext();
                var users = userContext.UserProfiles.ToList();

                foreach (var user in users)
                {
                    if (user.UserName == userEmail)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return false;
        }