Thursday, 26 March 2015

Overriding default HTML encoding in jQuery Template

${template-variable} syntax of jQuery Template encodes the HTML if present in the value passed to the template. You can override the default encoding behaviour using {{html template-variable-containing-html}} instead of the ${template-variable} syntax. Here is an example.


<div id="container">
    <script id="sampleTemplate" type="text/x-jquery-tmpl">
        <div id="cust_${id}">
        <span>${name}</span>:
      
       {{html phone}}

    </script>
</div>

<script type="text/javascript">

$(document).ready(function() {
 
var customer = {
            id: 101, 
            name: 'Test',
            phone: '<b>123-456-777</b><br/><b>111-223-455</b>'
        };

$('#sampleTemplate').tmpl(customer).appendTo('#container');

});

</script>

Monday, 9 March 2015

How to iterate through Microsoft Enterprise Library CacheManager?

Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager doesn't have a method / property that allow you retrieve the entire Cache items together. I had such a requirement and found a work around. This is using reflection to get "realCache" field in CacheManager and then looping through Cache.CurrentCacheState.

GetData() retrieves a single item from the Cache.

ICacheManager cacheManager = CacheFactory.GetCacheManager("cacheName");
object cacheItem = cacheManager.GetData("cacheKey");

Retrieving and iterating the entire Cache


using Microsoft.Practices.EnterpriseLibrary.Caching;

... 

string cacheName = "your-cache-name";
Cache cache;

if (TryGetCache(cacheName, out cache))
{
  foreach (DictionaryEntry cacheEntry in cache.CurrentCacheState)
  {
    object key = cacheEntry.Key;
    CacheItem cacheItem  = (CacheItem)cacheEntry.Value;
    object value = cacheItem.Value;
    Console.WriteLine("{0}: {1}", key, value)
  }
}

private static bool TryGetCache(string cacheName, out Cache cache)
{
  try
  {
    ICacheManager _cacheManager = CacheFactory.GetCacheManager(cacheName);
    cache = (Cache)_cacheManager.GetType().GetField("realCache", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(_cacheManager);
  }
  catch (Exception)
  {
    cache = null;
    return false;
  }
  return true;
}

Thursday, 5 March 2015

DateTime format strings in .NET

A date and time format string defines the text representation of a DateTime that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time. A custom format string consists of one or more custom date and time format specifiers.

Usually a format string is used with DateTime.ToString() or string.Format()

Examples

// DateTime to String

DateTime.Today.ToString("MMM dd, yyyy") // Mar 05, 2015

string.Format("{0:dd/MM/yy HH:mm:ss}", DateTime.Now) // 05/03/2015 14:05:33

string.Format("{0:hh:mm:ss tt}" , DateTime.Now) // 02:05:33 PM

// String to DateTime

string dateString = "Mar 05, 2015";
DateTime dateTime = DateTime.ParseExact(dateString , "MMM dd, yyyy", null);

Format Specifiers cheat sheet
Day of the month - "d", "dd"

Name of the day of the week - "ddd", "dddd" 

Month - "M", "MM", "MMM", "MMMM"

Year - "y", "yy", "yyy", "yyyy"

Hour (12 hour clock) - "h", "hh"

Hour (24 hour clock) - "H", "HH"

AM/PM designator - "t", "tt"

Minute - "m", "mm"

Second - "s", "ss"

MSDN >>

Download DateTime Formatting Utility from Microsoft : The Format Utility (Formatter.exe) is a Windows Forms application that allows you to apply standard or custom format strings to either numeric values or date and time values and to determine how they affect the result string.

Friday, 27 February 2015

Unit Testing ASP.NET MVC - Cheat Sheet

Mocking Request Cookie
var mockContext = new Mock<ControllerContext>();

mockContext.Setup(c => c.HttpContext.Request.Cookies).Returns(new HttpCookieCollection { new HttpCookie("test", "1") });

HomeController controller = new HomeController();
controller.ControllerContext = mockContext.Object;

var result = controller.Index()
Mocking Response Cookie
var mockContext = new Mock<ControllerContext>();

mockContext.SetupGet(c => c.HttpContext.Response.Cookies).Returns(new HttpCookieCollection());

HomeController controller = new HomeController();
controller.ControllerContext = mockContext.Object;

var result = controller.Index()

Assert.AreEqual(controller.ControllerContext.RequestContext.HttpContext.Response.Cookies["test"].Value, "1");

Mocking Request.IsAuthenticated
var mockContext = new Mock<ControllerContext>();
mockContext.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mockContext.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);

var controller = new HomeController();
controller.ControllerContext = mockContext.Object;
Mocking ModeState.IsValid

ModeState.IsValid property is read only. But you can add an error to the ModelState to set the IsValid flag false indirectly.

var controller = new HomeController();
controller.ModelState.AddModelError("Error", "Model is invalid");
ViewResult result = controller.Index() // ModeState.IsValid will be false when Index() is executed. 
Mocking Dependency

MathController depends on an implementation of IMathService to complete the action. In the following example a mock instance of IMathService is passed to MathController to test the Add() method

Mock mathService = new Mock<IMathService>();
mathService.Setup(ms => ms.Add(1, 2)).Returns(3);

MathController controller = new MathController(mathService.Object);
var result = controller.Index(1, 2) as ViewResult;

Assert.AreEqual(result.ViewBag.Sum, 3);
mathService.Verify(ms => ms.Add(1,2), Times.Exactly(1));
Mocking Exception
Mock mathService = new Mock<IMathService>();
mathService.Setup(ms => ms.Add(1, 0)).Throws(new ArgumentException("Invalid argument(s)"));

MathController controller = new MathController(mathService.Object);

try
{
      var result = controller.Index(1, 0) as ViewResult;
}
catch(ArgumentException ex)
{
      Assert.AreEqual("Invalid argument(s)", ex.Message);
}
Testing RedirectResult

If your method returns a RedirectResult then you can check the result url against the expected

var controller = new RedirectController();

RedirectResult result = controller.SendMeSomewhereElse();

Assert.AreEqual("~/Some/Other/Place", result.Url);
Testing RedirectToRouteResult

If your method returns a RedirectToRoute i.e. if your action method returns RedirectToAction() or RedirectToRoute() then you can check the action name in RouteValues against the expected value. In the following example CustomerController.Create() is tested to check if the request is redirected to Index after creating the customer.

 var controller = new CustomerController();

var result = controller.Create(new Customer {Name = "Test"}) as RedirectToRouteResult;

Assert.AreEqual("Index", result.RouteValues["action"]);

Mocking HttpContext

Click here to see how to Mock HttpContext

Friday, 13 February 2015

ActionResult types in ASP.NET MVC

ActionResult (System.Web.Mvc.ActionResult) Subtypes

ContentResult - Returns a user-defined content type.

Helper method: System.Web.Mvc.Controller.Content()

EmptyResult - Represents a return value that is used if the action method must return a null result (void).

Helper method: (None)

FileContentResult - Sends the contents of a binary file to the response.

Helper method: System.Web.Mvc.Controller.File()

FileStreamResult - Sends binary content to the response through a stream.

Helper method: System.Web.Mvc.Controller.File()

FilePathResult - Sends the contents of a file to the response.

Helper method: System.Web.Mvc.Controller.File()

HttpStatusCodeResult - Returns a specific HTTP response code and description.

Helper method: (None)

HttpUnauthorizedResult - Returns the result of an unauthorized HTTP request.

Helper method: (None)

HttpNotFoundResult - Indicates the requested resource was not found.

Helper method: System.Web.Mvc.Controller.HttpNotFound()

JavaScriptResult - Returns a script that can be executed on the client.

Helper method: System.Web.Mvc.Controller.JavaScript()

JsonResult - Returns a serialized JSON object.

Helper method: System.Web.Mvc.Controller.Json()

PartialViewResult - Renders a partial view, which defines a section of a view that can be rendered inside another view.

Helper method: System.Web.Mvc.Controller.PartialView()

RedirectResult - Redirects to another action method by using its URL.

Helper method: System.Web.Mvc.Controller.Redirect()

RedirectToRouteResult - Redirects to another action method.

Helper method: System.Web.Mvc.Controller.RedirectToAction() or RedirectToRoute()

ViewResult - Renders a view as a Web page.

Helper method: System.Web.Mvc.Controller.View()

MSDN >>

Wednesday, 11 February 2015

How to add a section conditionally in ASP.NET MVC?

Here you go

@if(sectionRequired)
{
@:@section OptionalSection
{
<div class="content">
  Some text
</div>
}
}

You can set the Razor variable sectionRequired as required.

Deep cloning objects in JavaScript

There are a lot of ways to clone objects in Javascript and here are two of them.

Using JSON library

var person = {
    name: "Jack",
    age: 21,
    address: {houseNumber: 11, postcode: 'BR3'}
};
 
var jill = (JSON.parse(JSON.stringify(person)));
jill.name = "Jill";
 
console.log(person);
console.log(jill);

Using jQuery’s $.extend()

var person = {
    name: "Jack",
    age: 21,
    address: {houseNumber: 11, postcode: 'BR3'}
};
 
var jill = $.extend(true, {}, person);
jill.name = "Jill";
 
console.log(person);
console.log(jill);

$.extend() method is a little slower than the JSON exploit, but that shouldn’t really be a problem when you’re only doing a few clones.

Click here to read more

Using anonymous function as an alias to jQuery DOMReady function

Below syntax is a shorthand to jQuery.ready() function. The anonymous function passed to jQuery is only a callback function, it won't considered as a "JavaScript Module".

$(function(){
  
});

I.e. it does exactly the same thing that the below code block does, specify a function to execute when the DOM is fully loaded.

$(document).ready(function(){
  
});

But even though below code looks similar to the first syntax its is treated differently. This is called as module pattern or immediately invoking function in JavaScript

(function($) {
  
})(jQuery);

  • A module pattern or immediately invoking function executes immediately after it’s defined. It does not wait for the DOM to be ready.
  • Passing jQuery in to the parenthesis is to provide local scoping to the global variable.
  • All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.
  • To allow external code to access to a variable or function we can expose it to the global ‘window’ object.
    (function(){
      var foo = 'Hello';
      var bar = 'World!'
      
      function baz(){
          return foo + ' ' + bar;
      }
    
      window.baz = baz; //Assign 'baz' to the global variable 'baz'...
    })();
    
    console.log(baz()); 
    
Modules are a pattern of implementation that use an immediately invoking function to provide scope and privacy around a “module” of related functionality.

Click here to read more about JavaScript Module Pattern.

If the anonymous function passed to the DOM ready() method has lot of code in it then you can use an object literal to organize the handles and callbacks as shown in below example.

var dom = {
 
    onReady: function() {
        $( "#btn1" ).click( dom.animate);
    },
 
    animate: function( event ) {
        $( "#yayeffects" ).toggle();
    } 
};
 
$( document ).ready( dom.onReady );

Wednesday, 4 February 2015

jQuery - How to get Html including the selector?

As you know jQuery .html() method can be used to get the HTML contents of the first element in the set of matched elements. But sometimes you might want to get the HTML including the container as well.

For example if you have below html

<div id="container">
 <div id="content">jQuery is awesome</div>
</div>

and if you use $('#container').html() it will give you

<div id="content">jQuery is awesome</div>
i.e. it returns the "innerHTML" of the "container" DIV.

There are many workarounds to it i.e. to get html including the "container".

Using wrap()

If you wrap the container in a dummy P tag you will get the container HTML as well.

var outerHtml  = $('#container').wrap('<p/>').parent().html();
Using clone()
var outerHtml = $("<div />").append($('#container').clone()).html();

Using wrap actually affects the DOM tree displayed to the user. This doesn't.

Tuesday, 27 January 2015

jQuery Ajax Cheat Sheet

jQuery.ajax( url [, settings ] ) performs an Asynchronous HTTP (Ajax) requests using jQuery.

Basic settings

Url

$.ajax({url: '/Products/Details/1234' })

Querystring

$.ajax({url: '/Products/Details?id=1234&showorders=false' })

type: HTTP Method

$.ajax({url: '/Products/Details/1234', type: 'POST' })

data: Data to be sent to the server.It is converted to a query string, if not already a string. It's appended to the url for GET-requests.

$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234} })

$.ajax({url: '/Products/Details', type: 'POST', data: $('form1').serialize() })

var contact = {firstName:"Bob", lastName:"Bob", mobile:"9907833", email: "bob@example.com"};
$.ajax({url: '/Contact/Create', type: 'POST', data: JSON.stringify(contact) })

contentType: Type of data send to the server

default value is 'application/x-www-form-urlencoded; charset=UTF-8'
$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234}, contentType: 'application/json; charset=UTF-8' })

dataType: type of data expecting from server. If none is specified, jQuery will try to infer it based on the MIME type of the response - xml, json, script, or html

$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234}, dataType: 'html' })

headers: Helps to set http header(s)

$.ajax({url: '/Products/Details', headers: { Accept: "application/json; charset=utf-8", "Content-Type": "application/x-www-form-urlencoded" }, data: $('form1').serialize() })

Handling succeeded request/response

$.ajax({url: '/Products/Details?id=1234',  
               success: function (result, textStatus, jqXHR) {
                    alert("success");
                }
})

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second complete" );
});

Handling failed request/response.

$.ajax({url: '/Products/Details?id=1234',  
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus);alert(jqXHR.status);alert(errorThrown);
                }  })

Handling response based of HTTP status code

$.ajax({url: '/Products/Details?id=1234',  
               
statusCode: {
                    201: function (s) {
                        $('#result').html(s);
                    },
                    404: function () {
                        alert("Not Found!");
                    }
                }
})

Ajax Shorthand Methods

jQuery.get() Load data from the server using a HTTP GET request.

$.get( "test.php", function( data ) { $( "body" ).append(data) });

jQuery.getJSON() Load JSON-encoded data from the server using a GET HTTP request.

(function() {
$.getJSON( "example.json", function() {
  console.log( "success" );
})
.done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "" ).attr( "src", item.media.m ).appendTo( "#images" );
      });
    });
})();

jQuery.getScript() Load a JavaScript file from the server using a GET HTTP request, then execute it. jQuery.getScript() sets cache to false by default.

$.getScript("/jscript/test.js")

jQuery.post() Load data from the server using a HTTP POST request. Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

$.post( "/product/list", function( data ) {
  $( ".result" ).html( data );
});

jQuery.load() Load data from the server and place the returned HTML into the matched element.

$( "#result" ).load( "/product/list" );

Thursday, 22 January 2015

Html helper extension method for creating pagination links in ASP.NET MVC

Add below Extension method to your project
using System;
using System.Web.Mvc;
using System.Text;

namespace YourWebUI.HtmlHelpers
{
    public static class PagingHelpers
    {
        public static MvcHtmlString PageLinks(this HtmlHelper html, int totalPages, Func pageUrl)
        {
            StringBuilder pageLinks = new StringBuilder();
            for (int i = 1; i <= totalPages; i++)
            {
                TagBuilder pageLink = new TagBuilder("a");
                pageLink.MergeAttribute("href", pageUrl(i));
                pageLink.InnerHtml = i.ToString();
                pageLinks.Append(pageLink.ToString());
                pageLinks.Append(i == totalPages? "" : " | ");
            }
            return MvcHtmlString.Create(pageLinks.ToString());
        }
    }
}
Add the namespace YourWebUI.HtmlHelpers to web.config
  <system.web.webPages.razor>
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        ...
        <add namespace="YourWebUI.HtmlHelpers"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>
Razor syntax for calling the method
 @Html.PageLinks(5, x => Url.Action("Index", new { page = x }))
Sample output
<a href="/?page=1">1</a> | <a href="/?page=2">2</a> | <a href="/?page=3">3</a> | <a href="/?page=4">4</a> | <a href="/?page=5">5</a>
Click Here to see a different way of doing this.