Thursday, March 28, 2013

Factory Method Pattern

Factory method pattern provides a way for extensibility. It is a creational pattern. Factory Method pattern, is a method that can be used to create one of the Implemented contracts (Instance of a Concrete class) among choices. Usually creational patterns hides the instantiation from the user.

 

Scenario:

You want to provide choice to your class users in a specific situation. Those choices fulfils the contract in different ways.

 

Basic Solution For this Scenario:

For example you have a part of code that has to add or multiply two values based on a configuration. You will implement this like

  • You will write two methods for Add and Multiply.
  • You will ask you user to call you methods based on the configuration.

 

void Calc(int n1, int n2)

{

    char op= GetOpConfig();

    int r;

    switch(op)

    {

    case ‘+’:

        r=Add(n1, n2);

    case ‘*’:

        r=Multiply(n1, n2);

    }

    Display(r);

}

 

Problem:

User has to change the code when you are implementing new methods like Subtract. User has to add another case to implement this.

 

void Calc(int n1, int n2)

{

    char op= GetOpConfig();

    int r;

    switch(op)

    {

    case ‘+’:

        r=Add(n1, n2);

    case ‘*’:

        r=Multiply(n1, n2);

    case ‘-’:

        r=Subtract(n1, n2);

    }

    Display(r);

}

 

So you both has to alter the code when the requirement changes.

 

Solution:

You can use Factory Method pattern to solve this issue.

  • Understand the scenario and bring up a common contract from it (basically with a class, interface or delegate). The common contract should be abstract superset.
  • Here what I mean by superset is, it should cover all the requirements.
  • Consider you are implementing a negation operation that requires only one operand. As you are making it common, you have to use the second operator in the abstract but leave it ignored during negation implementation.
  • Consider you are implementing ternary operation that requires three operators, then the super class should cover all.
  • If you have completed the factory method with two operators and you have a new requirement to support ternary operator that is almost a BREAKING CHANGE.
  • Implement your different implementations of contract with that superset’s abstract.
  • Implement a factory method, that receives a code for a specific instance (which is given to the user in a document) and returns instance of implemented contract based on the received code.
  • Document the usage with following details and give it to the user.
  • Contract Details such as properties and methods defined in the contract

Factory method parameters and possible values Factory method is implemented.

 

Implementation:

Ok. Lets implement a sample for the above requirements.

 

Understanding the scenario

  • We are going to provide the users with a way to calculate.
  • We want to make it extensible so that new operators can be added later.

 

Creating Common Contract

 

  • Calculation basically requires two operands
  • Calculation will return one result.
  • For unary operator, user won’t give second operand. Implemented contract will ignore the second operator.

 

public abstract class Operation {
    public int Num1 { get; set; }
    public int Num2 { get; set; }
    public int Result { get; set; }
    public abstract void Calc();
}

 

Implementing Contract

  • Above contract can be implemented for Add and Multiply as follows

public class Add : Operation {
    public override void Calc() {
        Result= Num1 + Num2;
    }
}

public class Multiply : Operation {
    public override void Calc() {
        Result = Num1 * Num2;
    }
}

 

Implementing Factory Method

 

  • Factory method can be implemented with a single static method as coded below

public class Calculation {
    public static Operation GetOperation(char op) {
        switch (op) {
            case '+': return new Add();
            case '*': return new Multiply();
        }
        return null;
    }
}

 

 

Using Factory Method

 

  • Calling factory method is easy. It is just like calling regular methods.

var cal = Calculation.GetOperation(op);
cal.Num1 = n1;
cal.Num2 = n2;
cal.Calc();
var ret = cal.Result;

 

  • value for op can be hard coded or from a configuration.

 

Extending with Factory Method Pattern

  • New implementation can be added anytime without affecting the users code.
  • Adding a subtract will be easy as mentioned below

public class Subtract : Operation {
    public override void Calc() {
        Result = Num1 - Num2;
    }
}

  • Adding a simple case block will be enough in Factory method.

case '-': return new Subtract();

 

We can implement the same using interfaces or delegates as contracts

Friday, March 22, 2013

Html5- Geolocation API- With Google Maps

Following is a stand alone HTML5 code that shows a simple sample for Html5 Geolocation API

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>     <title>Location Sample</title>     <script src="http://maps.google.com/maps/api/js?sensor=true"></script>     <script>         window.onload = Window_OnLoad;                  function Window_OnLoad() {             var lbl = document.getElementById('lblLocation');             if (navigator.geolocation) {                 lbl.innerHTML = "Geolocation supported";                 navigator.geolocation.getCurrentPosition(                     function (location) {                         lbl.innerHTML = location.coords.latitude + "," + location.coords.longitude;                         ShowGoogleMap(location.coords);                         AddMarker(location.coords);                     }                     );             }             else {                 lbl.innerHTML = "Geolocation not supported";             }         }         var map;                 function ShowGoogleMap(Coords) {             var mapOptions = {                 zoom: 15,                 center: new google.maps.LatLng(Coords.latitude, Coords.longitude),                 mapTypeId: google.maps.MapTypeId.ROADMAP             };             var mapDiv = document.getElementById("divMaps");             map = new google.maps.Map(mapDiv, mapOptions);         }         function AddMarker(Coords, Title) {             var markerOptions = {                 position: new google.maps.LatLng(Coords.latitude, Coords.longitude),                 map: map,                 title: Title,                 clickable: true             };             var myLocationMarker = new google.maps.Marker(markerOptions);         }             </script>
</head>
<body>     <span id="lblLocation"></span>     <div id="divMaps" style="width:400px; height:400px"></div>
</body>

</html>

Monday, March 18, 2013

Singleton Pattern

Singleton is a Creational Design Pattern. Often we may need to group a related members into a single class but only one instance of a class is enough for example Helper classes. We can solve this problem with many methods. A simple method would be using a static class with static methods.

 

// Singleton class
public static class Singleton {

    private static Data data;
    public static void commonMethod1() {
    }
    public static void commonMethod2() {
    }
}

 

As we marked the Singleton class as static, an instance to the Singleton class cannot be created. To access the singleton methods, we can directly invoke them using the class name as the methods are also static.

Singleton.commonMethod1();

 

Disadvantage of this implementation is we don’t have the control over the instantiation and destruction of this class as everything is defined as static.

 

To overcome this, we can implement the singleton pattern as below.

Saturday, March 09, 2013

Extension Methods

Extensions methods allows you to add methods to an existing classes without modifying or inheriting it.

 

Previously we were adding static methods outside the class and calling it by passing the object as a parameter.

 

using System;

class Program {
    static void Main(string[] args) {
        var emp = new Employee() { Id = 1, Name = "John" };
        SampleExtensions.Print(emp);
    }
}

public class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class SampleExtensions {
    public static void Print(Employee emp) {
        Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
    }
}

 

We can upgrade this code using Extension methods. All we need is to

  • Create a static class
  • Add static method
  • Add this prefix before the first parameter declaration

 

Note: Extension methods only works with reference types

 

using System;

class Program {
    static void Main(string[] args) {
        var emp = new Employee() { Id = 1, Name = "John" };
        emp.Print();
    }
}

public class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class SampleExtensions {
    public static void Print(this Employee emp) {
        Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
    }
}

This in fact, improves the readability of the code, so it is easy to understand.

Saturday, March 02, 2013

Including JQuery in ASP.Net Project

JQuery can be included in your asp.net web application or web site using any one of the following methods.

  • Using Nuget Package Manager
    • In Visual Studio, Open Nuget package manager console, (Tools\Libarary Package Manager\Package Manager Console)
    • It will open a tool window
    • In that, type following command to install jquery
      • install-package jquery
  • Downloading from jquery from Official JQuery site
    • Go to official jquery site, (www.jquery.com)
    • Click on the download jquery button to download the latest verion.
    • Page will be directed to download page
    • In the jquery can be downloaded from any one of following mode
      • uncompressed- development
      • compressed- production
    • Include the downloaded file to the application using add existing item in that project.

JQuery

JQuery is a javascript library which basically designed to work on all the browsers.

JQuery contains many modules to simplify our day to day coding work.

 

More information can be found in Official JQuery Site.

 

JQuery can be used in any html based applications. As it is a javascript library, we can use it with .Net, Java, Php etc.. based web applications.

 

Current version of JQuery is 1.9.1

Microsoft Releases Microsoft ASP.NET and Frameworks 2012.2

Microsoft today released Microsoft ASP.NET and Frameworks 2012.2.

 

Link:

 http://www.microsoft.com/en-us/download/details.aspx?id=36829&WT.mc_id=rss_alldownloads_devresources

 

This release updates ASP.NET and includes updates to Visual Studio 2012 or Visual Studio 2012 Web Express.

For more information see instructions in the release notes at http://go.microsoft.com/fwlink/?LinkID=275132.

Features and updates:

ASP.NET Web API

  • ASP.NET Web API now includes support for OData endpoints that support both ATOM and JSON-light formats. With OData you get support for rich query semantics, paging, $metadata, CRUD operations, and custom actions over any data source. Read more about ASP.NET Web API OData support at http://go.microsoft.com/fwlink/?LinkID=271141.
  • New built-in tracing functionality lets you easily diagnose problems with Web API whether you’re running in Visual Studio or on Windows Azure. Tracing output from Web API is automatically written to the Visual Studio output window, IntelliTrace, and any other trace listener that you would like, including Windows Azure Diagnostics.
  • The output shows the full Web API pipeline for all requests, including any exceptions or errors that occur, what controller and action were selected, model binding, the format that was negotiated, and the response.
  • Updated Web API projects now contain a link to an automatically generated help page that shows how to call your web API.
  • The help page shows all of your API endpoints, the HTTP verbs they support, parameters, and sample request and response messages.
  • You can customize the help page as you like. For more information see http://go.microsoft.com/fwlink/?LinkID=285385.

ASP.NET SignalR

  • ASP.NET SignalR is a new library for ASP.NET developers that simplifies the process of adding real-time web functionality to your applications.
  • Real-time web functionality is the ability to have server-side code push content to connected clients instantly as it becomes available.
  • You may have heard of the HTML5 WebSocket API that enables efficient bidirectional communication between the browser and server. SignalR uses Websockets when it is supported by the browser and the server, and gracefully falls back to other techniques and technologies when it is not. Either way, your application code stays the same.
  • SignalR provides a simple API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), grouping connections, and authorization. Read more about SignalR at http://go.microsoft.com/fwlink/?LinkID=285432.

ASP.NET MVC

  • The new Facebook Application template makes writing Facebook Canvas applications easy.
  • In a few simple steps, you can create a Facebook application that gets data from a logged in user and integrates with their friends.
  • The template includes a new library to take care of all the plumbing involved in building a Facebook app, including authentication, permissions, accessing Facebook data and more.
  • This lets you focus on building the business logic in your app.
  • The Facebook apps you can build with this new template are hosted on the web and displayed inside the Facebook chrome via an iframe.
  • A new Single Page Application MVC template allows developers to build interactive client-side web apps using HTML 5, CSS 3, and the popular Knockout and jQuery JavaScript libraries, on top of ASP.NET Web API.
  • The template creates a “todo” list application that demonstrates common practices for building a JavaScript HTML5 application that uses a RESTful server API. You can read more at http://go.microsoft.com/fwlink/?LinkID=285433.