Friday, 20 July 2012

How to find event target using jQuery?

This can be done using event.target property. It returns a reference to the DOM element that initiated the event. t is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

Example: Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.


<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<ul>
  <li>item 1
    <ul>
      <li>sub item 1-a</li>
      <li>sub item 1-b</li>
    </ul>
  </li>
  <li>item 2
    <ul>
      <li>sub item 2-a</li>
      <li>sub item 2-b</li>
    </ul>
  </li>  
</ul>

<script>

function handler(event) {

var $target = $(event.target);

  if( $target.is("li") ) {
    $target.children().toggle();
  }
}

$("ul").click(handler).find("ul").hide();

</script>

</body>
</html>


Friday, 13 July 2012

Deserializing ASP.NET AJAX JSON date using JavaScript

Modern websites are using AJAX a lot to improve customer experience by redudcing/avoiding full page reload in response to a user interaction. When AJAX is used with ASP.NET DateTime values are deserialized into below format.

"\/Date(1342137600000)\/"

Following JavaScript function can be used to deserialize it into a JavaScript Date object.

function GetDateFromJSONString(s) {
                    var d = s.replace(/\/Date\(/gi, '');
                    d = d.replace(/\)\//gi, '');
                    return  new Date(Number(d));
}

var s = "\/Date(1342137600000)\/";

alert(GetDateFromJSONString(s));

The issue with this is that JavaScript will apply the locale timezone of the client's machine while doing the deserialization which may result in a different Date value. This can be avoided by doing the deserialization bit differrently using JavaScript's toUTCString() method. This function will deserialize it into UTC Date.

var monthNames = { JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, 
JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11 }

function GetUTCDateFromJSONString(s) {
         var d = s.replace(/\/Date\(/gi, '');
         d = d.replace(/\)\//gi, '');
         var utc = new Date(Number(d)).toUTCString(); 
         //Sample value: Mon, 1 Feb 1982 00:00:00 UTC
         utc = utc.split(',')[1].substring(1).split(' ');
         utc[0] = utc[3] != '00:00:00' ? Number(utc[0]) + 1 : utc[0]; 
         return new Date(utc[2], monthNames[utc[1].toUpperCase()], utc[0]);  
}

var s = "\/Date(1342137600000)\/";

alert(GetUTCDateFromJSONString(s));



You can read more about toUTCString() method on w3schools.com. Click Here

Thursday, 12 July 2012

How to center DIV in a DIV?

This can be achieved by applying below CSS to the inner div:
#outer {
  width: 100%;
}

#inner {
    width: 50%;
    margin: 0px auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing div will work. The margin: 0px auto is what does the actual centering. It can be done in a different way as well.
#outer {
  width: 100%;
  text-align: center;
}

#inner {
  display: inline-block;
}
That makes the inner div into an inline element that can be centered with text-align.

Tuesday, 10 July 2012

ASP.NET MVC 3 and the @helper syntax within Razor

The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates. They enable better code reuse, and can also facilitate more readable code.

Key points:

  • Just like a standard C#/VB method, it can contain any number of arguments (you can also define the arguments to be either nullable or optional). Unlike standard C#/VB methods @helper methods can contain both content and code, and support the full Razor syntax within them – which makes it really easy to define and encapsulate rendering/formatting helper methods.

  • You can invoke @helper methods just like you would a standard C# or VB method.

  • @helper method can be defined within the same view template as the code that called it. Alternatively, we can define the @helper method outside of our view template, and enable it to be re-used across all of the view templates in our project. We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a \App_Code directory that you create at the root of a project.

@helper DisplayPrice(Decimal price)
{
      if(price == 0)
      {
         <span>FREE</span>
      }
      else
      {
         <text> <b>Price:<b> &pound;@(price) </text>
      }
}
Click here for more information about the @helper syntax

Import a namespace in Razor View Page?

If you want to import a namespace in your CSHTML file it can be done using @using (C#) or @imports (VB.NET) statement.

C# Example

@using System.Configuration;

Tuesday, 19 June 2012

Classic vs. Integrated mode in IIS 7

IIS 6.0 and previous versions allowed the development of .NET application components via the ASP.NET platform. ASP.NET integrated with IIS via an ISAPI extension, and exposed its own application and request processing model. This effectively exposed two separate server pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble and only for requests mapped to ASP.NET in the IIS script map configuration.

IIS 7.0 integrates the ASP.NET runtime with the core web server, providing a unified request processing pipeline that is exposed to both native and managed components known as modules.

The many benefits of integration include:
  • Allowing services provided by both native and managed modules to apply to all requests, regardless of handler. For example, managed Forms Authentication can be used for all content, including ASP pages, CGIs, and static files.
  • Empowering ASP.NET components to provide functionality that was previously unavailable to them due to their placement in the server pipeline. For example, a managed module providing request rewriting functionality can rewrite the request prior to any server processing, including authentication.
  • A single place to implement, configure, monitor and support server features such as single module and handler mapping configuration, single custom errors configuration, single url authorization configuration.
Follow this link to read more on this

Classic mode is where IIS only works with ISAPI extensions and ISAPI filters directly. This is how IIS 6 and below behaved. Using classic mode, ASP.NET is simply an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). When using classic mode the server uses two piplines to handle requests, one for native code and the other for managed code. In this mode the application doesn't take full advantage of everything IIS 7.X has to offer.

Integrated mode handles all requests through a unified pipeline for IIS and is tightly integrated with ASP.NET through that same pipeline. ASP.NET sees every relevant request and manipulates things along the way rather than acting as an external plugin. With integrated mode ASP.NET runs much more efficiently in IIS and will yield greater performance for your site.

Thursday, 14 June 2012

ASP.NET MVC - Domain specific routes using RouteConstraint

I’ve come across using different routes depending upon the domain that the end user is browsing. That might be different based on language (browsing your “.co.uk” site gets English URLs, browsing “.fr” gets French), or perhaps based on brand. Maybe some functionality on your web site is only available to certain sub-brands. Or perhaps you want to direct users that visit uat.mydomain.com to new functionality so they can test it. All of this becomes possible with a Route Constraint. These are simply used to validate whether a route should match a particular incoming URL.

HostConstraint

To apply this kind of filtering based on the host in the URL (i.e. the domain the user is browsing) is such a simple piece of code;
public class HostConstraint : IRouteConstraint
{
    private readonly Regex _host;
 
    public HostConstraint(string pattern)
    {
        _host = new Regex(pattern, 
                RegexOptions.Compiled | RegexOptions.IgnoreCase);
    }
 
    public bool Match(
        HttpContextBase httpContext, 
        Route route, 
        string parameterName, 
        RouteValueDictionary values, 
        RouteDirection routeDirection)
    {
        return _host.IsMatch(httpContext.Request.Url.Host);
    }
}
You can see this constraint takes a Regular Expression pattern to describe host names that it should match, and simply checks the Url.Host on the current HttpContext for success.

Using HostConstraint

Using our new class is really simple - we add it to an anonymous type in the MapRoute call;
routes.MapRoute(
    "Default_us",
    "ussitemap",
    new { controller = "Home", action = "SiteMap" },
    new { host = new HostConstraint("\\.com$") }
);
 
routes.MapRoute(
    "Default_fr",
    "frenchsitemap",
    new { controller = "Home", action = "SiteMap" },
    new { host = new HostConstraint("\\.fr$") }
);