Calling .NET functions from JavaScript
Download full code from here.
Introduction
Javascript/Jquery is the client side language and it runs on the browser. It is fast because it doesn’t depend on the server for the response. Nowadays, jQuery is being used in the web development very much. It is fast and can really creates a cool and attractive web site. Jquery has a functionality to call the web service ($.ajax()). In this method we call the web service which is running on some server and this method gets the response which can be used as the developer wants to do. One important thing in ASP.NET is if you need to call the .NET function and you are not using that function in other pages, then it is not justifiable to create a web service and call the function. ASP.NET provides you a cool mechanism to utilize your server side function from your client side without officially creating the web service.
PageMethods and WebMethod attribute
Every method that you want to call from the client side code must be public and static .NET function and as web service method it must have System.Web.Services.WebMethod attribute. Then in your aspx page you can call your .NET function using PageMethods.MethodName. And you need to have ScriptManager control in your page with EnablePageMethods true.
WebMethodCall.aspx.cs
[System.Web.Services.WebMethod]
public static string GetName(string name)
{
return "Hello <strong>" + name + "</strong>";
}
For example we have a GetName method in our code behind. So for this method to enable to call from client code, we need to add WebMethod attribute on it.
And its corresponding aspx page will have following javascript code to call the .NET function and display it in a div.
WebMethodCall.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
<script language="javascript" type="text/javascript">
function Clicked() {
//PageMethods.set_path('WebMethodCall.aspx');
PageMethods.GetName('Pradip', Success, Failure);
}
function Success(result, userContext, methodName) {
$('#content').html(result);
}
function Failure(error, userContext, methodName) {
$('#content').text(error.get_message());
}
</script>
</div>
<a onclick="Clicked()" href="#">GetName call</a>
<br/>
<br/>
<div id="content" style="background-color: #B0B0B0; width: 500px; height: 500px;">
</div>
The code above is straightforward. In above code we called the .NET function ‘GetName’ using PageMethods.GetName which has three parameters: name parameter, success callback function and failure callback function. On Success we get the result object (in our case string) which is displayed as html in content div.
Even though the code above is very simple, you can call a complex database call and calculation from your client code. You just need to extend your server side function.
Download full code from here.
Issue when using with URL Routing
When you use the URL routing, the method of calling .NET function from javascript that I described above will not work as expected because if you look into the page source you can see the form action to ‘HomePage’ and when you debug javascript you can see service path as ‘HomePage’. So, for this we need to do some correction on this path. We need to call PageMethods.set_path(url) method to set the service path. You can just uncomment the code inside the Clicked() function. Now, you can see our code works for both ASPX page and page using URL routing.
Conclusion
Even web service is used very much while it is required to call .NET functions from client side code (Javascript/JQuery), when the function is used just in one page and it is not justifiable to build web service as it costs performance and separate service, it is good to use this method when you need to call .NET functions from client code.
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
Installing SharePoint 2010 in Windows 7 (64 bit)
Installing SharePoint 2010 in Windows 7 (64 bit)
Many people faces problem in installing SharePoint 2010 Server in windows 7 because it doesn’t directly support it and you will get error about operation system while attempting to install. But there are certain steps which can guide you to install SharePoint 2010 in your machine. I hope you know how to install SharePoint 2007 in windows 7. Don’t afraid, it is not the prerequisites for the installation of SharePoint 2010. However, if you need it you can see it here. But that tweaks doesn’t work for 2010. So you must follow some steps to run SharePoint 2010 in your Windows 7 (64 bit) machine.
1) Install the following update.
2) Extract the installation files from the setup using command d:\Software\SharePoint10\SharePointServer /extract:d\SharePointServerFiles. In my case source directory is d:\Software\SharePoint10 and target directory is d:\ SharePointServerFiles.
3) In the target directory find the config.xml a following d:\ SharePointServerFiles \files\Setup\ and add the following line of text in configuration node <Setting Id=”AllowWindowsClientInstall” Value=”True”/>. Now your configuration file would be something like below:
<Configuration> <Package Id="sts"> <Setting Id="LAUNCHEDFROMSETUPSTS" Value="Yes"/> </Package> <DATADIR Value="%CommonProgramFiles%\Microsoft Shared\Web ServerExtensions\14\Data" /> <Package Id="spswfe"> <Setting Id="SETUPCALLED" Value="1"/> </Package> <Logging Type="verbose" Path="%temp%" Template="SharePoint Server Setup(*).log"/> <!--<PIDKEY Value="Enter Product Key Here" />--> <Setting Id="SERVERROLE" Value="SINGLESERVER"/> <Setting Id="USINGUIINSTALLMODE" Value="1"/> <Setting Id="SETUPTYPE" Value="CLEAN_INSTALL"/> <Setting Id="SETUP_REBOOT" Value="Never"/> <Setting Id="AllowWindowsClientInstall" Value="True"/> </Configuration>
4) Now, it is the time to install the prerequisite installer files. First install filter pack in the path d:\ SharePointServerFiles \PrerequisiteInstallerFiles\FilterPack\ FilterPack.msi. Now install following components:
- Microsoft Sync Framework
- SQL Server Native Client
- Windows Identity Foundation (Windows6.1-KB974405-x64.msu)
If you have Visual Studio 2010 installed in your machine then you may not have to install previous two components.
5) Now, turn on the windows features for IIS for the components as shown in figure (AT LEAST, please). Type ‘optionalfeatures’ in run and enter to open windows features.
6) Now run setup.exe from ‘d:\ SharePointServerFiles’ to get installation wizard and choose Standalone installation to install all on one developer workstation.
7) After the end of installation you need to run the configuration wizard. But before that you need to install some hotfix for SQL Server. Install SQL Server 2008 KB 970315 x64. You need to request the hotfix and Microsoft will send you in email the link and password that required for extraction. Note that you must install this hotfix to avoid the exception while configuration wizard is creating configuration database.
8) Now, you can run your configuration wizard to configure SharePoint in your machine. Don’t panic; it takes time. Good luck.
Issues
1. I can open the Central Administrator site but links are not enabled in Central Administration -> Application Management -> Manage Web Applications. You cannot create new web application and extend existing one.
Sol: Make sure you have Windows Identity Foundation installed. Get it from here. Now do not directly open the central admin site but first open Internet Explorer as administrator and open central admin page. Now, if still it is not working, you would like to use 64-bit IE (Same happened in my case). Furthermore, you can disable UAC to enable link but it is not good practice to disable UAC just for SharePoint.
2. Exception in Database Configuration step: An exception oftype Microsoft.SharePoint.Upgrade.SPUpgradeException was thrown. Additional exception information: Failed to call GetTypes on assembly Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c. Could not load file or assembly ‘System.Web.DataVisualition, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.
Sol: The reason of this exception is the configuration doesn’t find the Chart Controls. Download it and install and re-run the configuration.
NOTE: If you have any issue, feel free to post it.
Builder Pattern in C#
Builder Pattern
Full code can be downloaded from here.
Introduction
GOF definition –“Separate the construction of a complex object from its representation so that the same construction process can create different representations.” Builder pattern focuses on constructing a complex object step by step and returns the product as the final step. It creates one of the several targets.
Motivation
The most common motivation for using Builder is to simplify the client code which creates the complex object. The main advantage will be client can still make the object but without knowing what actually is happening inside. Consider an example of creating different vehicles like car, motorcycle and bus. What builder helps us to simplify here is giving the client the complete vehicle with the only information about what is the type. Client does not need to worry how the different vehicles are being created.
Architecture
Builder contains the abstract interface for building the product. And there will be different ConcreteBuilder which has the different implantations of creating product. Director contains the instance of the Builder and constructs the product according to the Builder instance. Product is our final output which we need to create.
Code
I have created the sample program which demonstrates the way to develop the different rules similar to the Microsoft Outlook. Full code can be downloaded from here.
Builder abstract class
Note the RuleBuilder instance in MailManager. We can omit it with parameter in CreateRule method. I did above code so as to follow the class diagram. ——Rule Move Rule—— Description: Move the mail from one folder to another Condition: When new mail arrived with title ‘xyz’ Result: Escape inbox and copy mail to ‘abc’ folder ——Rule Delete Rule—— Description: Delete the mail with specific condition Condition: When new mail arrived with title ‘xxx’ OR mail arrived from address xxx@hotmail.com Result: delete it Builder is a type of Creational pattern like Factory but it gives us more control in each step of construction process. It is not a widely used pattern but it is an important one. Whenever we need to create different objects with some set of operations then we must think about Builder.</span>
abstract class RuleBuilder
{
protected Rule _rule;
public Rule Rule { get { return _rule; } }
public abstract void SetDescription();
public abstract void BuildCondition();
public abstract void BuildAction();
}
Product class
class Rule
{
IDictionary<string, string> _properties;
public Rule(string name)
{
_properties = new Dictionary<string, string>(0);
_properties["name"] = name;
}
public string this[string key]
{
get { return _properties[key]; }
set { _properties[key] = value; }
}
public void Show()
{
Console.WriteLine("------Rule {0}------", _properties["name"]);
Console.WriteLine("Description: {0}", _properties["description"]);
Console.WriteLine("Condition: {0}", _properties["condition"]);
Console.WriteLine("Result: {0}", _properties["action"]);
}
}
Director class
class MailManager
{
public RuleBuilder RuleBuilder { set; private get; }
public void CreateRule()
{
RuleBuilder.SetDescription();
RuleBuilder.BuildAction();
RuleBuilder.BuildCondition();
}
}
Output
Conclusion
Bridge Design Pattern in C#
Bridge
Download full code from here.
Introduction
GOF definition: “Decouple an abstraction from its implementation so that the two can vary independently.” Bridge uses encaptulation, aggregation and use (probably) inheritence to separate responsibilities into different classes. This pattern is useful when both the abstraction as well as what it does often vary.
Motivation
Consider a situation that we have a different type of switch mechanism which has different implementation of ‘On’ and ‘Off’. For instance, Computer has different type of powering on/off mechanism than that of lamp. In this case we can use the implementation in a single class using if…else but what if we need to add those mechanism for water pump, mobile, vehicles. Then our code will be ugly if we continue to do the work using if…else. The Bridge design pattern proposes refactoring these issues by using two orthogonal hierarchies – one for independent abstractions, and the other for dependent implementations.
Architecture

This class structure shows that the Abstraction is completely separated from the implementation which can vary independently. Abstraction contains the instance of the implementor. In fact Abstraction behaves as wrapper of implementor but can have its own set of logic. Here I have shown only one refined abstraction but it can be many also according to the need of the logic.
Code
Complete code can be downloaded from here.
Here, I will give you the very simple example of the Bridge pattern which uses the one RefinedAbstraction and two different concrete implementations which defined the On/Off mechanism for Computer and Electric Lamp.
AbstractSwitch
abstract class AbstractSwitch
{
public AbstractSwitch(bool initialSwitchState)
{
_switchState = initialSwitchState;
}
public virtual bool On()
{
return _switchImplementation.On();
}
public virtual bool Off()
{
return _switchImplementation.Off();
}
public virtual void ShowInformation()
{
_switchImplementation.ShowInformation();
}
public SwitchImplementation SwitchImplementation
{
get { return _switchImplementation; }
set
{
_switchImplementation = value;
if (_switchState)
_switchImplementation.On();
}
}
private bool _switchState;
private SwitchImplementation _switchImplementation;
}
Notice the SwitchImplementation instance and it’s uses in methods in AbstactSwitch class.
Abstract Implementation
abstract class SwitchImplementation
{
public abstract bool On();
public abstract bool Off();
public abstract void ShowInformation();
}
Our every concrete implementation will extend the SwitchImplementation instance.
Conclusion
Unlike Adapter which makes things after designed Bridge makes things work before they are. Note that Bridge is designed up-front to let the abstraction and the implementation vary independently.








