Dynamic Pages with ASP.NET

May 29, 2011 1 comment

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">

&nbsp;

<asp:WebPartZone ID="WebPartZoneTop" runat="server">

<ZoneTemplate>

</ZoneTemplate>

</asp:WebPartZone>

</td>

</tr>

<tr>

<td>

&nbsp;

<asp:WebPartZone ID="WebPartZoneLeft" runat="server">

<ZoneTemplate>

</ZoneTemplate>

</asp:WebPartZone>

</td>

<td style="width: 50%;">

&nbsp;

<asp:WebPartZone ID="WebPartZoneCenter" runat="server">

<ZoneTemplate>

</ZoneTemplate>

</asp:WebPartZone>

</td>

<td>

&nbsp;

<asp:WebPartZone ID="WebPartZoneRight" runat="server">

</asp:WebPartZone>

</td>

<td>

&nbsp;

</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">

&nbsp;

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

&nbsp;

<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%;">

&nbsp;

<asp:WebPartZone ID="WebPartZoneCenter" runat="server">

<ZoneTemplate>

</ZoneTemplate>

</asp:WebPartZone>

</td>

<td>

&nbsp;

<asp:WebPartZone ID="WebPartZoneRight" runat="server">

</asp:WebPartZone>

</td>

<td>

&nbsp;

</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>

&nbsp;&nbsp;&nbsp;

</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.

Categories: .net, ASP.NET

Dining Philosopher Problem and AutoResetEvent.

April 13, 2011 1 comment

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.

Categories: .net, Programming C#, Threading

C# 4.0 dynamic Keyword

February 7, 2011 Leave a comment

Introduction

Generally, C# is statically typed languages and checked type at the compile time. Languages like Ruby, Python are dynamic and determined the objects at the run time. Visual C# 2010 introduces a new keyword, dynamic which is a static type, but an object of type dynamic bypasses static type checking. So C# can use the features of dynamic language. It was introduced for C# 4.0 only and not for .net 4.0.

Whenever you use the dynamic keyword you tell the compiler to turn off the compile time checking. For example

intellisense

You can notice intellisense is saying it is dynamic expression and operation will be resolved at runtime.  Consider above example:

dynamic dynamicString = "Test";
Console.WriteLine(dynamicString.GetType());
dynamic dynamicInteger = 9;
Console.WriteLine(dynamicInteger.GetType());

Above line of code will give an output. System.String and System.Int32.

Another thing is you can call any function and any property. If it is not declared yet, your code will still compile but you will get runtime exception.

dynamic dynamicString = "Test";
dynamicString.Display();
dynamicString.Name = "Pradip";

Note in above code actually dynamicString is String type but you can call method like Display() and property like Name which are not in String. Your code compile well but you will get run time exception.

var Vs dynamic?

You might be familier with the powerful var keyword from .net which is used for implicitly typed variables and for anonymous types. It is static and occurs at compile time. You can’t change the type of the variable at run time.

var varString = "Test";
varString.Display();

In above code, second line will result the compile time error.

Now lets look this piece of code.

dynamic dynamicString = "Test";
var varString = dynamicString;
varString.Display();

Now, varString is dynamic type and above code will compile. var is not a type, var keyword just instruct the compiler to infer the type from the variable’s initialization expression. So, we can use dynamic and var keyword together and they are mutually exclusive in nature.

Reflection and dynamic

Reflection is one way from which you can call invoke method (property and other also) dynamically. Compiler won’t throw any exception about even if there is no exception. But there will be complex long code in your program. For example to use String.Substring you need to write following code.

String str = "Pradip";
Type type = str.GetType();
 String subStr = (String)type.InvokeMember("Substring", System.Reflection.BindingFlags.InvokeMethod, null, str, new Object[] { 3 });

Now, using dynamic you can get same result with clean and neat code.

dynamic dynamicString = "Pradip";
String subString = dynamicString.Substring(3);

Of course, above example is not good enough to give explanation of using dynamic over reflection but you will find it better to use dynamic keyword in you application which uses reflection very much.

Adding/Removing method and property at runtime

Using dynamic keyword you can add/remove method or property from the object at the runtime. For this .net 4.0 provides ExpandoObject and DynamicObject classes defined in System.Dynamic namespace. Here is an example of adding property and method.

dynamic myObject = new ExpandoObject();
myObject.Name = "Pradip";
myObject.Display = new Action<String>(o => Console.WriteLine(myObject.Name));
myObject.Display(null);

COM Interop and dynamic

Many COM interop allow the variation in arguments type and has the return type as Object. So, there needs the casting to appropriate one to use it as the strongly typed variable. The magical dynamic keyword allows us to treat the object in COM signature as dynamic and hence prevents casting. As a result, our code will become more readable and clean.

Without dynamic we would write like this.

((Excel.Range)excelApp.Cells[1, 2]).Value2 = "Pradip";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 2];

And using dynamic we can write.

excelApp.Cells[1, 2].Value = "Pradip";
Excel.Range range2010 = excelApp.Cells[1, 2];

Finally

I hope, you got some knowledge about the NEW dynamic keyword in C# 4.0. The more you use it, the more you will be familier. For now we can say that dyanamic keyword has added the dynamic programming feature in statically typed language C#.

 

Categories: .net, Programming C#
Follow

Get every new post delivered to your Inbox.