Using ASP.NET Identity with VB

5.3k Views Asked by At

I have researched Google and this site extensively, and cannot find an answer. I'm trying to add ASP.NET Identity to Visual Studio, and I've been working off of this page.

The problem is, everything from that article is in C#, and my project is specifically in Visual Basic (ASP.NET Framework 4.5.1, not MVC). Also, I'm too new to web dev to know exactly what to change. I found a C# to VB converter, and it worked for the most part but I'm still missing something since I get errors within VS. I'm not even 100% sure I can get Identity to work in VB instead of C#, though I don't see why not.

I'm trying to keep this as concise as possible, so I'll denote the issues in bold.

This is the register.aspx page:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Register.aspx.vb" Inherits="WebFormsIdentity.Register" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body style="font-family: Arial, Helvetica, sans-serif; font-size: small">
    <form id="form1" runat="server">
    <div>
        <h4 style="font-size: medium">Register a new user</h4>
        <hr />
        <p>
            <asp:Literal runat="server" ID="StatusMessage" />
        </p>                
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="UserName" />                
            </div>
        </div>
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="Password" TextMode="Password" />                
            </div>
        </div>
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="ConfirmPassword">Confirm password</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" />                
            </div>
        </div>
        <div>
            <div>
                <asp:Button runat="server" OnClick="CreateUser_Click" Text="Register" />
            </div>
        </div>
    </div>
    </form>
</body>
</html>

No errors in VB, but upon after running the page I get a 'Parser Error' in the browser: "Parser Error Message: Could not load type 'WebFormsIdentity.Register'."

This is the code behind; the majority of the issues are with this page:

Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports System.Linq

Namespace WebFormsIdentity
    Partial Public Class Register
        Inherits System.Web.UI.Page
        Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
            ' Default UserStore constructor uses the default connection string named: DefaultConnection
            Dim userStore = New UserStore(Of IdentityUser)()
            Dim manager = New UserManager(Of IdentityUser)(userStore)

            Dim user = New IdentityUser() With { _
                Key .UserName = UserName.Text _
            }
            Dim result As IdentityResult = manager.Create(user, Password.Text)

            If result.Succeeded Then
                StatusMessage.Text = String.Format("User {0} was created successfully!", user.UserName)
            Else
                StatusMessage.Text = result.Errors.FirstOrDefault()
            End If
        End Sub
    End Class
End Namespace

On the line under 'Dim user', the word 'Key' has this error:

Name of field or property being initialized in an object initializer must start with '.'.

On the line with 'Dim result', the word 'Password' has this:

'Password' is not declared. It may be inaccessible due to its protection level

On the line under 'result.Succeeded', the word 'StatusMessage' has this:

'StatusMessage' is not declared. It may be inaccessible due to its protection level.

And finally, same line, 'user.UserName' has this:

'UserName' is not a member of 'System.Security.Principal.IPrincipal'.

I've only been using VB for about six weeks, so I'm a baby dev. I do know how to declare things, but I don't understand why the author of the above link didn't have to do anything extra in his code, except that it is C#.

Anyway, thanks for reading and for the assistance in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

I was able to resolve my issue. Steps:

1) Completely uninstalled VS 2013 Premium
2) Installed VS 2013 Ultimate
3) When starting a new project, instead of using an empty template I chose 'Web Forms' with the default 'Individual User Account' Authentication.
4) From the NuGet packages, installed 'Microsoft ASP.NET Identity EntityFramework'

Running the application then worked properly; I was able to register a user without any errors.

For future reference, the correct code was as follows. Notice that 'Owin' references had to be imported.

Register.aspx:

<%@ Page Title="Register" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="Register.aspx.vb" Inherits="WebFormsIdentity.Register" %>

<%@ Import Namespace="WebFormsIdentity" %>
<%@ Import Namespace="Microsoft.AspNet.Identity" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <h2><%: Title %>.</h2>
    <p class="text-danger">
        <asp:Literal runat="server" ID="ErrorMessage" />
    </p>

    <div class="form-horizontal">
        <h4>Create a new account</h4>
        <hr />
        <asp:ValidationSummary runat="server" CssClass="text-danger" />
        <div class="form-group">
            <asp:Label runat="server" AssociatedControlID="Email" CssClass="col-md-2 control-label">Email</asp:Label>
            <div class="col-md-10">
                <asp:TextBox runat="server" ID="Email" CssClass="form-control" TextMode="Email" />
                <asp:RequiredFieldValidator runat="server" ControlToValidate="Email"
                    CssClass="text-danger" ErrorMessage="The email field is required." />
            </div>
        </div>
        <div class="form-group">
            <asp:Label runat="server" AssociatedControlID="Password" CssClass="col-md-2 control-label">Password</asp:Label>
            <div class="col-md-10">
                <asp:TextBox runat="server" ID="Password" TextMode="Password" CssClass="form-control" />
                <asp:RequiredFieldValidator runat="server" ControlToValidate="Password"
                    CssClass="text-danger" ErrorMessage="The password field is required." />
            </div>
        </div>
        <div class="form-group">
            <asp:Label runat="server" AssociatedControlID="ConfirmPassword" CssClass="col-md-2 control-label">Confirm password</asp:Label>
            <div class="col-md-10">
                <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" CssClass="form-control" />
                <asp:RequiredFieldValidator runat="server" ControlToValidate="ConfirmPassword"
                    CssClass="text-danger" Display="Dynamic" ErrorMessage="The confirm password field is required." />
                <asp:CompareValidator runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword"
                    CssClass="text-danger" Display="Dynamic" ErrorMessage="The password and confirmation password do not match." />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <asp:Button runat="server" OnClick="CreateUser_Click" Text="Register" CssClass="btn btn-default" />
            </div>
        </div>
    </div>
</asp:Content>

Register.aspx.vb:

Imports System
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Owin

Partial Public Class Register
    Inherits Page
    Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
        Dim userName As String = Email.Text
        Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
        Dim signInManager = Context.GetOwinContext().Get(Of ApplicationSignInManager)()
        Dim user = New ApplicationUser() With {.UserName = userName, .Email = userName}
        Dim result = manager.Create(user, Password.Text)
        If result.Succeeded Then
            ' For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            ' Dim code = manager.GenerateEmailConfirmationToken(user.Id)
            ' Dim callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request)
            ' manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=""" & callbackUrl & """>here</a>.")

            signInManager.SignIn(user, isPersistent := False, rememberBrowser := False)
            IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
        Else
            ErrorMessage.Text = result.Errors.FirstOrDefault()
        End If
    End Sub
End Class
2
On

OK. First remove word "KEY" - it's came from Telerik convertor - I do not know the reason. Second. On your HTML code duplicate ID=UserName and ID=Password win name="UserName" and name="Password" Hope this will help.