Archive

Posts Tagged ‘ASP.NET MVC’

ASP.NET Identity v2 and CodeFluent Entities

April 30, 2014 Leave a comment

Update (2014/06/23) - please check out this related post :

A few weeks ago, we wrote about ASP.NET Identity v1 and CodeFluent Entities. The ASP.NET Identity system is designed to replace the previous ASP.NET Membership and Simple Membership systems. It includes profile support, OAuth integration, works with OWIN and is included with the ASP.NET templates shipped with Visual Studio 2013.

ASP.NET Identity 2.0 was released last month so today we’ll see how to use it with CodeFluent Entities.

What’s new?

One of the drawbacks of the first release was that the primary key must be of type “string”. This new version allows to use any type as primary key. To do so, interfaces now have a second generic parameter, “TKey”, to specify the type of the primary key (int, Guid, etc.).
They also introduce new interfaces:

  • IUserLockoutStore<User, TKey>: allow to lock-out an account after a determined failed connection attempts
  • IUserEmailStore<User, TKey>: allow to store an email address and to confirm it (by sending an email for example)
  • IUserPhoneNumberStore<User, TKey>: allow to store a phone number and to confirm it (by sending a SMS for example)
  • IUserTwoFactorStore<User, TKey>: enable two-factor authentification (for example login/password and a token sent by email or SMS)

The implementation

 

Here’s the CodeFluent Entities Model to support those interfaces:

model

You’ll note that our model contains:

  • Implementation rules. We don’t even have to add partial class, everything is in the model
  • validation rules (EmailValidation) to ensure email address is valid
  • Unique contraints (UserName, Email, Role Name)

As for ASP.NET Identity v1, each method is only one or two lines of code:

public class UserStore :
    IUserStore<User, Guid>,
    IUserPasswordStore<User, Guid>,
    IUserSecurityStampStore<User, Guid>,
    IUserRoleStore<User, Guid>,
    IUserLoginStore<User, Guid>,
    IUserClaimStore<User, Guid>
{
    public Task<User> FindAsync(UserLoginInfo login)
    {
        return Task.FromResult(User.LoadByProviderKey(login.ProviderKey));
    }

    public Task ResetAccessFailedCountAsync(User user)
    {
        user.AccessFailedCount = 0;
        return Task.FromResult(0);
    }

    public Task<int> GetAccessFailedCountAsync(User user)
    {
        return Task.FromResult(user.AccessFailedCount);
    }

    // and so on
}

The full implementation is available on our GitHub repository.

The R&D team.

ASP.NET Identity and CodeFluent Entities

February 20, 2014 Leave a comment

Update (2014/06/23) – please check out these related posts :

The ASP.NET Identity system is designed to replace the previous ASP.NET Membership and Simple Membership systems. It includes profile support, OAuth integration, works with OWIN and is included with the ASP.NET templates shipped with Visual Studio 2013.

ASP.NET Role and Membership providers are out of the box features provided by CodeFluent Entities. Today we’ll see how to create an ASP.NET Identity implementation with CodeFluent Entities.

Let’s do this ! :)

What do we have to do?

ASP.NET Identity provides a bunch of interfaces to define Users, Profiles, Logins, Roles, and how to store them.

A user is defined by the Microsoft.AspNet.Identity.IUser interface and a role is defined by the Microsoft.AspNet.Identity.IRole interface. Those interface are very generics:

public interface IUser
{
    string Id { get; }
    string UserName { get; set; }
}

public interface IRole
{
    string Id { get; }
    string Name { get; set; }
}

ASP.NET Identity also introduce the concept of user store to persist user information. There are different levels of functionalities depending of your needs:

Finally, the Microsoft.AspNet.Identity.UserManager is a higher level API that will coordinate different components such as the UserStore, the Password hasher and the user and password validation in order to manage users in your application.

Now you should have understood that to do our custom ASP.NET Identity we’ll implement the IUser, IRole and IUser*Store interfaces (yes all of them).

Let’s create the model

 

CodeFluentEntitiesAspNetIdentity

User must implement the IUser interface. This can be done by adding an implementation Rule. The same apply for Role with the IRole interface.

To ensure the uniqueness of the username and role name we declared them at CollectionKey. This will also add automatically the methods User.LoadByUserName and Role.LoadByName.

To implement the UserStore we’ll need two more methods. The first one is to find a customer by a provider key. To do so we add a CFQL method on the user entity:

LOADONE(string providerKey) WHERE ExternalLogins.ProviderKey = @providerKey

We also need to delete a claim by User, Type and Value. This can also be done by CFQL

DELETE(User, Type, Value) WHERE User = @User AND Type = @Type AND Value = @Value

Those methods will be translated into stored procedures during the build process. Note that with CFQL you don’t have to bother with JOIN nor types ! :)

Below is a part of UserStore and RoleStore implementation :

public class UserStore :
    IUserStore<User>,
    IUserPasswordStore<User>,
    IUserSecurityStampStore<User>,
    IUserRoleStore<User>,
    IUserLoginStore<User>,
    IUserClaimStore<User>
{

    public Task CreateAsync(User user)
    {
        if (user == null) throw new ArgumentNullException("user");
        return Task.Run(() => user.Save());
    }

    public Task DeleteAsync(User user)
    {
        if (user == null) throw new ArgumentNullException("user");
        return Task.Run(() => user.Delete());
    }

    public Task<User> FindByIdAsync(string userId)
    {
        return Task.Run(() => User.LoadByEntityKey(userId));
    }
// ...
}

public class RoleStore : IRoleStore<Role>
{
    public Task CreateAsync(Role role)
    {
        return Task.Run(() => role.Save());
    }

    public Task<Role> FindByNameAsync(string roleName)
    {
        return Task.Run(() => Role.LoadByName(roleName));
    }
// ...
}

Now we can use the UserStore through the UserManager and the RoleStore through the RoleManager:

new UserManager<User>(new UserStore())
new RoleManager<Role>(new RoleStore())

In the article we show that the code generated by CodeFluent Entities can easily be used with really new Framework like ASP.NET Identity. This is possible as CodeFluent Entities generates rock-solid foundation on which you can build your application !

The full implementation is available for download.

Happy user storing,

The R&D team.

April 11th 2012 Links: VB6, .NET Portable Class Libraries, Internet Explorer 10, ASP.NET MVC 4, eBooks

April 11, 2012 Leave a comment

Following the steps of Scott Guthrie’s link-listing series, here’s our new batch of links in our own series:

 

Windows

Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008, Windows 7, and Windows 8

Good news for those still using VB 6: it’ll be supported on Windows 8!

 

It’s the end of mainstream support for Windows Vista

April 10, 2012: That’s the date Windows Vista support moves from mainstream to extended (meaning paid for everything but security updates).

 

Visual Studio

Hidden Gems in Visual Studio 11 Beta – .NET Portable Class Libraries

Scott Hanselman details Portable Class Libraries which is a feature available in Visual Studio 2010 (through an extension) and in Visual Studio 11.

 

TFS 11 Power Tools Beta Available

Good news TFS 11 power tools (beta) are now publicly available Smile 

 

Dev

ASP.NET MVC 4 now open source

Yay! All sources are on CodePlex! if you haven’t already, go check them out because that’s some good looking .NET code Smile

 

The Danger of the Large Object Heap (LOH)

Another article which we like on the same subject is: “Large Object Heap Uncovered” (written by Maoni Stephens).

We actually wrote an article ourselves which is quite related to the subject as well: Manipulating SQL Blobs With Streams.

 

IndexedDB Updates for IE10 and Metro style apps

IndexedDB is a W3C Working Draft that enables you to store, search, and retrieve data on the user’s device, even when Internet connectivity is disabled.  IndexedDB is a feature of the Web platform shared by IE10 and Metro style apps in the Windows 8 Consumer Preview.”

Hmm, very interesting…

 

eBooks

Grab a free copy of “Under the hood of .NET Memory Management”

We did it, it was worthy, so we thought we’d share Winking smile

 

Free ebook: Introducing Microsoft SQL Server 2012

With SQL Server 2012 now available, I’m sure it’ll come in handy.

 

Cheers,

Carl Anderson

CodeFluent Entities: Attributes

February 23, 2012 1 comment

Using CodeFluent Entities you can define attributes on other concepts such as Entities, Methods or Properties and what gets really interesting is that the .NET Business Object Model Producer translates those CodeFluent Entities Attributes into actual .NET attributes Smile

Now say you want to specify some specific attributes on your generated .NET classes or data annotations on your properties, defining attributes in your model would be the way to go!

To do so select your concept such as a property and click on “Add Attribute” in the ribbon, the following dialog will show up:

image

In the attribute name set the full type name of your attribute such as System.ComponentModel.DataAnnotations.RequiredAttribute”.

Note: Setting the attribute class using the drop down list in the lower part of the form allows you to specify where this attribute should be placed in the generated classes. Default is in the entity class, but you can also place it in the service class, the service interface, or the proxy class.

In the screenshot below we defined a Required data annotation attribute on the Name property of our entity:

image

Then here’s the output after generating our model over:

[System.ComponentModel.DataAnnotations.RequiredAttribute()]
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Name
{
    (…)

To specify a parameter to your attribute, go back to your model, select your attribute and click on the Arguments property in the property grid:

image

And let’s add an error message to our required attribute:

image

Generate over and here’s the result:

[System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage="Name is required")]
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Name
{
    (…)

 

Carl Anderson

Follow

Get every new post delivered to your Inbox.

Join 44 other followers