Wednesday, January 3, 2018

Asp.Net Identity SQLite Provider on Empty Web Forms project

  Previously, I installed the Asp.Net Identity SQLite on a non-empty Web Form Project. This time, I'll try installing it on an Empty Web Form project so I can minimize the Nuget packages installed and I can learn which Nuget packages it depends on.


Firstly, I create a ASP.NET Empty Web Site targeting .Net Framework 4.7.1



Then on Nuget Package Manager for Solution, Uninstall all the Nuget Packages. This will make it truely empty Web Form project.


Then Install the following Nuget Packages and its dependencies:
  1. AspNet.Identity.SQLite
  2. Microsoft.AspNet.Identity.Owin
  3. Microsoft.Owin.Host.SystemWeb
After installing all the packages and its dependencies, notice they are 15 packages installed.

Insert the ConnectionString into the web.config
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\Identity.db;Version=3;" providerName="System.Data.SQLite" />
  </connectionStrings>


Create an App_Data folder then create an SQLite database name Identity.db inside the App_Data folder using any SQLite Editor of your choise. In my case, I'm using SQLiteStudio.

You can find a file named SQLiteIdentity.sql on the root of your website.




Copy the script into the Query Editor then execute it. It will generate 5 tables.

Then create an App_Code folder, create the following files:
  1. IdentityModels.vb
  2. Startup.Auth.vb
  3. Startup.vb

*Click on the filename to get the code
Then create a web form name Default.aspx.

Import the namespace 

Imports Microsoft.AspNet.Identity

On the web form, insert the 3 text-boxes with the following IDs:
  1. UserName
  2. Password
  3. ConfirmPassword
Then insert a label named ErrorMessage.
Then insert a button named Register.

Add the following code into the Register button


        Dim manager = New UserManager()
        Dim user = New ApplicationUser() With {.UserName = UserName.Text}
        Dim result = manager.Create(user, Password.Text)
        If result.Succeeded Then
            IdentityHelper.SignIn(manager, user, isPersistent:=False)
            IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
        Else
            ErrorMessage.Text = result.Errors.FirstOrDefault()
        End If

With this, the page is ready to register a user.

Then we will pun a login status and logout function

Insert a LoginStatus and a LoginName control. Then put this code into for the LoginStatus

    Protected Sub LoginStatus1_LoggingOut(sender As Object, e As LoginCancelEventArgs) Handles LoginStatus1.LoggingOut
        Context.GetOwinContext().Authentication.SignOut()
    End Sub

Done.


But, in case of error releted tu SQLite.Interop.dll when running, try following this step
Unable to load DLL 'SQLite.Interop.dll': The specified module could not be found
























No comments:

Post a Comment