Dynamic Pages with ASP.NET
Download complete code from here.
Introduction
If you are familiar with the SharePoint technologies you might have known that you can edit the appearance of certain portion of the page. Moreover in publishing page you can add and delete as many parts in the page as you like.
Fig: Showing Edit enabled Page
Now a day web page is not just a static page which just shows the static information to the user. It would be more flexible to give the user to customize the view they want so that they can move the parts around the page, hide the parts and modify the property of parts. Adding such functionality is expensive and requires lot of works of developer and of course more error prone.
In this article I will give you the general overview of using web part manager and web part zone.
Introducing WebPartManager
WebPartManager control is an ASP.NET server control introduced from .NET 2.0. There is not any visual effect of this control in the page. But wait. This control can add items to and delete items from each zone of the page. This means there is no meaning for a page to contain only WebPartManager. There should be at least one WebPartZone. WebPartManager is page dependent control and it manages on that particular page. However you can add it in you master page if you require.
After adding the WebPartManager control into the webpage, now it is a time to create a Zone in that page. You can any techniques to create several zones in your page. This is directly dependent on your business logic. For this article I am using Table to create zone. I am creating four zones.
Note that you can drag and drop the control from toolbox into your page or you can write a code.
<asp:WebPartManager ID="WebPartManagerDefault" runat="server"> </asp:WebPartManager> <table style="width: 100%;"> <tr> <td colspan="4"> <asp:WebPartZone ID="WebPartZoneTop" runat="server"> <ZoneTemplate> </ZoneTemplate> </asp:WebPartZone> </td> </tr> <tr> <td> <asp:WebPartZone ID="WebPartZoneLeft" runat="server"> <ZoneTemplate> </ZoneTemplate> </asp:WebPartZone> </td> <td style="width: 50%;"> <asp:WebPartZone ID="WebPartZoneCenter" runat="server"> <ZoneTemplate> </ZoneTemplate> </asp:WebPartZone> </td> <td> <asp:WebPartZone ID="WebPartZoneRight" runat="server"> </asp:WebPartZone> </td> <td> </td> </tr> </table>
Now you have added the WebPartZone in your page. Inside WebPartZone you can add almost anything that can be added in your web form. You can add HTML elements, User controls, and Web parts and so on.
Let’s add two asp controls; image control and calendar control in the page. Now, your code looks like this
<asp:WebPartManager ID="WebPartManagerDefault" runat="server"> </asp:WebPartManager> <table style="width: 100%;"> <tr> <td colspan="4"> <asp:WebPartZone ID="WebPartZoneTop" runat="server"> <ZoneTemplate> <asp:Image ID="ImageBanner" runat="server" ImageUrl="~/Images/Banner.png" Title="Image Control" /> </ZoneTemplate> </asp:WebPartZone> </td> </tr> <tr> <td> <asp:WebPartZone ID="WebPartZoneLeft" runat="server"> <ZoneTemplate> <asp:Calendar ID="CalendarDefault" runat="server" Title="Calendar Control"></asp:Calendar> </ZoneTemplate> </asp:WebPartZone> </td> <td style="width: 50%;"> <asp:WebPartZone ID="WebPartZoneCenter" runat="server"> <ZoneTemplate> </ZoneTemplate> </asp:WebPartZone> </td> <td> <asp:WebPartZone ID="WebPartZoneRight" runat="server"> </asp:WebPartZone> </td> <td> </td> </tr> </table>
If you run the project now you will get the output like this
Fig: output 1
You can see the title of each control. They are taking title from the ‘Title’ attribute of control. Even the control doesn’t contain this property by default you can add it so that you can have meaningful title displayed rather than default ‘untitled’. Note that you can customize the control. You can minimize it, restore it or you can close it. If you make some changes for example minimize the asp image control and reopen the page you can see your image control in minimize state. GREAT!!!
Now let try one more thing, let’s close the image control. Now, you can see it is nowhere in the page. Even if you reopen your page there will not be any image control.
Note that the customization information is saved in App_Data folder in ASPNETDB database.
Introducing different mode of the page
Now I will give you the description of different mode of the page. User can add, move or change the page they are in by changing the page mode. For now let’s add the DropDownList in the page and make certain change in the code behind.
<tr> <td colspan="4" align="right"> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList> </td> </tr>
Changes in code-behind.
protected void Page_Init(object sender, EventArgs e)
{
foreach (WebPartDisplayMode wpMode in WebPartManagerDefault.SupportedDisplayModes)
{
string modeName = wpMode.Name;
ListItem listItem = new ListItem(modeName, modeName);
DropDownList1.Items.Add(listItem);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
WebPartDisplayMode displayMode = WebPartManagerDefault.SupportedDisplayModes[DropDownList1.SelectedValue];
WebPartManagerDefault.DisplayMode = displayMode;
}
Open the page. You will see two drop down items. One is browse and one is design. If you change the mode to design mode you can move your web part from one web part zone to another.
But still where is my closed web part?
In this section I will show you to add two additional modes of page. One is catalog mode in which you can see your closed web part and you can add web part to any zone. Another is edit mode in which you can edit the property of your web part including display. If you have created your custom web part you can make the property editable when you are in edit mode. (I will show you how to do this on another article.)
For now let’s add the following piece of design code in your working page.
<asp:CatalogZone ID="CatalogZoneMain" runat="server"> <ZoneTemplate> <asp:PageCatalogPart ID="PageCatalogPartMain" runat="server" /> <asp:DeclarativeCatalogPart ID="DeclarativeCatalogPartMain" runat="server"> <WebPartsTemplate> <asp:TextBox ID="TextBox" runat="server" Title="Text Box"></asp:TextBox> </WebPartsTemplate> </asp:DeclarativeCatalogPart> </ZoneTemplate> </asp:CatalogZone> <asp:EditorZone ID="EditorZoneMain" runat="server"> <ZoneTemplate> <asp:AppearanceEditorPart ID="AppearanceEditorPartMain" runat="server" /> <asp:BehaviorEditorPart ID="BehaviorEditorPartMain" runat="server" /> <asp:LayoutEditorPart ID="LayouteEditorPartMain" runat="server" /> <asp:PropertyGridEditorPart ID="PropertyGridEditorPartMain" runat="server" /> </ZoneTemplate> </asp:EditorZone>
Now you can see two additional page modes in your drop down menu. If you select catalog mode you can see your closed web part. You can add this web part in your page. Moreover, if you click on Declarative Catalog link you will get another the list of web part (in this case only one, textbox control). You can add this web part to any web part zone.
If you select edit mode you can now edit the property of web part like Appearance and Behavior. Generally, normal user shouldn’t see this option. There are more than those properties for editing which is still invisible. To view those properties you need to change your web.config file. Add following configuration in System.web.
<webParts> <personalization> <authorization> <allow users="*" verbs="enterSharedScope" /> </authorization> </personalization> </webParts>
And add following piece of code in Page_Load
if (WebPartManagerDefault.Personalization.Scope == PersonalizationScope.User
&& WebPartManagerDefault.Personalization.CanEnterSharedScope)
{
WebPartManagerDefault.Personalization.ToggleScope();
}
When you change the mode to edit and chose edit for any web part or control, you should be able to see something like this.
Fig: Web part in edit mode.
Modifying Zone property and Verbs in Web Part
There are many properties those are used to assure certain behavior of web part zone. For example if you don’t want to change the web part of certain zone, then you can use the AllowLayoutChange property. You can use LayoutOrientation property to make sure you add web part in either horizontal or vertical orientation.
Verbs are property of web part which enable/disable the corresponding feature in the web part. The available verbs are CloseVerb, ConnectVerb, DeleteVerb, EditVerb, ExportVerb, HelpVerb, MinimizeVerb and RestoreVerb. They all have their own meaning. For example if you use following code in your page then you will not able to edit your web part. The corresponding menu will be disabled.
</pre> <asp:WebPartZone ID="WebPartZoneTop" runat="server"> <EditVerb Enabled="false" /> <ZoneTemplate> <asp:Image ID="ImageBanner" runat="server" ImageUrl="~/Images/Banner.png" Title="Image Control" /> </ZoneTemplate> </asp:WebPartZone> <pre>
Fig: Disabled edit option
Conclusion
There are plenty of other stuffs that are part of web part. I will show you them on another articles step by step. Web part is very vast and powerful section in ASP.NET. Web part helps developers to make dynamic and modular pages. I will show you to create your own custom web part in another article.
Dining Philosopher Problem and AutoResetEvent.
Introduction
Full code can be downloaded from here.
I think we all know the famous classic problem of dining philosopher. In this problem, we consider n philosophers sitting in round table and n forks and all of them want to eat the spaghetti in front of each one. To eat spaghetti, philosopher must have two forks. The problem is philosopher 1 is taking one fork and waiting philosopher2 for second fork. Similarly, philosopher 2 is taking a fork and waiting philosopher3 for a fork. And philosopher n is taking a fork and waiting philosoper1 for a fork. So, what is actually happening is each philosopher cannot get the two forks at a time because each philosopher is taking a fork and waiting. So, here is the DEADLOCK.
For 5 philosophers we can assume the figure

Fig: Dining Philosopher Problem
Similar incident can be happens in our program and operating system where many processes are struggling to get the resources. There are certain criteria which must meet to cause the deadlock. They are:
1. Each resource can be used by only one thread or process.
2. Thread/Process is holding a resource and waiting for other resource to continue.
3. Resources those are granted previously cannot be forcibly taken away.
4. There must be chain of threads/processes (more than two); each is waiting for the resource held by next
thread/process.
To avoid deadlock, we can negate any of the above conditions. For dining philosopher problem, we will negate the second condition to avoid deadlock.
Code
Full code can be downloaded from here.
I have used AutoResetEvent to implement the dining philosopher problem. I have used one AutoResetEvent as mutex and n others as philosopher events.
There are three states of philosopher.
enum State
{
Thinking,
Eating,
Hungry
}
Let’s look at the code:
private void TakeForks(int i)
{
_mutex.WaitOne();
_philosophersState[i] = State.Hungry;
TryGetForks(i);
_mutex.Set();
_philosopherEvents[i].WaitOne();
}
private void TryGetForks(int i)
{
if (_philosophersState[i] == State.Hungry &&
_philosophersState[right(i)] != State.Eating &&
_philosophersState[left(i)] != State.Eating)
{
_philosophersState[i] = State.Eating;
_philosopherEvents[i].Set();
}
}
private void PutForks(int i)
{
_mutex.WaitOne();
_philosophersState[i] = State.Thinking;
TryGetForks(right(i));
TryGetForks(left(i));
_mutex.Set();
}
First of all philosopher tries to take both fork. If it is not possible, it waits for the signal from its left and right. Whenever it gets the signal, philosopher again tries to acquire both forks and same process repeats.
void checkForConflict(int i)
{
if (_philosophersState[left(i)] == State.Eating)
Console.WriteLine("Conflict between " + left(i) + " and " + i);
if (_philosophersState[right(i)] == State.Eating)
Console.WriteLine("Conflict between " + i + " and " + right(i));
}
Above code checks for the conflict and displays conflict message whenever two philosophers try to eat using same resource. Our program mustn’t print the conflict messages.
Conclusion
Dining philosopher is a classic deadlock problem of operating system. Every deadlock can be avoided by negating any of the four essential conditions of deadlock.
I have used AutoResetEvent as mutex and for signalling purpose. However, we can use others also.
C# 4.0 dynamic Keyword
Introduction
dynamic dynamicString = "Test"; Console.WriteLine(dynamicString.GetType()); dynamic dynamicInteger = 9; Console.WriteLine(dynamicInteger.GetType());
dynamic dynamicString = "Test"; dynamicString.Display(); dynamicString.Name = "Pradip";
var Vs dynamic?
var varString = "Test"; varString.Display();
dynamic dynamicString = "Test"; var varString = dynamicString; varString.Display();
Reflection and dynamic
String str = "Pradip";
Type type = str.GetType();
String subStr = (String)type.InvokeMember("Substring", System.Reflection.BindingFlags.InvokeMethod, null, str, new Object[] { 3 });
dynamic dynamicString = "Pradip"; String subString = dynamicString.Substring(3);
Adding/Removing method and property at runtime
dynamic myObject = new ExpandoObject(); myObject.Name = "Pradip"; myObject.Display = new Action<String>(o => Console.WriteLine(myObject.Name)); myObject.Display(null);
COM Interop and dynamic
((Excel.Range)excelApp.Cells[1, 2]).Value2 = "Pradip"; Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 2];
excelApp.Cells[1, 2].Value = "Pradip"; Excel.Range range2010 = excelApp.Cells[1, 2];
Finally



