30 Sep 2011

Extend Search Engine SharePoint


Search engine can index the following content sources:

  • Microsoft SharePoint sites
  • File shares
  • Internet websites
  • Microsoft Exchange public folders
  • External databases
  • External Line of Business (LOB) systems

architecture of SharePoint 2010 search engine.
Architecture of SharePoint 2010 search engine.

the external locations can provide search capabilities through various protocols, including the
OpenSearch 1.0/1.1 protocol (http://www.opensearch.org/). The main search engines on the
Internet implement the OpenSearch protocol.


Developer is allowed to extend the search engine mainly in the following areas:

  • Search UI
  • OpenSearch
  • Query Object Model and Federated Search Object Model
  • Query Web Service ( search.asmx)
  • Ranking
  • Custom Content Sources :  You can develop custom connectors, protocol handlers,
    content filters, and security trimmers.


Developing Custom Web Parts

A custom Web Part inherited from the Search Core Results Web Part

public class CustomCoreResultsWebPart : CoreResultsWebPart {
protected override void ModifyXsltArgumentList(
Microsoft.SharePoint.WebPartPages.ArgumentClassWrapper argList) {
// Invoke the base implementation
// Add a parameter with the current user name
String currentUserName = SPContext.Current.Web.CurrentUser.Name;
argList.AddParameter("CurrentUserName", String.Empty, currentUserName);

Base class : CoreResultsWebPart

Methods to override:





It is important to know that all of the Web Parts that render the search pages are coordinated by a unique SharedQueryManager object.

Federation Framework

Adds to SharePoint the capability to define multiple search locations on which to search.

Can use one of the following target providers:

  • Search Index on this Server

  • FAST Index

  • OpenSearch 1.0/1.1

Manage Federated Locations page.


You can define a new location either by filling out a definition form or importing a definition file with the extension .osdx (Open Search Definition XML).

Federation location query is executed in realtime

You can export all the federated locations as .osdx files

By default, a Federated Results Web Part works asynchronously to avoid making the user wait during query results retrieval, but you also have the option to switch to a synchronous query pattern.

Advanced Workflows SharePoint


A dependency property is a property that makes use of a shared repository for the workflow’s state

Namespace: System.Workflow.ComponentModel

Dependency Properties

A dependency property is a property that makes use of a shared repository for the workflow’s state

Dependency properties can be defined in three ways:

  1. Standard Property
  2. Metadata Property
  3. Attached Property

Custom Actions for SharePoint Designer 2010

You can write custom workflow activities  in Visual Studio of your own, making them available as custom actions in SharePoint Designer 2010,


BaseClass: Activity

Important Method to override : Execute
protected override ActivityExecutionStatus Execute( ActivityExecutionContext executionContext) { }

XML manifest file: .ACTIONS extension.


Custom Conditions for SharePoint Designer 2010

A custom condition is just a logical condition that allows the workflow to perform a specific action only if the condition evaluates to true.

user interface of SharePoint Designer 2010 rendering the sample custom condition.

Workflow Event Receivers

A workflow event receiver is a custom class that inherits from the SPWorkflowEventReceiver.

WorkflowStarting Occurs after a workflow instance is starting.
WorkflowStarted Occurs after a workflow instance has been started.
WorkflowPostponed Occurs after a workflow instance has been postponed.
WorkflowCompleted Occurs after a workflow instance is completed.

Workflow Services

It would be better to have an infrastructural service that decouples the communication between the workflow and the CRM. In addition, the time delay spent waiting for the offer code from the external CRM shouldn’t burden the workflow engine.

The external data exchange infrastructure makes use of the CallExternalMethod and HandleExternalEvent activities

The offers approval workflow, extended with the CRM integration.


Base Class: SPWorkflowExternalDataExchangeService
Base abstract class WorkflowSubscriptionService

public override void CallEventHandler(Type eventType, string eventName, object[] eventData, SPWorkflow workflow, string identity, System.Workflow.Runtime.IPendingWork workHandler, object workItem) {}


Workflow Service Deployment

The deployment of a workflow service requires you to build a strongly-named assembly in
order to install the assembly file into the GAC. Next, you need to configure the workflow service
in the web.config of the web application

<WorkflowService Assembly="Dev.SP2010.ExternalCRMService, Version=,
Culture=neutral, PublicKeyToken=665aa2h4h32k420cb" Class="Dev.SP2010.


NOTE:  You can define a feature receiver with a WebApplication scope to automatically configure the web.config file
The SharePoint Server Object Model provides a class named SPWebConfigModification specifically for the purpose configuring the contents of the web.config file automatically.

Full Trust Proxies SharePoint

The architecture of sandboxed solutions provides the capability to utilize external full-trust proxies, deployed and authorized by farm administrators so that you can provide full-trust code execution capabilities to sandboxed solutions.

Full-trust proxies can be installed by farm administrators only,

Implementing a Full-Trust Proxy

Namespace: Microsoft.SharePoint.UserCode
Base Class: SPProxyOperation base abstract class

public class RetrieveNWindCustomers : SPProxyOperation {
public override object Execute(SPProxyOperationArgs args) {
// Operation that require more security rights compar to a SandBox Solution


After implementing the proxy, you need to define a feature with a feature receiver that will
use some custom code for registering it in the farm


Consuming the Full-Trust Proxy

Example: A Web Part that employs the full-trust proxy

   1:  public class ShowNWindCustomers : WebPart {
   2:  protected override void CreateChildControls() {
   3:  RetrieveNWindCustomersArgs args =
   4:  new RetrieveNWindCustomersArgs() {
   5:  SqlConnectionString = this.SqlConnectionString,
   6:  };
   7:  // Invoke the proxy operation
   8:  DataSet data = SPUtility.ExecuteRegisteredProxyOperation(
   9:  typeof(MYPROXYCLASSNAME).Assembly.FullName,
  10:  typeof(RetrieveNWindCustomers).FullName,
  11:  args) as DataSet;
  12:  // ....................
  13:  }
  14:  }

Assembly and Solution Validator SharePoint


Namespace: Microsoft.SharePoint.UserCode

Base Class: SPSolutionValidator,


public virtual void ValidateAssembly(SPSolutionValidationProperties properties,
SPSolutionFile assembly);
public virtual void ValidateSolution(SPSolutionValidationProperties properties);


ValidateAssembly : Validates a single assembly

ValidateSolution: Validate entire solution

To deploy a solution validator you need to select a farmlevel solution and add a farm-level feature.

A solution validator must be registered in the environment, and for this purpose, you can use
a Windows PowerShell script or a custom feature with a feature receiver, both registering the
solution validator by using the SharePoint Server Object Model.

28 Sep 2011

Removing the seconds from DateTime


date = date.AddSeconds( - date.Second));


DateTime date = DateTime.Now;
Console.WriteLine("Date without seconds = {0}", date.AddSeconds(- date.Second));

25 Sep 2011

Claims-Based Authentication SharePoint


architecture of a system with externalized authentication

The externalized authentication provider is generally defined as the Identity Provider (IP) and often publishes a Security Token Service (STS).

The application or software solution externalizing the authentication process is called Service Provider (SP) or Relying Party (RP).

The consumer, who uses the SP authenticating with the IP is generally called the Subject

Web Services Federation Language 1.1 (WS-Federation):  “defines mechanisms to
allow different security realms to federate, such that authorized access to resources managed
in one realm can be provided to security principals whose identities are managed in other

Active Requestor:
Active Scenario (SOAP-oriented) is used by SharePoint 2010 in the service applications’ communication infrastructure.

Passive Requestor:
Web browser based scenario, SharePoint and web/HTTP


sequence diagram of WS-Federation for the Passive Requestor scenario.

Sequence diagram of WS-Federation for the Passive Requestor scenario.

Authorization SharePoint

Authorization in SharePoint is based on Permissions Levels,

Permission Levels can be assigned to users (SPUser) or groups (SPGroup).

A Permission Level is made of a set of permissions,

SharePoint 2010 defines a default set of Permission Levels:

  • View Only View pages, list items, and documents. Document types with server-side
    file handlers can be viewed in the browser but not downloaded.
  • Limited Access View specific lists, document libraries, list items, folders, or documents
    when given permissions.
  • Read View pages and list items, and download documents.
  • Contribute View, add, update, and delete list items and documents.
  • Design View, add, update, delete, approve, and customize.
  • Full Control

24 Sep 2011

Authentication and Authorization SharePoint


Supported authentication methods:

Windows Authentication
Providing support for NTML, Kerberos, Anonymous, Basic, and Digest authentication

Forms-Based Authentication (FBA)
There are providers for LDAP and SQL Server; however, you can develop custom providers of your own. FBA is based on the standard forms authentication provided by Microsoft ASP.NET

SAML token-based Authentication
Uses an external identity provider that supports SAML 1.1 and WS-Federation Passive profile, includes Active Directory Federation Services v. 2.0 (AD FS 2.0), LDAP, or custom third-party identity

About Authentication Types

NTLM-integrated authentication is easier to configure— but it is more limited in capabilities

NTLM is based on the user’s password hash and the front-end server does not have the user’s

Kerberos-integrated authentication utilizes a ticketing infrastructure that is not
based on the user’s password.
Get tickets from a Key Distribution Center (KDC).

Authentication mode:


Classic mode

Supports only the Windows Authentication

Single-server deployment : local users’ repository of the server

Farm deployment: Active Directory repository,

Supported Windows Authentication methods: NTLM, Kerberos, Anonymous, Basic, and Digest


Claims-based mode

Supports all the three available authentication methods

Introduced with SharePoint 2010

With the new claims-based mode you can enable multiple authentication methods within the same zone

The Sign In page, in which end users select the authentication method when multiple authentication

It employs the concept of claims identity, representing each user’s identity as tokens made of claims

Claims are issued by a Claim Provider and packaged into a Security Token, which is emitted by a Security Token Service, also known as an Identity Provider

Claim :

    • ClaimType URI that uniquely defines the type of the claim
    • ClaimValue real content
    • ClaimValueType data type of the ClaimValue



Authentication engine of SharePoint normalizes all the users’ identities into SPUser instances, converting every identity into a set of claims

functional schema of the identity normalization process managed by SharePoint 2010


Windows Authentication

Under claims-based authentication mode, the Windows identities will be converted to a set of claims representing the current user.

User ID of the current user. For Windows Authentication, it assumes a value of “0#.w|[Username]”, where the string “0#.w|” is a trailer and [Username] is the user name of the user. The “w” stands for Windows Authentication.

Extracting claims from a current user’s identity.

ClaimsIdentity ci = this.Page.User.Identity as ClaimsIdentity;
if (ci != null) {
this.Controls.Add(new LiteralControl("<h2>Claims</h2>"));
foreach (Claim c in ci.Claims) {
this.Controls.Add(new LiteralControl(
"<div>ClaimType: {0} - ClaimValue: {1} - ClaimValueType: {2}</div>",
c.ClaimType, c.Value, c.ValueType)));


Forms-Based Authentication

Capability to authenticate your users against an external repository of users, which by default can be an LDAP or a Microsoft SQL Server

By default using the standard SQL Membership Provider of ASP.NET
You can also develop custom membership providers

UserID: “0#.f|[MembershipProvider]|[Username]”, where the string “0#.f|” is a trailer, [MembershipProvider] is the name of the configured Membership Provider, and [Username] is the
username of the user. The “f” stands for FBA.

Configuring the SQL Server Database:

You can invoke ASPNET_REGSQL.EXE within the Visual Studio Command Prompt and have it create a SQL Server database file

Web.config of the sample site for configuring FBA

<add name="FBASP2010" connectionString="server=SP2010DEV\SQLEXPRESS;database=FBA_
ClaimsSP2010;integrated security=SSPI;"/>
<membership defaultProvider="FBASQLMembershipProvider">
<add connectionStringName="FBASP2010" applicationName="/"
passwordAttemptWindow="5" enablePasswordRetrieval="false"
enablePasswordReset="false" requiresQuestionAndAnswer="true"
requiresUniqueEmail="true" passwordFormat="Hashed"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

<roleManager enabled="true" defaultProvider="FBASQLRoleManager">
<add connectionStringName="FBASP2010" applicationName="/"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<authentication mode="Forms" />
<deny users="?"/>
<!-- Configuration omitted for the sake of brevity -->


Configuring SharePoint web.config Files

Web.config located in the C:\inetpub\wwwroot\wss\VirtualDirectories folder of every front-end server


<add name="FBASP2010" connectionString="server=SP2010DEV;database=FBA_
ClaimsSP2010;integrated security=SSPI;"/>


<membership defaultProvider="i">
<add name="i" type="Microsoft.SharePoint.Administration.Claims.
SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" />
<add connectionStringName="FBASP2010" applicationName="/"
passwordAttemptWindow="5" enablePasswordRetrieval="false"
enablePasswordReset="false" requiresQuestionAndAnswer="true"
requiresUniqueEmail="true" passwordFormat="Hashed"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
<add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider,
Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add connectionStringName="FBASP2010" applicationName="/"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />


Following web.config needs to be configured:

  1. web.config of the target web application
    Location: C:\inetpub\wwwroot\wss\VirtualDirectories

  2. web.config of the SharePoint Central Administration web application 
    Location: C:\inetpub\wwwroot\wss\VirtualDirectories

  3. web.config of the internal Security Token Service (STS) of SharePoint
    Location: SharePoint14_Root\WebServices\SecurityToken folder.

Configuring SQL Server Permissions

Enable the Windows identities configured for:

  1. SharePoint Central Administration Application Pool

  2. Security Token Service Application Pool

  3. Target Web Application Application Pool

Set for following database role memberships:

  1. aspnet_Membership_FullAccess

  2. aspnet_Roles_FullAccess

Configure the FBA providers through the SharePoint Central Administration interface

Application Management-> Manage Web Applications –> choose the FBA target—>
on the Ribbon click the Authentication Providers command

Edit Authentication configuration page of the SharePoint Central Administration.
Edit Authentication configuration page of the SharePoint Central Administration.

Enabling FBA Users or Roles

Notice that if you now try to browse for users or roles, you will be able to browse both
Windows and FBA users within the same browsing windows

Select People And Groups dialog with multiple authentication providers configured.

21 Sep 2011

Workflow Forms SharePoint


A. Custom .ASPX forms

You can use the same workflow solution with both Microsoft SharePoint Foundation 2010
and Microsoft SharePoint Server 2010

B. Microsoft InfoPath 2010

It don’t support SharePoint Foundation 2010



Association Form

Association form provides the default configuration parameters for automatic startup

Initiation Form

The initiation form targets end users and is presented to them when they manually start a workflow instance.

Modification form

Modification form is useful when you need to change the configuration of a workflow
instance that is already running

Sequential workflow with custom approval


It will be presented to the administrative users while associating the workflow with its target list or Content Type.

C# code behind the out-of-the-box association form page

   1:  public partial class OffersApprovalAssociationForm : LayoutsPageBase {
   2:  // Private fields declaration omitted for the sake of simplicity
   3:  protected void Page_Load(object sender, EventArgs e) {
   4:  InitializeParams();
   5:  }
   6:  private void PopulateFormFields(SPWorkflowAssociation existingAssociation) {
   7:  // Optionally, add code here to pre-populate your form fields.
   8:  }
   9:  // This method is called when the user clicks
  10:  // the button to associate the workflow.
  11:  private string GetAssociationData() {
  12:  // TODO: Return a string that contains the association data that
  13:  // will be passed to the workflow. Typically, this is in XML format.
  14:  return string.Empty;
  15:  }
  16:  protected void AssociateWorkflow_Click(object sender, EventArgs e) {
  17:  // Optionally, add code here to perform additional steps
  18:  // before associating your workflow
  19:  try {
  20:  CreateTaskList();
  21:  CreateHistoryList();
  22:  HandleAssociateWorkflow();
  23:  SPUtility.Redirect("WrkSetng.aspx", SPRedirectFlags.RelativeToLayoutsPage,
  24:  HttpContext.Current, Page.ClientQueryString);
  25:  }
  26:  catch (Exception ex) {
  27:  SPUtility.TransferToErrorPage(String.Format(
  28:  CultureInfo.CurrentCulture, workflowAssociationFailed, ex.Message));
  29:  }
  30:  }
  31:  protected void Cancel_Click(object sender, EventArgs e) {
  32:  SPUtility.Redirect("WrkSetng.aspx", SPRedirectFlags.RelativeToLayoutsPage,
  33:  HttpContext.Current, Page.ClientQueryString);
  34:  }
  36:  }

Workflow Task Forms

Every time a workflow needs to query its users, it assigns them a task.

Workflow Task provides a standard user interface as well as standard fields,
such as Predecessors, Priority, Status, % Complete, and so on. In a real workflow solution, you
probably need to prompt end users with a custom user interface and with custom fields.

  1. Display Form

  2. Edit Form

Workflow Association SharePoint

Associate Workflow with List

Browse to the Settings page of the target list and select the Workflow Settings menu item, under the Permissions And Management menu group

Associate the workflow with a target list


Workflow Versioning



Remove option
Forcibly remove the workflow association without waiting for any running
instances to conclude, the workflow engine of SharePoint will terminate running instances


No New Instances
It prevent new instances of the workflow,
Just after the completion of all the running instances, you can forcibly remove the association.

Correlation Tokens

The hosting environment determines the right workflow instance to deliver the event to, based on that instance ID and the correlation token

Using a correlation token that correlates all the activities related to a specific task
will help the runtime and the workflow instance to uniquely identity the target task inside the
workflow and the corresponding target activity for the event.


Site Workflows

You need to start them manually. To start such workflows, go to the View All Site Content page and select the Site Workflows command

You can start the workflow, provide initiation parameters (if there is an initiation form page), and monitor the workflow status page and history list.

19 Sep 2011

Workflows Architecture SharePoint


WF-Workflow Foundation Overview

Proposed by Microsoft since .NET Framework 3.0.

WF is the foundation for creating custom workflow-enabled solutions

Current version of Workflow Foundation (also known as WF4) is the one that is shipped together with Microsoft .NET Framework 4.0. It is a completely fresh new engine, which is absolutely not compatible with the previous versions of WF (WF 3.0/WF 3.5, or WF 3.x).

However, SharePoint 2010 still uses the previous version of the workflow engine that is WF 3.x


Workflow Foundation Architecture

WF workflow is a set of elements called activities

Simplified overall architecture of WF 3.x.

The main and native runtime services offered by WF 3.x are

  • Loader
  • Scheduler
  • Persistence
  • Tracking
  • Commit Work Batch
  • Communication

Native Activities Offered by WF in . NET 3

  • CallExternalMethod
  • Code
  • Compensate
  • CompensatableSequence
  • ConditionedActivityGroup
  • Delay
  • EventDriven
  • EventHandlingScope
  • FaultHandler
  • HandleExternalEvent
  • IfElse
  • InvokeWebService
  • InvokeWorkflow
  • Listen
  • Parallel
  • Policy
  • Replicator : Replicator can submit the same approval task to a group of approvers.
  • Sequence
  • Suspend
  • SynchronizationScope
  • Terminate
  • Throw : Throw an exception
  • TransactionScope
  • CompensatableTransactionScope
  • WebServiceInput
  • WebServiceOutput
  • WebServiceFault
  • While
  • ReceiveActivity :  Receives data by using a WCF channel and a specific service
    contract, .net 3.5 feature
  • SendActivity


Workflow Types

  1. Sequential workflow
  2. State machine workflow


Sequential workflow [ SequentialWorkflowActivity]

is a workflow that defines a chronologicallyordered flow. it can only move forward, from the starting activity to the ending activity.

Good choice for those scenarios in which you do need very limited user interaction or no user interaction.

for example : data-intensive activities, machine interaction, conversion processes

State machine workflow [ StateMachineWorkflowActivity]

There are rules for moving between one state and another.
Every time a state machine workflow moves into a specified state, it can execute a custom
sequence of steps before moving to the next state

Example: document approval, multi-step process approval, order processing


imageWorkflow designer of a sample sequential workflow


State machine workflow


Activity lifecycle of an activity instance during workflow execution


Architectural schema of Workflow Foundation 3.x hosted in SharePoint 2010.


Workflow Targets and Association

  1. List or Library
  2. Content Type
  3. Site , Example: scheduled maintenance tasks

Types of workflow associations supported by SharePoint 2010

Each workflow definition comprises an XML definition file, the workflow itself, the assemblies
required for the correct workflow execution, and any UI form.

18 Sep 2011

Developing Service Applications


Service Application Architecture

Service application is new version of the Shared Services Provider (SSP) infrastructure of SharePoint 2007.

A service application is a middle-tier service that can be shared between multiple web application instances of the same farm or even across multiple farms.

All the native services of SharePoint 2010 are implemented as service applications


Architectural schema of SharePoint 2010, based on various native service applications


Architecture of a single service application


A service application shared across multiple farms.

By default, SharePoint 2010 installs and preconfigures a couple of service applications

  • Application Discovery and Load Balancer Service Application
  • Security Token Service Application


To manage the service applications environment, you can use the SharePoint Central

Service Application Framework

This is a framework of classes from which you can inherit to build your custom service applications

Creating a Service Application

The main and fundamental components of a service application are

Service engine

Service database

A set of custom rights

Administrative pages

Management scripts for the Windows PowerShell management console.

A proxy library for consuming the service application.

Consumer page, Web Part, or component to use in sites

Custom Protocol Service Application

Business logic to Integrate SharePoint 2010 with an external protocol engine


imageThe custom service applications’ management page, available in SharePoint Central Administration.


You will learn how to define such a page for your developed service:

Upon clicking the OK button, you will see the Protocol Service Application in the list of configured services. However, to use the service you will need to start it on a server of the farm.


After you activate a service instance on a specific server, the Application Discovery And Load Balancer Service Application will begin announcing the availability of that service instance through that specific server, and you will be ready to consume it.


To develop the service application, you need to define a new solution in Visual Studio 2010.
You should create at least four projects

  1. Service application
    This project defines the service, the service application, and all the management pages and scriptlets. It is based on an “Empty SharePoint Project.”
  2. Service contracts
    If you decide to implement the service application as a WCF service, you will need to isolate the communication contracts to share them between the service application and the service application proxy. This project is based on a “Class Library” project targeting .NET Framework 3.5 for x64 or anyCPU platforms.
  3. Service application proxy
    This project implements the code to invoke the service via the base service application proxy. It is based on an “Empty SharePoint Project.”
  4. Service consumer
    This project will host the consumer’s controls, such as Web
    Parts, Web Part Pages, and so on. It is based on an “Empty SharePoint Project.”

17 Sep 2011

Site Definitions versus Web Templates SharePoint


  1. Web template requires only the proper rights to upload the .WSP, Web Template is a sandboxed solution
    A site definition requires physical access to the file system of the servers in the farm.
  2. A web template can be deployed and used in the cloud
    A site definition cannot be deployed in a cloud environment (SharePoint Online or Office 365),
  3. A web template can be versioned without affecting existing site instances
  4. Changes in the pages defined in a web template, will be available only in new sites,
    Changing the layout of pages provisioned through a site definition will also affect previously deployed sites
  5. A web template can do almost everything you can do with a site definition.

Site Templates Development SharePoint

SharePoint 2010 provides many ways for defining site models.

You could have a site definition, which is a site model defined on the file system and stored under the folder SharePoint14_Root\TEMPLATE\SiteTemplates of every front-end server.

You could create a web template either using Microsoft Visual Studio 2010
Saving an already existing site instance through a specific page available in the Site Settings page (under the menu item Save Site As Template in the Site Actions menu group).

A web template can also be exported from SharePoint Designer 2010 as a .WSP package.


Native Site Definitions

Native site definitions are stored in the file system of the servers, in the SharePoint14_Root\TEMPLATES\SiteTemplates


The standard dialog for choosing the template for a new subsiteimage


SharePoint load model from the file name like WEBTEMP*.XML in the SharePoint14_Root\TEMPLATE\{IdCulture}\XML folder,


<?xml version="1.0" encoding="utf-8"?>
<!-- _lcid="1033" _version="14.0.4762" _dal="1" -->
<!-- _LocalBinding -->
<Templates xmlns:ows="Microsoft SharePoint">
<Template Name="GLOBAL" SetupPath="global" ID="0">
<Configuration ID="0" Title="Global template" Hidden="TRUE" ImageUrl=""
Description="This template is used for initializing a new site." ></Configuration>


The WEBTEMP*.XML files are just directories of site templates’ configurations. The actual configuration is included in an XML file, named ONET.XML, which is located in the XML subfolder
of every site definition

The ONET.XML file for the standard STS site template defining STS#0.

<Configuration ID="0" Name="Default" MasterUrl="_catalogs/masterpage/v4.master">
<List FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101" Type="101"
QuickLaunchUrl="$Resources:core,shareddocuments_Folder;/Forms/AllItems.aspx" />
<List FeatureId="00BFEA71-6A49-43FA-B535-D15C05500108" Type="108"
Folder;/AllItems.aspx" EmailAlias="$Resources:core,discussions_EmailAlias;" />
<!-- Code omitted for the sake of brevity -->
<Module Name="Default" />
<!-- BasicWebParts Feature -->
<Feature ID="00BFEA71-1C5E-4A24-B310-BA51C3EB7A57" />
<!-- Three-state Workflow Feature -->
<Feature ID="FDE5D850-671E-4143-950A-87B473922DC7" />
<!-- TeamCollab Feature -->
<Feature ID="00BFEA71-4EA5-48D4-A4AD-7EA5C011ABE5" />
<!-- MobilityRedirect -->
<Feature ID="F41CC668-37E5-4743-B4A8-74D1DB3FD8A4" />
<!-- WikiPageHomePage Feature -->
<Feature ID="00BFEA71-D8FE-4FEC-8DAD-01C19A6E4053" />

Site Definitions

Steps to manually create a custom site definition:

  1. You could simply copy an existing site definition folder  from SharePoint14_Root\TEMPLATES\SiteTemplates
  2. Change the ONET.XML file to select the lists definition to use for creating list instances, the modules to provision, and the features to activate
  3. Define a custom WEBTEMP*.XML file and copy it into the proper folder, within SharePoint14_Root\TEMPLATES\{IdCulture}\XML

In custom site templates you should use values equal to or greater than 10000 for the ID attribute, to avoid overriding the IDs of native templates



Site Definitions with Visual Studio


The New Project window of Visual Studio 2010 with the Site Definition project template highlighted.

“How to: Create a Custom Site Definition and Configuration,” available on MSDN Online at http://msdn.microsoft.com/en-us/library/ms454677.aspx

For the site definition, your only choice is a farm solution deployment

The template project outline is made up of the minimal contents for defining a site definition: an ONET.XML file, a WEBTEMP*.XML file, and a default.aspx home page.

Avoid activating the features into the deployment target site, it will be site admin task to use the site template.



Custom Web Templates

The list of available site models is made up of site definitions and web templates

A custom web template is created by exporting the definition of an existing site instance,
with or without its content, and storing the result into the content database as a sandboxed

AdjustHijriDays = "Integer"
AlternateCssUrl = "Text"
AlternateHeader = "Text"
BaseTemplateID = "Integer"
BaseTemplateName = "Text"
BaseConfigurationID = "Integer"
CalendarType = "Integer"
Collation = "Integer"
ContainsDefaultLists = "TRUE" | "FALSE"
CustomizedCssFiles = "Text"
CustomJSUrl = "Text"
Description = "Text"
ExcludeFromOfflineClient = "TRUE" | "FALSE"
Locale = "Integer"
Name = "Text"
ParserEnabled = "TRUE" | "FALSE"
PortalName = "Text"
PortalUrl = "Text"
PresenceEnabled = "TRUE" | "FALSE"
ProductVersion = "Integer"
QuickLaunchEnabled = "TRUE" | "FALSE"
Subweb = "TRUE" | "FALSE"
SyndicationEnabled = "TRUE" | "FALSE"
Time24 = "TRUE" | "FALSE"
TimeZone = "Integer"
Title = "Text"
TreeViewEnabled = "Text"
UIVersionConfigurationEnabled = "TRUE" | "FALSE">

The easiest way to create a WebTemplate feature using Visual Studio is to design the site
in the browser. Then you can save it as a template and export the resulting .WSP package
file, downloading it from the Solution Gallery page of the Site Collection. From there, you
simply need to import the .WSP into Visual Studio, creating a new project of type “Import
SharePoint Solution Package.”

WebTemplate feature has been implemented by Microsoft specifically to satisfy the requirement of deploying web templates through sandboxed solutions.

To customize the web template project, you can manually open the imported ONET.XML file
and change its contents.


File Conversion Services SharePoint

It is a feature of SharePoint2007

“Document Converter Services Overview,” available on MSDN Online at http://msdn.microsoft.com/en-us/library/aa979484.aspx

Developing a custom document converter of your own, you can read the document, “Document Converter Framework Sample,” available on MSDN Online at


Word Automation Services

Supported input formats:
Open XML File Format documents (.docx, .docm, .dotx, .dotm)
Word 97-2003 documents (.doc, .dot)
Rich Text Format files (.rtf)
Webpages (.htm, .html, .mht, .mhtml)
Word 2003 XML Documents (.xml)


supported output formats are:
Open XML File Format documents (.docx, .docm, .dotx, .dotm)
Word 97-2003 documents (.doc, .dot)
Rich Text Format files (.rtf)
Webpages (.htm, .html, .mht, .mhtml)
Word 2003 XML Documents (.xml)
Portable Document Format (.pdf)
Open XML Paper Specification (.xps)



Converts a document from .DOC to .XPS by using the Server Object Model of the Word Automation Services,

   1:  String siteUrl = "http://dev.sp2010.local/";
   2:  String wordAutomationServiceName = "Word Automation Services";
   3:  using (SPSite site = new SPSite(siteUrl)) {
   4:  using (SPWeb web = site.OpenWeb()) {
   5:  SPFile sourceFile = web.GetFile("Shared%20Documents/Source.doc");
   6:  ConversionJob job = new ConversionJob(wordAutomationServiceName);
   7:  job.UserToken = site.UserToken;
   8:  job.Settings.UpdateFields = true;
   9:  job.Settings.OutputFormat = SaveFormat.XPS;
  10:  String sourceUrl = web.Url + "/" + sourceFile.Url;
  11:  String destinationUrl = web.Url + "/" +
  12:  sourceFile.Url.Replace(".doc", ".xps");
  13:  job.AddFile(sourceUrl, destinationUrl);
  14:  job.Start();
  15:  }
  16:  }


How to monitor the status of a conversion job?

   1:  static void MonitorJob(Guid jobId) {
   2:  ConversionJobStatus job = new ConversionJobStatus(
   3:  "Word Automation Services", // Name of the service instance
   4:  jobId, // The JobId to monitor
   5:  null); // Guid of the subscription in case of multiple servers
   6:  Console.WriteLine("Job name: {0}", job.Name);
   7:  Console.WriteLine("Total job activities:\t\t{0}", job.Count);
   8:  Console.WriteLine("Job activities succeeded:\t\t{0}", job.Succeeded);
   9:  Console.WriteLine("Job activities failed:\t\t{0}", job.Failed);
  10:  Console.WriteLine("Job activities in progress:\t\t{0}", job.InProgress);
  11:  Console.WriteLine("Job activities canceled:\t\t{0}", job.Canceled);
  12:  Console.WriteLine("Job activities not started:\t\t{0}", job.NotStarted);
  13:  }


Important Classes:

ConversionJob class, provided by the Word Automation Services’ engine and available in assembly Microsoft.Office.Word [named Microsoft Office 2010 Component]


Document Management


Document Sets

Document set is a special Content Type that holds multiple documents in a unique container

Purpose of document set is to store multiple documents belonging to the same project.

It has a custom user interface based on a dedicated welcome page, dedicated versioning of the entire set, specific workflows, synchronization of metadata between the document set and the items that it contains, and custom behaviors in general.


The basic ID of the Document Set content type is 0x0120D520, because it is inherited from the Document Collection Folder content type (ID 0x0120D5).
Folder content type (ID 0x0120)


Handling Document Sets by Code

namespace Microsoft.Office.DocumentManagement.DocumentSets

Main Members of the DocumentSet Class

Creates a DocumentSet instance object within an existing SPFolder instance.

Exports the current DocumentSet into a packaged (ZIP compressed) file.

Static method that gets the DocumentSet object from a specified SPFolder object.

Import Static method that imports a DocumentSet from a package previously exported
via the Export method.

Exporting a document set into a .ZIP file

   1:  using (SPSite site = new SPSite("http://dev.sp2010.local/")) {
   2:  using (SPWeb web = site.OpenWeb()) {
   3:  SPList library = web.Lists["Work Orders"];
   4:  // Search for items of type Document Set
   5:  foreach (SPListItem item in library.Items) {
   6:  // In case the ContentTypeId of the item inherits from a DocumentSet
   7:  if (DocumentSetTemplate.Id.IsParentOf(item.ContentTypeId)) {
   8:  // Get a reference to the DocumentSet instance
   9:  DocumentSet ds = DocumentSet.GetDocumentSet(item.Folder);
  10:  // Export the item as a .ZIP content
  11:  Byte[] package = ds.Export();
  12:  using (FileStream fs = new FileStream(ds.Item.Title + ".zip",
  13:  FileMode.CreateNew, FileAccess.Write, FileShare.None)) {
  14:  using(BinaryWriter bw = new BinaryWriter(fs)) {
  15:  bw.Write(package);
  16:  bw.Flush();
  17:  }
  18:  }
  19:  }
  20:  }
  21:  }
  22:  }


Document ID – * New feature SharePoint2010

This is a provider-based identifier generator that creates unique identifiers for documents in libraries so that they can be used to retrieve documents independently from their location.

Activate -  Site Collection-level feature, called “Document ID Service,”




Document path based on document ID ( Document Id feature must enabled)
http://{your site URL}/_layouts/DocIdRedir.aspx?ID={Document ID Value}

Custom Document ID Provider


   1:  namespace Microsoft.Office.DocumentManagement {
   2:  public abstract class DocumentIdProvider {
   3:  protected DocumentIdProvider();
   4:  public abstract bool DoCustomSearchBeforeDefaultSearch { get; }
   5:  public abstract string GenerateDocumentId(SPListItem listItem);
   6:  public abstract string[] GetDocumentUrlsById(SPSite site,
   7:  string documentId);
   8:  public abstract string GetSampleDocumentIdText(SPSite site);
   9:  }
  10:  }


After implementing a custom Document ID Provider, you need to register it to make it the
default provider.

Event Receivers SharePoint 2010


All event receivers provides two events Before and After.

Before events ( Synchronous) are those that happen just after the event occurred, but before SharePoint writes any data to the SharePoint content database
Such events are useful for custom validation, rules checking, and cancelation of users’ actions.
Before events run in the same process and thread as the current action
Example: ItemAdding Occurs before an item is going to be added to a list.

After events ( Asynchronous) are those that happen after SharePoint commits the data to the SharePoint content database
After events by default run in a background thread; however, you can force them to run synchronously
Example: ItemAdded Occurs after an item has been added to a list.

Event Receiver Base Classes:


All of these receiver base classes (except for SPEmailEventReceiver and SPFeatureReceiver)
inherit from a common base class named SPEventReceiverBase,



Example: An event receiver that traps ItemUpdating Before and ItemAdded After events

public class ContactItemEventReceiver : SPItemEventReceiver {
public override void ItemUpdating(SPItemEventProperties properties) {
String newEmail = (String)properties.AfterProperties[“Email”];
// Validate the email
      if (!regex.IsMatch(newEmail)) {
          // If it is not valid, cancel the current operation
         properties.Cancel = true;
         properties.ErrorMessage = “Invalid email value!”;
public override void ItemAdded(SPItemEventProperties properties) {

// Action after save
String newEmail = (String)properties.AfterProperties[“Email”];
// send mail



You can create a new Visual Studio 2010 project, selecting the “SharePoint 2010 – Event Receiver” project template




List event receivers are useful to enforce validation rules and policies and help avoid chaos to a website’s structure, you can enforce common naming conventions or common sets of validation rules
to each and every list created from a web browser.

SPListEventReceiver with which you can trap changes to the fields of an existing list as well as
actions related to adding or deleting lists instances.


The Events Provided by the SPListEventReceiver Base Class
FieldAdded Occurs after a field has been added to a list definition.
FieldAdding Occurs before a field is going to be added to a list definition.
FieldDeleted Occurs after a field has been removed from a list definition.
FieldDeleting Occurs before a field is going to be removed from a list definition.
FieldUpdated Occurs after a field has been updated to a list definition.
FieldUpdating Occurs before a field is going to be updated to a list definition.
ListAdded Occurs after a new list has been added to a SPWeb instance.
ListAdding Occurs before a new list is added to a SPWeb instance.
ListDeleted Occurs after a list has been deleted from a SPWeb instance.
ListDeleting Occurs before a list is deleted from a SPWeb instance.


Example : A list-level event receiver that traps field events

public class ContactsListEventReceiver : SPListEventReceiver {
public override void FieldAdding(SPListEventProperties properties) {
// Check if the list template is our custom list template
if (properties.TemplateId == 10001) {
properties.Cancel = true;
properties.ErrorMessage =
“You cannot change this list definition through the web browser”;
public override void FieldDeleting(SPListEventProperties properties) {
// Almost the same code as FieldAdding event
public override void FieldUpdating(SPListEventProperties properties) {
// Almost the same code as FieldAdding event



You can catch some events related to Site Collection deletion, both before and after the action, and for website creation, deletion, moving, and provisioning

Web-level event receivers are usually most useful for enforcing custom policies, custom, layout templates, or checking naming conventions, and restrict the deletion.

The Events Provided by the SPWebEventReceiver Base Class

SiteDeleted Occurs after a Site Collection has been deleted.
WebAdding Occurs before an SPWeb is being added to a list collection.
WebProvisioned Occurs after an SPWeb has been provisioned into a Site Collection.



You can intercept events related to running workflows.

Events Provided by the SPWorkflowEventReceiver Base Class

WorkflowCompleted Occurs after a workflow instance is completed.
WorkflowPostponed Occurs after a workflow instance has been postponed.
WorkflowStarted Occurs after a workflow instance has been started.


Whenever the workflow completes, you can read the CompletionType property from within the WorkflowCompleted event. The property might have any of the following values:



Allow you to intercept events when the list receives e-mail messages.

public class EmailEventReceiver : SPEmailEventReceiver
      public override void EmailReceived(SPList list,  SPEmailMessage emailMessage,  String receiverData)
             if (!validSenders.Contains(emailMessage.Sender))
                  throw new Exception(“Invalid sender email”);
         base.EmailReceived(list, emailMessage, receiverData);

Avoiding Event Loops

If you simply change an item inside an event receiver, such as ItemUpdated event, the event will fire again.

To disable event firing, all the event receivers inherit a Boolean property named EventFiringEnabled from the SPEventPropertiesBase base class.

It’s good practice to always set this flag to false at the beginning of your event receiver code, and then set it back to true at the end of code execution.

Event Deployment and Binding

Technique#1: A feature element file for provisioning a custom event receiver

Technique#2: using custom code


SharePoint 2010 has the ability to deploy an event receiver not only at the web level, but also at the Site Collection level.  except the SPEmailEventReceiver.

Another deployment feature introduced with SharePoint 2010 is the ability to bind an event receiver to a list template, using its ListTemplateId property,