webSecurity.INitializedatabaseconnection() throughs an exception “Unable to find the requested .NET Framework Data Provider”

Integrating Simple Authentication with Existing database using Model First
Trying to learn the new things in MVC 4 I wanted to work with Simple Authentication so that’s the curve for today .
Since there is some love lost between me and Code First I wanted to try it out with one of the databases I already have and keep it simple. I tried to follow the different long blogs out there how to do it and I was hoping all would go smooth and fine but before long I was stack with the error “Unable to find the requested .NET Framework Data Provider” when I call

WebSecurity.InitializeDatabaseConnection()

So if you are here with the same error without further due let me tell u what is wrong.
Under ur class

InitializeSimpleMembershipAttribute

the method

SimpleMembershipInitializer()

and the line of code

WebSecurity.InitializeDatabaseConnection

is throwing the exception and the problem is WebSecurity.InitializeDatabaseConnection method cann’t use connection string with

System.Data.EntityClient

which is used when we are using the model first paradigm.

So what’s the solution?

Well a solution can be to create another connection string meant to be for Websecurity purpose with

providerName="System.Data.SqlClient".

Don’t worry I amn’t gone leave you just like that lets me show you how I did it follow my lead. For the sake of simplicity I have just created a simple Internet application. Which will have all the Account related models and controllers and pages.

Create a new MVC 4 Project

The following are the class’s that will be added for you by default

Class created

\Models\AccountModels.cs defines a basic user account and includes data annotations to define keys and such

\Filters\InitializeSimpleMembershipAttribute.cs creates the membership database using the above model, then calls WebSecurity.InitializeDatabaseConnection which verifies that the underlying tables are in place and marks initialization as complete (for the application’s lifetime)
\Models\AccountModels.cs defines a basic user account and includes data annotations to define keys and such
\Filters\InitializeSimpleMembershipAttribute.cs creates the membership database using the above model, then calls WebSecurity.InitializeDatabaseConnection which verifies that the underlying tables are in place and marks initialization as complete (for the application’s lifetime)

“With SimpleMembership it was decided that it was easier to allow you, the developer, to have control of the users table and let SimpleMembership handle storing the authentication credentials. For example, you might already have a users table and want to integrate it with SimpleMembership. All SimpleMembership requires is that there are two columns on your users table so that we can hook up to it – an “ID” column and a “username” column. The important part here is that they can be named whatever you want. For instance username doesn’t have to be an alias it could be an email column you just have to tell SimpleMembership to treat that as the “username” used to log in.” Matthew M.Osborn

Since a great deal of control is given to us on the user table I just wanted to use my already existing database and just create a table called user with id and username columns.

Entity

Now go to your web.config file and look for you connection strings. You will have two connection strings

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Membership-20130118230532;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Membership-20130118230532.mdf" providerName="System.Data.SqlClient" />

  <add name="TestMembershipEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ICECOOL-PC\MYINSTANCE;initial catalog=TestMembership;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

The First connection string is the connection string that’s created by default when u created the project and its created to handle your web security features. If the database doesn’t exist it will be generated during our first run.
The Second connection is the connection string to my existing database and if you pay attention you can see that providers for the two are different. Since we want our Authentication activities to be handled with our existing database lets delete or comment out the first connection string. After deleting the first connection string add a connection string to the same database as the second connection string but this time with appropriate provider that is System.Data.SqlClient.

<add name="ConnStringForWebSecurity" connectionString="data source=ICECOOL-PC\MyInstance;Initial Catalog=TestMembership;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
Before

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

        public DbSet<UserProfile> UserProfiles { get; set; }
    }
After

public class UsersContext : TestMembershipEntities
    {
        public UsersContext()           
        {
        }

    }
Before

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

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

Next go to Models and AccountModels.cs and change your Inheritance to TestMembershipEntities or the Entity that is you defined and then Delete the Code First class defined in there and also change the decorator of you constructor method and the property defined in it.

Two more thing to do ; go to Filters/InitializeSimpleMembershipAttribute.cs  and go to SimpleMembershipInitializer class and replace the code as follows. What we did below is comment out code we wont be using and since we are using model first and we have the table and also change the connection string parameter for the WebSecurity.InitializeDatabaseConnection method and the table name and column name it expects as per our table definition.

Before

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();
                        }
                    }

                    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);
                }
            }
        }
After

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();
                    //    }
                    //}                    WebSecurity.InitializeDatabaseConnection("ConnStringForWebSecurity", "TestUser", "Id", "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);
                }
            }
        }

Finally Modify your web.config file by adding

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

in side your <appSettings>.   

.sdf files with WPF! Where is My Data ? :(

Hi There!

Recently I have been working on an application where I needed to use MSSQL CE and I never taught I would have faced some stubborn problems that cost me a day of my time trying to solve it.

Well my Problem was, The Data I saved was nowhere to be seen when I close the application I enter data with. It was really a L  problem when I entered data with DDL it worked and the data persisted but when I enter it with my App I see the data in my list boxes and controls until I Rebuild the project and rerun it. The data was also nowhere to be found when I run DML queries on the database. If this is also ur problem well u are at the right place cheer up I have the solution too.

I was using XPO as an ORM and I taught it might be that and I tried using ADO.net and also EF. But they yielded the same result and additional to that EF had some issues with Auto increment columns in MSSQL CE and the work around on that was having a GUID which was expensive to my solution and also which isn’t at all part of the solution.

K to the solution:

Now Click on the database file in Your Project and go to the properties tab and take your time and give it a thorough look.

.sdf File Properties

Now our focus is on the Property value pare Copy to Out Put Directory = Do not Copy. Well that’s the value you should have but I am sure u have either Copy always or Copy if newer in place. So that is your problem . J . so let me now describe what , how and why it caused you this problem.

The trick is every time you run the application, a copy of your database is taken to the output directory. The out put directory refers either bin\debug or bin\release.    And the reason why you don’t see the data you saved from the original database is no data is saved there data is saved inside the one in output directory.  As a solution set the copy to output directory to do not copy and then you can even delete the original db file in the project. Things you need to note is when you build setup for the project remember to add the databae as file inside ApplicationFolder with the Primary output.

So all along you have been tricked with the fact that your data is saved in a different place than you thought and just like me, the reason that wont make you think otherwise is the fact that no database connection error occurs due to path error when running the application which convinces you to think that the database is at the right place.

Installing Windows 8 on a virtual Hard Disk and yet Not so Virtual! :)

Finally!

So i have been waiting for a long time to install Windows 8 Developer Edition on my PC and did i get to do it or what!

I have a 32 bit machine ! and its the only pc that i own and i do  all my work staff on this pc.

Because of this formatting my pc and installing windows 8 on my pc was not even an option. The other options i had were

  •  virtualization solution (Virtual Machines), doesn’t not work on my machine as my machine doesn’t support virtualization,  and since we will be running it on top of another OS we will have some performance issues and u don’t want to your first date with windows 8 to be like that.
  • Dual boot. Dual booting . Ya I have a bad experience with that 😦
  • Boot on real hardware from a Virtual Hard Disk (Last but not Least).
So the Choice of the day for this adventure is the last one :  Booting on Real hardware using Virtual Hard Disk.
I expect u to be confused from the above statement and its natural; if you haven’t heard about it before.
yes! we can attach a virtual hard disk;  yes the same harddisk as the virtual machines use and boot from it  as a separate HD or as a physicall hard Disk. Dnt worry you will understand as you go  further down.

A Virtual Hard Disk allows multiple operating systems to reside on a single host machine. This method enables developers to test software on different operating systems without the cost or hassle of installing a second hard disk or creating a separate  partition on a single hard disk. And how i discovered abt it because of testing a software. Its Advantages are as far as ur imagination can go but here are some from Wikipedia.

Advantages

Significant benefits result from the ability to boot a physical computer from a virtual hard drive:

  • Ease of deployment: IT organizations can deploy standardized, ‘pre-built’ configurations on a single VHD. As an example, software engineering organizations which need a specific set of tools for a particular project could simply ‘pull’ the appropriately-configured VHD from a network location.
  • Backup-and-Restore: Changes to the contents of a VHD (such as infection by a virus, or accidental deletion of critical files) are easily undone.
  • Multi-User Isolation: Many current operating systems support having multiple users, but offer varying degrees of protection between them (e.g., one user of the OS could become infected by a virus which infects other users, or make changes to the OS which affect other users). By giving each user their own version of the operating system — say, by creating for each of them a differencing VHD based on a base installation of the OS — changes to any particular child image would have no effect on any of the other child images. However, a virus can be programmed to search for VHDs and infect it – it’s more a matter of securing file permissions and using the appropriate accounts (restricted user always, administrator or super user only when installing software or configuring the operating system).
k so lets get started!
First lets create a VHD (Virtual Hard Disk). I am gone create the VHD on my Logical D(E) Drive. C Contains my OS which is Windows 7.
Open CMD in Admin  and Follow me
1. Right diskpart  and yes pls press Enter 🙂
2. Right  create  vdisk file = d:\vhdwin8\Win8.vhd type=expandable maximum=60000   vhdwin8 is the Folder i choose to create it into.
3. if you look at the picture Below  you will see that  the command  didn’t commit successfully and this was because d is not the name of the drive it is E: but logically it is refereed as D   that is why when u install it later on u should refer to the disk by d  not E. but from here you should use E. this only applies if you have names to your disks other than the logical name. i.e. if it is   D(D)  u don’t  need to worry
so change d with E and follow through the above command.
4. Now Lets Select our VHD and Create a partition for it. Follow this Commands
DISKPART> select vdisk file=e:\vhdwin8\Win8.vhd

DISKPART> attach vdisk

DISKPART> create partition primary

and now we have successfully created our partition.

5. The Next Step is You need to Download Windows 7 USB/DVD download tool and make a boo-table Windows 8 Dvd. Oops i forgot u can get the Windows 8 Developers Edition Realease from here Windows 8 Developer Preview with Developer Tools . here you will find the ISO images. if u are one of my friends reading this well i have both 64 bit and 32 bit downloaded so call me and bring ur blank DVD with you.
so if you have the ISO install teh Windows 7 USB/DVD Download tool and Locate the File  and Burn it on a DVD.
The Advantage of this App is that it makes Your DvD bootable.
6. Ooooooooooook ! Great  So now you have you Windows 8 Burned-Baked & Ready on your DVD. So Insert it and Restart your PC
and press F12 as it boots and from the Boot Option select CD/DVD and Proceed.
7. We are Already there!  Stay Focused. This is the most Important Part
when you get to this window during the installation  don’t select any of the options.  Rather  press SHIFT + F10
and a command window will appear .
In the Command Window Select the VHD for it. to do that follow this Commands:
DISKPART> select vdisk  file=d:\vhdwin8\Win8.vhd
DISKPART> attach  vdisk
did you notice this time around I used d  instead of E  if u try to use E it will say VHD not found.
8. After the Above step Go to the Install Window and press the Refresh button for the HD lists. and you will see the new hard disk  with a size of 58.6 GB and select  that hard disk and let the installation finish.
9. you are done! 🙂 after it finishes the installation it will restart and you will see unfamiliar interface for the the boot manager ! it looks way cooler than that Black and white thing we used to have. if you get to Eject the CD you will get such a view else you will have a third option that says Setup.
10. So that’s it in simple 10 steps with out causing any problems for Win 7 you have Win 8 on ur PC and you can also feel the real experience unlike that of the one on Virtual Machine.
One of the things you will get to ask with your Windows 8 experience is where is the Close button for the metro Apps.
well with that question your Windows 8 Adventure Begins  and learning begins by asking  and my dear friend i say digg as much as u can abt windows 8. it looks to be promising and Exciting.
thanks for hanging in there through out this Blog!

Error with Account and privilege SQL SERVER 2008 R1

A new Experience with SQL Server!
So today i was installing SQL Server 2008 and it gave me a problem saying error with Account and privillage and it was saying this at the middle of the installation and how I got to solve the problem is the interesting thing. the pc name and the user account name were the same name. and that was the problem i changed the PC name and wala we were up and running.

XPO and Computed Columns!

Did u Know?

XPO Doesn’t support Computed Columns @ server side
The main problem when using computed columns at server side is the fact that XPO always updates every column when changes are made to the object which ends up causing an SQL exception since it tries to update the computed column to. But like everything in this world there is another way around it

The First way is setting the computed column Property in the persistence class with a modifier [Delayed(true)]
what this Dose is it updates the column only when its modified. and in our case computed columns don’t get updated ever from the persistence side.
The Down side of this is u need to right this manually in the Generated persistance class and we all know the trouble this creates later on but in a well documented project i believe its a good and simple trick.

The Other solution and the suggested one is named Using Persistent Alias:
if u have the patience to read go here and read it.
http://www.devexpress.com/Support/Center/p/Q327330.aspx

i will read it in the future at list this is why i have it here so i can remember something i can read :). and also to share with my friends.

At the End of the day what worked out for me is to comment the set part of the property generated in the persistence class;

The disadvantage is  you always have to remember to comment it when u regenerate the persistence class.