0

I'm working on a project with an existing database (NOT codefirst). I'm trying to implement login/register/logoff and also integrate social media in this website.

However, I think I'm doing it wrong. I always get the "The ASP.NET Simple Membership database could not be initialized" - error.

So for the record, I want to check with the given emailadress and paswoord, if the user is in the database

This is the view in which I enter e-mailaddress and pasword to log in.

 @model DAL_EF.Account

@{
    ViewBag.Title = "Politici Online | Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Login</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.Js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{ 
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Enter username and password</legend>

        <div class="editor-label">
            Emailadres
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.emailadres)
            @Html.ValidationMessageFor(model => model.emailadres)
        </div>

        <div class="editor-label">
            Wachtwoord
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.wachtwoord)
            @Html.ValidationMessageFor(model => model.wachtwoord)
        </div>

        <p>
            <input type="submit" value="Login" />
        </p>
    </fieldset>
}

<section class="social" id="socialLoginForm">
    <h2>Use another service to log in.</h2>
    @Html.Action("ExternalLoginsList", new { ReturnUrl = ViewBag.ReturnUrl })
</section>

This is the controller:

 //
    // POST: /Account/Login/
    [HttpPost]
    public ActionResult Login(DAL_EF.Account model, string returnUrl)
    {
        // Lets first check if the Model is valid or not
        if (ModelState.IsValid)
        {
            using (PoliticiOnlineEntities entities = new PoliticiOnlineEntities())
            {
                string username = model.emailadres;
                string password = model.wachtwoord;

                bool userValid = entities.Account.Any(user => user.emailadres == username && user.wachtwoord == password);

                // gebruiker gevonden in de database!
                if (userValid)
                {

                    //FormsAuthentication.SetAuthCookie(username, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
        }

        //als we zover zijn geraakt, dan is er iets gefaald ... We laten het form terug zien
        return View(model);
    }

This is the InitializeSimpleMembershipAttribute:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Ensure ASP.NET Simple Membership is initialized only once per app start
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

    private class SimpleMembershipInitializer
    {
        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("PoliticiOnlineEntities", "Account", "accountID", "emailadres", autoCreateTables: 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);
            }
        }
    }
}

This is the connectionstring (I removed sensitive information):

<add name="PoliticiOnlineEntities" connectionString="metadata=res://*/PoliticiOnline.csdl|res://*/PoliticiOnline.ssdl|res://*/PoliticiOnline.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=*****;initial catalog=****;persist security info=True;user id=********;password=*****;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
Jesper
  • 316
  • 1
  • 14
  • exclude InitializeSimpleMembershipAttribute, as this is not relevant in this context. – aamir sajjad Apr 29 '14 at 11:36
  • @aamirsajjad when I do this, I don't use this anymore or what? so the Websecurity.InitializeDatabaseConnection is not necessary to execute? – Jesper Apr 29 '14 at 11:54
  • do you know what is the best way to add roles using a database first approach? – Jesper Apr 29 '14 at 12:05
  • it is not necessary in database first approach most of the time. – aamir sajjad Apr 29 '14 at 12:05
  • But I have to implement this?? We have 4 different kind of users: administrator, moderator, user and politician – Jesper Apr 29 '14 at 12:12
  • Did you check these QA's: http://stackoverflow.com/questions/15112214/using-mvc-4-simplemembership-with-an-existing-database-first-ef-model http://stackoverflow.com/questions/15473514/mvc4-simple-membership-with-custom-database-and-database-first-issue – Kevin Junghans May 01 '14 at 12:42

0 Answers0