Monday, September 13, 2010

User Control vs. Custom Control in ASP.NET

ASP.NET provides two models of creating web controls  – user controls and custom controls.

In this article, we will discuss about following points.

1. What is User Control?
2. What is Custom Control?
3. What is the difference between User Control and Custom Control?
4. How to select appropriate Web Control out of two?

Go through the following explanation of all points.

1. What is User Control?
 
User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it. These are custom, reusable controls, and they use the same techniques that are employed by HTML and Web server controls. They offer an easy way to partition and reuse common user interfaces across ASP.NET Web applications. They use the same Web Forms programming model on which a Web Forms page works.

How to create a user control

The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only difference is that a user control does not include the <html>, <body>, and <form> elements since a Web Forms page hosts the user control. To create a user control, follow these steps:

• Open a text or HTML editor, and create a server-side code block exposing all the properties, methods, and events.
<script language="C#" runat="server">
public void button1_Click(object sender, EventArgs e)
{
          label1.Text = "Hello World!!!";
}
</script>
• Create a user interface for the user control.
<asp:Label id="label1" runat="server"/>
<br><br>
<asp:button id="button1" text="Hit" OnClick="button1_Click" runat="server" />

How to use a user control in a Web Forms page

• Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio .NET 2003, Microsoft Visual Studio 2005, or any text editor.

• Declare the @ Register directive. For example, use the following code.
<%@ Register TagPrefix="UC" TagName="TestControl" Src="test.ascx" %>
Note Assume that the user control and the Web Forms page are in the same location.

• To use the user control in the Web Forms page, use the following code after the @ Register directive.
<html>
<body>
<form runat="server">
<UC:TestControl id="Test1" runat="server"/>
</form>
</body>
</html>

How to create an instance of a user control programmatically in the code behind file of a Web Forms page

The previous example has instantiated a user control declaratively in a Web Forms page using the @ Register directive. However, you can instantiate a user control dynamically and add it to the page. Here are the steps for doing that:

1. Create a new Web Forms page in Visual Studio.

2. Navigate to the code behind file generated for this Web Forms page.

3. In the Page_Load event of the Page class, write the following code.

// Load the control by calling LoadControl on the page class.
Control c1 = LoadControl("test.ascx");

// add the loaded control in the page controls collection.
Page.Controls.Add(c1);
Note You can add a user control dynamically at certain events of the page life cycle.

How a user control is processed

When a page with a user control is requested, the following occurs:

• The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and generates a class that derives from the System.Web.UI.UserControl class.

• The parser then dynamically compiles the class into an assembly.

• If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for the user control, and the file is precompiled by the designer itself.

• Finally, the class for the user control, which is generated through the process of dynamic code generation and compilation, includes the code for the code behind file (.ascx.cs) as well as the code written inside the .ascx file.

2. What is Custom Control?

Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does.

How to choose the base class for your custom control

To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:

• You should derive from System.Web.UI.Control if you want the control to render nonvisual elements. For example, <meta> and <head> are examples of non-visual rendering.

• You should derive from System.Web.UI.WebControls.WebControl if you want the control to render HTML that generates a visual interface on the client computer.

If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class with these existing classes and can change their default behavior.

In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For example, you can use the WebControl class to control the look and styles through properties like font, color, and height.

How to create Custom Control

• Create Class Library project in Visual Studio.

• Add new class to your project called SimpleLabel, and derive SimpleLabel from the ‘System.Web.UI.Control’ class. It will create ‘SimpleLabel.ascx’ and ‘SimpleLabel.ascx.cs’ files.
public class SimpleLabel : Control {}

• Add some functionality to the class.
protected override void Render(HtmlTextWriter writer)
{
          writer.Write("Hello World from custom control");
}

• Compile the class library project. It will generate the DLL output.

• Open an existing or create a new ASP.NET Web application project.

• Add a Web Forms page where the custom control can be used.

• Add a reference to the class library in the references section of the ASP.NET project.

• Register the custom control on the Web Forms page.
<%@ Register TagPrefix="CC " Namespace=" CustomServerControlsLib " Assembly="CustomServerControlsLib " %>

• To instantiate or use the custom control on the Web Forms page, add the following line of code in the <form> tags.
<form id="Form1" method="post" runat="server">
<CC: SimpleLabel id="ctlSimpleControl" runat="server">
</CC: SimpleLabel >
</form>

• Run the Web Forms page, and you will see the output from the custom control.

3. What is the difference between User Control and Custom Control?
 
FactorsUser ControlCustom Control
CreationCreation is similar to the way Web Forms pages are created; well-suited for rapid application development (RAD)Writing involves lots of code because there is no designer support
ContentA much better choice when you need static content within a fixed layout, for example, when you make headers and footersMore suited for when an application requires dynamic content to be displayed; can be reused across an application, for example, for a data bound table control with dynamic rows
DesignWriting doesn't require much application designing because they are authored at design time and mostly contain static dataWriting from scratch requires a good understanding of the control's life cycle and the order in which events execute, which is normally taken care of in user controls
DeploymentDesigned for single-application scenarios

Deployed in the source form (.ascx) along with the source code of the application

If the same control needs to be used in more than one application, it introduces redundancy and maintenance problems
Designed so that it can be used by more than one application

Deployed either in the application's Bin directory or in the global assembly cache

Distributed easily and without problems associated with redundancy and maintenance
Locationwe have to use it within the application and it rests in the application directorywe can keep it in the Toolbox and use it whenever we want
 
4. How to select appropriate Web Control out of two?

The single most important factor is how the control will be used – will the control be application specific or generic and redistributable? If the control is application specific and contains a lot of static layout, such as a site header and footer, a user control would make sense. If the control is generic, redistributable, and contains dynamic layout, such as the server controls that ship with the .NET SDK, then a custom control would be more suitable.

Read more on my other blogs also:
Web Controls
Infix to Postfix Conversion
SharePoint 2010 Overview

Web Controls in ASP.NET

When we drag a control from the Web Controls section of the toolbox onto a form, VS.NET automatically gives the tag a runat=”server” attribute and an ID. The IDE also automatically adds a protected field to our code behind class for us to interact with the control programmatically. In the following example we have dragged a TextBox control onto the web form, and adjusted the appearance using the Properties window of the web form designer.


<asp:TextBox id="TextBox1" runat="server" Font-Names="Courier New"/>

We can also interact with this control from code behind.

protected System.Web.UI.WebControls.TextBox TextBox1;
private void Page_Load(object sender, System.EventArgs e)
{
          TextBox1.Text = "Foo Berry Tea";
          TextBox1.BackColor = Color.LightGray;
          TextBox1.ForeColor = Color.Red;
}

Notice the web control version of a textbox operates at a slightly higher level of abstraction when compared to the HTML control. For example, the TextBox control has properties to set the colors (BackColor, ForeColor). We don’t need to know how to use inline styles – the code for the control will take care of rendering the correct HTML to achieve the desired appearance in the client’s web browser.

The web controls section of the toolbox also offers some controls you won’t find in pure HTML. These controls, like the RegularExpressionValidator, produce a combination of HTML and JavaScript on the client to offer more functionality than you can get from available HTML controls.

The web control approach is object oriented, easier to use server-side, and more robust than using HTML controls. Since everything in software development has a trade-off, you might be wondering what the downside to using a web control is (some may say the trade-off is performance, but in reality the overhead of using a web control is almost negligible). There really is no downside to using web controls over HTML controls – we should always favor using the web control.

The next question then might be: why did Microsoft give us two sets of controls if web controls are always superior? One answer might be that HTML controls offer a path for porting HTML and ASP applications to .NET. Just give an HTML tag a runat and ID attribute and one can start using the control from code-behind. Another answer is that we can still find scenarios where HTML controls are useful in brand new .NET applications.

Tuesday, September 7, 2010

SharePoint Object Model

SharePoint Object Model is the way of accessing, creating, deleting the SharePoint lists, document libraries, features, meetings, subsites, etc through the visual studio code. It uses SharePoint hierarchy from SPSite to SPField for the same.


There are several namespaces (around 50) that house the SharePoint object model. Out of these 50 namespaces we are using only 16 namespaces, rest of the namespaces are reserved for Microsoft internal use.
SharePoint Object Model is used for operations on following fields:
  • Document Library
  • Lists
  • Features
  • Meetings
  • Sites
  • Solutions
  • User Profiles
  • Business Data Catalog

Refer the following diagram to get an idea about SharePoint Object Model overview.
Above diagram shows how the SharePoint List is accessed using SPSite, SPWeb objects.
Let’s see how the SharePoint Object Model is used for every SharePoint entity.

1) Document Library:

NameSpace: Microsoft.Sharepoint

Classes: SPDocumentLibrary, SPPictureLibrary

Document libraries are a special type of list designed to store documents. To access a document library through object model we need to use Microsoft.Sharepoint namespace. To use this namespace in ASP.net we need to add a reference of Microsoft.Sharepoint.dll. This dll we can find from the below mentioned path:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

Lets take each and every class in this namespace:
          In C# code: SPDocumentLibrary obj = (DocumentLibrary)oList.
         oList is an object for list. The above code will cast the list object into Document Library.
  • SPPictureLibrary Class: This class represents a picture library in Windows SharePoint Services. Both classes are used in the same manner.
         In C# code: SPPictureLibrary oPictureLibrary = (SPPictureLibrary)list;

         The only difference is: As the name indicates SPDocumentLibrary is used for Document Library and   SPPictureLibrary is used for Picture Library.
         Code Example:


2) Lists:

NameSpace: Microsoft.Sharepoint

Classes: SPList, SPListItem, SPLIstItemCollection

SPList object represent a List, SPListItem represent a List Item in the List and SPListItemCollection object represent a full item collection in the SPLIST.
  • SPList: Represents a list on a Microsoft SharePoint Foundation Web site.
  • SPListItem: Represents an item or row in a SharePoint list.
  • SPListItemCollection: Represents a collection of SPListItem objects
Code Example:


3) Features:

NameSpace: Microsoft.Sharepoint

 
Classes: SPFeatureDefinition, SPFeatureScope, SPElementDefinition, SPFeature, SPFeatureProperty

 
For using the features through SharePoint object model we need Microsoft.Sharepoint dll and you can get the dll from the above mentioned path.
  • SPFeatureDefinition Class: Contains the base definition of an SPFeature, including its name, identifier, scope, and version
  • SPFeatureScope Class: Specifies the scope to which the feature applies.
  • SPElementDefinition Class: Serves as the base class for implementing element types within Windows SharePoint Services
  • SPFeature Class: Represents the state of a feature at its corresponding scope
  • SPFeatureProperty Class: Represents a single Feature property.
Code Example:

 

4) Meetings:
NameSpace: Microsoft.Sharepoint.Meetings

Classes: SPMeetings, MtgUtility
For using meetings through object model we need to add Microsoft.Sharepoint dll as mentioned above. The classes under this category are explained as below:
SPMeeting Class: - Provides methods and properties that can be used to work with a Meeting Workspace. Suppose if you want to create a meeting workspace through object model then we need to use this class. There are different kind of meeting template that can be handled like Basic meeting, Decision Meeting, Multiple meeting etc.
MtgUtility: - Initialize a new instance of the MtgUtility class. To access the MtgUtility service and its methods, set a Web reference to http://Server_Name/[sites/][Site_Name/]_vti_bin/xxx.asmx.
Code Example:


5) Sites:


NameSpace: Microsoft.Sharepoint, Microsoft.Sharepoint.Administration (only for SPSiteCollection)

Classes: SPSite, SPSiteCollection, SPWeb

Sites objects are used to access the SharePoint site, the classes under this category of SharePoint Object model are explained as below:

SPSite: Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.

SPWeb: Represents a Windows SharePoint Services Web site

SPSiteCollection: Represents a collection of SPSite objects or site collections that are associated with a particular Web application, including a top-level Web site and all its sub-sites. Each SPSite object, or site collection, is represented within a SPSiteCollection objects that consists of the collection of all site collections in the Web application.

Code Example:

 
6) Solutions:


NameSpace: Microsoft.Sharepoint.Administration

Classes: SPSolution, SPFeatureReceiver, SPSolutionCollector

It provides administrative types and members for managing a Windows SharePoint Services deployment. There are so many classes, delegates, interface under this namespace.

SPSolution: Represents a solution on a farm.

SPFeatureReceiver:
Base abstract class that can be overridden to trap the activation, deactivation, installation, or uninstallation of a Feature.
Use the SPFeatureReceiver class to trap events that are raised after the Feature installation, uninstallation, activation, or deactivation action has been performed.
It is not possible to cancel an installation or uninstallation through Feature events.

SPSolutionCollector: Represents a collection of SPSolution objects.

7) User Profiles:

NameSpace: Microsoft.Office.Server.UserProfiles

Classes: UserProfile, UserProfileManager

UserProfile: Represents a user profile for a person in the user profile database

UserProfileManager: A collection of UserProfile objects used to access user profile data. To access a specific user profile, call the UserProfileManager class to create a UserProfile object and retrieve the corresponding data from the user profile database.

Code Example:


8) Business Data Catalog:


NameSpace: Microsoft.Office.Server.ApplicationRegistry.Administration

Classes: EntityCollection, ApplicationRegistry

EntityCollection: Represents a collection of Entity objects. Provides methods to create and enumerate entities.

ApplicationRegistry: Provides access to all of the line-of-business (LOB) systems and LOB system instances registered in the Business Data Catalog. This is the top-level object in the Business Data Catalog's object model. It is the entry point for you to create, read, update and delete all the metadata objects including LobSystem, Entity and Method. The ApplicationRegistry object has its own ACL and a user should at least have the Edit right on it to create a new LobSystem.


Memory issues with the Object Model:

• Management of these objects should be done with care. They use unmanaged resources, especially SPSite and SPWeb, so Dispose must be called at the finally block or else your application will leak memory.

• Another important memory issue involves the SharePoint indexing. Playing around with the code you probably noticed that everything is grouped into collections, such as the Sites collection and the Lists collection and can be accessed through indexing (i.e. Sites[i]). Well, under the hood SharePoint creates a new instance for each index and each of them needs to be disposed separately. This means that very easily, by a simple if (Sites[i] != null) you're leaking an object.MS came out with a tool called ‘SPDisposeCheck to help manage the SP objects.

You can visit my others blogs also related to SharePoint:
 
Checkpoints for creating Custom Event Handlers
Strong Named Assembly in SharePoint
SharePoint 2010 Overview

Thursday, August 12, 2010

Checkpoints for creating Custom Event Handlers

You must have gone through many articles to create Custom Event Handles by the time. But before actually creating custom event handler,keep the following points in mind:

1. Security:

The assembly you deploy to the Global Assembly Cache(GAC) is running with full trust. Watch out for the following:
Denial of Service attack: If a user uploads 10000 items to a list, what is the effect it will have to the systems your assembly uses.
SQL Injection attack: If a user attempts to insert SQL statements into a column of a list that your assembly uses to update a database, what mechanisms are you using to make sure the input is valid.
Cross Site scripting attack: What is the effect of adding script to a column that your assembly uses to update another area in SharePoint?

2. Performance:

This is a important factor while building custom event handler.
Load: What burden are you placing on your web front end servers to run the assembly each time an event occurs? Use performance counters to determine this.
Long Running Operations: Consider creating a custom SharePoint timer job. Kick off/ Schedule the Timer Job from the event rather than running all the logic inside the event. This will allow you to use the features of SharePoint to view whether the Timer Job ran successfully.
Sync vs Async Events: Synchronous events have to wait until your code completes before returning the page, whereas Asynchronous events show the page immediately.

3. Error Handling:

When using synchronous events and you decide to cancel an event, let the user know why the event was cancelled. For example, update a Task List with a message why it failed.
Log your errors so that you can determine what issue is occurring when your system is in production environment.

4. Connections:

Cater for external systems being down when you are trying to connect to them. Don’t let your code / solution go belly up because you cannot connect to a database.

5. Bulk Operations:

The MSDN documentation mentions that event handlers will not fire when bulk operation is occurring. For example, when a new list is created, the FieldAdding event will not fire.

So now you are ready to create a custom event handler successfully by keeping above points in mind.

You can also visit my other blogs to know about different topics:
Virtualization Concepts
Strong Named Assembly in SharePoint
SharePoint Taxonomy
SharePoint Object Model

SharePoint 2010 Overview

SharePoint 2010 provides the business collaboration platform for developers to rapidly build solutions using familiar tools while leveraging a rich set of out of the box features. Visual Studio 2010 and SharePoint Designer 2010 make developers more productive and Visual Studio Team Foundation Server delivers support for application lifecycle management. Developers can integrate Line of Business data in SharePoint 2010 with read/write capability delivered by Business Connectivity Services. Sandboxed Solutions can be deployed to a shared hosting environment to limit the impact of unpredictable code to the other applications in use.

Sites:
SharePoint:Out of the Box Features- The capability to store and retrieve both list and document content in an easy and flexible way with connectivity to the Microsoft Office client applications.
SharePoint:Extensibility Points-Web Parts, Master Pages, Pages, Delegate Controls, InfoPath Forms, and solutions leveraging the Word File Conversion Service. Access Services for deploying Access solutions to SharePoint.

Communities:
SharePoint:Out of the Box Features-The capability to locate and interact with people through expertise, relationships, tagging, and rating of content.
SharePoint:Extensibility Points-Predefined searches, search web parts, tagging interfaces, rating interfaces, and custom user interfaces.

Content:
SharePoint:Out of the Box Features-The capability to manage content whether that content is a web page, a document, or a set of documents and records management of the content that is created.
SharePoint:Extensibility Points-Custom page types, field controls, content types, document sets, remote blog storage providers, workflows and Word Services. Records management extensibility and Public Web Sites extensibility.

Search:
SharePoint:Out of the Box Features-The capability to search content inside and outside of SharePoint including information in structured database systems.
SharePoint:Extensibility Points-Predefined search result transformations, web parts leveraging search for navigation and location of content, and connections to back end systems. Also IFilters and Protocol Handlers.

Insights:
SharePoint:Out of the Box Feature-The capability to leverage Excel to access and display data on a web page, Dashboards, and Key Performance Indicators to transform raw data into actionable information.
SharePoint:Extensibility Points-Excel Services, Excel User defined functions, key performance indicators, and dashboards

Composite:
SharePoint:Out of the Box Feature-The capability for business users to create their own solutions through connection and arrangement of the features of the platform.
SharePoint:Extensibility Points-Web parts, workflows and InfoPath Forms Services that increase the tools available for the end user.

User Interface

The look and feel of SharePoint has radically changed from earlier versions of the product. In addition to being more accessible to the user it allows for improved extension points and fewer workarounds. The new user interface components that you can extend and build applications with include the fluent UI ribbon and an extensible dialog system. Figure shows the new home page for the default team site template in edit mode.


Building User Interface
SharePoint 2010 leverages wiki concepts for managing content and extends these concepts by allowing for the inclusion of web parts within the wiki pages themselves. In previous versions you were allowed to add web parts to web part zones. In SharePoint 2010 the developer (and the user) has compete control of the user interface including the placement of web parts anywhere on the page. For instance, this means that it is possible to put the results of a survey next to text describing the survey. So the results of code and content can be comingled on the page to create rich live content scenarios.

Multi-Browser Support

Microsoft says they recognize the need to support multiple browsers such as Safari and FireFox.

SharePoint 2010 Ribbon

The context sensitive ribbon interface is now integrated into the SharePoint 2010 user experience. Your applications can extend the ribbon interface to include new menu items and options both on a global level and based on the context of the user. Following figure shows how SharePoint changes the ribbon when a user selects a list web part. The arrow shows the addition of the List Tools section to the ribbon when the list web part is selected.


SharePoint 2010 Dialog Framework

A serious challenge in user interface design for the web is the long page refresh times and the constant switching of context from one page to another. SharePoint 2010 has solved these concerns through the use of AJAX requests for partial updates and by providing a flexible popup dialog framework that allows you to pop up entry boxes on top of the existing page. Instead of having users navigate to a new page and then come back after the data entry is completed the user stays on the same page and a dialog appears above the page.

The dialogs are just pages which are loaded with a special master page and are therefore completely customizable by users and developers to meet their needs. Following figure shows a new announcement being entered in a dialog over a wiki web page.


Live Preview & Themes

The ability to set a theme for your look and feel within SharePoint is improved. Included is the ability to take your PowerPoint theme and upload and apply it to your SharePoint site.
If you are modifying a web page, you now have Live Preview capability, so you can see how the change will look before you actually accept it.

New Silverlight Web Part

There are times when the user interface needs to provide a level of interactivity that is simply not possible with XHTML technologies. That is where Silverlight steps in. Silverlight is the best way to leverage your .NET development skills in creating rich interactive experiences for the web. SharePoint now includes native support for Silverlight files. Simply develop your Silverlight application (.XAP) and deploy it to the server. You can then add the Silverlight application to your web page by adding the Silverlight web part and providing the location of the .XAP file. The Silverlight application is shown as a part of the page as in the example in following figure.


Empowering the Business

There are a couple of different ways to look at SharePoint 2010. Although the developer perspective is important, maybe the most critical is how it makes the lives of business users easier and lets them do more without the need for IT assistance.

Visio Integration

Use Visio 2010 for documenting and describing business processes? Now you can publish those diagrams directly to SharePoint with the back end connection remaining intact. So the view of the diagram is real time. What's nice about this capability is that not everyone needs to have a license for Visio to see the diagram.


SharePoint Designer 2010

SharePoint Designer 2010 is a fully functional participant in the solution creation lifecycle for SharePoint 2010. Applications can be created with the SharePoint web user interface and with SharePoint Designer 2010 as complete applications. Or they can be packaged into a SharePoint Solution (WSP) file that can be imported into and further edited by Visual Studio 2010. For example a declarative re-usable workflow can be prototyped in SharePoint Designer 2010 and moved in to Visual Studio 2010.

A site dashboard in SharePoint Designer 2010 allows you to see at a glance the basic information about the site. The navigation bar allows you to navigate into more details about the specific lists and libraries. Following figure shows the site dashboard for a site including the basic site information, permissions, and sub-sites.


SharePoint Designer 2010 Business Connectivity Services Design

Workflows operate on SharePoint data – or any data that SharePoint can operate on. Business Connectivity Services extends that reach of workflows and other SharePoint features to data outside of SharePoint. SharePoint Designer 2010 makes the process of defining external entities easy. A wizard guides you through making connections to an external system whether it is Windows Communication Foundation (WCF) Service, a Web Service, a .NET class, or a database. Once the connection is made you will see a list of the entities. By right clicking on the entity you can have SharePoint Designer automatically generate the actions needed to support the entity. Within just a few minutes you can create the connections for all of the tables in your database and connect those to external lists in SharePoint. Figure shows the AdventureWorks customer entity that was created by connecting to the Microsoft SQL Server AdventureWorks sample database.




Search

The addition of FAST to SharePoint gives a much improved search experience. Microsoft says their goal is to help you get the "right results on the first page". Those results include not only SharePoint content, but possibly business data and people — the Rich People Search Function from SharePoint 2007 will comes with SharePoint 2010.

Visit my other blogs also:
Checkpoints for creating Custom Event Handlers
Virtualization Concepts
SharePoint Taxonomy

Infix to Postfix Conversion

Infix postfix operations include interconversion of expressions. Let us know about Infix to Postfix Conversion in brief.

Infix Expression:

Any expression in the standard form like "2*3-4/5" is an Infix (Inorder) expression.

Postfix Expression:

The Postfix (Postorder) form of the above expression is "23*45/-".

Infix to Postfix Conversion:

In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the infix to postfix conversion is as follows:

• Scan the Infix string from left to right.

• Initialize an empty stack.

• If the scanned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty Push the character to stack.

• If the scanned character is an Operand and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character. Repeat this step till all the characters are scanned.

• (After all characters are scanned, we have to add any character that the stack may have to the Postfix string.) If stack is not empty,add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty.

• Return the Postfix string.

Example for Infix to Postfix Conversion:

Let us see how the above algorithm will be implemented using an example.

Infix String: a+b*c-d

Initially the Stack is empty and our Postfix string has no characters. Now, the first character scanned is 'a'. 'a' is added to the Postfix string. The next character scanned is '+'. It being an operator, it is pushed to the stack.

Next character scanned is 'b' which will be placed in the Postfix string. Next character is '*' which is an operator. Now, the top element of the stack is '+' which has lower precedence than '*', so '*' will be pushed to the stack.


The next character is 'c' which is placed in the Postfix string. Next character scanned is '-'. The topmost character in the stack is '*' which has a higher precedence than '-'. Thus '*' will be popped out from the stack and added to the Postfix string. Even now the stack is not empty. Now the topmost element of the stack is '+' which has equal priority to '-'. So pop the '+' from the stack and add it to the Postfix string. The '-' will be pushed to the stack.


Next character is ’d’ which is added to Postfix string. Now all characters have been scanned so we must pop the remaining elements from the stack and add it to the Postfix string. At this stage we have only a '-' in the stack. It is popped out and added to the Postfix string. So, after all characters are scanned, this is how the stack and Postfix string will be:


End result:

• Infix String : a+b*c-d

• Postfix String : abc*+d-

This was the simple way for Infix to Postfix conversion

Feel free to read my blogs:
Virtualization Concepts
SharePoint Taxonomy
Checkpoints for creating Custom Event Handlers

Virtualization Concepts

What is Virtualization?

Virtualization is a proven software technology that is rapidly transforming the IT landscape and fundamentally changing the way that people compute. Today’s powerful x86 computer hardware was designed to run a single operating system and a single application. This leaves most machines vastly underutilized. Virtualization concept lets you run multiple virtual machines on a single physical machine, sharing the resources of that single computer across multiple environments. Different virtual machines can run different operating systems and multiple applications on the same physical computer. Virtualizaion technology is production-proven, used by more than 170,000 customers, including 100% of the Fortune 100.

Virtual Machine Definition:

A virtual machine (VM) is an environment in virtualization concept,is usually a program or operating system, which does not physically exist but is created within another environment. In this context, a VM is called a "guest" while the environment it runs within is called a "host." Virtual machines are often created to execute an instruction set different than that of the host environment. One host environment can often run multiple VMs at once. Because VMs are separated from the physical resources they use, the host environment is often able to dynamically assign those resources among them

Pre-requisites for installing Microsoft Virtual Server 2005 R2:

 x86 based 1GHz processor with L2 cache

 Super VGA monitor

 Network interface card

 Min. 1GB-2GB RAM

 5GB HDD files space

 IIS enabled

Top 5 Reasons to Adopt Virtualization Software:

1. Get more out of your existing resources: Pool common infrastructure resources and break the legacy “one application to one server” model with server consolidation.
2. Reduce datacenter costs by reducing your physical infrastructure and improving your server to admin ratio: Fewer servers and related IT hardware means reduced real estate and reduced power and cooling requirements. Better management tools let you improve your server to admin ratio so personnel requirements are reduced as well.
3. Increase availability of hardware and applications for improved business continuity: Securely backup and migrate entire virtual environments with no interruption in service. Eliminate planned downtime and recover immediately from unplanned issues.
4. Gain operational flexibility: Respond to market changes with dynamic resource management, faster server provisioning and improved desktop and application deployment.
5. Improve desktop manageability and security: Deploy, manage and monitor secure desktop environments that users can access locally or remotely, with or without a network connection, on almost any standard desktop, laptop or tablet PC.

What is a Virtual Machine?


A virtual machine is a tightly isolated software container that can run its own operating systems and applications as if it were a physical computer. A virtual machine behaves exactly like a physical computer and contains it own virtual (i.e., software-based) CPU, RAM hard disk and network interface card (NIC).

An operating system can’t tell the difference between a virtual machine and a physical machine, nor can applications or other computers on a network. Even the virtual machine thinks it is a “real” computer. Nevertheless, a virtual machine is composed entirely of software and contains no hardware components whatsoever. As a result, virtual machines offer a number of distinct advantages over physical hardware.

Types of Virtual Machine based on their use and degree of correspondence to any real machine:

1) System Virtual Machine:

A system virtual machine provides a complete system platform which supports the execution of a complete operating system (OS).

System virtual machines (sometimes called hardware virtual machines) allow the sharing of the underlying physical machine resources between different virtual machines, each running its own operating system. The software layer providing the virtualization is called a virtual machine monitor or hypervisor. A hypervisor can run on bare hardware (Type 1 or native VM) or on top of an operating system (Type 2 or hosted VM).

The main advantages of system VMs are:
• multiple OS environments can co-exist on the same computer, in strong isolation from each other
• the virtual machine can provide an instruction set architecture (ISA) that is somewhat different from that of the real machine
• application provisioning, maintenance, high availability and disaster recovery

The main disadvantage of system VMs is: a virtual machine is less efficient than a real machine because it accesses the hardware indirectly

2) Process Virtual Machine:

A process virtual machine is designed to run a single program, which means that it supports a single process.

A process VM, sometimes called an application virtual machine, runs as a normal application inside an OS and supports a single process. It is created when that process is started and destroyed when it exits. Its purpose is to provide a platform-independent programming environment that abstracts away details of the underlying hardware or operating system, and allows a program to execute in the same way on any platform. A process VM provides a high-level abstraction — that of a high-level programming language (compared to the low-level ISA abstraction of the system VM). Process VMs are implemented using an interpreter; performance comparable to compiled programming languages is achieved by the use of just-in-time compilation.

What is a Virtual Infrastructure?



A virtual infrastructure lets you share your physical resources of multiple machines across your entire infrastructure. A virtual machine lets you share the resources of a single physical computer across multiple virtual machines for maximum efficiency. Resources are shared across multiple virtual machines and applications. Your business needs are the driving force behind dynamically mapping the physical resources of your infrastructure to applications—even as those needs evolve and change. Aggregate your x86 servers along with network and storage into a unified pool of IT resources that can be utilized by the applications when and where they’re needed. This resource optimization drives greater flexibility in the organization and results in lower capital and operational costs.

A virtual infrastructure consists of the following components:

• Bare-metal hypervisors to enable full virtualization of each x86 computer.

• Virtual infrastructure services such as resource management and consolidated backup to optimize available resources among virtual machines

• Automation solutions that provide special capabilities to optimize a particular IT process such as provisioning or disaster recovery.

Decouple your software environment from its underlying hardware infrastructure so you can aggregate multiple servers, storage infrastructure and networks into shared pools of resources. Then dynamically deliver those resources, securely and reliably, to applications as needed. This pioneering approach lets our customers use building blocks of inexpensive industry-standard servers to build a self-optimizing datacenter and deliver high levels of utilization, availability, automation and flexibility.

This gives you brief idea about virtualization concept. I hops this was helpful to you.

Refer my other blogs for other topics:
SharePoint Taxonomy
Checkpoints for creating Custom Event Handlers
Strong Named Assembly in SharePoint

Strong Named Assembly in SharePoint

What is Strong Name?

A strong name is a .NET assembly name combined with its version number and other information to uniquely identify the assembly. This allows multiple versions of the same assembly to peacefully co-exist in the global assembly cache, where shared assemblies are typically stored.

A strong name consists of five parts:

1) Simple Name – Usually the name of the file (without the extension) that contains the assembly

2) Public Key – RSA cryptographic public key that helps verify the assembly's authenticity

3) Version – Four-part version number, in the form of Major.Minor.Build.Revision

4) Culture – Target audience for the assembly, such as "neutral" (default audience), "en-us" (English – United States) or "fr" (France) etc.

5) Processor Architecture – Defines the assembly's format, such as MSIL (intermediate language) or x86 (binary for Intel x86 processors)

An example of Strong Named Assembly:

Strong name is "Mini-Launcher, Version=0.3.612.24542, Culture=neutral, PublicKeyToken=ffa52ed9739048b4, ProcessorArchitecture=MSIL"

Why Use Strong Names?

Strong names are required to store shared assemblies in the global assembly cache (GAC). This is because the GAC allows multiple versions of the same assembly to reside on your system simultaneously, so that each application can find and use its own version of your assembly. This helps avoid DLL Hell, where applications that may be compiled to different versions of your assembly could potentially break because they are all forced to use the same version of your assembly.

Another reason to use strong names is to make it difficult for hackers to spoof your assembly, in other words, replace or inject your assembly with a virus or malicious code.

You can ensure that a name is globally unique by signing an assembly with a strong name.
Strong names satisfy following requirements:

1) Strong names guarantee name uniqueness by relying on unique key pairs. No one can generate the same assembly name that you can, because an assembly generated with one private key has a different name than an assembly generated with another private key.

2) Strong names protect the version lineage of an assembly. A strong name can ensure that no one can produce a subsequent version of your assembly. Users can be sure that a version of the assembly they are loading comes from the same publisher that created the version the application was built with.

3) Strong names provide a strong integrity check. Passing the .NET Framework security checks guarantees that the contents of the assembly have not been changed since it was built. Note, however, that strong names in and of themselves do not imply a level of trust like that provided, for example, by a digital signature and supporting certificate.

What is a strong name key file?

A strong name key file has a .snk extension and contains a unique public-private key pair. You use the strong name key file to digitally sign your assembly (see below). Note that this type of file is not secure, as the private key in a .snk file can be easily compromised.

For added protection, Visual Studio can encrypt a strong name key file, which produces a file with the .pfx (Personal Information eXchange) extension. The .pfx file is more secure because whenever someone attempts to use the encrypted key, she will be prompted for the password.

How do I create a strong name key file for a .NET assembly?

1) Select your assembly project in the Visual Studio 2008 Solution Explorer.

2) Click the Properties button. The project properties will appear in the main window.

3) Select the Signing tab:


4) Check the Sign the assembly checkbox.

5) In the Choose a strong name key file drop-down, select New. The "Create Strong Name Key" dialog appears:


6) In the Key file name text box, type the desired key name. Typically this is the name of your assembly but can be anything. Visual Studio will automatically append the proper file extension.

7) If desired, you can protect the strong name key file with a password. To do so, check the Protect my key file with a password checkbox, then enter and confirm the password.

8) Click the OK button.

How to get Strong Named Token?

1) Go to External Tools... from Tools menu.


2) Click Add.
3) enter the Title, Commands (SDK path of sn.ese) and Arguments.

4) Click Apply to get the new tool in Tools menu to get SN Token.

Finally check the received SN token entry in GAC by right clicking the entry. You can see the desired result as follows:


This is the simple way to create and get the Strong Named Assembly in SharePoint. It is not too different from the strong named assembly in dot net.
Thank you for reading my blog. Please go through my other blogs:

SharePoint Taxonomy

What is Taxonomy?

Taxonomy is the practice and science of classification. The word finds its roots in the Greek τάξις, taxis (meaning 'order', 'arrangement') and νόμος, nomos ('law' or 'science'). It is the science of classification according to a pre-determined system, with the resulting catalog used to provide a conceptual framework for discussion, analysis, or information retrieval.

What is SharePoint Taxonomy?

In context of SharePoint taxonomy, we usually get many questions related to SharePoint website. Some of them I have listed below:

1. What type of content does the site contain?

2. Who can view the site?

3. Who can manage the site?

4. Who can publish content to the site?

5. What is the site’s URL?

6. How much space can the site consume?

7. What does the site look like?

8. How long should the site remain active?

All these questions are successfully answered by creating SharePoint Taxonomy.

SharePoint Taxonomy basically deals with data (aka. metadata) as well as the policies, workflows, permissions, etc.

Following is the sample SharePoint Taxonomy metadata:



With the exponential growth of implementations worldwide, come greater challenges and opportunities for improving knowledge management and information access within the enterprise. The need for consistent organizing principles across enterprise information is of ever increasing importance and, when done correctly, can result in leaps and bounds in employee productivity.

Before we get to any of the details however, let’s remind ourselves that the purpose of building and maintaining taxonomies is to improve the find ability of information by:

-Defining preferred terms along with their synonyms and variants;

-Establishing equivalent, hierarchical, associative or custom relationships between those terms;

-Increasing the effectiveness of site navigation; and

-Enhancing enterprise search by leveraging functionality such as faceted navigation.

The first and cost effective approach is to leverage features and functionality inherently part of the platform itself. Doing so means the implementation of sharepoint taxonomy is done through a combination of site content types, column definitions and custom lists.

A typical implementation of taxonomy might look something like this: As an administrator you navigate to the root or site collection settings and do the following:

1. Define SharePoint Taxonomy Metadata – Create custom site lists to be used for the management of metadata attributes you want to surface as controlled vocabularies for your site users.

2. Define Site Columns – Create new site columns that get their information from the custom lists created above via lookup fields.

3. Define Content Types – Create new site content types and add the appropriate site columns as required.

4. Allow the Management of Content Types – Enable the management of content types on site lists and libraries that require these consistent organizing principles.

We should have a sample check-list of items of what needs to be done to implement a SharePoint site. . The list of items can be extremely detailed, but to some degree they needed a simple list just so they could get started and know what needs to get done and when they will have to spent more time on. Here is that simple list. This is your “get started” list that you should incorporate into your project timeline.

-Document libraries and lists
-Analyze document usage
-Plan document libraries
-Plan lists
-Plan enterprise content storage
-Site Navigation
-Metadata
-Content types
-Information management policies (Labels, Barcodes, Auditing, Expiration)
-Records management
-Moving content
-Plan content deployment
-Workflows
-Site Templates
-Working with site templates and definitions
-Content approval
-Versioning
-Check-outs
-Standardization across sites
-People and groups (permissions)

The SharePoint taxonomy provides much more than a common set of terms, it provides a foundation upon which future decisions are made. It provides a scalable hierarchy that allows a SharePoint deployment to grow in an organized, predictable, and understandable manner.

You can visit my other blogs:
Virtualization Concepts
Strong Named Assembly in SharePoint