In order to make the application more loosely coupled we should use interfaces. In Dependency injection pattern there exist a class called as assembler or container that takes care of instantiation of classes taking care of dependencies among the classes using interfaces, constructor arguments or any input property. Why would we need another assembler or container to instantiate the objects in our project? That we can do by our own self in our UI layer and work without failure …right!! Well this is good question and I would try to answer it as per my understanding.

Suppose we have 10 different classes in our Business Object (BO) layer and in our web application if we are going to instantiate all those classes as per the requirement in our page (I know it’s very foolish example but yes now it is coming in my mind… L sorry). So here the page has to know that which class I have to instantiate and if some class do need some input parameter in there constructor then we have to pass the appropriate constructor argument while instantiating the object of the class. So if eventually we need to modify the BO layer then the web application project would also have to be change accordingly and compiled that is against the Law of Loosely Coupled Architecture. In order to adhere to the principle of loose coupling, we have to keep our web application layer or UI layer or client layer separate than our concrete business objects or BO layer. So that when we update our business objects it should not accounts for web application changes or compilations.

For creating loosely coupled architecture there are various patterns available according to the requirement one can use those patterns. Some of them are like Factory Pattern, Abstract Factory Pattern, MVP pattern etc.  In our above requirement that we just discussed lets apply Factory pattern to make the application more loosely coupled. So we will use Factory class to create our 10 instances of 10 classes present in BO layer. By this we are abstracting the object creation part out of the page or UI layer. However, yet we have not achieved 100% loose coupling you can ask why? The answer to your why is suppose if we want to send some arguments to the constructor of the class then again it should be passed from the UI layer to the Factory class in order to create the object of classes with the supplied arguments. Here again the UI layer has to know that which class needs which argument before creating the instance. Therefore, indirectly it is coupled with the concrete BO classes and prone change when those concrete classes’ changed. Here our UI layer is doing something extra which it was not supposed to do. According to the Principle of Separation of Concerns the UI layer should only display the data and raise the event that’s it so here the Separation of concern principle is also defeated.

Now here comes Container / Dependency Injection Principle that says we should have some central location there we can put our mappings for our required classes, interfaces and constructor arguments. And we should have someone who will each time look to these settings and give the appropriate object after instantiating it properly with appropriate data. So that the UI layer has to not worry about the instantiating of classes UI guy has to not even remember which class name and which argument I would need to call during instantiating. This gives us the complete Separation of Concern principle and also makes our project more Loosely Coupled.  This mechanism is also called as Dependency Injection that is using the Containers we can now inject the dependencies while instantiating the object of the class without allowing the UI layer to aware with this. Eventually we can change our UI layer to Windows UI or Silverlight it does not matter our project will work 100% loosely coupled with and properly. One more benefit that we will get is Unit test would become much simpler as we have used Interfaces and Containers we can easily mock our data and can do Unit Testing. So it’s more of Test Driven Architecture that is in high demand in today’s Agile era of SDLC. After applying IOC (Inversion of Control) to do Dependency Injection we could achieve Agile methodology as well.

I have used Microsoft Unity Application block for Dependency Injection. Sometime I will surely post the code how to use the Unity. In Unity we use web.config file for container we generally put our mappings inside the web.config file.

There are three main styles of dependency injection. The names I’m using for them are Constructor Injection, Setter Injection, and Interface Injection.

Constructor Injection: It is something where the assembler would create the instance of the class using the interface it also populates the required properties via the constructor. While instantiating the object it finds the appropriate object or variable to be passed to the constructor and creates the instance. It can go to any level, i mean there may be the chances that a class can have internally another class and it can also get some data at its constructor level. That also can be taken care by assembler class. This assembler is also called as Inversion of Control. We can use Picco or Unity to work with constructor injection.

Setter Injection: In setter injection we have setter methods for setting the property while instantiating the classes. And we put the property name and the value name value may be a class or interface or some text file name etc. That mapping we put in our web.config file it we use Unity. So here our assembler will look at the config file and will get us the object of the class after populating the property of the class. That’s cool na… 🙂

 Interface Injection: The container uses the declared injection interfaces to figure out the dependencies and the injectors to inject the correct dependents. Suppose we have the requirement to use the some methods of an interface A so if you inherit that interface in order to implement few methods then you can’t because if you inherit it then you have to implement its all methods because it’s a contract.  In this scenario you can inherit with another new Interface B that would inject the and in your class you would have the interface A as the property. Interface B would have one setter method which will accept the interface A. So if you inherit with B then it would set your property interface A and now you can use the as many methods of A as you want because, now it is more of an object A which you have in your class not the whole interface.

 Let’s suppose you if you took the cable connection at your home then you have to watch all the channels those they would broadcast whether you want them or not. However, suppose if you want to watch only selected channels and you may want change your selected channels eventually. Then better to have one Set up box installed at your home that would cater you exactly what you want only and you have to pay only for those channels which you entertain or enjoy or watch… cool na… 🙂

So here in my above basic lay man example the Setup Box is the Interface Injector. So using Interface injector you can enjoy your favorite channels (Methods). Instead of taking the entire cable connection and watch all channels (or inherit the interface to implement all unwanted methods) So in future if you want to use another class or 3rd party tool (that is other different channels) also to use instead of the current class (current channels) then you just need to change in the settings of the web.config (setup box settings) and you are all set to go… no need to change your entire code (entire Setup box)

I hope I was able to put my thoughts on Inversion of control and dependency injection. If you have your comments to help me understand more better then please do the favors, you are most welcome. Good Luck… Happy IOC…  🙂

Almost 3 years ago Scottgu announced that Microsoft would begin offering product support for jQuery. Now Microsoft is playing a great role on contributing to jQuery plugin. From past 8 to 9 months they were striving on 3 major jQuery plugins.

They were:

          1. Templating

          2. Data-Linking

          3. Globalization
The good news is Templating plugin created by Microsoft is going to be added officially as a new feature in jQuery 1.5 version 

 
1) Client side templating (jquery.tmpl.js)
 

Say suppose you want to get a set of data and display stuffs in structured manner then use template. Initially we used to concatenate the strings and display the data that was very slow process.
Below is one example how to use the template plugin. In below code we are displaying the product object data in UI. The data inside the product can be fetched from server by calling $.ajax
 
Above script is html its type sets to text / html that says the browser not to interpreted
Content within. It injects the HTML. Braces indicating the placeholder for knowing more about the template plugin please read.


<form runat="server" id="form1">
<h1>Product</h1>
<div id="productContainer"></div>
</div>
</form>
<script id="productTemplate" type="text/html"><div>
<h3>${name} = $(formatCurrency(price)})</h3>
<img&nbsp;src ="Products/${picture}"/>
<p>
{{html description}}
</p>
</div>
</script>

Above script is html its type sets to text / html that says the browser not to interpreted
Content within. It injects the HTML. Braces indicating the placeholder for knowing more about the template plugin please read.

 

<Script type="text/javascript">
//Array of products
var products = [
{name : "Apple",price : 3.44, picture : "Apple.png", description: "<i><b>Super</b></i> delicious"}
,{name : "Bacon",price : 4.55, picture : "Bacon.png", description: "Quality bacon"}
,{name : "Ice Cream",price : 12.00, picture : "IceCream.png", description: "Low fat ice cream."}
];

//render the array of products
$("#productTemplate")
.tmpl(products)
.appendTo("#productContainer");
tmpl method returns the fragment of html and append to productcontainer.
function formatCurrency(num) {
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
return "$" + parsefloat(num).tofixed(2);
}
</script>

2) Data Linking (jquery.datalink.js)

Data linking plugin gives the easy way to synchronized to UI field and data object. Its easy way to track the changes in happened in the UI elements and vice versa. Initially we used to check the each form input element which changed and then update the javascript object and then send it to server for update. Now we don’t need to bother about the changes happened in the UI element. The moment any UI element is changed the javascript object will get automatically updated and vice versa. By default linkdata plugin does two-way data binding.

Jquery.datalink.js uses jQuery 1.4.3 version therefore please makes sure that you are including this version of jquery while using datalink plugin.

Let’s look at the below example. Here we have 2 input fields which are linked with a javascript object say product. Now any changes made in product object will reflect in UI automatically and vice versa is true.

product Name : <input name="name" id="name" type="text"/>
product price : <input name="price" id="price" type="text"/>
<script class="hiddenSpellError"><!--mce:1--></script>
<script class="hiddenSpellError"><!--mce:2--></script>
//link product form to product object
var product = {}
$("form").link(product);

//changes to product object will be sync'ed&nbsp;with product form
$(product).data("name","Ice Cream");

//changes to product form will be synced with product object
$("#btnSave").click(function ( ) {
e.preventDefault();
//show product object
alert([product.name, product.price]);
});

3) Jquery glob (jquery.glob.js)

Globalization plugin can be used to localize the website to any region.
You want to globalize or localize your own plugin then use this plugin.
Features:
1.Supports over 350 different cultures, including country-specific cultures and language, country-neutral cultures.

2.Culture information for each culture is available through a simple data structure, accessible to plugins for their own purposes.

3.Supports formatting dates to any of these cultures, including those that have non-Gregorian calendars, Gregorian calendars with a year offset, and calendars with multiple Eras.

4.Supports formatting numbers to strings as numbers, currency, or percentages, to any of these cultures, including those with very special formatting rules, such as number group sizes that differ between currency and percentages, or have a different number of digits.

5.Supports parsing dates and numbers from the culture specific string representation of them back into JavaScript dates and numbers.

6.Supports localization through a localize() API that handles selecting the best known match automatically.

7.Supports the Accept-Language header value as-is, to select the culture best suited to the user per their browser settings.

8.Extensibility allows for plugins to access and add to the culture information, including cultures it does not already support.

9.Retrofitted the jQueryUI DatePicker plugin to use this plugin, rather than its existing globalization support. This was fairly simple to do and immediately opens up the range of cultures supported by the plugin to the full set of cultures supported by jQuery.glob.js.

Let’s see below example we want to use the date picker and make it globalize so that in any country if we use this then it will show the calendar on their language.

</span>
<select id="<span class=">selectCulture"></select>
<option> Loading...</option>
</select>
<div id="picker">
</div>
//populate select list
var select = $("#selectCulture").get(0);
select.options.length = 0;
$.each($.cultures, function ( ) {
select.options[select.options.length] = new Option (this.englishName, this.name);
});

$("#selectCulture").change(function () {
//set culture form select list
$.preferCulture(this.value);

//Destroy and create datepicker
$("#picker").datepicker("destroy").datepicker({
changeMonth:true,
changeYear : true
});
});
</script>
<span style="font-family: <span class=;">Calibri</span>; font-size: large;"> 

Menu Widget

Posted: February 6, 2011 in jQuery
Tags: ,

I was trying to make my own menu widget using jQuery and  I came with this below Widget.


//Menu Widget created by Rupesh
(function ($) {

    JDQMenu = {

        options: {

          items: { "Reports":[{

                      "File" : { "Report1":"#","Report2":"#","Report3":"#" }

                      ,"Edit" : { "Report4":"#",  "Report5":"#" }

                      ,"Report" : { "Report6":"#",  "Report7":"#" }

                      ,"Help" : {"How to see Reports":"#"}

                  }]

                  ,"Clients" : [{

                      "Search" : { "Client1":"#","Client2":"#","v3":"#" }

                      ,"Edit" : { "Client4":"#",  "Client5":"#" }

                      ,"Help" : {"How to see Clients":"#"}

                  }]

                  ,"Tools" : [{

                      "View": { "Tool1":"#","Tool2":"#","Tool3":"#"}

                       ,"Help" : {"How to find Tools":"#"}

                  }]

            }

            ,selected_menu : "Reports"

        }

        ,_init : function ( ) {

           this._create_menu( );

        }

        ,_create_menu : function ( ) {

           var that= this,el = that.element,itms=that.options.items,sel=$.trim(that.options.selected_menu);

           if( sel !="default") {

           //save element in widget cache

            var data = $(this).data(sel);

                //refresh the menu

                el.empty();

                //take element from inner widget cache data

                if(data) {

                    el.append(data);

                } else {

                    if( itms[sel] ) {

                        var menu_itms = itms[sel][0];

                        $.each(menu_itms , function ( i,v ) {

                            el.append( $("
	<li>").append( $("<a>",{"class":"menu_trigger", "href":"#","text":i}) ).append("") );</a></li>
                            $.each(v,function(n,k){

                                el.find("ul#"+i+"").append($("<a>",{"href":k,"text":n}));</a>

                            })

                        })

                       $(this).data(sel,el.find("li"));

                   }

                }

                //Show the menu by triggering it

                $("a.menu_trigger").first().trigger("mousedown");

           }

        }

        ,show_menu : function (el) {

            el  = el.replace("#",'');

            this.options.selected_menu = el;

            this._create_menu( );

        }

    };

    $.widget("ui.JDQMenu", JDQMenu);    

})( jQuery );

Now for using this widget you just have to add one ul element and call our JDQMenu widget’s.

 
<ul id="menu">
</ul>
<script type="text/javascript?
$("#menu").JDQMenu();
</script>

In any jQuery Plugin there JavaScript local alias pattern is being used as a best practice. They have localized the global jQuery object as an alias $. It is a handy and popular pattern for JavaScript developer however, that is not very well know from C# developers or fledging JavaScript people.
Local alias pattern has 3 benefits:
1)      It allows using short-cut custom name for a global namespace, thus shortening the code writings, page size decreases.
2)      It does not populates the global scope variables
3)      It allows us to make global variable to make it localize and thus faster to refer the variable.
As we know to refer the global variable is slower than to referring the local scoped variable.


See the below example:
(function ($) {
        $.fn.myPlugin : function(){
        …//new plugin code.
}
}
)(jQuery)

In the above code jQuery object is being passed as an argument to the self executing function which is being aliased by $. Therefore, inside the function we can use the alias $ without any hesitation as it is referring to the jQuery object.

If we had just used $ as an alias to jQuery without passing it as an argument and bringing it inside out local scope then there would have lot of chances that in some other JavaScript library $ may be overridden by some other object or value and it might have broke our code.
In below code if you see window object is being passed as an argument.


(function( window, undefined ) {
//jquery code..
// Expose jQuery to the global objectwindow.jQuery = window.$ = jQuery;
}) (window);

By passing one argument “window” while calling it, we are able to localize the window object. The second argument is not being passed therefore; the 2nd parameter would be assigned as undefined.
There is a chance that in somewhere else the undefined is assigned with some other value that may be overridden by the jQuery code therefore, in jQuery function they have made undefined as a local parameter so that they can use the undefined without worrying about the external world.
By making our object locale we are not populating the global scope with other variables.


namespace Rupesh.AliasDemo {
    using System;
    using System.Collections;
    using CountriesCode = Utility.Constant.Countries;

In above code you can see that one alias has been created for Utility.Constants.Countries as CountriesCode.
So now under the Rupesh.AliasDemo namespace in each class, CountriesCode can be used as shortcut alias instead of writing the whole name (Utility.Constant.Countries).
This will make more easiness while writing the code, will save time and number of lines of code.
After knowing this I am vastly using this pattern in my C# as well as JavaScript code.

At the outset, I used to write programs that just work because, I had to complete and deliver the project on time.

I remember, when was assigned a task to create web application that will create New Enrollment request on a given account number. After slogging the whole day, writing code and proper testing, I created one small application that was allowing user to upload an Excel Sheet consisting of list of Account Number. This application iterates through each account number validates and creates one New Enrollment Request on each account. If it fails then moves to create request on next account number without breaking the execution. Application worked splendidly and my manager became happy that I did the job on time and application was working fine… J

As software programmer, you might know that software project never becomes perfect and client requirement never ends. Same thing happened to me and on the next day, my Manager again came and asked to update the application so that it will also create Account Maintenance Request. I worked for that, done changes throughout the application, put everywhere if else condition needed to check the new account maintenance request type, and finally gave him the application. It worked good… But my manager’s expectations never stopped…

In my project work story the pain part was…, for every new requirement in project, I had to change each and every page, class and doing that repetitively made my code much confusing and disordering.

Then I read about the Open/Closed Principle (OCP) of Object oriented programming. This principle states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. What I understood from this principle that software application should be designed such that, if eventually new requirements comes up then project should not allow any changes and it can only be extended.

I planned to re-create my application in such a way that it fits with the idea of Open/Closed Principle. Therefore, implemented Factory Pattern to make project more object-oriented. Converted each request as an object, created one base abstract class (BaseRequest)having one abstract method like CreateRequest inherited by an Interface (IRequest) hence followed Template pattern as well. Created New Enrollment and Account Maintenance classes inherited form the BaseRequest class and implemented the CreateRequest method in each request class. Created one Factory class that returns the required request Object based on the request type and made its return type the interface IRequest that was pointing to the real request concrete object hence maintained the loose coupling architecture.

After doing all above mentioned stuffs, project became more object-oriented and loosely coupled architecture by adhering to the precepts of OCP and factory design pattern. Now, life became little easy, say if some new requirement comes up in future for adding one new request type say “withdrawal request” in project then I just have to introduce one new “withdrawal” request class inheriting with the BaseRequest class, implanting the create request method. Changed the Factory class to return withdrawal request object based on some logical condition. That’s it, my work is done and project is ready. Project became more extendable and less changeable, that is very close to the precepts of Open/Close principle.

After redesigning project, comparatively it required fewer changes and efforts to implement new requirements. However, you can see although after implementing the open closed principle and factory design pattern, I had to change the code in Factory class to handle the new Request added in application. That code modification in factory class was compulsory and it could not be avoided.

I read all design patterns, analyzed my project requirement and made best attempts to make an architecture that will never allow any changes in project under any circumstances for implementing new requirement but, failed.

In order to implement new requirements in existing software project, changes have to be done. However, software architecture should be such that it should allow fewer changes and more flexible to extend.

The moral of the story is obvious that there exist no software program that is 100 % closed for changes and 100% adheres to the Open/Closed Principle.


Recently, I received one question how to send the xml data from one page to another page without using any state management or caching technique of Asp.Net.

Say, there are two pages page1.aspx and page2.aspx. In page1.aspx, we have one button named OpenPage2 after clicking on this button, page2 will be opened up. On page2, we want the xml data sent from page1.

I suggested the below way:

We can post the xml data from one page to another page by using XmlHttpRequest.

In page1, we can have two divs, first with id div1 for page1 and another div with id div2. On the div2, we can load page2 using jQuery’s load utility method, on click of button. Simultaneously show and hide the required div’s. When page2 has to be shown then show div2, hide div1 and vice versa. Pass xml string data to page2 using JSON object. Before sending the xml string data encode it, using JavaScript escape method.


var xmlData = escape("<Name>Rupesh</Name><Age>28</Age>");

$.load( “page2.aspx”, {“xmlkey”: xmlData } );

Hence, in the page load event of page2.aspx, the same xml string data can be extracted from the request parameters. Since, xmlData would be in encoded format in order to decode it HttpUtility.UrlDecode can be used like below.


string xmlData =  Request.Params[“xmlkey”];

xmlData = HttpUtility.UrlDecode(xmlData);

Below is the complete code.
In page1.aspx put one hidden field and on page load event of the page1.aspx store your xml data inside the hidden field so that from the client side you can get the xml data from the same hidden field and post it to page2.


//-----put below code in Page1.aspx----//

<script type="text/javascript">

var xmlData; //JavaScript object where xml string should be stored.

function openPage2 ( )  {

//Hide the div1 before opening the page2

$("#div1").hide();

//Before opening the page2 you can store the xml string in javascript object.

//The XML string can be taken from the hidden field. Use escape method to encode the data

xmlData = escape( $("#hdnXml").val() );

//Show div2 and load page2 on div2

$("#div2")

.load( "page2.aspx" , { "xmlkey" : xmlData} )

.show()

}

</script>

<div id="div1">

<input type="hidden" id="hdnXml" name="hdnXml" />

<button click="openPage2();">Open Second Page</button>

</div>

<div id =div2"></div>

//------Page1.aspx End ----

//Put below code in Page2.aspx
<script runat="server">

protected void Page_Load(object sender, EventArgs e)

{

if(!IsPostBack) {

//Use urlDecode to decode the xml data

string xml = HttpUtility.UrlDecode(Request.Params["xml"]);

}

}

</script>

we could have used query string and send the data using query string also but as we know for query string there is size limit up to 256 chars. If we store the data in cookies variable then cookies also have size limit of up to 4096 Bytes and there may be the chances that cookies are not enabled in client machine.
Therefore, I suggested to use POST method in order to sending the data to the other page. The size limit for POST method depends on type of browser and IIS. I think in IIS 6 and 7 the size limit is 200KB.


Hi all,

I recently installed Internet Explorer 8 in my laptop and wondering many new features about the IE8. I was enjoying the good and new features of IE8. However, I was not aware what these features are called, from where they came and can I install my own new features in to my IE 8 browser etc.?

One feature which I firstly observed in IE8 was, when I select some text on browser then I see one icon comes up. On click of that icon one menu box opened up and it suggests me many actions to do like, search it with Bing,  Blog with Window Live, Mail with Window Live, etc.  I was not aware that this feature is called Accelerator and we can install our own custom accelerators as well !

Then I learned more about the IE8 and found that There are such 8 new features in IE8 as below.

  1. Defining Page Regions with Web Slices

Web Slice is one of the cool features of IE8. It allows you to divide the page in various parts, see and update the only part in which you are interested.

For example suppose, you visited amazon.com and saw the price of camera which you wish to buy. If you want to track the price of your selected camera so that the moment it’s price will decrease you will buy that camera. For doing this you have to daily visit the same site and search for your camera and look its price.

But, if you are browsing in IE8 then on hover at the part of the camera on the browser, you may see there will one icon will come up. On Click of that icon, pop-up window will crop up with massage subscribe to this web slice. By subscribing to that webslice, you will see that one new tab will come at the menu bar of the browser. That tab will show you the title of the camera and on click of the tab it will show the small pop-up that will display the current updated price of your selected camera. It keeps update automatically without refreshing your browser.

Now you need not go to the whole amazon site, search for your camera and see the current update price daily daily.

The other features are as below.

2. Expiration and Update Frequency

3. Accelerators

4. Search Suggestions

On typing the search content IE8 will show you suggested texts. You can give your own suggested texts by installing various search suggestion providers.

5. AJAX Navigation

6. DOM Storage

DOM storage allows to store and retrieve data at client side using unique key. Data size can be up to 10 MB.

7. Offline and Online Working Modes

8. XMLHttpRequest Time Outs

Internet Explorer 8 provides a new client-side object called XDomainRequest, which allows developers to access remote domains without requiring implementation of a server-side proxy. If the remote server provides an Http Header called Access-Control-Allow-Origin:* all other remote sites will be able to request data from the current Web page. The client-side use of XDomainRequest object is the same as the ordinary XmlHttpRequest.

Please read article New Features in IE8 written by Daron Yöndem. He has explained entire above mentioned 8 points aptly.