Friday, August 28, 2009

ASP.NET Page Life Cycle - Interview Huh !!!

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend and obviously to clear some BULLSHIT INTERVIEW !!!

General Page Life-cycle Stages (Courtsy MSDN, CP, UsualDosage, Several Blogs...)
In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page.



Putting together an acronym for the page life cycle is easy enough. Since the Page Request technically isn't a part of the life cycle (it only indicates whether we actually will start the cycle or load a cached page) we won't include it in the acronym.
S � Start
I � Initialize
L � Load
V � Validate
E � Event Handling
R � Render
That gives us "SILVER", which is very easy to remember. However, it is important remember that the last part of the cycle is unload. You can remember it as "SILVER-U" or "SILVER-YOU" if that helps !!! Now that it's easy to remember the order of steps for the page lifecycle, we'll summarize exactly what happens and what events are pertinent to each stage.

1. Start
This is where page properties such as Request, Response, IsPostBack and UICulture are set. As a developer, you most likely won't really need to do anything in this stage of the cycle. If you need to access or override behavior for this step, use the PreInit method to create or re-create dynamic controls, set a master page or theme or read or set profile property values. It is important to note that if the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

2. Initialize
This stage can be very important to developers. Here, themes are applied, and unique ids are generated and set for controls. Developers have access to the Init, InitComplete and PreLoad methods in this stage. Microsoft's recommended usage for these methods is as follows:
Init � This event is raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
InitComplete � This event is raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad - Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

3. Load
This stage is perhaps the most utilized by developers. In this stage controls are loaded with information retrieved from view and control states. The OnLoad is the event method that fires during this stage. This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.

4. Validation
If you have controls that require validation, they are validated here and you can now check the IsValid property of the control. The event associated with this is Validate, which contains one overloaded method that accepts a validation group string. The overloaded method instructs the controls in the specified group to validate.

5. Event Handling
The event handling for server controls occurs during this stage. This means that events such as Click, SelectedIndexChanged, etc are applied to your server controls, and, in the case of a postback, these event handlers are fired by the control. The accessible events of note in this stage are as follows:
LoadComplete � At this step, all of the controls for the page have been loaded.
PreRender � A few things of import happen here. First, the page object will call EnsureChildControls for each control, and finally for the page. Additionally, any data bound control that has a DataSourceID set will call its DataBind method. It is important to note that the PreRender event occurs for each control on the page. At the conclusion of this event, ViewState will be saved for the page and all of the controls.
SaveStateComplete � ViewState has been saved. If you have actions that do not require changes to controls but require ViewState to have been saved, you can handle the SaveStateComplete event.

6. Render
Render is not really an event. Rather, the page object calls this method on each control, which in turn writes out the HTML markup for the control to the browser. This stage is keenly important to developers who create custom controls, because the standard approach is to override the Render method for the control in order to output the custom markup. If your control inherits from a standard ASP.NET server control, you probably won't need to override the Render method unless you want to exhibit a different behavior than the control's default. This is outside the scope of this document, but for more reading, you can reference Microsoft's Developing Custom ASP.NET Server Controls. (http://msdn2.microsoft.com/en-us/library/zt27tfhy.aspx)

7. Unload
This final event occurs first for each control, then, finally, for the page. At this point, all controls have been rendered to the output stream and cannot be changed. During this event any attempt to access the response stream will result in an exception being thrown. This event is primarily for cleanup routines such as closing open database connections and open file streams, or, event logging and other tasks.

Methods
The following methods (which can all be overridden) occur in order during the lifecycle of an ASP.NET page. Please realize that some of these methods are called recursively, and multiple times depending on the content of the page. This list is the generalized order in which methods fire when a page loads. You can test this by creating a default ASP.NET application, overloading each of the below methods, and setting a breakpoint on each.
1. Construct
2. ProcessRequest
3. FrameworkInitialize
4. InitializeCulture
5. If child controls are present:
a. AddParsedSubObject
b. CreateControlCollection
c. AddedControl
d. ResolveAdapter
6. DeterminePostBackMode
7. OnPreInit
8. OnInit
9. TrackViewState
10. OnInitComplete
11. OnPreLoad
12. OnLoad
13. OnLoadComplete
14. EnsureChildControls
a. CreateChildControls
15. OnPreRender
16. OnPreRenderComplete
17. SaveViewState
18. OnSaveStateComplete
19. CreateHtmlTextWriter
20. RenderControl
a. Render
b. RenderChildren
21. VerifyRenderingInServerForm
22. OnUnload
23. Dispose

So, after theory comes the Practical Lab... Here, comes a code stub, which one can very easily use to learn clearly about page life cycle.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("protected void Page_Load" + "
");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("protected void Page_PreRender" + "
");
}
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("protected void Page_PreInit" + "
");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("protected void Page_Init" + "
");
}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("protected void Page_InitComplete" + "
");
}

protected void Page_PreLoad(object sender, EventArgs e)
{
Response.Write("protected void Page_PreLoad" + "
");
}
protected void Page_ControlEvents(object sender, EventArgs e)
{
Response.Write("protected void Page_ControlEvents" + "
");
}
protected void Page_SaveStateComplete(object sender, EventArgs e)
{
Response.Write("protected void Page_SaveStateComplete" + "
");
}
protected void Page_Render(object sender, EventArgs e)
{
Response.Write("protected void Page_Render" + "
");
}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Response is not available in this context.
}
/////////////////////////////////////////////////////////////
protected override void AddedControl(Control control, int index)
{
Response.Write("AddedControl Fired on " + control.ID + "
");
base.AddedControl(control, index);
}
protected override void AddParsedSubObject(object obj)
{
base.AddParsedSubObject(obj);
Response.Write("AddParsedSubObject" + obj.ToString() + "
");
}
public override void ApplyStyleSheetSkin(Page page)
{
base.ApplyStyleSheetSkin(page);
Response.Write("ApplyStyleSheetSkin " + page.ToString() + "
");
}
protected override void Construct()
{
base.Construct();
// No Response Object here yet!
}
protected override void CreateChildControls()
{
base.CreateChildControls();
Response.Write("CreateChildControls
");
}
protected override ControlCollection CreateControlCollection()
{
Response.Write("CreateControlCollection
");
return base.CreateControlCollection();
}
// etc. etc. just type the keyword "override" and select from the list! protected void Page_Load(object sender, EventArgs e)
}

Ref: http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://69.10.233.10/KB/aspnet/ASPNET_Page_Lifecycle.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.page_events.aspx

In depth Pic Analysis: (Courtsy: Léon Andrianarivony)

Windows SharePoint Services - Architectural Perspective

Windows® SharePoint® Services (WSS) provides team-oriented collaboration Web sites, a platform for building Web-based applications that use the WSS collaboration features, and a framework for deploying and managing these sites and applications.

Functional Architecture
WSS is designed to support a broad range of deployments. At a high level, four different types of systems are involved:
1. The End-User Client (EUC) is a computer on which an individual user is requesting specific file operations. These requests are communicated using HTTP-based protocols, including HTTP, DAV and Microsoft FrontPage Server Extensions.
2. The Web Front-End (WFE) is a computer that receives requests from an EUC and provides WSS capabilities by manipulating information stored in a database. These database requests are expressed in the T-SQL language and communicated using the TDS protocol.
3. The Back-End Database (BEDS) is a computer that runs Microsoft® SQL™ Server and responds to requests from the WFE server.
4. An Active Directory server responds to authentication requests from the EUC, WFE, and BEDS. These components could use an alternate authentication mechanism besides Active Directory.
These systems are shown in the following diagram.



Figure 1: Intersystem protocol relationships

WFE and BEDS are considered part of the WSS deployment; the EUC is normally a user's desktop or laptop computer that connects to WSS services, and Active Directory is part of the generally available infrastructure. Both WFE and BEDS can run on a single computer, so the simplest WSS deployment could be just a single server. Alternatively, multiple instances of WFE and BED computers can be installed for greater throughput and redundancy.

Storage Architecture
WSS provides a flexible model for storage which allows for a robust variety of data management and organization techniques. The following diagram presents a high-level view of the containers in this hierarchy. These containers provide important organizational and management tools for content stored in WSS, and also form the core securable objects.


Figure 2: SharePoint storage object hierarchy

Advanced Storage Concepts
In addition to basic file system concepts, WSS provides a variety of specialized file system objects and operations as described below -

Thickets
For some complex HTML documents, WSS provides the capability to store the document separated into its component sibling documents. This group of documents is treated like a single document for most file operations, but is stored as a set of related documents within the file store location.

Ghosting
Sites and Lists tend to share a relatively small set of common system files across many instances within the BEDS. To avoid having to store these files repeatedly for every Site or List in the BEDS, WSS allows files to be ghosted, meaning that the content of the file is not actually stored in the BEDS. Instead, a reference to a location on the WFE where the source of the file can be found is stored in the file metadata.

Versioning
WSS can be configured on a per-List or per-Document Library basis to store multiple versions of Documents. If versioning is configured for a storage location, each new version of a Document is stored with an incrementing version number that can be either in the form 'Major Version Number' (#) or 'Major Version Number.Minor Version Number' (#.#).
If Major Version Number.Minor Version Number version numbering is used, individual Documents start their numbering at 0.1, and the version can be promoted to a Major Version using the Publishing feature. Prior versions of a document can be retrieved by users with the appropriate access rights.

Publishing
WSS can be configured on a per-List or per-Document Library basis to allow publishing features with Documents. If publishing features are configured for a storage location, each version of a Document can be configured as a draft, and therefore, not be available to be viewed by users without the appropriate access rights for viewing unpublished versions.

Large File Access
When dealing with very large files, obtaining the complete file contents in a single buffer as part of one operation can be a burden on system resources. Instead, the BEDS provides functionality to return files larger than a specified size to the WFE in a series of smaller chunks that can be processed more smoothly.

BLOB Storage Outside the Content Database
WSS provides the ability to allow file metadata to be stored by WSS in a Content Database, while allowing the actual file contents to be stored in an external file system. The term Binary Large Object (BLOB) refers to the SQL Server concept of unstructured, binary data streams that are commonly associated with files.
WSS does not natively provide a BLOB store. There are two APIs that allow a BLOB storage provider to be built and registered with WSS:
External BLOB Storage: For more information about External BLOB Storage, see [MSDN-WSSEBS].
Remote BLOB Storage: For more information about Remote BLOB Storage, see [MSDN-SQLRBS]. Windows SharePoint Services 4.0 supports Remote BLOB Storage providers.

Content Databases
A Content Database stores and manages end-user content. Each Web Application will have one or more Content Databases. The WSS Content Database stores the data and documents that end-users have associated with their SharePoint Site. The contents of this database are fully normalized in order to efficiently perform the kinds of operations required for the high-scale, highly-configurable system previously described. The role of a WSS WFE is to fetch the appropriate data from these multiple locations within SQL using the appropriate set of queries and stored procedures and to correctly interpret and map the results into a correct response to the EUC.

Configuration Database
The Configuration Database describes the topology of the farm and global settings. Each farm will have only one Configuration Database. The Configuration Database is essentially the definition of the WSS deployment, for either a single instance of WSS or for a farm. In the farm context, the Configuration Database contains information representing the global settings that are required to provide consistent operation across all servers within the farm, and to map requests to particular Content Databases.

Thursday, August 27, 2009

WSP and WSPBuilder --- Penicillin in the life of a SharePoint Developer!!!

SharePoint Solution Package AKA WSP

The Windows SharePoint Services solution framework provides a way to bundle all the components for extending Windows SharePoint Services in a new file that is called a solution file. A solution file has a .CAB-based format but a .WSP extension. A solution is a deployable, reusable package that can contain a set of Features, site definitions, and assemblies that apply to sites, and that you can enable or disable individually. You can use the solution file to deploy the contents of a Web Part package, including assemblies, class resources, .dwp files, and other package components.

Benefits of the Solution Framework
The solution framework provides the following advantages:
1. A unified infrastructure for deploying solutions.
2. Integrated deployment.
a. Deploy new solutions and upgrade existing solutions across the farm.
b. Synchronize a front-end Web server so that its state is consistent with the state of other servers in the farm.

What a WSP can contain?
A solution package is a cabinet (.cab) file with a .wsp file name extension and a manifest file. It can contain the following components:
1. Site definitions
2. Feature definitions and their corresponding element definitions and files
3. Web Part files (*.webpart, *.dwp)
4. Template files and root files, which can include the following:
a. _layouts files
b. Resources (*.resx)
c. Resource files (for example, *.doc or *.xls)
5. Assemblies, which can include the following:
a. Safe control entries
b. Resources
6. Code access security policies

Solution files have a hierarchical structure—a manifest file is at the root—while feature, resource, or site definition directories are contained in subdirectories. In turn, feature definitions define where associated files are located inside of the solution.
The solution creator can define the remaining structure; however, it is recommended that files for a particular feature or site definition be placed in that feature or site definition's subdirectory.

What is a solution manifest.xml file ?
The solution manifest (always called manifest.xml) is stored at the root of a solution file. This file defines the list of features, site definitions, resource files, Web Part files, and assemblies to process. It does not define the file structure—if files are included in a solution but not listed in the manifest XML file, they are not processed in any way.
Following is the structure of a manifest.xml file -


What is a solution feature.xml file ?

Features reduce the complexity involved in making simple site customizations, and are robust when upgrades are applied to a deployment. Features eliminate the need to copy large chunks of code to change simple functionality. Features thus reduce versioning and inconsistency issues that may arise among front-end Web servers. Features make it easier to activate or deactivate functionality in the course of a deployment, and administrators can easily transform the template or definition of a site by simply toggling a particular Feature on or off in the user interface.
Features provide the following capabilities:
1. Scoping semantics for determining where custom code runs
2. Pluggable behavior for installing or uninstalling Features within a deployment
3. Pluggable behavior for activating or deactivating Features at a given scope
4. A scoped property bag for storing data required by a Feature within its scope
5. The basis of a unified framework for distributed deployment of Windows SharePoint Services solutions

Feature Implementation
To implement a Feature you add a subfolder containing a Feature definition within the Features setup directory (Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES). The Feature subfolder includes a Feature.xml file that defines the base properties of the Feature and lists elements bound to it, such as XML files containing element manifests and any other supporting files. A Feature folder may contain only a Feature.xml file, or it may contain a Feature.xml file and any number of supporting element files, including XML files, but also .aspx, .htm, .xsn, .resx, .dll, and other file types.
Following is the structure of a feature.xml file -


Note:
When you create a folder within the Features directory through Windows Explorer by right-clicking a folder, pointing to New, and then clicking Folder, the new folder does not have inherited permissions. If you deploy a Feature in the folder, then some Windows SharePoint Services pages, such as for site settings or list views, throw an exception. You can fix this problem by right-clicking the new folder, click Properties, click Security, and then click Advanced. On the Permissions tab, delete uninherited permissions from the folder. You can also fix this problem by creating the new folder at the command prompt through the md command.

After creating the Feature folder, you can install and activate the Feature through command-line operations of stsadm.exe, or through the object model. You can also activate a Feature through the user interface. Installing a Feature makes its definition and elements known throughout a server farm, and activating the Feature makes the feature available at a particular scope.

What is a solution elements.xml file ?
Elements.xml is referred via Feature.xml. Here, Module URLs are targets within MOSS; File URLs are relative to the Module URL. Following is the structure of a feature.xml file -



So, after the basics of WSP, we need to learn WSPBuilder...

You can download it from the following link -
http://www.codeplex.com/wspbuilder

A very good documentation cum tutorial can be found from -
http://www.zimmergren.net/archive/2009/04/08/wspbuilder-walkthrough-of-the-visual-studio-add-in.aspx

So, before ending this post lets summarize the whole thing in novice statements -

Manifest.xml: Instructs SharePoint where to deploy the files held in the cabinet. File paths depend on the containing XML element: assembly paths are relative to the target /bin directory, TemplateFiles are relative to the 12-hive's TEMPLATE directory, DwpFiles are relative to the wwwroot\wss\VirtualDirectories\wpcatalog directory, and FeatureManifests and Resources are both relative to the 12-hive's TEMPLATE\FEATURES directory.

Feature.xml: ElementFile locations are relative to the directory structure where the feature is installed (eg. as specified in Manfiest.xml)

Elements.xml (via Feature.xml): Module URLs are targets within MOSS; File URLs are relative to the Module URL

Web Deployment Projects with Visual Studio 2005 ??? WHY ???

Visual Studio 2005 provides deployment support through its Copy Web Site and Publish Web Site features. While these are ideal for many scenarios, there are other, more advanced scenarios where developers need the following capabilities:

More control over assembly naming and output.
Custom pre-processing and post-processing for the build.
The ability to exclude, add, and transform files and directories during builds.
The ability to modify the Web.config file to change database connection strings, application settings, or the URLs for Web references, depending on the build configuration. (For example, it might be necessary to use different values for development, test, staging, and release settings).

For details, just visit the following link :

http://msdn.microsoft.com/en-us/library/aa479568.aspx

To merge the assemblies created during ASP.NET 2.0 pre-compilation

In a SharePoint centric project, one needs to build User Controls and WebParts. Now, both of them should have different namespace and after compilation will create different assemblies. Another scenario is, if you are building Web Application Project in VS 2005, then you dont have any dll as the result of compilation. But, in SharePoint centric development you need one assembly which you are ssupposed to put in the GAC.

To solve this kind of irritating problem, Microsoft provides an add-in that consists of a tool to merge the assemblies created during ASP.NET 2.0 pre-compilation, and provides a comprehensive UI within Visual Studio 2005 to manage build configurations, merging, and using pre-build and post-build tasks with MSBuild.
You can download the add-in from the following location -

http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx

After downloading and Installation, open up your solution. Select Web Application Project in the Solution Explorer, riht click and select Add Web Deployment Project. Next give the name and location for it and select OK.
Now, In Solution Explorer, select Web Deployment Project that you have just added and right click on it and select Property. In the property dialog box, you can manipulate its behaving patterns, like - strong name key, assembly name, version etc. etc. When you are done save it and Then Build the Web Deployment Project. Next, go to the location in your hard drive where the web deployment project physically resides. There you will find the Bin folder, inside which your new born sweet assembly resides... :)

Monday, August 24, 2009

Delegates and SPSecurity.RunWithElevatedPrivileges()

ASP.Net provides a powerful way of doing things without actually knowing the meaning of code.
It is quite common to get a code stub from seniors for a particular purpose and pasting it inside own class, changing the logic and pressing F5!!! :) ... Visual Studio always rocks...
When I first started learning SharePoint, the code stub given to me by my seniors, always looks very peculiar to me!!! Specially the following line -

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ospSite = new SPSite(ConfigurationManager.AppSettings["SiteURL"].ToString()))
{
ospWeb = ospSite.OpenWeb();
}
});


So lets drill down it. First comes Delegates.

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example:

public delegate int PerformCalculation(int x, int y);

Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.
This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.

Delegates Overview

Delegates have the following properties:
Delegates are similar to C++ function pointers, but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods don't need to match the delegate signature exactly.
C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

Now, Here comes an exciting question : When to Use Delegates Instead of Interfaces ?

Both delegates and interfaces allow a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct; a delegate
can created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object with no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should they use an interface?

Use a delegate when:
An eventing design pattern is used.
It is desirable to encapsulate a static method.
The caller has no need access other properties, methods, or interfaces on the object implementing the method.
Easy composition is desired.
A class may need more than one implementation of the method.

Use an interface when:
There are a group of related methods that may be called.
A class only needs one implementation of the method.
The class using the interface will want to cast that interface to other interface or class types.
The method being implemented is linked to the type or identity of the class: for example, comparison methods.

Now, here comes the main subject of today's post: running code in sharepoint with elevated rights, an operation sometimes required, sometimes abused and often misunderstood.
The WSS Object Model provides a huge number of classes, some of which can carry-out potentially dodgy actions, so require elevation to run. Ordinarily you'd just deal with this by logging in as a user with rights to carry out the operation, but occasionally this isn't practical or possible, and that's where today's subject comes in.
Let's say, just as an example, you're creating an anonymously-accessible site. In a Control on on of the pages you want to enumerate subsites of your site, and grab some properties thereof, maybe for display, maybe for some other operation in your code - however, this isn't something an anonymous identity can do.
In steps our hero - RunWithElevatedPrivileges()
Used correctly, this method allows a specified block of code to run in the context of the SharePoint System Account, a powerful method with much potential. Here's the summary from the SDK:

[SharePointPermissionAttribute(SecurityAction.Demand, Impersonate=true)] [SharePointPermissionAttribute(SecurityAction.Demand, ObjectModel=true)] public static void RunWithElevatedPrivileges ( CodeToRunElevated secureCode)

Now the CodeToRunElevated parameter can be a reference to a void, parameterless method or an anonymous method via delegate() - please, follow the SDK link if that's unclear.
Pretty simple, huh? Yep, well as always there's a catch or two.

1. If you're manipulating any Object Model elements within your elevated method, you need to get a fresh SPSite reference inside this call. For example

SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite mySite = new SPSite(
http://sharepoint/);
SPWeb myWeb = SPSite.OpenWeb();
// further implementation omitted
});

2. You can't just use SPContext.Current.Site to get your SPSite reference - or you'll ber handed the object with the security context of the anonymous (or non-elevated) user and your elevation will not work as expected.

3. If you need to Update() anything inside this block, you'll need to call SPSite.AllowUnsafeUpdates() on your new site reference (or web reference) as per this SDK entry.

So those are the gotchas. Following those we have the obvious security warnings - be careful what you do within this call, as the system identity has full control over SharePoint and could do Very Bad Things if incorrectly used. Sanitise any user input very carefully if you're going to let it anywhere near this method - you certainly don't want a user finding some injectable exploit into this code. Exercise caution over what you do, for this power must be used wisely.

Sunday, August 23, 2009

Exploring Content Type & Creating a Custom Content Type with Event Receivers

Before proceeding to create a custom content type, lets first define it.

Content Types, a core concept used throughout the functionality and services offered in Windows SharePoint Services 3.0, are designed to help users organize their SharePoint content in a more meaningful way. A content type is a reusable collection of settings you want to apply to a certain category of content. Content types enable you to manage the metadata and behaviors of a document or item type in a centralized, reusable way.
For example, consider the following two types of documents: software specifications and legal contracts. It is reasonable that you might want to store documents of those two types in the same document library. However, the metadata you would want to gather and store about each of these document types would be very different. In addition, you would most likely want to assign very different workflows to the two types of documents.

So, What is METADATA ???

Metadata is binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into a PE file, metadata is inserted into one portion of the file, while your code is converted to Microsoft intermediate language (MSIL) and inserted into another portion of the file. Every type and member defined and referenced in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on.
Metadata describes every type and member defined in your code in a language-neutral manner. Metadata stores the following information:
Description of the assembly.
Identity (name, version, culture, public key).
The types that are exported.
Other assemblies that this assembly depends on.
Security permissions needed to run.
Description of types.
Name, visibility, base class, and interfaces implemented.
Members (methods, fields, properties, events, nested types).
Attributes.
Additional descriptive elements that modify types and members.

Benefits of Metadata

Metadata is the key to a simpler programming model, eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference. Metadata allows .NET languages to describe themselves automatically in a language-neutral manner, unseen by both the developer and the user. Additionally, metadata is extensible through the use of attributes. Metadata provides the following major benefits:

1. Self-describing files.

2. Language interoperability and easier component-based design.
3. Attributes.

Now, back to content type: A content type can include the following information:
The metadata, or properties, you want to assign to this type. These are represented by columns added to the list or document library when you add the content type.
Custom New, Edit, and Display forms to use with this content type.
Workflows available for items of this content type. These can be defined to start automatically based on a selected event or condition, or through user selection.
For document content types, the document template on which to base documents of this type.
Any information necessary for custom solutions associated with this content type. You can store this information in the content type as one or more XML documents


So, after theory comes the practical part. Now, for How to: Create a Custom Content Type with Event Receivers please go through the following simple step by step document available in the MSDN -

http://msdn.microsoft.com/en-us/library/dd206944.aspx

Debugging SharePoint Applications

You can greatly simplify debugging by using Visual Studio extensions for Windows SharePoint Services. There are three possibility -

1. Debugging with Visual Studio extensions for Windows SharePoint Services

Press the F5 key to begin debugging with Visual Studio extensions for Windows SharePoint Services. The following procedure demonstrates how to enable F5 debugging.
To enable F5 debugging
Locate and open the target SharePoint application's Web.config file. By default, it is located in C:\Inetpub\wwwroot\wss\VirtualDirectories\80.
Find the following line of code and change the debug attribute to true.
<"compilation batch=”false” debug=”false”"> - (Remove first and last quote)
Save the changes to the Web.config file.
In Visual Studio, right-click the SharePoint project, and then click Properties.
Click the Debug tab, and then type the target SharePoint URL in the Start browser with URL box.
Place a breakpoint in the code, and then press F5.

2. Performing Manual Debugging

You can debug a SharePoint application without using Visual Studio extensions for Windows SharePoint Services by attaching it to the W3wp.exe process. The following procedure demonstrates how to do this.
To attach to the W3wp.exe process
Make sure that the SharePoint application is using the latest compiled source code. This may require that you recompile your source and install the assemblies into the global assembly cache. Alternatively, you may need to copy the assemblies to the bin folder of SharePoint's virtual directory. In either case, you must run the Microsoft Internet Information Services (IIS) command-line utility Iisreset.exe.
Place a breakpoint in the code you want to debug.
On the Debug menu, click Attach to Process.
In the list of available processes, find the W3wp.exe process, and then do the following, as applicable:
If the W3wp.exe process is not listed, make sure that the Show processes from all users and Show processes in all sessions check boxes are selected.
If the W3wp.exe process still is not listed, open a Web browser and navigate to the application's SharePoint site. After you navigate to the SharePoint site, return to Visual Studio. In the Attach to Process dialog box, click the Refresh button to locate the W3wp.exe process.
If you see multiple W3wp.exe processes listed and are not sure which one of them is running the code, click them all.
Click the Attach button.

3. Performing Remote Debugging

You can debug a SharePoint application when it is running on a remote computer by attaching it to the remote W3wp.exe process. The following procedure demonstrates how to do this.
To attach to a remote W3wp.exe process
Make sure that the remote SharePoint application is using the latest compiled source code. This may mean that you must recompile your source and install the assemblies into the global assembly cache of the remote server. Alternatively, you may need to copy the assemblies to the bin folder of SharePoint's virtual directory on the remote computer. In either case, you must run the Microsoft Internet Information Services (IIS) command-line utility Iisreset.exe.
Make sure that the Visual Studio 2008 Remote Debugger is installed on the remote computer.
Start the Visual Studio 2008 Remote Debugger on the remote computer. For more information about using the remote debugger, see How to: Run the Remote Debugging Monitor on MSDN.
In Visual Studio on the local computer, open the solution, and then set a breakpoint.
On the Debug menu, click Attach to Process.
In the Qualifier text box, type the name of the remote computer, and then click Refresh.
In the Available Processes list, find the W3wp.exe process, and then do the following, as applicable:
If the W3wp.exe process is not listed, make sure that the Show processes from all users and Show processes in all sessions check boxes are selected.
If the W3wp.exe process still is not listed, open a Web browser and navigate to the application's SharePoint site. After you navigate to the SharePoint site, return to Visual Studio. In the Attach to Process dialog box, click the Refresh button to locate the W3wp.exe process.
If you see multiple W3wp.exe processes listed and are not sure which one of them is running the code, click them all. Click Attach.

Saturday, August 22, 2009

The SharePoint Object Model

A very basic question every SharePoint developer face at the time of interview is - 'Describe The SharePoint Object Model'. So, let me answer that question pictorially. The SharePoint Object Model is shown below -


Server and Site Architecture: Object Model Overview (Courtsy MSDN)
Windows SharePoint Services offers a highly structured server-side object model that makes it easy to access objects that represent the various aspects of a SharePoint Web site. From higher-level objects, you can drill down through the object hierarchy to obtain the object that contains the members you need to use in your code.

Entry Points
Depending on the type of custom application or solution that you are creating, you use different entry points into the object model to obtain the appropriate object from which to start. For example, if you are customizing administration and configuration of a deployment, you can use the static ContentService property to return the current Web service object and its collection of Web applications. To modify settings in the administrative Web application, instead use the AdministrationService property. Collection classes that derive from the Microsoft.SharePoint.Administration.SPPersistedObjectCollection class inherit a GetValue method that you can use to return a specific object from a collection.

Note:
If you are creating a Web Part, custom Web service, or Web application to work with site collections, individual sites, or lists, you can use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list. When you create a Web application in the /_layouts virtual directory, its functionality becomes available to all sites on the Web server. Outside of an HTTP context, such as in a console application or a Windows application, use a constructor of the SPSite class to obtain a specific site collection and to reach various objects within the collection. For more information, see Getting References to Sites, Web Applications, and other Key Objects.

Server Architecture
The following diagram shows the Windows SharePoint Services server architecture in relation to the collections and objects of the Microsoft.SharePoint.Administration namespace.


The SPFarm object is the highest object within the Windows SharePoint Services object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.
Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.
Each SPService object represents a logical service or application installed in the server farm. A service object provides access to server farm-wide settings of the load-balanced service that a respective service instance implements. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, Microsoft SQL Server, the database service, etc. and also objects for Web services, such as Windows SharePoint Services or services in the Microsoft Office system.
An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.
An SPDatabaseServiceInstance object represents a single instance of a database service running on the server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.
Each SPWebApplication object represents a load-balanced Web application based in Internet Information Services (IIS). The SPWebApplication object provides access to credentials and other server farm wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property collection of content databases used in the Web application. The SPWebApplication class replaces the obsolete SPVirtualServer class; but it can still be helpful to think of a SPWebApplication object as a virtual server; that is, a set of one or more physical servers that appear as a single server to users.
An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a SharePoint Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.
An SPSiteCollection object represents the collection of site collections within the Web application. The Item property or indexer gets a specified site collection from the collection, and the Add method creates a site collection within the collection.

Site Architecture
The following diagram shows the Windows SharePoint Services site architecture in relation to the collections and objects of the Microsoft.SharePoint namespace.


Each SPSiteobject, despite its singular name, represents a set of logically related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The Microsoft.SharePoint.SPSite.OpenWebmethod of the SPSite class returns a specific Web site.
Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.
Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.
Each SPField object has members that contain settings for the field.
Each SPListItem object represents a single row in the list.
If you install "Infrastructure Update for Windows SharePoint Services 3.0 (KB951695)," custom solutions may fail if they call the SharePoint object model while impersonation is suspended. If you use Windows authentication and your code calls the SharePoint object model from an IIS worker process, the request must impersonate the calling user’s identity. Windows SharePoint Services configures ASP.NET to impersonate the calling user automatically, but your code may work unexpectedly, or fail, if you suspend impersonation--for example, by calling the RevertToSelf function of the Windows API, or by calling the System.Security.Principal.WindowsIdentity.Impersonate method and passing IntPtr.Zero as the value of the user token parameter. Even if your code does not explicitly revert to self, it might be called by ASP.NET after it reverts to self, such as happens when implementing a virtual path provider; if your code does not impersonate the calling user, it might not function properly.

Next to the Object Model, it is always good to learn some best coding practices when using SharePoint object model. So here you can find that -

http://msdn.microsoft.com/en-us/library/bb687949.aspx

Monday, August 17, 2009

SharePoint Site back up and restoration

Copying sharePoint site from one developers pc and then restoring it in another developers pc is a very common task in a sharePoint developers life. The steps to do this are -
1. Open Command Prompt and Go to Program Files->Common Files->Microsofft Shared->Web Server Extension->12->Bin
2. next write - For site collection backup
stsadm -o backup -url <"URL name"> -filename <"file name with full path"> [-nositelock] [-overwrite]
3. Check if the back up has been successfully completed or not.
4. If yes, then create one web application from the central admin and note down the url of the web application
5. now, in the command prompt write -
For site collection restore
stsadm -o restore -url <"web app URL name"> -filename <"back up file name with path"> [-hostheaderwebapplicationurl] <"Web application URL"> [-overwrite]
6. now reflect necessary changes in the config files and start using restored site.

Thursday, August 6, 2009

Resolving "Session State not enabled" error when creating workflow in SharePoint Site

If you are getting "Session State not enabled" error while creating workflow in SharePoint Site, open the web.config file of that site present in the inetpub and change 'enableSessionState' attribute to True as shown below -

Next, uncomment the highligted section shown below -

Now, go back to the site and press F5 and you are done.