Could not load file or assembly ‘WebGrease’ one of its dependencies. The located assembly’s manifest definition does not match the assembly reference


Usually when you would run an update-package command in Package Manager Console, you would encounter such error messages, in this instance the case is with Webgrease assembly

The reason for this error message is that the application is trying to load a different version of the assembly than what is present in the packages folder, and since there is a mismatch, its failing. A couple of things to quickly check in this scenario are:

  • Check the web.config file for assembly bindings
<dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
  • Check the version of the assembly referenced in your project

Clearly you can see the mismatch in the version of the referenced assembly and the assembly binding in the web.config file. All you have to do is to update the web.config file with the correct version of the assembly for binding. so,

<dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>

And that should be all!

Advertisements

Decoupling Asp.Net Identity 2.0 from Entity Framework in MVC5: Part 1


Usually the Asp.Net Identity 2.0 framework is aptly suited for most simple applications. However in complex line of business applications there is often a need to extend this base framework to map to growing application needs and architecture.
Today we are going to take a spin around the Asp.Net Identity 2.0 and see how we can de-couple it from the Entity framework and extend it further.

The implementation of the ApplicationDbContext that comes as a part of the standard template when we add Asp.Net Identity 2.0 to a MVC5 application is something like:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false) {
    }

    static ApplicationDbContext() {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create() {
        return new ApplicationDbContext();
    }
}

The IdentityDbContext does inherit from DbContext and in additions takes care of the Asp.Net Identity entities and related entities.

We will cover the entire post in 3 parts

Part 1

  • Implement the IdentityUser, IdentityRole and IdentityUserRole classes to support role based configuration for Asp.Net Identity framework
  • Make the ApplicationDbContext work with DbContext instead of IdentityDbContext<TUser> class
Part 2
  • Implement the UserStore without Claims and External Logins support to work with the new IdentityUser class
  • Implement RoleStore to work with the new IdentityRole class

Part 3

  • Implement Custom UserManager class to work with our new UserStore and IdentityUser entity
  • Implement Custom RoleManager class to work with our new RoleStore and IdentiyRole entity
  • A sample MVC5 application working with our custom system implementing basic user authentication and registration process using Asp.Net Identity

IdentityUser and Configuration class

public class IdentityUser: IUser
{
    #region Constructors

    public IdentityUser()
    {
        this.Id = Guid.NewGuid().ToString();
        this.Roles = (ICollection<IdentityUserRole>)new List<IdentityUserRole>();
    }

    public IdentityUser(string username): this()
    {
        this.UserName = username;
    }

    #endregion

    #region IUser<string> Members

    public string Id { get; set; }

    [Index("UserNameIndex", IsUnique=true)]
    public virtual string UserName { get; set; }

    public virtual string PasswordHash { get; set; }

    public virtual string SecurityStamp { get; set; }

    public virtual string Email { get; set; }

    public virtual int AccessFailedCount { get; set; }

    public virtual bool EmailConfirmed { get; set; }

    public virtual ICollection<IdentityUserRole> Roles { get; set; }

    #endregion

    #region Methods

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<IdentityUser> manager)
    {
        var identity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return identity;
    }

    #endregion
}

public class IdentityUserConfiguration: EntityTypeConfiguration<IdentityUser>
{
    public IdentityUserConfiguration()
    {
        HasKey(t => t.Id);
        Property(t => t.Id).HasMaxLength(128);
        Property(t => t.UserName).IsRequired().HasMaxLength(256);
        Property(t => t.PasswordHash).IsRequired();
        Property(t => t.SecurityStamp).IsRequired();
        Property(t => t.Email).IsRequired().HasMaxLength(256);
        Property(t => t.EmailConfirmed).IsRequired();

        HasMany(t => t.Roles)
            .WithRequired(t => t.User)
            .HasForeignKey(t => t.UserId);

        ToTable("AspNetUsers");
    }
}

IdentityRole and configuration class

public class IdentityRole: IRole
{
    #region Constructors

    public IdentityRole()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    public IdentityRole(string roleName): this()
    {
        this.Name = roleName;
    }

    public IdentityRole(string roleName, string id)
    {
        this.Name = roleName;
        this.Id = id;
    }

    #endregion

    #region IRole<string> Members

    public string Id { get; set; }

    [Index("RoleNameIndex", IsUnique=true)]
    public virtual string Name { get; set; }

    #endregion
}

public class IdentityRoleConfiguration: EntityTypeConfiguration<IdentityRole>
{
    public IdentityRoleConfiguration()
    {
        HasKey(t => t.Id);
        Property(t => t.Id).HasMaxLength(128);
        Property(t => t.Name).IsRequired().HasMaxLength(256);

        ToTable("AspNetRoles");
    }
}

IdentityUserRole and Configuration class

public class IdentityUserRole
{
    #region Properties

    public string UserId { get; set; }
    public virtual IdentityUser User { get; set; }

    public string RoleId { get; set; }
    public virtual IdentityRole Role { get; set; }

    #endregion

    #region Constructors

    public IdentityUserRole()
    {
    }

    public IdentityUserRole(string userId, string roleId)
    {
        this.UserId = userId;
        this.RoleId = roleId;
    }

    #endregion
}

public class IdentityUserRoleConfiguration: EntityTypeConfiguration<IdentityUserRole>
{
    public IdentityUserRoleConfiguration()
    {
        HasKey(t => new
        {
            t.RoleId,
            t.UserId
        });

        Property(t => t.UserId).HasColumnName("UserId");
        Property(t => t.RoleId).HasColumnName("RoleId");

        ToTable("AspNetUserRoles");
    }
}

And our new ApplicationDbContext class now becomes

public class ApplicationDbContext: DbContext
{
    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(null);
    }

    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        this.Configuration.ValidateOnSaveEnabled = true;
        this.Configuration.AutoDetectChangesEnabled = true;
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.AddFromAssembly(typeof(IdentityModel.Configurations.IdentityUserConfiguration).Assembly);
    }
}

In the next part we will look at the implementations of:

  • UserStore
  • RoleStore

Simple jquery function to set active navigation link with Twitter Bootstrap


Usually in a web application you would want the user to know which link is active by highlighting the active link. Twitter Bootstrap has a class

.active

that we can use to do this. This class needs to be applied to an

<li> <a href="#"></a> </li>

tag.

Html Structure

<ul class="nav">
    <li>
        <a href="/Home/Index">Index</a>
    </li>
    <li>
        <a href="/Home/About">About</a>
    </li>
</ul>

Jquery function

$(document).ready(function () {
    $('.nav a').each(function () {
        var url = $(this).attr('href');
        if (currentlocation == url) {
            $(this).closest('li').addClass(&quot;active&quot;);
        }
    });
});

And that’s it! Of course there are a lot many other approaches as well that we can use. This is just a most simplistic to get something up and running in a simple project.

C# dynamic and ExpandoObject to fetch data from Sql Server


A little while ago I was working on a simple application that would let the user define or upload an HTML template and then upload the data that would map to the template. The data could be csv or an excel file. The user could define multiple HTML templates and correspondingly upload data files for each template. The HTML templates and the data files were to be stored in the application for anytime use.

Obviously I had to figure out a mechanism to read the Excel sheet’s columns and corresponding data and get that into an SQL table. That was simple enough. Using the LinqToExcel library  I could read the excel data as simply as:


var excelFactory = new ExcelQueryFactory(fileName);                
var worksheet = excelFactory.GetWorksheetNames();
var columnNames = excelFactory.GetColumnNames(worksheet.FirstOrDefault());
                
var data = (from row in excelFactory.Worksheet(0)
            select row).ToList();

And then just simply store that list into the database.
But the issue was when I was reading that data back from the SQL database, I didn’t have any POCO classes to map that data to for my application to understand. So, this is what ended up doing in the end:

A simple function to read data from the database provided the table name

public IEnumerable<dynamic> GetData(string tableName)
{
    using (var connection = new SqlConnection(this.GetConnectionString()))
    {
        var commandText = "select * from " + tableName;
        using (var command = new SqlCommand(commandText, connection))
        {
            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    yield return GetDynamicData(reader);
                }
            }
            connection.Close();
        }
    }
}

private dynamic GetDynamicData(SqlDataReader reader)
{
    var expandoObject = new ExpandoObject() as IDictionary<string, object>;
    for (int i = 0; i < reader.FieldCount; i++)
    {
        expandoObject.Add(reader.GetName(i), reader[i]);
    }
    return expandoObject;
}

And then just cast each item in the returned

IEnumerable<dynamic>

to an

IDictionary<string, object>

and bind that to my view or do any processing with it.

Restrict an Administrator to create new users as per his allocated quota in a Multi-Tenant environment


Lately I have been working on a Multi-Tenant application using the latest MVC5 framework. The application is essentially an Ecommerce reporting and product analysis and forecasting application that can pull clients stock and sales information from different ecommerce channels like Amazon, Ebay, Groupon and Magento

Here is what the primary technology stack I’ve used in the application looks like:

  • Asp.Net MVC5
  • Asp.Net Identity Framework 2.0.1
  • Entity Framework 6.0.1
  • SQL Server 2008
  • Html5, CSS3, JQuery

So, as with any other Multi-Tenant application the application had various Subscription Levels or packages. Each Tenant can subscribe to any one Subscription Package which had a number of features. One of the features was the number of User Accounts the Tenant Administrator could create. This would vary depending on his subscription level. The Tenant Owner could request to add more user accounts to his subscription by paying a cost per user, and then that would be the user accounts limit.

So, basically there was a need for a Gated User creation process based on the Subscription Level of the Tenant and any additional users he had requested. I thought about a few approaches like:

  • Storing the Number of users allowed in the Session for a Tenant and then checking it each time I would create a user
    • The problem with this approach was that there were other features as well who’s creating was to be gated. So essentially I would need to store every feature in the session. Or store a list of features in the session. And then in the case of Users, when an additional user was requested then I would have to updated that value in the session variable as well along with updating the database. A bit that I didn’t wanted to manage
  • Setup a role for the ability to create users and remove it when they have created too many. Whenever they create a user, check to see if they meet the threshold, if they do, remove this privilege from their account.
    • This method was too cumbersome. Imagine if the admin removes a user, then if the role “CanCreateUsers” is not present, then we first add it, then do the whole process of adding entity, then if the limit reaches, then we remove this role again. And we do that on every User add and remove, plus also when an Owner requested additional user to the account. Its too much overhead and invitation to bugs

So after thinking about a few approaches I ended up using a mix of the ActionMethodSelectorAttribute and a simple HtmlHelperExtension along with an enum that described my gated actions. The code is as follows:

GatedAction enum

public enum GatedAction
{
    CreateUser,
    CreateAnotherFeature,
    ...
}

ActionMethodSelectorAttribute – SubscriptionActionAttribute

public class SubscriptionActionAttribute: ActionMethodSelectorAttribute
{
    public GatedAction Action { get; set; }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        var tenantId = controllerContext.RouteData.GetTenantId();
        using (var context = new ApplicationDbContext())
        {
            var tenant = context.Set<Tenant>().Include("Subscription").FirstOrDefault(t => t.Id == tenantId);
            switch (Action)
            {
                case GatedAction.CreateUser:
                    var totalAllowedUsers = tenant.AdditionalUsersRequested + tenant.Subscription.UsersAllowed;
                    var existingUsersCount = tenant.Users.Count();
                    return (existingUsersCount <= totalAllowedUsers);
                ...
                default:
                    return false;
            }
        }
        return false;
    }
}

GatedActionLink – HtmlHelper extension

public static MvcHtmlString GatedActionLink(this HtmlHelper helper,
    string icon,
    string text,
    string actionName,
    string controllerName,
    GatedAction action,
    RouteValueDictionary routeValues = null,
    IDictionary<string, object> htmlAttributes = null)
{
    ControllerBase controllerBase = string.IsNullOrEmpty(controllerName) ? helper.ViewContext.Controller : helper.GetControllerByName(controllerName);
	ControllerContext controllerContext = new ControllerContext(helper.ViewContext.RequestContext, controllerBase);
    ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerContext.Controller.GetType());
    ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

    htmlAttributes = htmlAttributes ?? new Dictionary<string, object>();
    if (actionDescriptor == null)
        htmlAttributes.Add("disabled", "disabled");            

    return helper.ActionLinkWithIcon(icon, text, actionName, controllerName, routeValues, htmlAttributes);
}
</pre>

And that’s it really. Now all I have to do is to decorate my action method like this:

[HttpGet]
[SubscriptionAction(Action = GatedAction.CreateUser)]
public async Task CreateUser()
{
...
}

and in my view the create action link would be like:

@Html.GatedActionLink("glyphicon glyphicon-plus", "create user", "CreateUser", "Manage", GatedAction.CreateUser, new RouteValueDictionary { { "area", "Users" } }, new Dictionary { { "class", "btn btn-default btn-xs" } })

And that’s all. We are sorted. I only update my database and rest is handled by my custom filter attribute and the html helper extension.

Online Catalog: My first Git published on Git-hub


Recently been working on getting an end to end implementation of an example that would use ASP.Net MVC4, Twitter Bootstrap and a lot other Microsoft and other open source technologies as a shop window and showcase of these products being used together in harmony.
So here I am with the first check in for “Online Catalog”, an online product catalog with integrated Admin section and shopping cart along with a full order management and reporting functionality.

Please feel free to drop in your comments and or any suggested changes. I will be updating this repository in the time to come with newer functionality being added until its marked complete.

Watch out this space for updated and new code availability!!
https://github.com/JinishBhardwaj/Online-Catalog

Prism: Controlling module loading and initialization


Lately, we’ve been working on a project for a client. The project is built ont he silveright platform and uses the Prism architecture and has several modules.
One of the issues that our client had was that everytime they started the application they found that the modules we shuffled and placed differently. The underlying problem is that all the modules in prism are loaded asynchronously and by default, gives the user very little control on loading and initialization. But, that dosent mean it doesnt support excersing some control over this process.

Below is a simple class that sorts the modules alphabetically once they have been loaded and then initializes them in that order:

public class CustomModuleInitializer : IModuleInitializer
{
    #region Class members

    private bool moduleLoadCompleted;
    private readonly IModuleInitializer defaultInitializer = null;
    private List modules = new List();
    private readonly IModuleCatalog moduleCatalog;
    private static int _modulesCount;
    private static int _counter;

    #endregion

    #region Constructors

    public CustomModuleInitializer(IUnityContainer container, IModuleCatalog moduleCatalog)
    {
        this.defaultInitializer = container.Resolve("moduleInitializer");
        this.moduleCatalog = moduleCatalog;
        _modulesCount = moduleCatalog.Modules.ToList().Count;
    }

    #endregion

    #region Implementation of IModuleInitializer

    public void Initialize(ModuleInfo moduleInfo)
    {
        if (this.moduleLoadCompleted)
        {
            defaultInitializer.Initialize(moduleInfo);
            return;
        }

        modules.Add(moduleInfo);

        if (!ModuleLoaded()) return;
            this.SortModules();
        foreach (var module in modules)
        {
            defaultInitializer.Initialize(module);
        }
        modules = null;
        moduleLoadCompleted = true;
        }
    }

    private static bool ModuleLoaded()
    {
        _counter++;
        return _counter == _modulesCount;
    }

    private void SortModules()
    {
        if (modules.Count > 0)
        {
            modules.Sort((x, y) => string.Compare(x.ModuleName, y.ModuleName));
        }
    }
    #endregion
}

And then in the Bootstrapper just override the Configure Container method like this:

protected override void ConfigureContainer()
{
    base.ConfigureContainer();
    var defaultContainer = Container.Resolve();
    Container.RegisterInstance("moduleInitializer", defaultContainer);
    Container.RegisterType(new ContainerControlledLifetimeManager());
}

And its sorted !