So, why use SimpleMembership? because its simple :)

why use sql compact 4? and uh EF 4.3 Code First? anyone who have shared hosting like me know the pain of don’t have access to sql server management studio

so, the goal is simple, we have asp.net simple membership with 0 configuration

01. Add assembly compilation to web config (at the child of <system.web>)

<compilation debug="true" targetFramework="4.0" >
<assemblies>
<add assembly="WebMatrix.WebData"/>
<add assembly="WebMatrix.Security"/>
<add assembly="System.Data.SqlServerCe"/>
</assemblies>
</compilation>

02. Clear default membership, roles, profile

<profile>
</profile>
<roleManager enabled="true">
</roleManager>

03. enable simpleMembership

<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>

04. Create ef code first class to represent table user and its db context

public class User
    {
        [Key]        
        public int Id
        {
            get;
            set;
        }

        [Required]
        public string Username
        {
            get;
            set;
        }
    }

public class MyDbContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public MyDbContext()
          :base()
        {
        }
    }

05. Initialize everything, put it on application_start

string connectionString = @"Data Source='|DataDirectory|\data.sdf';password=secret";
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0","", connectionString);
Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());
           
using(MyDbContext context=new MyDbContext())
{
var debug01=context.Users.ToList();
}

WebSecurity.InitializeDatabaseConnection(connectionString, "System.Data.SqlServerCe.4.0", "User", "Id", "Username", true);

using(MyDbContext context=new MyDbContext())
{
var debug02=context.Users.ToList();
}

if (!WebSecurity.UserExists("administrator"))
            {
                var x = WebSecurity.CreateUserAndAccount("administrator", "adminSecret");
            }

Note:
Notice i do not add sql compact 4 database manually, its created automatically using code first
so, the .sdf file is hidden on your visual studio on app_data directory

WebSecurity.CreateAccount somehow throw provider exception :( so use CreateUserAndAccount instead..

and thats it…

About these ads