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