Archive

Archive for the ‘ASP.NET MVC’ Category

Have a toast with toastr.js

February 28, 2014 2 comments

In this post I am going to talk about a very simple notification jQuery plugin call toastr and I believe not many people have heard about it.

It is relatively simple to use and I often use it as debugging tool when I am writing JQuery plugin or trolling through JavaScript code.

Lets get started with a new ASP.NET MVC project and nuget the package with the following command.

PM> Install-Package toastr

 

The nuget package will add the css and the JavaScript file to the Asp.Net MVC project and we need to wire up the toastr.css and the toastr.js in our bundle config as shown below.

BundleConfig.cs

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js","~/Scripts/toastr.js",
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css","~/Content/toastr.css",
                  "~/Content/site.css"));
    }
}

Now I’m going to create a simple page with 4 buttons showing characteristics of toastr notification functionality.

Index.cshtml

    <div class="jumbotron">
        <div class="row">
            <div class="col-md-3">
                <h3>Toastr Success</h3>
                <p><a id="toastr-success" class="btn btn-success">Success</a></p>
            </div>
            <div class="col-md-3">
                <h3>Toastr Information</h3>
                <p><a id="toastr-info" class="btn btn-info">Information</a></p>
            </div>
            <div class="col-md-3">
                <h3>Toastr Warning</h3>
                <p><a id="toastr-warning" class="btn btn-warning ">Warning</a></p>
            </div>
            <div class="col-md-3">
                <h3>Toastr Error</h3>
                <p><a id="toastr-error" class="btn btn-danger">Error</a></p>
            </div>
        </div>

In the below JavaScript code I am setting some of the toastr option like the position of the popup and wiring up the button click to the toastr notification function.

<script type="text/javascript">
    $(document).ready(function () {
        toastr.options = {
            "closeButton": true,
            "positionClass": "toast-bottom-full-width",
            "onclick": null,
            "showDuration": "0",
            "hideDuration": "0",
            "timeOut": "0",
            "showMethod": "fadeIn"
        };
        $('#toastr-success').click(function () {
            toastr.success('This is a success notification from toastr.')
        });

        $('#toastr-info').click(function () {
            toastr.info('This is an information notification provided by toastr.')
        });

        $('#toastr-warning').click(function () {
            toastr.warning('This is a warning notification provided by toastr.')
        });

        $('#toastr-error').click(function () {
            toastr.error('This is an error notification provided by toastr.')
        });
    });
</script>

The JavaScript code is pretty straight forward and there are other options you can set such as whether a user interaction is required or not on the pop-up, do you need to call another function as part of post processing etc.

And here is the final page in action and for demonstration purpose I have taken the screenshot of all the notification in one page.

Have a toast with toastr

and here is what it would look like in a mobile device.

Have a toast with toastr - Mobile View

Happy toasting !!!

Using Output Cache Profile in ASP.NET MVC

September 29, 2013 2 comments

Caching is a quintessential part of any web application, as it improves the performance and load on the web server. The simplest way to add caching to your ASP.NET MVC application is to decorate your action method with the Output Attribute as following :-

 

[OutputCache(Duration=60,VaryByParam="none")]
public ActionResult Index()
{
    var employees = db.Employees;
    return View(employees.ToList());
}

However it is not a good practice to hard code such parameter values and specially when you have to apply different values for different set of caching. For example 60 second for long, 30 seconds for medium and 10 seconds for short caching.First problem with this approach is that you have to be very careful where you are making these changes and second problem is that for some reason if you have to change these values then you have to do search and replace, which is a very bad thing and totally against the DRY ( Don’t Repeat Yourself ) principle.

So overall it is a good practice to use the output cache profile and lets see how we can declare it in our web.config file.

Web.config

<caching>
   <outputCacheSettings>
     <outputCacheProfiles>
       <add name="Long" duration="60" varyByParam="none"/>
       <add name="Medium" duration="60" varyByParam="none"/>
       <add name="Short" duration="10" varyByParam="none"/>
     </outputCacheProfiles>
   </outputCacheSettings>      
 </caching>

And here is how we use the cache profile in our action method.

[OutputCache(CacheProfile="Long")]
public ActionResult Index()
{
    var employees = db.Employees;
    return View(employees.ToList());
}

 

This is very straight forward and nothing unusual but whats the point of blogging about something which hasn’t got any gotchas. And the gotcha is that you can’t use the cache profile on a child action and MVC will through this strange exception “Duration must be positive number.”

 

The above exception is actually misleading and basically output cache profile are not supporting for child action, partial views etc,however the fix for this problem is very easy and all we have to do is just extend the OutputCacheAttribute class. So we will write our own Partial cache attribute class .

PartialCacheAttribute.cs

   1:  public class PartialCacheAttribute : OutputCacheAttribute
   2:  {
   3:      public PartialCacheAttribute(string cacheProfileName)
   4:      {
   5:          var cacheSection = (OutputCacheSettingsSection)WebConfigurationManager
   6:                              .GetSection("system.web/caching/outputCacheSettings");
   7:   
   8:          var cacheProfile = cacheSection.OutputCacheProfiles[cacheProfileName];
   9:   
  10:          Duration = cacheProfile.Duration;
  11:          VaryByParam = cacheProfile.VaryByParam;
  12:      }   
  13:  }

 

As you can see nothing special we are using the GetSection method of WebConfigurationManager class and from that section we are getting the cache profile by its name at line 8. Now our child action method is all set to be decorated with this custom attribute and this is how the action method looks like :-

[ChildActionOnly]
[PartialCache("Short")]
public string GetEmployeesCount()
{
    return db.Employees.Count().ToString();
}

 

This was an issue with MVC 3 and still it’s an issue with MVC 4, but I hope this will get fixed in in MVC 5 😉

JQuery Template

March 3, 2011 2 comments

One of the reasons I started blogging was to document my project and learning experiences while working on complex problems. Right from the beginning of my career I was good in writing quick prototypes and small end-to-end proof of concepts, but what I was really not good at was the ability to remember it after sometime. So that way my blog is becoming my software repository and I am glad that it helping other guys who are about to use a particular technology or design principle.

In today’s post I am going to talk about JQuery Template although I did mention briefly about it in my previous post a 8 months ago. But this time I am going to show a full end to end solution and some tips.

The powerful thing about JQuery template is that the template runs in the browser (i.e. on client side) and hence you are taking the client CPU in order to process the template, it’s also better than using string concatenation server side and building HTML string.

So I am going to show a simple list of contact i.e Full name,Age,Phone and some sort of description and our contact class looks like this.

Contact.cs

public class Contact
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Phone { get; set; }
    public string Description { get; set; }

    public Contact(string name,int age,string phone,string description)
    {
        Name = name;
        Age = age;
        Phone = phone;
        Description = description;
    }
}

and the controller

ContactController.cs

public class ContactController : Controller
{
    public JsonResult GetContacts()
    {
        List<Contact> contacts = new List<Contact>()
        {
            new Contact("Joe Blogg",29,"02-6290-0011","A good fellow"),
            new Contact("James Weathers",39,"02-6290-0012","An intelligent fellow"),
            new Contact("John Smith",49,"02-6290-0013","A very wise fellow")
        }; // Just for the demo

        return Json(contacts, JsonRequestBehavior.AllowGet);
    }
}

The reason for returning a JSONResultSet is to show you guys how we can use JQuery to invoke the controller action. Lets see how the view looks like.

Index.aspx

<%@ Page Title="" Language="C#" 
         MasterPageFile="~/Views/Shared/Site.Master" 
         Inherits="System.Web.Mvc.ViewPage<JQueryTemplate.Models.Contact>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Contact
</asp:Content
>
<
asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Contact</h2>
    <script type="text/javascript">

        var templateName = "contactTemplate";
        var resultList = "#contactList";

        $(document).ready(function () {
            $("#jq-getData").click(function () {
                showContacts();
            });
        });

        function showContacts() {
            $.getJSON("/Contact/GetContacts", function (data) {
                var markup = getMarkup();
                clearResultList();
                loadTemplate(templateName, markup);
                applyTemplate(data);
            });
        };

        function getMarkup() {
            var markup = "<tr><td colspan=’2′ title=’${Description}’>${Name}</td><td>Age: ${Age}</td><td>Phone: ${Phone}</td></tr>";
            return markup;
        };

        function clearResultList() {
            $(resultList).empty();
        };

        function loadTemplate(templateName, markup) {
            $.template(templateName, markup);
        };

        function applyTemplate(data) {
            $.tmpl(templateName, data).appendTo(resultList);
        };

    </script>

    <input type="button" id="jq-getData" value="Click" />
    <table><tbody id="contactList"></tbody></table
>
</
asp:Content
>

Okay that looks bit lengthy code and I will try to break it down, I will start with the main function showContacts as it is main method which orchestrate other methods.

1. Get Json data for contacts by invoking the GetContacts action on the controller.

2. Get the markup (html template).

3. Clear the Dom element which will hold the output before any processing.

4. Load the template with the template name and assign the markup to it.

5. Apply the template.

As far as writing the template is concern it’s pure html tags and mark each place holders with the “${attribute}” pattern. The important thing is that the attributes in the template placeholder has to match the property of attribute of your JSON object.Lets run the application and see how it renders on the browser.

Result output

Nothing special as you can see the JSON object has the same attribute as it was in the template markup and the template engine was able to map it and process the html. Lets take a look into the caching headers send by the web server when we requested this JSON object.

Result output

As you can see “Last modified” and “Last fetched” are showing the current time but the “Expiry” header is showing a back date of “1970”, this means that every time the page is refreshed or loaded it will request the JSON over and over again and it can impact on your website performance and scalability. Lets fix it by providing some caching into this request by adding and Output Cache directive to the GetContacts action.

[OutputCache(Duration=60,VaryByParam="")]
public JsonResult GetContacts()
{
    List<Contact> contacts = new List<Contact>()
    {
        new Contact("Joe Blogg",29,"02-6290-0011","A good fellow"),
        new Contact("James Weathers",39,"02-6290-0012","An intelligent fellow"),
        new Contact("John Smith",49,"02-6290-0013","A very wise fellow")
    };

    return Json(contacts, JsonRequestBehavior.AllowGet);
}

After this build the solution and request the page again and you will see the expiry headers are added to the response and now the page will be cached on the browser for a minute.

Result output

That’s it for today and I hope you guys will find this end-to-end JQuery Template solution useful for your projects.BTW the Jquery template is available from Microsoft CDN site at http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js.

Automapper

November 2, 2010 3 comments

Recently a friend of mine was talking to me about his interesting project and in the conversation I mentioned him to use Automapper. As he was not aware of it but when I started explaining him he really got intrigued by it. I provided him the link and thought about blogging about it.

As you have guess it, it’s mainly a very smart mapping tool and will do all your left right hand code mapping. Whether it’s a MVC project where you do a lot of mapping between View-Model to DTO’s or whether you are working in an integration, this is something you can’t miss. You can download the assembly from codeplex at http://automapper.codeplex.com/releases/view/44802

Lets see some examples. Lets say i have two classes PersonDisplayVm & PersonDto and the dto instance is called item and the Vm instance is called model. So inorder to map the two objects so that we can copy value from dto to model we create a map between the classes and use the Map function to map it like this.

  Mapper.CreateMap<PersonDto, PersonDisplayVm>();
  Mapper.Map(item, model);

and this is how my two classes look like

public class PersonDisplayVm
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? Age { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

public class PersonDto : IPersonDto
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? Age { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

As you can see it already saved a lot of lines of code where we have to painstakingly assigning  value of one attribute in the left hand side to the corresponding value in the right hand side.

Following TDD and our good habit of writing test lets write a quick test.

[TestFixture]
public class When_testing_person_mapping
{
public PersonDto GetPersonDto()
{
     return new PersonDto
                {
                    Id = 1,
                    FirstName = "Joe",
                    LastName = "Blogg",
                    Age = 45,
                    CreatedDateTime = DateTime.Now
                };
}

[Test]
public void Should_be_able_to_map_dto_to_vm()
{
     var dto = GetPersonDto();
     var vm = new PersonDisplayVm();
     Mapper.CreateMap<PersonDto, PersonDisplayVm>();
     Mapper.Map(dto, vm);
     Assert.IsTrue(dto.Id == vm.Id);
}

Now lets say if for some reason in my display view-model I have the created datetime as string if we try to do a automapping from view-model to dto then we get an exception like

Exception of type ‘AutoMapper.AutoMapperMappingException’ was thrown.

as the string datetime when intialize with DateTime.Now add AM PM string into the string field and automapper can’t map it directly.In order to fix this problem you have to create a custom type convertor like this

public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
{
    public DateTime Convert(ResolutionContext context)
    {
        return System.Convert.ToDateTime(context.SourceValue);
    }
}

And add the custom type converter before our mapping happens like this

[Test]
public void Should_be_able_to_map_dto_to_vm()
{
    var dto = GetPersonDto();
    var vm = new PersonDisplayVm();
    Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
    Mapper.CreateMap<PersonDto, PersonDisplayVm>();
    Mapper.Map(dto, vm);
    Assert.IsTrue(dto.Id == vm.Id);
}

And you will see our test this time passes with no exceptions.

Now lets say you have another system or some legacy code where the Person class returned has a PersonId field instead of Id and it would be real waste to write another class which looks like the legacy class and write the whole mapping yourself.

This is where some of extensibility point of this mapper comes into play so lets say your legacy class or any other class looks like this.

public class PersonLegacyDto
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? Age { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

to map the PersonId field to Id field in PersonDto class you can simple specify it like this.

[Test]
public void Should_be_able_to_map_legacy_to_dto()
{
    var dto = GetPersonDto();
    var personLegacy = GetLegacyPerson();
    Mapper.CreateMap<PersonLegacyDto, PersonDto>()
        .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.PersonId))
        ;

    Mapper.Map(personLegacy, dto);
}

and you will see it does rest of the stuff, the .ForMember is an fluent interface so you can chain them for multiple property mapping.I use it quite often as it saves tones of writing left hand right hand code and saves a lot of time and energy. Hope you will find it handy to use and although I am using it in MVC project but can be used in any service/data layer project as well.

HTML Atrributes in MVC 2

October 22, 2010 Leave a comment

Recently I was working with a very interesting form problem and MVC 2, anyway I manage to solve the problem and wanted to use jQuery validation plugin. I knew i had use the htmlattributes property to inject the attributes and this is how it is done.

 

<div class="editor-field">

    <%: Html.TextBoxFor(model => model.Date, new {size = 25}) %>

    <%: Html.ValidationMessageFor(model => model.Date)%>

</div>

 

So here we are saying to the MVC View engine is that when the textbox for the Date field is generated add size as an html attribute with a value of 25,and this is how the output looks in Firebug.

So far so good and now I wanted to use JQuery Validation plugin to validate the date textbox before I submit the form. This is how JQuery validation plugin does a automatic validation of a form.

This is direct code from the Jquery validation plugin page which is at http://docs.jquery.com/Plugins/validation

However when i tried using the class reserved as a htmlattribute I got a clueless runtime error as “CS1513: } expected” and after some mucking around I came to know that you have to use @class instead of class . So when i change my code to this ..

<div class="editor-field">

    <%: Html.TextBoxFor(model => model.Date, new {@class = "required"}) %>

    <%: Html.ValidationMessageFor(model => model.Date)%>

</div>

and as you can see we got what we wanted:)

Mocking Routes

August 18, 2010 1 comment

I have a done a couple of post on how good TDD is and the use of Moq framework and today I am sharing some code to put all these ideas into practice with a real life project.

I have been working in ASP.NET MVC for sometime and this is one area where I first started using Moq and TDD i.e. testing ASP.NET MVC routes. This unit test project is part of the SparkViewEngine post i did some time ago and goes on to show good the MVC architecture is.

The first and foremost thing is to follow the triple “A” principle for writing unit test i.e.

  • Arrange
  • Act
  • Assert

Lets write some code to Mock the HttpContextBase in order to simulate an Http web request and then we are going to test our routes to verify that it maps to our controllers properly.

Mocking the HttpContextBase

As part of the “Arrange” we will create a RouteCollection object and pass it to RegisterRoutes method of the application class. This is the class which inherits from HttpApplication class and gets created in your Global.asax.cs file when you create a new MVC application.

Testing

In the next test we will test that our routes for a detail view. This is where the whole principle of “Separation of Concerns” really shines, we are able to test our routes with hosting on web server, without creating any web page or server pages etc.

Testing Person details

If you notice carefully you can see how I have named these test and have a lot of resemblence with Behaviour Driven Development (BDD) as I am a huge fan of BDD too.

Test View

If your arrange your test view as shown above you will see the highlighted line is really good in terms of readability. Just follow the pattern like

     For {Namespace} when {Class Name} the result expected is {Test Name}

You will see it reads like “For SparkViewEngineTest when TestingRoutes the result expected is This_goes_to_Person_Index_action” .

The whole sentence makes a lot of sense and is quite helpful when working on large projects with lots of unit test. (Another nice pattern to follow for your projects)

And when we run our unit tests we can verify our results.

ASP.NET MVC 3 Preview 1 released

I am excited to see that the ASP.NET MVC 3 Preview 1 has been released and you can get it from microsoft download website.

The features I am interested are:-

  • Razor View Engine and support for multiple view engines
  • Service Location and Dependency Injection Support

And here is this cool video of scott hanselman and Phil haack talking about MVC 3 Preview 1.

Categories: ASP.NET MVC Tags: