Pages

Saturday, June 29, 2013

Asp.net MVC 4 - use Database First > Entity Data Model

Asp.net mvc 4, all the tutorials show simple membership being utilized with Code First (latest trend in database setup/usage). This is how to utilize simple membership with Database First using Entity Data Model.

This was discovered via a StackOverFlow.com answer: http://stackoverflow.com/questions/15112214/using-mvc-4-simplemembership-with-an-existing-database-first-ef-model

1) Create MVC 4 app and run it to create the default membership database and tables (mvc does this automatically).

2) Change .../Filters/InitializeSimpleMembershipAttribute.cs as follows:

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("DefaultConnection", "UserProfile", "UserId", "UserName", 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);
                }
            }
        }

3) Comment out sections in /Models/AccountModels.cs:

public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }

        //public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<ExternalUserInfo> ExternalUsers { get; set; }
    }

    //[Table("UserProfile")]
    //public class UserProfile
    //{
    //    [Key]
    //    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    //    public int UserId { get; set; }
    //    public string UserName { get; set; }
    //}

4) Create an entity data model (*.edmx file) as normal.

5) In /Controllers/AccountController.cs and anywhere else where DB interaction is needed, replace as follows:

//using (UsersContext db = new UsersContext())

using (evEntities ent = new evEntities())
{
      // code to access database
}

Saturday, June 8, 2013

asp.net mvc 4.0 facebook login

http://www.asp.net/mvc/overview/getting-started/using-oauth-providers-with-mvc

1) Set up basics for Facebook login

Get app id and secret id from facebook developers app page. Set site URL to match the site URL that I want FB to communicate with. Example, if localhost, set URL in facebook app page to: http://localhost:23422 ... but if pushed to live, then change URL in facebook app page to proper web address.

Set the id values in /App_Start/AuthConfig.cs

2) Grab basic data (no token needed) after login verified

3) Grab "ExtraData" (no token needed)



Set up Migrations.
PM> enable-migrations
PM>  add-migration initial –IgnoreChanges
PM> update-database

Make model changes.
PM> add-migration nameAnything
PM> update-database (this syncs up DB with new changes reflected in "add-migration"


4) Use Nuget to get the Facebook SDK (more info: http://ntotten.com/2012/12/19/facebook-authentication-with-the-facebook-c-sdk-and-asp-net-mvc-4/) ...



5) Use Facebook SDK library to mine down and grab more data (token needed)



Be sure to write code to close session upon logout. Otherwise, default is to log out after 20 min (I think) of being idle. Look for Nanonerd's post/answer:

http://stackoverflow.com/questions/13117728/fb-logout-with-c-sharp-sdk/17015865#17015865

(edit "next = 'http://localhost:51042/'" with proper URL)

public ActionResult LogOff()
    {
        WebSecurity.Logout();

        if (Session["facebooktoken"] != null)
        {
            var fb = new Facebook.FacebookClient();
            var logoutUrl = fb.GetLogoutUrl(new { access_token = Session["facebooktoken"], next = "http://localhost:51042/" });

            Response.Redirect(logoutUrl.AbsoluteUri);
            Session.RemoveAll();
        } 

        return RedirectToAction("Index", "Home");
    }