Archive for March, 2011


From last 4 days, I have been struggling on how I should load the UserControldynamically in my default page. I know in today’s world where .Net 4.0 came up, MVCis there and in future C# 5.0 is also coming and I am talking of same old UserControlsthat we used to talk in .Net 1.1 -2.0 era. Well I can’t do anything because in my project we have a lots of UserControls and they are not migrating the application from old legacy style to what we have dynamic rendering html using jQuery ajax and other stuffs.

Anyway coming back to my problem how to load user control in a page dynamically? It has simple one line answer that we can put one placeholder and load our usercontrolinside the placeholder at runtime by this way we would be able to render the usercontrol in page dynamically.

protected void Page_Load(object sender, EventArgs e)
{
UserControlusercontrol= this.LoadControl("ucmycontrol.ascx") as UserControl;
placeholder.Controls.Add(usercontrol);
}


However, this is not as easy as I said now. Let’s go deeper and think on what are the problems that would arise by loading usercontrol by above fashion. There may be various issues however let me talk on 2 major issues listed below:
1) ViewState would not be saved and retrieved.
2) Any Custom Events or dynamically added control events would not fire

Now take one by one let’s take number one problem

viewstate would not maintain
What this mean exactly? Let’s understand it with a simple silly example. Say you have any label in your usercontrol and in page load if you have put your name on the label’s text property. Now, you do button click or by any way if you posted back your page then the label would no more be displaying your name after rendering the page. Think why? Isn’t it weird? 😦

Normally, what happens is when you put some value inside the text property of the label. And if postbackhappens then the page viewstateused to save the unique ID and value of the label and before rendering the usercontrolit loads the viewstatedata by identifying the same label unique id. Therefore, you normally see your value again after postback as well.

As we know the HTTP protocol is stateless. Therefore, whatever is loaded in first time pageload, when the postbackoccurs then server would not aware of the previous status of the page controls and its value. Hence .Net framework has introduced viewstatein order to store the previous state of the page controls. So that it persists after postbackas well. Thanks to ViewState. Don’t take me wrongly if I would say thanks to viewstate. As I am not supporter of the viewstateas I know it causes many problems those are separate concern and separate topic of discussion. You might be heard about the concept of Leaky Abstraction. Sometimes I feel .net ViewState is also one of the example of Leaky Abstraction. Any ways lots of digression happened lets concentrate on our basic problem.

Then why in our dynamically loaded user control viewstate stuff is not loading? Well, In order to understand this first we need to understand the page life cycle events. Are you ready to discuss them …? I am sure you might be saying ok … go ahead … am I not hearing you? 🙂

Anyway jokes apart. There are basically many events those gets fired automatically by the .net framework while loading the page however we are more concern about 12 major events.

Those are:
PreInit, Init, InitComplete, PreLoad, Load, Control events, LoadComplete, PreRender, PreRenderComplete, SaveStateComplete, Render, and Unload.

In the page life cycle events the tracking of viewstatechanges is turned on in between Init and InitCompleteevents. So in the initcompleteevent frameworks adds all the controls property id and value in the viewstatecollection so as to persist after postback. So in our case when we click on the button then the viewstatewould not find the usercontrolin init event because we are adding it in pageloadevent and that’s why it would fail to load the value of the label. So if we want to save our view state stuffs inside the usercontrolthen we have to add the usercontrolat oninitevent. So that we would make sure that viewstatebag is taking care of all the control properties inside the usercontrol.

So we have to make our code like below in order to make sure viewstate would work properly:

protected override void OnInit(EventArgs e)
{
UserControlusercontrol= this.LoadControl("ucmycontrol.ascx") as UserControl;
placeholder.Controls.Add(usercontrol);
base.OnInit(e);
}


So above code would solve our first problem.

Let’s go to our second problem
Any Custom Events or dynamically added control events would not fire:
Let’s first understand what the problem is all about. Suppose you have one custom delegate say alertDelegateand events alertEventon your usercontroland you want to handle the alertEventin your default page the container page where you are going to load your usercontrol. I mean, when you click a button inside the usercontroland raise the alertEventthen in your content page you would be able to handle the alertEvent as you are binding this event with the alertDelegate and some eventHandler present inside the default page. I know its bit clumsy to understand my example lets write it down in c# code in order to understand it clearly.
Let,s you have WebUserControl1 and below code inside its code behind.

namespace DynamicUserControlLoading
{
public delegate string alertDelegate(string msg);
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public event alertDelegatemyalertEvent;
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
if (myalertEvent != null) {
myalertEvent("He catch this event and show this message in content page");
}
}
}
}


And in your default page lets you have below code

protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1usercontrol= this.LoadControl("ucmycontrol.ascx") as WebUserControl1;
obj.myalertEvent += new alertDelegate(returnalert);
placeholder.Controls.Add(usercontrol);

}
private string returnalert(string msg)
{
return msg;
}


Then on click of the button present in the usercontrolit won’t be delegated to the default page in order to handle it by your returnalert method present in content or default page.

This problem is again related to the viewstatestuffs only as we know the Control Events get fired after the pageloadevent occurs as we were adding our placeholder in pageloadevent. However we are not persisting with the old controls after each postbackswe are adding a new instance of the usercontrol in each trip. Therefore, framework’s viewstate is not able to bind the events on the control events.

The solution to above problem is we have to add the events each time we created the usercontrolsnew instance in the placeholder however it should be in the oninit event only.

Therefore the code should be like below:

protected override void OnInit(EventArgs e)
{
WebUserControl1usercontrol= this.LoadControl("ucmycontrol.ascx") as WebUserControl1;
obj.myalertEvent += new alertDelegate(returnalert);
placeholder.Controls.Add(usercontrol);
base.OnInit(e);
}


Now we could to solve both of the above 2 problems and we could dynamically add the usercontrol in default page successfully.

Above solution would work properly however it would have below restrictions:
1) In each trip ( page load and post back ) you have to add the usercontrols new instance in place holder
2) In each trip you have to bind the custom events and if you have dynamic buttons then rebind the events in each trip to those dynamic buttons.
3) Once you loaded the usercontroland if you happened to inject some extra html through JavaScript or jQuery and if you do postback then it would throw exception that the control tree was changed. Therefore don’t change the places of control before posting the page back to the server.

Let me know if you have any suggestions or any correction on my understanding thanks for being with me… 🙂

Advertisements


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…  🙂