Monday 29 September 2014

SharePoint 2010 - Features Overview

Overview
Feature is a server side functional component which can be installed and activated at various scopes throughout a SharePoint instance. Additionally, a feature can be used to replace a standard control or functionality with your own custom functionality.
For example, the search box which appears in the upper-right corner of every standard SharePoint layout can be replaced with a custom search control.


Scope of a feature
Every feature has an activation scope that can assume one of the following values:
1) Farm - The feature will target the entire SharePoint farm.
2) WebApplication - The feature targets a single web application and all the contained Site Collections.
3) Site - The feature will target a single Site Collection and all of its websites.
4) Web - The feature targets a single website.

Components of feature
1) Feature Manifest (Feature.xml) - Each time you develop a feature, SharePoint at minimum creates an XML file, named Feature.xml and called the feature manifest, and stores it on every front-end web server of the farm in a sub-folder of the SharePoint 14_Root\TEMPLATE\FEATURES directory.
2) Feature Elements (Elements.xml) - These elements correspond to zero or more ElementManifest tags, which are still defined through XML files, and zero or more ElementFile tags, which declare files supporting the feature.

The feature manifest file structure
Following is the structure of a Feature manifest file.
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
ActivateOnDefault = "TRUE" | "FALSE"
AlwaysForceInstall = "TRUE" | "FALSE"
AutoActivateInCentralAdmin = "TRUE" | "FALSE"
Creator = "Text"
DefaultResourceFile = "Text"
Description = "Text"
Hidden = "TRUE" | "FALSE"
Id = "Text"
ImageUrl = "Text"
ImageUrlAltText = "Text"
ReceiverAssembly = "Text"
ReceiverClass = "Text"
RequireResources = "TRUE" | "FALSE"
Scope = "Text"
SolutionId = "Text"
Title = "Text"
UIVersion = "Text"
Version = "Text" >
</Feature>

Properties of Feature Manifest
1) ActivateOnDefault - An optional Boolean attribute with a default value of True. It applies only to Farm-scoped or WebApplication-scoped features anddetermines whether the feature will be activated by default during installation. For WebApplication-scoped features, if this attribute is set to True, the feature will also be activated when a new web application is created.
2) AlwaysForceInstall - This is an optional Boolean attribute with a default value of False. When set to True, it forces the feature to be installed—even if it is already installed.
3) AutoActivateInCentralAdmin - This is an optional Boolean attribute with a default value of False. It defines whether the feature will be activated by default in the Administrative website hosting the SharePoint Central Administration. It does not apply to Farm-scoped features.
4) Creator - This is an optional description of the feature’s creator.
5) DefaultResourceFile - This is optional text that defines the name of a common resource file, usually shared with other features released by the same creator. By default, SharePoint will look for resources in a file in the path SharePoint14_Root\TEMPLATE\FEATURES\FeatureName\Resources, with a file name such as Resources.Culture.resx (the Culture value can be any of the standard culture names defined by the Internet Engineering Task Force (IETF), such as en-US, it-IT, fr-FR, and so on.
6) Description - This is optional text that describes the feature in the features’ management UI. You can define it using a resource string in the form $Resources:ResourceName. For example, if the feature description is a resource item with a key value of “FeatureDescription,” the corresponding value should be $Resources: FeatureDescription.
7) Hidden - This is an optional Boolean attribute with a default value of False. When set to True, the feature will be hidden from the UI and can be activated or deactivated only through the command line tools or by using the Object Model.
8) Id - This is a required attribute of type text, which must contain an ID (GUID) that uniquely identifies the feature.
9) ImageUrl - This is optional text that defines the site-relative URL of an image used to render the feature in the UI.
10) ImageUrlAltText - This is optional text that defines alternate text for the image representing the feature in the UI (see ImageUrl). You can define this using a resource string, just like the Description property.
11) ReceiverAssembly - This is optional text that defines the strong name of an assembly that SharePoint will search for in the Global Assembly Cache (GAC) and that provides a receiver class to handle the feature’s events.
12) ReceiverClass - This is optional text that defines the full class name of a receiver class to handle the feature’s events. SharePoint will search for the receiver class name in the ReceiverAssembly.
13) RequireResources - This is an optional Boolean attribute with a default value of False. It determines whether SharePoint requires that resources exist for the language of the current website or Site Collection to make the feature visible in the UI. This attribute does not affect the capability to activate and manage the feature from the command line or from the object model.
14) Scope - This is a required text attribute. It defines the scope within which the feature can be activated. The possible values are: Farm, WebApplication, Site, and Web. SolutionId This is optional text that defines the ID of the solution to which the features belongs.
15) Title - This is optional text that defines the title of the feature and that is visible in the features’ management UI. It is limited to a maximum length of 255 characters. You can define it using a resource string, as described in the Description property.
16) UIVersion - This is optional text that declares the UI version supported by the feature. The accepted values are 3 (for Windows SharePoint Services 3.0) and 4 (for Microsoft SharePoint Foundation 2010).
17) Version - This is optional text that defines the version of the feature. It can be made of up to four numbers, delimited by periods. For example, it might be 1.0.0.0, 1.0.0.1, and so on.
The feature elements file structure
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Title="My Sample Web Part" Description="Deploys a custom Web Part." Id="c46c270e-e722-4aa0-82ba-b66c8dd61f4e" Scope="Site" Version="1.0.0.0">
<ElementManifests>
<ElementManifest Location="SampleWebPart\Elements.xml" />
<ElementFile Location="SampleWebPart\SampleWebPart.webpart" />
</ElementManifests>
</Feature>

Feature Element Types
Following are the available features elements in SharePoint 2010:
1) ContentTypeBinding - Used to provision a content type on a list defined in a site template. Can be scoped to Site.
2) ContentType - Defines a content type, ready to be used in lists or libraries. Can be scoped to Site.
3) Control - Used to customize the configuration of an existing delegate control, or to declare a new delegate control to override SharePoint’s standard controls. Can be scoped to Farm, WebApplication, Site, and Web.
4) CustomAction - Defines an extension to the standard user interface. For example, you can use CustomAction to define a new button on a ribbon bar, a new menu item on a standard menu, or a new link on a site settings page. Can be scoped to Farm, WebApplication, Site, and Web.
5) CustomActionGroup - Groups custom actions. Can be scoped to Farm, WebApplication, Site, and Web.
6) DocumentConverter - Declares a document converter that can convert a document from a type X to a type Y. Requires some custom development, to implement the converter. Can be scoped to WebApplication.
7) FeatureSiteTemplateAssociation - Allows associating a feature to a specific site template definition for the purpose of provisioning the feature together with the site definition, when you create a new site with that definition. Can be scoped to Farm, WebApplication, and Site.
8) Field - Declares a Site Column definition. Can be scoped to Site.
9) HideCustomAction - Hides an existing custom action defined by another custom action or implemented by default in SharePoint. Can be scoped to Farm, WebApplication, Site, and Web.
10) ListInstance - Provisions an instance of a list definition, together with a specific configuration. Can be scoped to Site and Web.
11) ListTemplate - Defines a list template for the purpose of provisioning a custom lists’ definitions. Can be scoped to Web.
12) Module - Allows provisioning custom pages or files to a site. Module can also be used to deploy configured Web Parts, ListView Web Parts over existing or provisioned lists, NavBar links, custom Master Pages, and to configure properties of the target feature. Can be scoped to Site and Web.
13) PropertyBag - Assigns properties and metadata to items (File, Folder, ListItem, Web) through features. Can be scoped to Web.
14) Receivers - Defines a custom event receiver. Can be scoped to Web.
15) WebTemplate - Allows deploying a website template, even through a sandboxed solution so that it can create site instances based on that template. Can be scoped to Site.
16) Workflow - Deploys a workflow definition on a target site. Can be scoped to Site.
17) WorkflowActions - Defines custom workflow actions for SharePoint Designer 2010. Can be scoped to Farm.
18) WorkflowAssociation - Associates a workflow with its target. Can be scoped to Site, Web.
Features and Solutions Deployment
To deploy a feature, you need to copy the feature’s folder to the SharePoint14_Root\TEMPLATE\FEATURES path of every target server for the feature. When this is complete, you can use the STSADM.EXE command line tool to install and later activate the feature.
Hope this article gave you an overview of the components of a feature. In the upcoming posts we will figure out the steps involved in the development and deployment of a SharePoint 2010 feature.

References
1) Microsoft SharePoint 2010 Developer Reference, by Paolo Pialorsi - Book

SharePoint 2010 - Connectable Web parts

Overview
In SharePoint, a web part can be 'connected' to another web part to provide some information at run-time.  The Provider web part pushes out the contracted information and the Consumer web part is set up to receive and consume the shared information.

Components of Connectable webparts
1) Interface: This custom interface will define the data to be shared from the Provider to the Consumer web part.
2) Provider web part: Implements a data interface - this interface is a definition of the data that will be shared from the Provider web part to the Consumer web part.
Provide a ConnectionProvider method which will expose the interfacing data to the Consumer web part.
3) Consumer web part: ConnectionConsumer method which will receive the interfacing data
Consume the interfacing data and provide enriching details to the user.

Steps for creating connectable web parts

1) Create an Empty SharePoint Project named ConnectedWebparts  in Visual Studio 2010.


2) we add a new C# Interface code class and name it IUser.


Code Snippet
  1. namespace ConnectedWebparts
  2. {
  3.     public interface IUser
  4.     {
  5.         string UserName { get; }
  6.     }
  7. }

3) Add a new web part named WPProvider in the project which will be the provider webpart. Make the changes as highlighted in the figure below.


Code Snippet
  1. namespace ConnectedWebparts.WPProvider
  2. {
  3.     [ToolboxItemAttribute(false)]
  4.     public class WPProvider : WebPart,IUser
  5.     {
  6.         //From the UI, we collect the user selections
  7.         Label lblUsername = null;
  8.         TextBox txtUsername = null;
  9.         Button btn = null;
  10.         protected override void CreateChildControls()
  11.         {
  12.             lblUsername = new Label();
  13.             txtUsername = new TextBox();
  14.             btn = new Button();
  15.             lblUsername.Text = "User name: ";
  16.             btn.Text = "Send User";
  17.             this.Controls.Add(lblUsername);
  18.             this.Controls.Add(txtUsername);
  19.             this.Controls.Add(btn);
  20.         }
  21.         public string UserName
  22.         {
  23.             get { return txtUsername.Text; }
  24.         }
  25.  
  26.         [ConnectionProvider("UserName")]
  27.         public IUser ConnectionProviderMethod()
  28.         {
  29.             // This method will expose the shared data to the Consumer.
  30.             return this;
  31.         }
  32.     }
  33. }

4) Add a new web part named WPConsumer in the project which will be the provider webpart. Make the changes as highlighted in the figure below.


Code Snippet
  1. namespace ConnectedWebparts.WPConsumer
  2. {
  3.     [ToolboxItemAttribute(false)]
  4.     public class WPConsumer : WebPart
  5.     {
  6.         Label lblUser = null;
  7.         IUser oIUser = null;
  8.         //Receive the data from the Provider web part here
  9.         [ConnectionConsumer("UserName")]
  10.         public void ConsumerMethod(IUser user)
  11.         {
  12.             oIUser = user;
  13.         }
  14.  
  15.         protected override void CreateChildControls()
  16.         {
  17.             // Here we utilize the data received from the Provider
  18.             Label lblDisplayText = new Label();
  19.             if (oIUser != null)
  20.             {
  21.                 if (oIUser.UserName != "")
  22.                     lblDisplayText.Text = "Hello " + oIUser.UserName;
  23.                 else
  24.                     lblDisplayText.Text = "Hello Guest";
  25.             }
  26.             else
  27.                 lblDisplayText.Text = "No provider connected";
  28.             this.Controls.Add(lblDisplayText);
  29.         }
  30.     }
  31. }

5) Build and Deploy the solution.

6) Add the Consumer webpart on the webpart page.


7) Add the Provider webpart on the webpart page.


8)  Edit the Provider webpart and connect it to the consumer.

9) Now the 2 webparts have been connected to each other using the interface. In the provider webpart, type a username in the textbox and click "Send User". You can see the name is displayed in the consumer webpart as highlighted in the figure below.

Reference
http://www.c-sharpcorner.com/uploadfile/DipalChoksi/connectable-web-parts-in-sharepoint-2010/
http://www.dotnetcurry.com/ShowArticle.aspx?ID=678

SharePoint 2010 - Handling page display modes in webpart

Overview
As you might already know that a SharePoint webpart page can be rendered in 3 different modes:-
1) Display mode: This is the page mode when the end user is browsing the site;
2) Design mode: This is the page mode when the user can design the page layout;
3) Edit mode: This is the page mode when the end user is configuring/customizing the page and/or its controls.

WebPartManager.DisplayMode Property
To identify the page display mode and render a Web Part accordingly, you need to query the DisplayMode property of the WebPartManager (SPWebPartManager in SharePoint).

Code Sample
Lets take a closer look by creating a simple webpart and analyzing the different display modes.

1) Create an empty SharePoint project and add a classic webpart named "WPDisplayModes".


2) Write the following code in the CreateChildControls() event. Looking at the code you will observe that WebPartManager.DisplayMode Property is used to define functionality for different modes.
i) For Display mode the text will be "You are now viewing the webpart in Page Display Mode."
ii) For Design mode the text will be "You are now viewing the webpart in Page Design Mode."
iii) For Edit mode the text will be "You are now viewing the webpart in Page Edit Mode."

Code Snippet
  1. protected override void CreateChildControls()
  2. {
  3.   if (this.WebPartManager.DisplayMode == WebPartManager.BrowseDisplayMode)
  4.   {
  5.     // Page Display mode
  6.     this.Controls.Add(new LiteralControl(@"<div>You are now viewing the webpart in Page Display Mode.</div>"));
  7.   }
  8.   else if (this.WebPartManager.DisplayMode == WebPartManager.DesignDisplayMode)
  9.   {
  10.     // Page Design mode
  11.     this.Controls.Add(new LiteralControl(@"<div>You are now viewing the webpart in Page Design Mode.</div>"));
  12.   }
  13.   else if (this.WebPartManager.DisplayMode == WebPartManager.EditDisplayMode)
  14.   {
  15.     // Page Edit mode
  16.     this.Controls.Add(new LiteralControl(@"<div>You are now viewing the webpart in Page Edit Mode.</div>"));
  17.   }
  18. }

3) Deploy the webpart. Open the target webpart page in Edit Mode and add the webpart.

4) The webpart page's initial mode will be Design mode, therefore the text displayed in the webpart will be "You are now viewing the webpart in Page Display Mode".

5) Click the webpart menu and choose Edit Web Part.

6) Now the webpart page's mode will be Edit mode, therefore the text displayed in the webpart will be "You are now viewing the webpart in Page Edit Mode."

7) Select "Stop Editing" button on the top-left corner of the page for rendering the page in Display Mode.

8)  Now the webpart page's mode will be Display mode, therefore the text displayed in the webpart will be "You are now viewing the webpart in Page Display Mode."

SharePoint 2010 - Configurable Web Part Properties

WebPart Properties
All Web Parts share a set of common properties that allow you to specify attributes for the appearance, layout, and other information. To view web part properties, click on the web part menu and select Edit web part".


On the right hand side you can see the web part properties window opens. Here you can make the basic changes like adjusting height, width, Title, etc.


Configurable WebPart Properties
Apart from the default properties, you may want to add you own custom properties which can be even used as parameters for the webpart. Configurable Web Parts are used to present a user-friendly interface for Web Parts configuration. The following attributes makes it possible to add custom properties.

The WebBrowsableAttribute class
The WebBrowsableAttribute class instructs the Web Parts infrastructure that the property has to be made available in the Web Part’s configuration panel. 

The PersonalizableAttribute class
The PersonalizableAttribute declares that the property can be personalized and defines the scope of the personalization. There 2 types of scopes:
1) Scope of type User, which means that the property can be personalized on a per-user basis.
2) Scope of type Shared, which means that the property personalization will be shared between all users.
Configurable WebPart Attributes
Following attributes enables the display of the custom properties in web part properties window.
1) [WebBrowsable(true)] - This will hide or show the property on the tool pane.
2) [Personalizable(PersonalizationScope.Shared)] - How the WebPart is configured, which can be per-user (PersonalizationScope.User), or for everyone (PersonalizationScope.Shared). 
3) [WebDescription("Description of List")] - Description for the property.
4) [WebDisplayName("My List Name")] - Label for the property.
5) [Category("Personalized Items")] - This will group your property according to category. If not declared, “Miscellaneous” will be used as the default.
6) [DefaultValue("Default")] - The default value for the property.
 Following are the steps for creating a Configurable Web Part Property :
1) Create two custom lists as follows:
i) "Products" with columns "Title", "Description" and "Price".
ii) "Customers" with columns "Title" and "Address".

2) Open Visual Studio and create a new Visual Web Part named MyVisualWP. In the "MyVisualWpUserControl.ascx" add a GridView control name "gvwProducts".
3) Open the solution in visual studio and modify the code in the Webpart file "MyVisualWP.cs" as follows. i) Add a configurable web part property named "ListName" using [WebBrowsable] attribute.
ii) Modify the CreateChildControls() to change the type of Control to Visual Web Part.
Following is source code for MyVisualWP.cs
Code Snippet
  1. namespace VisualWebpartDemo.MyVisualWP
  2. {
  3.     [ToolboxItemAttribute(false)]
  4.     public class MyVisualWP : WebPart
  5.     {
  6.  
  7.         [WebBrowsable(true),
  8.         Category("Personalize"),
  9.         WebDisplayName("List Name"),
  10.         WebDescription("Custom list name editable by user")]
  11.         [Personalizable(PersonalizationScope.Shared)]
  12.         public string ListName { get; set; }
  13.  
  14.         // Visual Studio might automatically update this path when you change the Visual Web Part project item.
  15.         private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebpartDemo/MyVisualWP/MyVisualWPUserControl.ascx";
  16.  
  17.         protected override void CreateChildControls()
  18.         {
  19.             MyVisualWPUserControl control = Page.LoadControl(_ascxPath) as MyVisualWPUserControl;
  20.             control.MyVisualWebpart = this;
  21.             Controls.Add(control);
  22.         }
  23.     }
  24. }

4) Now, go to the user control code behind file "MyVisualWPUserControl.ascx.cs" and modify code as highlighted below.
i) You will notice that we added a public property for getting the web part.
ii) Then we use the "ListName" property of the web part to specify the list name.
iii) We set the ViewFields property in the SPQuery object to display titles: Title", "Description", "Price"
and "Address".
Following is source code for MyVisualWPUserControl.ascx.cs
Code Snippet
  1. namespace VisualWebpartDemo.MyVisualWP
  2. {
  3.     public partial class MyVisualWPUserControl : UserControl
  4.     {
  5.         public MyVisualWP MyVisualWebpart { get; set; }
  6.         protected void Page_Load(object sender, EventArgs e)
  7.         {
  8.             if (MyVisualWebpart.ListName != null)
  9.             {
  10.                 SPSite oSite = SPContext.Current.Site;
  11.                 using (SPWeb oWeb = oSite.OpenWeb())
  12.                 {
  13.                     SPQuery oQuery = new SPQuery();
  14.                     oQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Description' /><FieldRef Name='Price' /><FieldRef Name='Address' />";
  15.                     oQuery.ViewFieldsOnly = true;
  16.                     SPList oList = oWeb.Lists[MyVisualWebpart.ListName];
  17.                     SPListItemCollection oColl = oList.GetItems(oQuery);
  18.                     gvwProducts.DataSource = oColl.GetDataTable();
  19.                     gvwProducts.DataBind();
  20.                 }
  21.             }
  22.         }
  23.     }
  24. }

5) Deploy the solution and open the web part page in edit mode. 

6) Go to the web part properties and you can see the new custom property that we added.


7) Enter the list name "Products" and click "Apply" button, you will see the items in the Products List are populated in the GridView.
8) Now change the List Name to "Customers" and click "Apply" button. You will see the items in the Customers list will be populated in the GridView.
Note:- The above code defined property that requires the end user to configure the Web Part manually, typing the target list name autonomously and  made use of the standard behaviour of SharePoint and the out-of-the-box CustomPropertyToolPart.
But this is not a user-friendly and error-free approach. The right solution would probably be to provide a drop-down list with all the lists available in the current website, thereby avoiding typo errors and the consequent time consuming debugging tasks.
To customize the Web Parts’ configuration user interface you can create custom classes called "Editor Parts" which are controls hosted in a specific WebPartZone called EditorZone.

SharePoint 2010 - Out of box webparts

Out Of Box (OOB) Webparts
These are the basic in-built components in SharePoint for displaying and managing list data without the need of any custom development. Not all of them will be available depending upon the version of SharePoint installed.

List of OOB Webparts in SharePoint 2010
Following is the list of OOB webparts in SharePoint 2010 along with the category.

List and Libraries
Announcements – Use this list to track upcoming events, status updates or other team news
Calendar – Use the Calendar list to keep informed of upcoming meetings, deadlines, and other important events
Links - Use the Links list for links to Web pages that your team members will find interesting or useful
Shared Documents – Share a document with the team by adding it to this document library
Site Assets – Use this library to store files which are included on pages within this site, such as images on Wiki pages.
Site Pages – Use this library to create and store pages on this site
Tasks – Use the Tasks list to keep track of work that you or your team needs to complete
Team Discussions – Use the Team Discussion list to hold newsgroup-style discussions on topics relevant to your team

Business Data
Business Data Actions – Displays a list of actions from Business Data Connectivity
Business Data Connectivity Filter – Filters the contents of Web Parts using a list of values from the Business Data Connectivity
Business Data Item – Displays one item from a data source in Business Data Connectivity
Business Data Item Builder – Creates a Business Data item from parameters in the query string and provides it to other Web Parts
Business Data List – Displays a list of items from a data source in Business Data Connectivity
Business Data Related List – Displays a list of items related to one or more parent items from a data source in Business Data Connectivity
Chart Web Part – Helps you to visualize your data on SharePoint sites and portals
Excel Web Access – Use the Excel Web Access Web Part to interact with an Excel workbook as a Web page
Indicator Details – Displays the details of a single Status Indicator. Status Indicators display an important measure for an organization and may be obtained from other data sources including SharePoint lists, Excel workbooks, and SQL Server 2005 Analysis Services KPIs.
Status Lists – Shows a list of Status Indicators. Status Indicators display important measures for your organization, and show how your organization is performing with respect to your goals.
Visio Web Access – Enables viewing and refreshing of Visio Web Drawings

Content Rollup
Categories – Displays categories from the Site Directory
Content Query – Displays a dynamic view of content from your site
Relevant Documents – Displays documents that are relevant to the current user
RSS Viewer – Displays an RSS feed
Site Aggregator – Displays sites of your choice.
Sites In Category – Displays sites from the Site Directory within a specific category
Summary Links – Allows authors to create links that can be grouped and styled
Table Of Contents – Displays the navigation hierarchy of your site
Web Analytics web Part – Displays the most viewed content, most frequent search queries from a site, or most frequent search queries from a search center
WSRP Viewer – Displays portlets from web sites using WSRP 1.1
XML Viewer – Transforms XML data using XSL and shows the results

Filters
Choice Filter – Filters the contents of Web Parts using a list of values entered by the page author
Current User Filter – Filters the contents of Web Parts by using properties of the current user
Date Filter – Filter the contents of Web Parts by allowing users to enter or pick a date
Filter Actions – Use the Filter Actions Web Part when you have two or more filter Web Parts on one  Web Part Page, and you want to synchronize the display of the filter results
Page Field Filter – Filters the contents of Web Parts using information about the current page
Query String (URL) Filter – Filters the contents of Web Parts using values passed via the query string
SharePoint List Filter - Filters the contents of Web Parts by using a list of values
SQL Server Analysis Services Filter – Filters the contents of Web Parts using a list of values from SQL Server Analysis Services cubes
Text Filter – Filters the contents of Web Parts by allowing users to enter a text value

Forms
HTML Form Web Part – Connects simple form controls to other Web Parts
InfoPath Form Web Part – Use this Web Part to display an InfoPath browser-enabled form

Media and Content
Content Editor – Allows authors to enter rich text content
Image Viewer – Displays a specified image
Media Web Part – Use to embed media clips (video and audio) in a web page
Page Viewer - Displays another Web page on this Web page. The other Web page is presented in an IFrame
Picture Library Slideshow Web Part – Use to display a slideshow of images and photos from a picture library
Silverlight Web part – A web part to display a Silverlight application

Outlook Web App
My Calendar – Displays your calendar using Outlook Web Access for Microsoft Exchange Server 2003 or later
My Contacts – Displays your contacts using Outlook Web Access for Microsoft Exchange Server 2003 or later
My Inbox – Displays your inbox using Outlook Web Access for Microsoft Exchange Server 2003 or later
My Mail Folder – Displays your mail folder using Outlook Web Access for Microsoft Exchange Server 2000
My Tasks – Displays your tasks using Outlook Web Access for Microsoft Exchange Server 2003 or later

PerformancePoint
PerformancePoint Filter – This web part displays PerformancePoint filters. Filters may be linked to other web parts to provide an interactive dashboard experience. Filter types include lists and trees based on a variety of data sources
PerformancePoint Report – This web part displays PerformancePoint reports. Reports may be linked to other web parts to create an interactive dashboard experience. Report types include: Analytic charts & grids, Strategy Maps, Excel Services, Reporting Services, Predictive Trend charts, and web pages
PerformancePoint Scorecard – This web part displays a PerformancePoint scorecard. Scorecards may be linked to other web parts, such as filters and reports, to create an interactive dashboard experience.
PerformancePoint Stack Selector – This web part displays a PerformancePoint Stack Selector. All PerformancePoint web parts, such as filters and reports, contained in the same zone will be automatically stacked and selectable using this web part.

Search
Advanced Search Box – Displays parameterized search options based on properties and combinations of words.
Dual Chinese Search – Used to search Dual Chinese document and items at the same time.
Federated Results – Displays search results from a configured location
People Refinement Panel – This webpart helps the users to refine people search results
People Search Box – Presents a search box that allows users to search for people
People Search Core Results – Displays the people search results and the properties associated with them.
Refinement Panel – This webpart helps the users to refine search results
Related Queries – This webpart displays related queries to a user query
Search Action Link – Displays the search action links on the search results page
Search Best Bet – Displays high-confidence results on a search results page.
Search Box – Displays a search box that allows users to search for information.
Search Core Results – Displays the search results and the properties associated with them
Search Paging – Display links for navigating pages containing search results.
Search Statistics – Displays the search statistics such as the number of results shown on the current page, total number of results and time taken to perform the search.
Search Summary – Displays suggestions for current search query
Search Visual Best Bet – Displays Visual Best Bet
Top Federated Results – Displays the Top Federated result from the configured location

Social Collaboration
Contact Details – Displays details about a contact for this page or site.
Note Board – Enable users to leave short, publicly-viewable notes about this page.
Organization Browser – This Web Part displays each person in the reporting chain in an interactive view optimized for browsing organization charts.
Site Users – Use the Site Users Web Part to see a list of the site users and their online status.
Tag Cloud – Displays the most popular subjects being tagged inside your organization
User Tasks – Displays tasks that are assigned to the current user.
What’s New – This Web part shows new information from specified lists and libraries
Whereabouts – Use to display Whereabouts information.

Adding a OOB Webparts
For adding a OOB webpart to your SharePoint page you can follow the same steps mentioned in the "Adding a Webpart" section of Webpart Overiew Post.

SharePoint 2010 - Server Object Model: Common Practices

Disposing Resources
The Garbage collector in .NET framework run non-deterministically to clear all unallocated resources in managed code. But in the case of unmanaged code like window handles, files, streams, database connections, sockets, and so on must be released explicitly to avoid performance lags.

Common Practice for Disposing Resources
To invoke Dispose, you should adopt a standard technique, such as one of the following:
1) "Using" Keyword
Writing code with “Using” keyword ensures that any unmanaged resources will be released as soon as they are no longer needed. It also ensures that exceptions can be handled without overloading the environment.
using (SPSite site = new SPSite("http://home:3000/")){
  // Work with the SPSite object; }
The compiler converts the using keyword into a try/finally code block as follows:
  SPSite site = null;
  try {
  site = new SPSite("http://home:3000/");
  // Work with the SPSite object
  }
  finally {
  if (site != null)
  site.Dispose();
  }
2) "Dispose()" Method
To release unmanaged resources the .NET Framework infrastructure provides the IDisposable interface, which exposes a Dispose() method.
public interface IDisposable {
void Dispose();}

Point to remember
1) When you dispose resources with the "using" keyword, we must be careful to remove only those object that we have created. Context based objects need not be removed since SharePoint will handle them.
For example: Following doesnt required disposal.
SPSite objSite = SPContext.Current.Site  // No Disposal needed since Context based.
2) If you want to handle exception then, put the code block inside try..catch since "Using" keyword is converted to only try...finally.
try {
SPSite site = SPControl.GetContextSite(HttpContext.Current);
// Work with the SPSite object
}
catch (SPException ex) {
// Handle exception
}

Exception Handling
The SharePoint Server Object Model provides a base class named SPException, which is the default exception thrown by the SharePoint Server Object Model and is also the type from which almost every specific SharePoint exception inherits.

Common Practice for Exception Handling
1) Catch and handle only those exceptions that you anticipate and can manage. In other words, you should avoid simply catching all exceptions using a catch all block, or an empty catch block.
2) That way, when an exception that you don’t anticipate occurs, it will bubble up to higher-level code that is able to handle it, if any exists.
3) If the exception is unexpected through the entire stack of the current request, it’s best to let the software crash. That is exactly what SharePoint does by default for unhandled exceptions.

4) The Correlation ID (GUID) shown in the above message box refers to the current request context, which you can use to search for the exception in the SharePoint log.
5) The default location for the Microsoft SharePoint 2010 log is in the SharePoint14_Root\LOGS folder. You can search the log manually using any basic text editor.

Concurrency Conflicts
Any server-side code has the potential to serve an unpredictable number of users, so changing data in a back-end DBMS carries the possibility of a concurrency conflict. Concurrency issues can also happen when working with data stored in SharePoint. Thus, due to the nature of SharePoint, which is a web-based product with (hopefully) a large number of concurrent users, it is highly probable that concurrency conflicts will arise while managing SharePoint’s items.

ChangeListItemConcurrently() Method
Observe the following code.
using (SPSite site = new SPSite("http://home:3000/")) {
using (SPWeb web = site.OpenWeb()) {
try {
SPList list = web.Lists["Contacts"];
SPListItem itemToChange = list.GetItemById(1);
itemToChange["Last Name"] += " - Changed!";
// Before Update, simulate a concurrent change
ChangeListItemConcurrently();
itemToChange.Update();
}
catch (SPException ex) {
Console.WriteLine(ex.Message);
}
}
}
When the above code invokes the "Update()" method to save changes, a concurrency conflict exception will be raised because the "ChangeListItemConcurrently()" procedure has already changed that item. The exception will be a "Microsoft.SharePoint.SPException" with this error message:
“Save Conflict. Your changes conflict with those made concurrently by another user. If you want your changes to be applied, click Back in your Web browser, refresh the page, and resubmit your changes.”
In order to solve this exception you must reload the SPListItem from the Content Database and then apply your changes again, just as a web user would do using his web browser.

AllowUnsafeUpdates and FormDigest
Lets analyse the difference between the security mechanism  provided by default and server object model.

The FormDigest field (Default security mechanism)
To avoid cross-site scripting issues, SharePoint applies a security check whenever you change data through the Server Object Model during HTTP requests. In fact, by default, SharePoint web forms use a form digest control to enforce security. The form digest is a hidden field POSTed by SharePoint web forms and checked by the security infrastructure on the server.

What happens to FormDigest in Object model?
When you make changes to objects by using the Server Object Model during an HTTP GET request, this input field will be missing, so by default SharePoint will throw an exception that looks like following: Microsoft.SharePoint.SPException: The security validation for this page is invalid. Similarly, if you send an HTTP POST request with a missing or invalid form digest value, you will receive the same error.

The AllowUnsafeUpdates() Method (Server Object Model)
This behavior applies only during HTTP requests. Therefore, when you reference the Server Object Model in a class library or a batch tool that runs outside of the ASP.NET pipeline, the security check will not occur.
With that in mind, if you are developing a webpage that will respond to HTTP GET requests, or a custom web form page that doesn’t inherit from the WebPartPage type and doesn’t use the Form Digest control, you will need to instruct SharePoint to skip the digest validation; otherwise, your code will not work.
SPWeb web = SPContext.Current.Web
SPList list = web.Lists["DevLeap Customers"];
try {
web.AllowUnsafeUpdates = true;  // Set the Boolean AllowUnsafeUpdates property of the current SPSite or SPWeb to true.
list.Title = list.Title + " - Changed!";
list.Update();
}
finally {
web.AllowUnsafeUpdates = false; // Set the Boolean AllowUnsafeUpdates property of the current SPSite or SPWeb to false.
}

References:
1) Microsoft SharePoint 2010 Developer Reference, by Paolo Pialorsi - Book

SharePoint 2010 - Server Object Model

Overview
As you might already know that the SharePoint 2010 is built upon .Net 3.5 framework and Asp.Net. Therefore, the SharePoint infrastructure provides a rich .Net object model for developing solutions using compatible server side language like (C#, VB.NET etc). This Server Object Model comprises a set of namespaces and classes which must run on a SharePoint server because this is the only server on which the Server Object Model runs; it has some dependencies that are satisfied only on servers in a SharePoint farm.

Startup Environment

  • If you use the default Visual Studio configuration, you should change the Target Framework setting in the Application configuration tab of the project from “.NET Framework 4.0 Client Profile” to “.NET Framework 3.5.” 
  • You should also change the Platform Target setting in the Build configuration tab of the project from “x86” to “x64” or to “Any CPU,” because Microsoft SharePoint 2010 works on 64-bit machines only.
  • The "Microsoft.SharePoint.dll" is the main server object model assembly which comprises of  the following 2 important namespace.
    • "Microsoft.SharePoint" - Consists of classes and members for developing solution in a top level SiteCollection, its subsites or lists (eg: SPSite, SPWeb etc).
    • "Microsoft.SharePoint.Administration" - Consists of classes and members for developing solutions at an admistrative level. (eg: SPFarm, SPServer etc)
  • When you create a SharePoint project in Visual Studio 2010, the "Microsoft.SharePoint.dll" assembly is automatically referenced.
  • On the other hand, for windows Console\WinForm applications, you need to reference "Microsoft.SharePoint.dll" explicitly. You can find it, along with many of the other assemblies, in the SharePoint14_Root\ISAPI folder.

Server Architecture
The following figure gives you a clear idea about the SharePoint Server Architecture with reference to "Microsoft.SharePoint.Administration" namespace.
From the above figure you can summarize the following point:
  • The "SPFarm" object is the highest object within the SharePoint Foundation object model hierarchy.
  • Each "SPServer" object represents a physical server computer. 
  • Each "SPService" object represents a logical service installed in the server farm.The WebApplications property gets the collection of Web applications that run the service.
  • An "SPWebService" object provides access to configuration settings for a specific logical service or application
  • Each "SPWebApplication" object represents a Web application hosted in an Internet Information Services (IIS) Web site. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property gets the collection of content databases used in the Web application.
  • The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property gets the collection of content databases used in the Web application.
  • An "SPContentDatabase" object inherits from the "SPDatabase" class and represents a database that contains user data for a Web application.
Site Architecture
The following figure will give you a better idea about the SharePoint Site Collection Architecture with reference to "Microsoft.SharePoint" namespace.
From the above figure you can easily summarize the following points:
  • The "SPSite" object represents a Site Collection. 
  • 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 "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 "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.
Conclusion
This is just a basic overview of overall Server Object Model architecture. In the next post we will dig in further into the Object Model Hierarchy. Stay Tuned!

References
1) http://msdn.microsoft.com/en-us/library/ms473633(v=office.14).aspx

SharePoint 2010 - Object Hierarchy

Object Hierarchy
Following is the hierarchy in which the classes supporting Server OM reside.


Object Hierarchy - Main Members
  • SPFarm
  • SPServer
  • SPService
  • SPWebApplication
  • SPSite
  • SPWeb
  • SPList
  • SPListItem

SPFarm
SPFarm class belong to the "Microsoft.SharePoint. Administration" namespace refers to a complete Farm. We can create a new farm from scratch or connect to an existing farm.
Connecting to Farm
1) Connect to Existing Farm: (the most common scenario), you provide a SQL Server connection string and the Farm’s secret passphrase to the public static Open() method.
public static SPFarm Open(SqlConnectionStringBuilder connectionString, SecureString passphrase)
Where, The connection string corresponds to the Farm configuration database that is defined while configuring the Farm using the SharePoint 2010 Products Configuration Wizard. It can also be found in the system registry at:
HKLM\Software\Microsoft\Shared Tools\Web Server Extensions\14.0\Secure\ConfigDB\dsn.
2) Connect to Local Farm: we can directly connect to a local Farm, using the static property
SPFarm objFarm = SPFarm.Local 
OR 
SPFarm objFarm = SPContext.Current.Site.WebApplication.Farm
Inside SPFarm
1) SPFarm contains global settings for all the servers, services, and solutions that are installed in a server farm.
2) Its Servers property contains a collection representing all the servers in the environment, and similarly the Services property has a collection representing all the services.
3) The SPFarm class has three child classes:
SPServer, which represents a single server within the farm;
SPService, which gives access to the farm’s services; and
SPSolution, which is used to deploy something to the farm.


SPServer
SPServer represents a server in a SharePoint farm.
We can get a current reference to the SPServer:
foreach (SPServiceInstance objService in SPServer.Local.ServiceInstances)
Console.Writeline("objService.TypeName");
Or, Instantiate any server’s object in a specific farm
SPServer objServer = new SPServer(“MyFarmServer″);


SPService
There are numerous services such as web services or Search Services running inside a SharePoint Server.Each of these services can be referenced through SPServices Object.
SPServiceCollection ObjServiceCollection = SPFarm.Local.Services;
foreach (SPService service in ObjServiceCollection){}


SPWebApplication
In object model, SPWebApplication class refers to each Web application configured in SharePoint. It is the topmost object in the site hierarchy.
SPWebApplication objSPWebApplication = SPContext.Current.Site.WebApplication;
Or
SPWebApplication objSPWebApplication = new SPSite("http://home:3000/").WebApplication;


SPSite
The SPSite represents a site collection. To access an SPSite instance, you can create it using one of the following available constructors:
public SPSite(Guid id);
public SPSite(string requestUrl);
public SPSite(Guid id, SPUrlZone zone); // public enum SPUrlZone {Default,Intranet,Internet,Custom,Extranet}
public SPSite(Guid id, SPUserToken userToken); // SPUserToken is the token for a valid SharePoint user.
public SPSite(string requestUrl, SPUserToken userToken);
public SPSite(Guid id, SPUrlZone zone, SPUserToken userToken);

We can create a new Site instance as follows:
SPSite  objSPSite = new SPSite("http://home:3000/");
 Or
SPSite  objSPSite = SPContext.Current.Site;

Note: When you create an SPSite instance using SPUserToken, you can impersonate the user who owns that token rather than the current user. You can import an SPUserToken instance from a previously exported array of bytes, or you can create one from a generic System.Security.Principal.IIdentity



SPWeb
The SPweb class represent a website or sub-site in a site collection. This class does not have a public constructor. The only way to obtain a reference to a website is through its parent SPSite. The SPSite class provides the OpenWeb() method which has the following overloads:

public SPWeb OpenWeb();
public SPWeb OpenWeb(Guid gWebId);
public SPWeb OpenWeb(string strUrl);
public SPWeb OpenWeb(string strUrl, bool requireExactUrl);

You can use an SPWeb reference to navigate the contents of the website:-
SPSite site = new SPSite("http://home:3000/");
SPWeb web = site.OpenWeb();
Console.WriteLine(web.Title);

You can also use an SPWeb reference to read or change its configuration.
SPSite site = new SPSite("http://home:3000/");
SPWeb web = site.OpenWeb("Samples");
web.Title = web.Title + " - Changed by code!";
web.Update();

Note: While working with the Server Object Model, you are reading and changing an in-memory representation of the current object. Thus, any changes you make will not be applied to the database unless you explicitly request the object to persist its state using the Update method.

SPList
SPList corresponds to a single list instance, whether that is a list of items or a document library.
SPSite site = new SPSite("http://home:3000/");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["MyList"];

Applying Filters on List
SPQuery class is used for  applying  filters on a list while retrieving items. Commonly used properties of SPQuery are:-

  1. Query – Filtering and sorting of data based on conditions.
  2. ViewFields – Retrict the number of fields to be retrieved.
  3. ViewFieldsOnly – If set true, remove the default fields (ID, Created, Modified) in ViewFields.

Sample Code
SPWeb objWeb = SpContext.Current.Web;
SPList objList = objWeb.Lists[“Products"];
SPQuery objQuery = new SPQuery();
objQuery.Query = "<Where><Eq><FieldRef Name='P_Category' /><Value Type='Lookup'>" + strCategory + "</Value></Eq></Where>";
oQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Price' /><FieldRef Name='Description' />";
oQuery.ViewFieldsOnly = true;
SPListItemCollection objColl = objList.GetItems(oQuery);
gvwProducts.DataSource = objColl.GetDataTable();
gvwProducts.DataBind();

Handling Document Libraries
Whenever you use an SPList instance, which corresponds to a document library, you can cast that instance to an SPDocumentLibrary type. When you need to enumerate the files contained in a document library, you can browse the SPListItem elements of the list, accessing their File property, which is of type SPFile.
SPSite site = new SPSite("http://home:3000/");
SPWeb web = site.OpenWeb();
SPDocumentLibrary docLibrary = web.Lists["MyDocs"] as SPDocumentLibrary;
foreach (SPListItem item in docLibrary.Items) {
  Console.WriteLine("{0} - {1}",item.File.Name,item.File.Length);}


SPListItem
SPListItem defines a reference to a specific item of a list.
SPList list = web.Lists["MyList"];
foreach (SPListItem item in list.Items) {
Console.WriteLine(item.Title);}


Sample Code : Programmatic drill down form Farm to List
The following codes drills down the various object in Server Object Model and displays the hierarchy from Farm to ListItems.
Console.ForegroundColor = ConsoleColor.Green;
Console.BufferHeight = 1000;
//Get local farm
SPFarm farm = SPFarm.Local;
Console.Write(farm.Id.ToString("N").ToLower());
//loop Services
foreach (SPService service in farm.Services)
{
    //find WebService
    if (service is SPWebService)
    {
        SPWebService webService = (SPWebService)service;
        //Loop WebApps
        foreach (SPWebApplication webApp in webService.WebApplications)
        {
            Console.Write(webApp.Id.ToString("N").ToLower());
            //Loop Site Collections
            foreach (SPSite site in webApp.Sites)
            {
                Console.Write(site.ID.ToString("N").ToLower());
                //Loop Sites
                foreach (SPWeb web in site.AllWebs)
                {
                    Console.Write(web.ID.ToString("N").ToLower());
                    //Loop Lists
                    foreach (SPList list in web.Lists)
                    {
                        Console.Write(list.ID.ToString("N").ToLower());
                        //Loop Items
                        foreach (SPListItem item in list.Items)
                        {
                            Console.Write(item.UniqueId.ToString("N").ToLower());
                        }
                    }
                    web.Dispose();
                }
                site.Dispose();
            }
        }
    }
}