Showing posts with label ASP.NET MVC 4. Show all posts
Showing posts with label ASP.NET MVC 4. Show all posts

Sunday, May 5, 2013

ASP.NET MVC, jQuery, Checkboxes, Tables, JSON

In this post we will be looking at the following:
1). Creating and populating a HTML table.
2). Clicking a button in the table, causing it to check a checkbox.
3). Clicking button outside of table, triggering a modal dialog to be loaded.
4). Send data back to the controller based on which checkbox was checked.
5). Send the data as text and then send it as JSON.

Here is what we are building, the main screen:


When a user clicks the Notify button off to the right, the checkbox in that row should be checked. Note in the screenshot Leonard and Raj are selected.


The user will click the Send Notifications button after they have made all of their selections. This will trigger a modal dialog to appear on the screen. The dialog will be populated with the email address of the selected/checked row in the table. The user can then fill out the body and reason, then have the email sent.


Spin up a new MVC project. Add a PersonViewModel class to the models folder:
public class PersonViewModel
{
   public int PersonId { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Age { get; set; }
   public string FavoriteFood { get; set; }
   public string Email { get; set; }
}

In the HomeController, delete the view. We will create a method to give us some data to play with. We will come back to the view in a moment.
public ActionResult Index()
{
   List<PersonViewModel> people = GetPeople();
   return View(people);
}

private static List<PersonViewModel> GetPeple()
{
   return new List<PersonViewModel>()
   {
      new PersonViewModel() { PersonId = 1, FirstName = "Sheldon", LastName = "Cooper", Age = "35", FavoriteFood = "Greek Food", Email = "sheldon@bigbang.com" }, 
      new PersonViewModel() { PersonId = 2, FirstName = "Leonard", LastName = "Hoffstadter", Age = "35", FavoriteFood = "Cheese", Email = "leonard@bigbang.com" },
      new PersonViewModel() { PersonId = 3, FirstName = "Raj", LastName = "Koothrappali", Age = "35", FavoriteFood = "Indian Food", Email = "raj@bigbang.com" },
      new PersonViewModel() { PersonId = 4, FirstName = "Howard", LastName = "Wallowitz", Age = "35", FavoriteFood = "Brisket", Email = "howard@bigbang.com" },
      new PersonViewModel() { PersonId = 5, FirstName = "Stuart", LastName = "Bloom", Age = "35", FavoriteFood = "Can of tuna", Email = "stuart@bigbang.com" }
   };
}

Now let's set up the view. The view will be strongly typed to an IEnumerable of PersonViewModel. Be sure to add script references for jQuery and jQuery UI, either inline or through bundling:
@model IEnumerable<YourProjectName.Models.PersonViewModel>

@{
   ViewBag.Title = "Index";
}

<div id="notificationDiv">
   <input type="button" id="btnSendNotifications" name="btnSendNotifications" value="Send Notifications" class="ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all" />
</div>

<table id="tblPeople">
   <tr class="tableHeader">
      <th></th>
      <th>Id</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
      <th>Favorite Food</th>
      <th>Email</th>
      <th></th>
   </tr>

   @foreach (var item in Model)
   {
      <tr>
         <td>
            <input type="checkbox" name="ckCheck" id='@("ckCheck"+@item.PersonId)' />
         </td>
         <td id="personId">@item.PersonId</td>
         <td id="firstName">@item.FirstName</td>
         <td id="lastName">@item.LastName</td>
         <td id="age">@item.Age</td>
         <td id="favoriteFood>@item.FavoriteFood</td>
         <td id="email">@item.Email</td>
         <td>
            <input type="button" id='@("btnNotify"+item.PersonId)' name="btnNotify" value="Notify" class="ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all" />
         </td>
      </tr>
   }
<table>

Let's break this down a bit. The notificationDiv at the top of the page is what will take care of sending the notifications. As we will see, the click event will spin through the table rows to find which checkboxes are clicked and grab the email addresses. We are using jQuery UI to style the buttons and make them a little more pretty. Next we go through and create the table header. Then we spin through the model and write out the data.

A few things to note. I am being a little lazy and using foreach here. MVC purists would say to use a partial view as to get rid of the logic in the view. I agree but I admit I am being a little lazy. Note the technique for getting unique ids for the checkboxes and the Notify button. Razor syntax makes this possible. Here we are using it in two places: id='@("ckCheck"+@item.PersonId)' and id='@("btnNotify"+item.PersonId)'. I like this technique as it is an easy way to get unique ids.

On to the next order of business. We are going to set up a modal dialog. The purpose of this dialog is to display to the user all the email addresses to be sent back to the server. This will give a nice visual display of letting them double check their selections. They can then enter the message and reason, and finally, submit the request. Right after the table declaration in the view, add:

<div id="dialogTarget" title="Send Notifications>
   <p>All form fields are required.</p>
   <table id="peeps">
      <tr>
         <td>Bcc Message To:</td>
         <td>@Html.TextBox("ccTo", "", new { style = "width:300px;" })</td>
      </tr>
      <tr>
         <td>Message:</td>
         <td>@Html.TextArea("message", new { style = "width:300px;height:120px;" })</td>
      </tr>
      <tr>
         <td>Reason:</td>
         <td>@Html.TextBox("Reason", "", new { style = "width:300px;" })</td>
      </tr>
   </table>
</div>

All of the HTML is now good to go. Let's lay in all the script. Again, make sure your script references are set up the way you like them. We will go through piece by piece. First we will add some CSS to our table rows for the zebra striping effect. Will come back later and fill in the css business:

$('#tblPeople tr:even').addClass("alt");
$('#tblPeople tr:odd').addClass("altOdd");

Each row in the table has a Notify button. We need to handle the click event for this button and find the checkbox in that row, then check that checkbox. Since our buttons and checkboxes have unique ids, we will use the input selector 'input[name^="btnNotify"]'. The name^ syntax means "attribute starts with". We will grab the last character of the button id which will be a number. That number will then tell us which checkbox we should find, then check that checkbox:
$('input[name^="btnNotify"]').click(function (e) {
   var lastChar = e.target.id.substr(e.target.id.length - 1);
   ($(e).closest('td').find($('#ckCheck' + lastChar).attr('checked', true)));
});
The Send Notifications button click event has to go through each row in the table and find which checkboxes have been clicked. When the checkbox state is checked, we have to grab the email address from that row and put it into an array. This click event will also set the value of the ccTo field of the dialog. The last step of the event is to open the dialog.
$('#btnSendNotifications').click(function (e) {
   var emailAddresses = new Array();

   $('#tblPeople tr').each(function () {
      var checkbox = $(this).find($('input[name="ckCheck"]'));

      if (checkbox.is(":checked")) {
         var email = $(this).find('#email');
         emailAddresses.push(email.text());
      }
   });

   $('#ccTo').val(emailAddresses);
   $('#dialogTarget').dialog('open');
});

When the modal dialog pops open it should display the email addresses that were selected. The user can then fill out the message and the reason. Clicking the Notify button will fire off an Ajax request back to the server. When we return from the server we have to make sure that all selected checkboxes are changed to not being selected:
$('#dialogTarget').dialog({
   modal: true,
   autoOpen: false,
   width: 500,
   buttons: {
      "Notify": function (e) {
         var ccTo = $('#ccTo').val();
         var message = $('#message').val();
         var reason = $('#reason').val();
         $.ajax({
            url: '@Url.Action("EmailInfo", "Home")',
            type: "POST",
            dataType: "text",
            data: ({ ccTo: ccTo, message: message, reason: reason }),
            success: function (result) {
               alert(result);
               $('#dialogTarget').dialog('close');
               $('#tblPeople tr').each(function () {
                  var checkBox = $(this).find($('input[name="ckCheck"]'));

                  if (checkBox.is(":checked")) {
                     checkBox.attr('checked', false);
                  }
               }
            },
            error: function (jqXHR) {
               alert('Error: ' + jqXHR.responseText);
            }
         });
      },
      "Cancel": function () {
         $(this).dialog('close');
         $('#tblPeople tr').each(function () {
            var checkBox = $(this).find($('input[name="ckCheck"]'));

            if (checkBox.is(":checked")) {
               checkBox.attr('checked', false);
            }
         });
      }
   }
});

I can already hear the cringing....what the, why are you sending text data back?!?!? Hey now, just showing something different. We will come back and make it JSON. Let's take care of the server side business. We will need an Action called EmailInfo that will be expecting three string parameters. This Action will simple return a content message.
[HttpPost]
public ContentResult EmailInfo(string ccTo, string message, string reason)
{
   string result = "Email has been sent.";
   return Content(result);
}

Ok let's switch it all over to JSON. We will need a view model, EmailViewModel:
public class EmailViewModel
{
   public string EmailAddresses { get; set; }
   public string Message { get; set; }
   public string Reason { get; set; }
}

Change the EmailInfo Action:
[HttpPost]
public ActionResult EmailInfo(EmailViewModel email)
{
   if (ModelState.IsValid)
   {
      return Json(new { Message = "Email has been sent." });
   }
   else
   {
      return Json(new { Message = "Error, email was not sent." });
   }
}

The only change that we need to make in the JavaScript is in the Ajax call, more specifically, the data variable, and the success callback:
$.ajax({
   url: '@Url.Action("EmailInfo", "Home"),
   type: "POST",
   dataType: "json",
   data: {
      emailAddresses: ccTo,
      message: message,
      reason: reason
   },
   success: function (result) {
      alert(result.Message);
      $('#dialogTarget').dialog('close');
      $('#tblPeople tr').each(function () {
         var checkBox = $(this).find($('input[name="ckCheck"]'));

         if (checkBox.is(":checked")) {
            checkBox.attr('checked', false);
         }
      });
   },
   error: function (jqXHR) {
      alert('Error: ' + jqXHR.responseText);
   }
});

The final step is the css garbage. First, we will remove the border that is put around the checkboxes:
input[type="checkbox"] {
   background: transparent;
   border: none;
   width: auto;
}

And the css for the table:
table {
   border: solid 1px #e8eef4;
   border-collapse: collapse;
}

table td {
   padding: 5px;
   border: solid 1px #e8eef4;
   border-color: black;
}

table th {
   padding: 6px 5px;
   text-align: left;
   border: solid 1px #e8eef4;
}

tr.alt td {
   background-color: #F7F7DE;
   border-style: solid;
   border-width: 1px;
   border-color: black;
}

tr.altOdd td {
   border-style: solid;
   border-width: 1px;
   border-color: #000000
}

tr.tableHeader th {
   color: #FFFFFF
   background-color: #6B696B;
   font-weight: bold;
   border-style: solid;
   border-width: 1px;
   border-color: #000000;

Tuesday, March 5, 2013

ASP.NET MVC & Areas

Areas are a very handy way to segregate you application when you have alot of controllers that are very specific to a behavior or when you need to separate areas of your application. A common scenario, for example, is when you need an Admin section. The tricky thing about areas is handling the routing. In this example we will have an Admin area and a section for regular users, which should look normal to you. You can have controllers with the exact same name in your areas/non-areas and there will be no conflict. Let's see how to do this.

When creating a new MVC project we get the Home Controller right out of the box...

public class HomeController : Controller
{
   public ActionResult Index()
   {
      return View();
   }
}

We will assume that you have added an Area to your project, Admin, and added a Home Controller. The Home Controller will more than likely look quite similar.

In order to get things to work properly, we need to add namespacing in two areas, RouteConfig.cs and AdminAreaRegistration.cs. First let's have a go with RouteConfig.cs. Let's assume our project name is GiftIdeas...

public class RouteConfig
{
   public static void RegisterRoutes(RouteCollection routes)
   {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.MapRoute(
         name: "Default",
         url: "{controller}/{action}/{id}",
         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
         namespaces: new string[] { "GiftIdeas.Controllers" }
      );
   }
}

The important piece is the line namespaces: new string[] { "GiftIdeas.Controllers" }. All this is basically doing is saying, for the routes defined here, look in this namespace GiftIdeas.Controllers.

The other adjustment we need to make is very similar. By default, when you add an area to your project, a file called *YourAreaName*AreaRegistration.cs will be added. This is where we need to add some code, actually, very similar code...

public class AdminAreaRegistration : AreaRegistration
{
   public override string AreaName
   {
      get
      {
         return "Admin";
      }
   }

   public override void RegisterArea(AreaRegistrationContext context)
   {
      context.MapRoute(
         "Admin_default",
         "Admin/{controller}/{action}/{id}",
         new { action = "Index", id = UrlParameter.Optional },
         new string[] { "GiftIdeas.Areas.Controllers" }
      );
   }
}

The other piece of the puzzle is that now that we have an area in place, how do we deal with navigating the links within the application? For this, we have to go into _Layout.cshtml in the Views/Shared folder. Of course, this is if you want to show links across the top of your application. The change that needs to be made is in the nav section of the body. When you fire up a MVC application, this is what that part normally looks like:

<nav>
   <ul id="menu"
      <li>@Html.ActionLink("Home", "Index", "Home")</li>
      <li>@Html.ActionLink("About", "About", "Home")</li>
      <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
   </ul>
</nav>

We have to add another parameter in order for all the routes to hook up and work, for each action link, it is the same...

<nav>
   <ul id="menu"
      <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
      <li>@Html.ActionLink("About", "About", "Home" new { area = "" }, null)</li>
      <li>@Html.ActionLink("Contact", "Contact", "Home" new { area = "" }, null)</li>
      <li>@Html.ActionLink("Admin", "Index", "Home", new { area = "admin" }, null)</li>
   </ul>
</nav>

With this in place, you should now be able to have controllers with the same name in different parts of you application.
A common scenario is that we pass an id to views. When you are working with views in an area it does look a little different. Let's take a look at how we do that. For example, let's say we want to render a view for a GiftIdeaViewModel. The view in the Admin area would look like this:
@model GiftIdeaViewModel

<div>
   @Html.HiddenFor(giftIdeaViewModel => giftIdeaViewModel.GiftIdeaId)
</div>
<br />
<div>
   Name: @Html.DisplayFor(giftIdeaViewModel => giftIdeaViewModel.Name)
</div>
<br />
<div>
   @Html.ActionLink("Edit", "Edit", "GiftIdea", new { area = "admin", id = @Model.GiftIdeaId }, null) |
   @Html.ActionLink("Details", "Details", "GiftIdea", new { area = "admin", id = @Model.GiftIdeaId }, null) |
   @Html.AcitonLink("Delete", "Delete", "GiftIdea", new { area = "admin", id = @Model.GiftIdeaId }, null) |
</div>

Just add the id in the anonymous object and you are good to go. About the null parameter, per the MSDN documentation, the null parameter is required only because the ActionLink method overloads that have a routeValues parameter also have an htmlAttributes parameter. However, this parameter is not required in order to be able to link between areas.

Cached Repository

Caching in MVC is not all that difficult. But, you can put an interesting twist on it. This blog post will look at using a cached repository. This awesome idea came to my attention after surfing the web and landing at Steve Smith's blog:

Cached Repository

Since we will be using a repository here, let's set that up first. The POCO will be a Person class:
public class Person
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

I do have certain patterns and techniques I like to use. Since some have been featured in past postings, the code will just be posted below...
using System.Data.Entity.ModelConfiguration.Configuration;

public interface IEntityConfiguration
{
   void AddConfiguraton(ConfigurationRegistrar registrar);
}

using System.Collections.Generic;
using StructureMap;

public class ContextConfiguration
{
   public IEnumerable<IEntityConfiguration> Configurations
   {
      get { return ObjectFactory.GetAllInstances<IEntityConfiguration>(); }
   }
}

The configuration class for our Person POCO:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

public class PersonConfig : EntityTypeConfiguration<Person>, IEntityConfiguration
{
   public PersonConfig()
   {
      HasKey(p => p.Id);
      Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
      Property(p => p.FirstName).HasColumnName("FirstName").HasColumnType("nvarchar").HasMaxLength(30).IsRequried();
      Property(p => p.LastName).HasColumnName("LastName").HasColumnType("nvarchar").HasMaxLength(30).IsRequired();

      ToTable("Person");
   }

   public void AddConfiguration(ConfigurationRegistrar registrar)
   {
      registrar.Add(this);
   }
}

Again, because I like to do things in a particular fashion, the setup using an IDbContext interface may seem overkill for this demo scenario, but it's still valid for when you build out full repositories. Suffice to say, is still retains value. Plus, some of us like seeing the different ways people set up their repositories and data access crud. Moving on:
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

public interface IDbContext
{
   IDbSet<TEntity> Set<TEntity>() where TEntity : class;
   DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
   void SaveChanges();
   void Dispose();
}

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Validation;

public class PersonContext : DbContext, IDbContext
{
   public PersonContext()
      : base("name=DefaultConnection")
   {
      this.Configuration.AutoDetectChangedEnabled = true;
      this.Configuration.ProxyCreationEnabled = true;
   }

   public IDbSet<Person> People { get; set; }

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

   public new DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class
   {
      return base.Entry<TEntity>(entity);
   }

   public new void SaveChanges()
   {
      try
      {
         base.SaveChanges();
      }
      catch (DbEntityValidationException ex)
      {
         throw new Exception(ex.Message);
      }
   }

   protected new void Dispose()
   {
      base.Dispose();
   }

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
      Database.SetInitializer(new PersonInitializer());

      ContextConfiguration ctxConfig = new ContextConfiguration();

      foreach (IEntityConfiguration configuration in ctxConfig.Configurations)
      {
         configuration.AddConfiguration(modelBuilder.Configurations);
      }
   }
}

The PersonInitializer class sets up seed data which will be omitted. Also omitted is the StructureMap code since that has been covered in another post, just want to keep moving along here.

For the repository, I like to take the generic approach. We will have a Repository<T> class, a concrete PersonRepository class, an IRepository<T> interface, and an IPersonRepository interface. For this posting, I am not going to show a full blown repository implementation, perhaps that will come in a later post. Presented here will just be a very scaled down version to get the point of caching across:
public interface IRepository<T> where T : class
{
   IQueryable<T> AsQueryable();
   IEnumerable<T> GetAll();
}

public class Repository<T> : IRepository<T> where T : class
{
   private IDbContext iDbContext;

   public Repository(IDbContext context)
   {
      this.iDbContext = context;
   }

   public IQueryable<T> AsQueryable()
   {
      return this.iDbContext.Set<T>().AsQueryable();
   }
}

public interface IPersonRepository : IRepository<Person>
{
}

public class PersonRepository : Repository<Person>, IPersonRepository
{
   public PersonRepository(IDbContext iDbContext)
      : base(iDbContext)
   {
   }
}

Now the normal repository business is set up. Let's set up the Cachec Repository. First, we will need the generic ICachedRepository interface. You can put whatever methods you want to cache on this interface from the generic IRepository<T> interface. Sticking with our example, we have two, AsQueryable and GetAll:
public interface ICachedRepository<out T> where T : class
{  
   IQueryable<T> AsQueryable();
   IEnumerable<T> GetAll();
}

Of course the next step is the class that implements this interface. Remember, we are hooking into the ASP.NET cache here. Here is the CacheRepository class:
public class CachedRepository<T> : ICachedRepository<T> where T : class
{
   private IDbContext iDbContext;
   private static readonly object CacheLock = new object();

   public CachedRepository(IDbContext iDbContext)
   {
      this.iDbContext = iDbContext;
   }

   public IQueryable<T> AsQueryable()
   {
      string cacheKey = "AsQueryable";
      var result = HttpRuntime.Cache[cacheKey] as IQueryable<T>;

      if (result == null)
      {
         lock (CacheLock)
         {
            result = HttpRuntime.Cache[cacheKey] as IQueryable<T>;
            if (result == null)
            {
               result = this.iDbContext.Set<T>().AsQueryable();
               HttpRuntime.Cache.Insert(cachKey, result, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);
            }
         }
      }

      return result;
   }

   public IEnumerable<T> GetAll()
   {
      string cacheKey = "GetAll";
      var result = HttpRuntime.Cache[cacheKey] as IEnumerabl<T>;

      if (result == null)
      {
         lock (CacheLock)
         {
            result = HttpRuntime.Cache[cacheKey] as IEnumerable<T>;
            if (result == null)
            {
               result = this.iDbContext.Set<T>().AsEnumerable();
               HttpRuntime.Cache.Insert(cacheKey, result, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);
            }
         }
      }

      return result;
   }
}

In each method, we start out by defining a cache key, this cache key is put into the ASP.NET cache. Next, we check the cache for the cache key, if they cache key is null, no results for that given key have been stored in the cache. Now we lock the cache. It may seem strange to check the cache again for the result but this is very common in situations involving locking, it's a double check. We check the cache again for the cache key, and compare the result. Again, if the result is null, there is nothing in the cache for this query. If null, we query the DbContext for that entity and store the result, along with the cache key, cache dependencies (null), absolute expiration (DateTime.Now.Add(20)), and a sliding expiration (TimeSpan.Zero).
To set up a cached person repository, we just follow the patterns:
public interface ICachedPersonRepository : ICachedRepository<Person>
{
}

And the class to consume the interface:
public class CachedPersonRepository : CachedRepository<Person>, ICachedRepository
{
   public CachedPersonRepository(IDbContext iDbContext)
      : base(iDbContext)
   {
   }
}

What does this look like? When I was doing this demo, I was using the Paged List package which is a nice utility you can get on NuGet for formatting results with paging and all that good stuff. I won't go into that here but anyway, we have our Home Controller, the Index method is where the action is happening. The code below is not very important, moreso for illustration purposes. Also, the StructureMap configuration is not shown as well:
private ICachedPersonRespository cachedPersonRepository;

public HomeController(ICachedPersonRepository cachedPersonRepository)
{
   this.cachedPersonRepository = cachedPersonRepository;
}

public ActionResult Index(string search = null, int page = 1)
{
   IPagedList viewModels = this.cachedRepository.AsQueryable()
                                            .OrderByDescending(p => Id)
                                            .Where(p => search = null || p.FirstName.EndsWith(search))
                                            .Select(p => new PersonViewModel()
                                            {
                                               Id = p.Id,
                                               FirstName = p.FirstName,
                                               LastName = p.LastName
                                            }).ToPagedList(page, 5);

   return View(viewModels);
}

When the application first loads and we hit this method, the cached repository will be checked with the call to AsQueryable(). If we were to step through the code upon page load, here is the breakdown:
public IQueryable<T> AsQueryable()
{
   // upon page load, define the cache key
   string cacheKey = "AsQueryable";

   // look in cache for the cach ekey
   var result = HttpRuntime.Cache[cacheKey] as IQueryable<T>;

   // first page load, result will be null, nothing in cache
   if (result == null)
   {
      // lock the cache
      lock (CacheLock)
      {
         // double check
         result = HttpRuntime.Cache[cacheKey] as IQueryable<T>;

         // check the result again, result will be null on first page load
         if (result == null)
         {
            // get entity of T AsQueryable
            result = this.iDbContext.Set<T>.AsQueryable();

            // insert into the cache
            HttpRuntime.Cache.Insert(cacheKey, result, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);
         }
      }
   }

   return result;
}

We have assigned the result to be cached for 20 seconds. This means that for the next 20 seconds, any call that comes into the cached repository with the call to AsQueryable(), the ASP.NET runtime will return the cached response. In his article, Steve Smith points out that this approach does violate the DRY principle. If you want to look into that, check this link:

Cached Repository with Strategy Pattern

Saturday, February 2, 2013

Integrating SimpleMembership with Entity Framework

Integrating SimpleMembership with Entity Framework is quite nice. Instead of having two databases, collapse it all into one and have alll the info you need in one place. I'll be using a MVC 4 Internet application in VS 2012. I'll be putting all the POCO's and support classes in the Models folder for simplicity. First order of business, in the Filters folder, delete the InitializeSimpleMembershipAttribute C# file, as this will not be needed. We need to remove two classes from the AccountModels C# file. Open up AccountModels in the Models folder and delete the UserContext and UserProfile classes. For SimpleMembership we will have to create the four tables necessary for it: webpages_Membership, webpages_OAuthMembership, webpages_Roles, and webpages_UsersInRoles. Additionally, we will also add a UserProfile table and a dummy Person table. I like to add some support files for the EntityConfig classes and this requires StructureMap. Grab StructureMap from NuGet, it doesn't have to be the StructureMap.MVC package, just the plain StructureMap package. In the Models folder, add a class file, IEntityConfiguration:
using System.Data.Entity.ModelConfiguration.Configuration;

public interface IEntityConfiguration
{
   void AddConfiguration(Configuration registrar);
}

Add a class file, ContextConfiguration:
using System.Collections.Generic;
using StructureMap;

public class ContextConfiguration
{
   public IEnumerable Configurations
   {
      get { return ObjectFactory.GetAllInstances(); }
   }
}

Just to get it out of the way quick, let's take care of bootstrapping StructureMap. Open global.asax.cs, in the Application_Start method, right above the call to AreaRegistration.RegisterAllAreas();, add SetStructureMap(); Now let's create that method:
private void SetStructureMap()
{
   ObjectFactory.Initialize(x =>
                               {
                                  x.Scan(scan =>
                                               {
                                                  scan.TheCallingAssembly();
                                                  scan.WithDefaultConventions();
                                                  scan.AddAllTypesOf();
                                               });
                               });
}

All the POCO's:
public class Membership
{
   public int UserId { get; set; }
   public DateTime? CreateDate { get; set; }
   public string ConfirmationToken { get; set; }
   public bool? IsConfirmed { get; set; }
   public DateTime? LastPasswordFailureDate { get; set; }
   public int PasswordFailuresSinceLastSuccess { get; set; }
   public string Password { get; set; }
   public DateTime? PasswordChangedDate { get; set; }
   public string PasswordSalt { get; set; }
   public string PasswordVerificationToken { get; set; }
   public DateTime? PasswordVerificationTokenExpirationDate { get; set; }
}

public class OAuthMembership
{
   public string Provider { get; set; }
   public string ProviderUserId { get; set; }
   public int UserId { get; set; }
}

public class Role
{
   public int RoleId { get; set; }
   public string RoleName { get; set; }
   public virtual ICollection UserProfiles { get; set; }
}

public class UserProfile
{
   public int UserId { get; set; }
   public string UserName { get; set; }
   public virtual ICollection Roles { get; set; }
}

public class Person
{
   public int PersonId { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

The EntityConfig classes will contain the validation and other schema information:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

public class MembershipConfig : EntityTypeConfiguration<Membership>, IEntityConfiguration
{
   public MembershipConfig()
   {
      HasKey(m => m.UserId);
      Property(m => m.UserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
      Property(m => m.ConfirmationToken).HasColumnName("ConfirmationToken").HasColumnType("nvarchar").HasMaxLength(128);
      Property(m => m.IsConfirmed).HasColumnName("IsConfirmed").HasColumnType("bit").IsOptional();
      Property(m => m.LastPasswordFailureDate).HasColumnName("LastPasswordFailureDate").HasColumnType("datetime").IsOptional();
      Property(m => m.PasswordFailuresSinceLastSuccess).HasColumnName("PasswordFailuresSinceLastSuccess").HasColumnType("int").IsRequired();
      Property(m => m.Password).HasColumnName("Password").HasColumnType("nvarchar").HasMaxLength(128).IsRequired();
      Property(m => m.PasswordChangedDate).HasColumnName("PasswordChangedDate").HasColumnType("datetime").IsOptional();
      Property(m => m.PasswordSalt).HasColumnName("PasswordSalt").HasColumnType("nvarchar").HasMaxLength(128).IsRequired();
      Property(m => m.PasswordVerificationToken).HasColumnName("PasswordVerificationToken").HasColumnType("nvarchar").HasMaxLength(128);
      Property(m => m.PasswordVerificationTokenExpirationDate).HasColumnName("PasswordVerificationTokenExpirationDate").HasColumnType("datetime").IsOptional();
   
      ToTable("webpages_Membership");
   }

   public void AddConfiguration(ConfigurationRegistrar registrar)
   {
      registrar.Add(this);
   }
}

using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

public class OAuthMembershipConfig : EntityTypeConfiguration<OAuthMembership>, IEntityConfiguration
{
   public OAuthMembershipConfig()
   {
      HasKey(o => new { o.Provider, o.ProviderUserId });
      Property(o => o.Provider).HasColumnName("Provider").HasColumnType("nvarchar").HasMaxLength(30).IsRequired();
      Property(o => o.ProviderUserId).HasColumnName("ProviderUserId").HasColumnType("nvarchar").HasMaxLength(100).IsRequired();
      Property(o => o.UserId).HasColumnName("UserId").HasColumnType("int").IsRequired();

      ToTable("webpages_OAuthMembership");
   }

   public void AddConfiguration(ConfigurationRegistrar registrar)
   {
      registrar.Add(this);
   }
}

using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

public class RoleConfig : EntityTypeConfiguration<Role>, IEntityConfiguration
{
   public RoleConfig()
   {
      HasKey(r => r.RoleId);
      Property(r => r.RoleId).HasColumnName("RoleId").HasColumnType("int").IsRequired();
      Property(r => r.RoleName).HasColumnName("RoleName").HasColumnType("nvarchar").HasMaxLength(256).IsRequired();

      ToTable("webpages_Roles");
   }

   public void AddConfiguration(ConfigurationRegistrar registrar)
   {
      registrar.Add(this);
   }
}

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

public class UserProfileConfig : EntityTypeConfiguration<UserProfile>, IEntityConfiguration
{
   public UserProfileConfig()
   {
      HasKey(up => up.UserId);
      Property(up => up.UserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
      Property(up => up.UserName).HasColumnName("UserName").HasColumnType("nvarchar").HasMaxLength(128).IsOptional();

      HasMany(up => up.Roles)
         .WithMany(r => r.UserProfiles)
         .Map(usersinroles =>
         {
            usersinroles.MapLeftKey("UserId");
            usersinroles.MapRightKey("RoleId");
            usersinroles.ToTable("webpages_UsersInRoles");
         });

      ToTable("UserProfile");
   }

   public void AddConfiguration(ConfigurationRegistrar registrar)
   {
      registrar.Add(this);
   }
}

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

public class PersonConfig : EntityTypeConfiguration<Person>, IEntityConfiguration
{
   public PersonConfig()
   {
      HasKey(p => p.PersonId);
      Property(p => p.PersonId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
      Property(p => p.FirstName).HasColumnName("FirstName").HasColumnType("nvarchar").HasMaxLength(128).IsRequired();
      Property(p => p.LastName).HasColumnName("LastName").HasColumnType("nvarchar").HasMaxLength(128).IsRequired();
   }

   public void AddConfiguration(ConfigurationRegistrar registrar)
   {
      registrar.Add(this);
   }
}

Of course we will be needing a DbContext class, add a file named MembershipContext:
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

public class MembershipContext : DbContext
{
   public MembershipContext()
      : base("name=DefaultConnection")
   {
   }

   public DbSet Membership { get; set; }
   public DbSet OAuthMemberships { get; set; }
   public DbSet Roles { get; set; }
   public DbSet UserProfiles { get; set; }
   public DbSet People { get; set; }

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
      Database.SetInitializer(new MembershipTestInitializer());

      ContextConfiguration ctxConfiguration = new ContextConfiguration();

      foreach (IEntityConfiguration configuration in ctxConfiguration.Configurations)
      {
         configuration.AddConfiguration(modelBuilder.Configurations);
      }
   }
}

Two things to note: We are passing in a connection string on the constructor of the MembershipContext class and we are setting up some initialization in a class called MembershipTestInitializer. Regarding the connection string, if you are using VS2010 and SQL Server 2008, you can just omit the constructor altogether. In that case, by default, EF will use SQL Server Express. If you are using VS2012 and you have SQL Server 2010 and 2012 installed, you have some options. If you omit the constructor, EF will use SQL Server Express. Or, there is a default connection set in web.config. That is what we are doing. If you open web.config you will see the default connection in the connectionStrings section. You will also see that it is using the new LocalDb. LocalDb adds some jargon in the connection string that will not give us the exact database name we want. You can strip that out, for example:
<connectionStrings>
   <add name="DefaultConnection"
   connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MembershipContext;
                     Integrated Security=SSPI; AttachDBFilename=|DataDirectory|\MembershipContext.mdf"
                     providerName="System.Data.SqlClient" />
</connectionStrings>

MembershipTestInitializer will contain seed membership info. This class will provide the bridge to bring SimpleMembership into our POCO's. After that, everything will be in one db:
using System.Data.Entity;
using System.Linq;
using System.Web.Security;
using WebMatrix.WebData;

public class MembershipTestInitializer : DropCreateDatabaseIfModelChanges
{
   protected override void Seed(MembershipContext context)
   {
      SeedMembership();
   }

   private void SeedMembership()
   {
      WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

      SimpleRoleProvider roles = (SimpleRoleProvider) Roles.Provider;
      SimpleMembershipProvider membership = (SimpleMembershipProvider) System.Web.Security.Membership.Provider;

      if (!roles.RoleExists("Admin"))
      {
         roles.CreateRole("Admin");
      }
      if (membership.GetUser("sheldon", false) == null)
      {
         membership.CreateUserAndAccount("sheldon", "Password01");
      }
      if (!roles.GetRolesForUser("sheldon").Contains("Admin"))
      {
         roles.AddUsersToRoles(new string[] { "sheldon" }, new[] { "admin" } );
      }
   }
}

The call to WebSecurity.InitializeDatabaseConnection came from the InitializeSimpleMembershipAttribute C# file we deleted earlier. That is what originally kicks off the SimpleMembership db creation. In that method we are passing the connection string, the name of the table for UserProfile, the UserId, and the UserName. All of those line up nicely with the UserProfile POCO.
At this point, if we run the application, nothing will happen. We need to perform some sort of action to create the database. Initially, you may think, ok let's go and create a user. That will not work at this point because the line of code, WebSecutiry.InitializeDatabaseConnection, in the SeedMembership method has not run. The MembershipContext class has not been called, which kicks all this off.
To rectify that, simply go into the Index method of the HomeController and create a new Person. This should be enough to create the database:
public ActionResult Index()
{
   MembershipContext context = new MembershipContext();
   context.People.Add(new Person()
   {
      FirstName = "Sheldon",
      LastName = "Cooper"
   });

   return View();
}

Let's go have a look at the database:
 

And there we have it, all the SimpleMembership tables in our MembershipContext database.
EF FTW, eat it Tater.

ASP.NET MVC, JSONP, jQuery UI

For this post, we're going to dive into JSONP with MVC. The aim is to return content from another site and display it in a modal dialog. We will need two separate web projects running at the same time to see this in action. Environment is VS2012, ASP.NET MVC 4.

We'll start with the client site. Just spin up a new MVC 4 project, call it Client. Open up the Index view for the HomeController and wipe everything out. This, will be the view:

<input id="txtBox1" type="text" />
<button id="getData">Get Data</button>
<div id="modal"></div>

@section scripts {

}

Add a new JavaScript files to the Scripts folder, name it Index.js. We'll just be setting up the modal dialog and the AJAX call:
$(document).ready(function() {
   $('#modal').dialog({
      title: "Bazinga",
      modal: true,
      autoOpen: false,
      height: 300,
      width: 500
   });

   $('#getData').click(function(e) {
      $.ajax({
         type: 'GET',
         dataType: 'jsonp',
         url: 'fill this out later,
         success: function(data) {
            $('#modal').html(data.data);
            $('#modal').dialog("open");
         },
         error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus);
            alert(errorThrown);
         }
      });
   });
});

Note the dataType on the AJAX call, jsonp. We will come back and fill out the URL once we set up the other site. If you want, you can use the AJAX $.getJSON method instead, as such:
$.getJSON('http://localhost:12345/Home/Index2?jsoncallback=?', function(data) {
   $('#modal').html(data.data);
   $('#modal').dialog("open");
});

To wrap up the Client site, open up BundleConfig in the App_Start folder. We will create a bundle for the scripts we need. Put this right at the top of the RegisterBundles method:
public static void RegisterBundles(BundleCollection bundles)
{
   bundles.Add(new ScriptBundle("~/bundles/app").Include(
               "~/Scripts/jquery-{version}.js",
               "~/Scripts/jquery-ui-{version}.js",
               "~/Scripts/Index.js"));
}

Jump over to _Layout.cshtml and just change the jQuery bundle to app...
@Scripts.Render("~/bundles/app")
Time to fire up another web project, call this one Widget. To make this work, we will need a JsonpResult. Also, we will be rendering our content from a view as a string. This is a pretty slick technique, and we have Rick Strahl to thank. Take some time and go check out his post to get all the details on it: Rendering ASP.NET MVC Views to String

First, let's take care of the JsonpResult. I added a folder called Extensions, added a new C# file called JsonpResult:
using System;
using System.Web;
using System.Web.Mvc;

public class JsonpResult : JsonResult
{
   public override void ExecuteResult(ControllerContext context)
   {
      if (context == null)
      {
         throw new ArgumentNullException();
      }

      HttpRequestBase request = context.HttpContext.Request;
      HttpResponseBase response = context.HttpContext.Response;
      string jsoncallback = (context.RouteData.Values["jsoncallback"] as string) ?? request["jsoncallback"];

      if (!String.IsNullOrEmpty(jsoncallback))
      {
         if (String.IsNullOrEmpty(base.ContentType))
         {
            base.ContentType = "application/x-javascript";
         }

         response.Write(String.Format("{0}(", jsoncallback));
      }

      base.ExecuteResult(context);

      if (!String.IsNullOrEmpty(jsoncallback))
      {
         response.Write(")");
      }
   }
}

The important part here is the jsoncallback string. We look in Values of RouteData for a jsoncallback string, if we find one, we return, if not, we look in the request. Then we write the content type out. You can see this in Fiddler, let's have a looky look....
 
Add another C# file to the Extensions folder, called ViewRenderer:
using System;
using System.Web.Mvc;

public class ViewRenderer
{
   protected ControllerContext Context { get; set; }

   public ViewRenderer(ControllerContext controllerContext)
   {
      Context = controllerContext;
   }

   public static string RenderPartialView(string viewPath, ControllerContext controllerContext)
   {
      ViewRenderer renderer = new ViewRenderer(controllerContext);
      return renderer.RenderPartialView(viewPath);
   }

   public string RenderPartialView(string viewPath)
   {
      return RenderViewToStringInternal(viewPath, true);
   }

   protected string RenderViewToStringInternal(string viewPath, bool partial = false)
   {
      ViewEngineResult viewEngineResult = null;

      if (partial)
      {
         viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath);
      }
      else
      {
         viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, null);
      }

      if (viewEngineResult == null)
      {
         throw new FileNotFoundException("The view could not be found");
      }

      IView view = viewEngineResult.View;
      string result = null;

      using (StringWriter sw = new StringWriter())
      {
         ViewContext ctx = new ViewContext(Context, view, Context.Controller.ViewData, Context.Controller.TempData, sw);
         view.Render(ctx, sw);
         result = sw.ToString();
      }

      return result;
   }
}

Now to set up the content that will be returned to the client. In the Views folder, add a folder named Tmpl. In the Tmpl folder, add a view named Widget.cshtml. This is just going to be a simple example of sending down some text and JavaScript. Of course you have to be careful, scripting attacks, etc. Anywho, the Widget.cshtml file:
<p>Remote HTML loaded via JSONP.</p>
<br /><br />
<input type="button" value="Press Me!" onclick="Message()" />

<script type="text/javascript">
   function Message() {
      alert("Bazinga punk!");
   }
</script>

The final step is setting up an ActionResult in the HomeController. All we need to do is pass the path of our widget and the controller context to the ViewRenderer, which will return a string. We use this string as the data for our JsonpResult. The GetWidget ActionResult method in the HomeController:
using Widget.Extensions;

[HttpGet]
public ActionResult GetWidget()
{
   string result = ViewRenderer.RenderPartialView("~/View/Tmpl/Widget.cshtml", ControllerContext);
   return new JsonpResult()
              {
                 Data = new { data = result },
                 JsonRequestBehavior = JsonRequestBehavior.AllowGet
              };
}

I almost forgot. Run the Widget project. We need to grab the URL and put it in the AJAX call in the Client project. All you will need to change is the port number for the localhost. The completed AJAX call should look as such:
$('#getData').click(function(e) {
   $.ajax({
      type: 'GET',
      dataType: 'jsonp',
      url: 'http://localhost:61691/Home/GetWidget?jsoncallback=?',
      success: function(data) {
         $('#modal').html(data.data);
         $('#modal').dialog("open");
      },
      error: function(jqXHR, textStatus, errorThrown) {
         alert(textStatus);
         alert(errorThrown);
      }
   });
});

You might be wondering, what the heck is up with that URL? Yes, yes. In order for cross-domain to work, you are required to add the "?jsoncallback=?" bit, that is the key. If you omit that, the call will not work.
Now to test it out. Fire up the Widget project, it will just appear as the default view since we didn't change any of that. Then fire up the Client project upon running....

 
Before we click the Get Data button, let's set a breakpoint in the Widget project. If everything works, we will hit it.

 
Click Get Data and...
 
Success! After stepping through the rest of that method, we should see the modal dialog pop up on the client....
 
The finale...