Tuesday, January 29, 2013

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.

Sunday, January 27, 2013

SharePoint 2010 - WebParts Overview

In this post we will  discuss about the fundamentals of Webparts in SharePoint 2010.

Webparts
A Web Part, also called a Web Widget, is an ASP.NET server control which is added to a Web Part Zone on Web Part Pages by users at run time. The controls enable end users to modify the content, appearance, and behavior of Web pages directly from a browser. It can be put into certain places in a web page by end users, after development by a programmer.

Types of Webparts
There are 2 types of webparts in SharePoint.
1) ASP.Net Webparts: These webparts are built on top of ASP.Net and inherit from the WebPart base class in the System.Web.UI.WebControls.WebParts. We can use these web part to create rich and highly reusable custom webparts.
2) SharePoint Webparts:  These Web Parts inherits from the WebPart base class in the Microsoft.SharePoint.WebPartPages namespace. These Web Parts can only be used in SharePoint websites to provide backwards compatability with MOSS 2003 webparts.

Webpart Archietecture
Following figure shows the overall architecture of a SharePoint Webpart.

Where, the main components supporting Webparts are:
1) Webpart Zones
To be able to fully utilize a Web Part in a page, you need to define a WebPartZone control, which is a container for a set of Web Parts.
2) Webpart Manager
Another fundamental control in the Web Parts architecture is the WebPartManager, which handles all the tasks related to Web Parts lifetime management, such as loading/unloading and serializing/deserializing their state within the current page, and connecting Web Parts into Web Part Zones. The WebPartManager control has been redefined in SharePoint into a custom implementation called SPWebPartManager, which handles some specific activities exclusively available in SharePoint.
3) Webpart Page
In order to leverage these controls, SharePoint also provides a custom page type called WebPartPage (available in the Microsoft.SharePoint.WebPartPages namespace) that includes a preconfigured and unique instance of a SPWebPartManager control and the main Web Part Zones, which are useful for rendering a page made of Web Parts.

Webpart Life Cycle Events
1) OnInit: Configuration values set using WebBrowsable properties and those in web part task pane are loaded into the web part.
2) LoadViewState: The view state of the web part is populated over here.
3) CreateChildControls: All the controls specified are created and added to controls collection. When the page is being rendered for the first time the method generally occurs after the OnLoad() event. In case of postback, it is called before the OnLoad() event. We can make use of EnsureChildControls() - It checks to see if the CreateChildControls method has yet been called, and if it has not, calls it.
4) OnLoad: User Generated Event  for e.g. button click on the web part.
5) OnPreRender: Here we can change any of the web part properties before the control output is drawn.
6) RenderContents: Html Output is generated.
7) SaveViewState: View state of the web part is serialized and saved.
8) Dispose: UnLoad.

Webpart Life Cycle Stages
Based on the events mentioned aove following are the webpart life cycle pages.
1) Initialization Stage
Web Part’s OnInit() is called BEFORE the Page’s OnInit()
The SPWebPartManager loads and applies any personalization settings
2) Loading Stage
Web Part’s OnLoad() is called AFTER the Page’s OnLoad()
3) Render Stage
CreateChildControls() is called.
OnPreRender() is called AFTER the page’s OnPreRender()
RenderContents() is called.

Adding a Webpart
Following are the steps to create a webpart page and add a webpart to it. In this example we will use the in-built content editor webpart.

1) Open SharePoint site and click on Site Action . From Site Action drop down select more option

2) Select Page option and then select Web Part page. And click on Create

3) Give a name of your choice to the page. Select a layout template. Select Share Document as place to save this page and click on Create.

4) You will get page template as below, if you have selected the same layout as of mine.

5) Click on Add a Web Part and select Media and Content from categories

6) Now in Content Editor type the text.

7) Stop Editing the page. Web part will be displayed as follows.
Hope you like this post!

Wednesday, January 23, 2013

SharePoint 2010 - Server Object Model: Common Practices

Today we will  go through some of the common practices that must be followed to effectively use server object model.

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

Monday, January 21, 2013

SharePoint 2010 - Object Hierarchy

In the previous post we had glimpse of the Server and Site architectures in Server Object Model. Lets take one step further and explore the Object Hierarchy in OM.

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();
            }
        }
    }
}



Friday, January 18, 2013

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

Wednesday, January 16, 2013

SharePoint 2010 - Developer Tools


In this post we will analyze the suitable developer tools for creating rich SharePoint Applications.

Though SharePoint is pure web development and any web editor can be used, still developers usually stick to  the main 2 development tools.

Visual Studio
Enables development using "SharePoint Object Model" with any of the supported server side languages (C#, VB.NET etc). You can quickly create...
  • Windows\console application, Webparts, Workflows, Features etc using object model
  • Site Definitions
  • Site Actions
  • and more...


SharePoint Designer
SharePoint Designer 2010 is a specialized HTML editor and web design freeware for creating or modifying Microsoft SharePoint sites and web pages. Using SPD 2010 you can develop SharePoint solution without using any code. Using SPD 2010 you can easily...
  • Create Dataview Web Parts for displaying list data.
  • Easy creation of  designer Workflows.
  • Easily Connect with External Data using BCS.
  • Customize SharePoint web forms (New, Edit, Display) 
  • Coding with Javascript and Jquery Scripts.
  • and more...


Tuesday, January 15, 2013

SharePoint 2010 - Lists and Libraries

In today's post we will discuss about Lists and Libraries in SharePoint 2010 Server.

SharePoint 2010 - Lists

What is a List?
A List is a collection of items and resemble database tables in structure and behaviour. List is the basic storage mechanism in SharePoint. You can create your own custom fields or content types to store data.
Lists can be configured to filter, sort or group items based on item data or properties.

Creating a new List
Go to SiteActions->Create. Opens a new dialogue for creating list. Choose a template of your choice, type a name for your list and click on the "create" button.

As you can see in the following figure, I have chosen the "Announcement" template and named my list as "Daily Announcements".

Once you click the "Create" button the list is created and ready for data insertion.

Click on "Add new announcement" link.

Add more data to the list.


Standard List Templates
Following are the Standard Template that you can choose while creating a new list.
1) Announcements: A list for publishing news items and information.
2) Calendar: A calendar that lets users schedule meetings and events and set deadlines. You can synchronize a Calendar list with Microsoft Outlook.
3) Contacts: A list of people, including their addresses. You can synchronize a Contacts list with Microsoft Outlook.
4) Custom List: This uses a “blank” list model, meaning that you can create whatever type of list that you like by defining custom columns and views.
5) External List: A list that supports reading and managing data from external data sources via Business Connectivity Services.
6) Links: A list that stores hyperlinks to sites and resources.
7) Survey: A list to create surveys, polls, or lists of questions. This type provides features for viewing a graphical summary of the responses.
8) Tasks: A list of tasks to execute, with deadlines, notes, and completion status.

Properties of a List
Following are some of the main properites of a list:-
1) Columns: You can define a set of custom columns describing the metadata of each item of the list.
2) Folders: Like file system folders, they can be used to partition data in subfolders. Through folders, you can also define custom permissions and partition data visibility.
3) Content Types: These are models of data that can be used to store different kind of items within a unique list instance. For example, you could have contacts of various types, such as customers, suppliers, employees, and so on. They could share some common columns, and have some specific columns, too.
4) Views: Every list can render with various views. A view can be used to group items by a specific field value or Content Type, to filter and/or order items, page the results, and so forth.
5) Permissions: Each list can have its own set of permissions, which can be different from the default permissions applied to the site.
6) Versioning: The list can keep track of changes and versions of items.
7) Workflows: These are business processes that execute when an item is created or modified.
8) Content Approval: This is a content approval engine that you can use to enrich content provisioning, adding approval rules and processes.
9) Alerts: An alerting infrastructure that you can employ to alert people about new, updated or deleted contents.
10) RSS Feeds: This provides the capability to subscribe to and monitor a feed from any kind of feed aggregator.
11) Offline capabilities: You can elect to keep data offline using tools such as Outlook or SharePoint Workspace.
12) Office Integration: This provides the ability to integrate list contents with Excel, Access, and other Office applications.
13) E-mail–enabled libraries: You can configure a document library to automatically receive e-mails, storing the messages, and optionally any attachment, as a document in the target library.

Custom Lists
Custom Lists are blank lists with the minimal set of fields required by SharePoint. By default, a Custom
List has only three public and visible fields, which are:
1) Title: This is a mandatory field that defines a title for each item in the list. It is useful for rendering list items and for accessing the contextual menu that SharePoint provides for each individual item in a list.
2) Created By: This is an auto-calculated field that stores information about the user who created the current item.
3) Modified By: Another auto-calculated field that stores information about the user who last modified the current item.


SharePoint 2010 - Libraries

What is a Library?
A Document Library is a particular kind of list that is designed to host files instead of generic items. It resembles folder structure and behaviour to store and manage files.

Creating a new Library
Go to SiteActions->Create. Opens a new dialogue for creating Libraries. Choose a template of your choice, type a name for your library and click on the "create" button.

Note:- Creating a library is similar to that of creating list. The only difference is that you upload files instead of entering list items. Also, in a library a few additional features will be available like opening library in windows explorer etc.

Standard Library Templates
1) Asset Library: Asset Library allows you to create a rich media library and lets you create, browse, share, organize and mange images, audio and video files.
2) Data Connection Library: Here you can create, browse, share, organize and manage files that contain information about connecting to external data connections.
3) Document Library: Here you can create, browse, share, organize and manage documents or other files. It also allows creating folders, versioning of documents and check-in/check-out of files.
4) Form Library: Here you store and manage Microsoft Office InfoPath forms (or XML files for use with Microsoft Office InfoPath) for instance business forms like a status report, purchase orders, etc...
5) Picture Library: Here you can upload and share pictures with others and it includes a built-in image viewer.
6) Report Library: Here you can create web pages and reports to track business metrics, goals, KPIs (Key Performance Indicators) and business intelligence information.
7) Slide Library: It allows you to create a library for storing and sharing Microsoft PowerPoint slides.
8) Wiki Page Library: It allows you to create and store customizable pages of content that are linked together and can be edited by several people.

Properties of a Library
Since the Library inherits from parent type "Lists", it will share all the properties of a list as mentioned in the "Lists - Properties" section above.

Common Library Commands
Following are some of the most commonly used commands or actions on a document.
1) New Document: Use this command to create a new document, starting from a document template.
2) Upload Document: Use this command to upload a single document or a set of documents.
3) New Folder: This command creates a new folder for organizing and navigating documents.
4) Edit Document: Use this command to open a selected document using its corresponding editing program. For example, if you have selected a .doc/.docx file, this command opens the file in Microsoft Word.
5) Check Out: This locks others out of the document so that you can have exclusive access to the file in read and write mode.
6) Check In: Releases the exclusive lock on the file, confirming any changes and creating a new version of the file (if file versioning is enabled).
7) Discard Check Out:  Releases the exclusive lock on the file, discarding any changes.
8) View Properties: Use this to see the metadata properties of a selected file.
9) Edit Properties: Edits the metadata properties of a selected file.
10) Delete Document: Deletes one or more selected files.
11) Download a Copy: Downloads a copy of a selected file.
12) Send To: Sends the selected file to a specific destination.

List & Library - Views
Every list has at least one default view that renders the fields of each item, using predefined ordering and filtering criteria. If you choose to create a new view, a page appears that asks you to choose a view format, based on a set of six predefined formats:
1) Standard View: This is the classic view style. You can choose fields, sorting and filtering rules, grouping, paging, and so on. The result will be a webpage.
2) Calendar View: This view shows data in a calendar format (daily, weekly, or monthly). You would likely use this only when you have data related to dates.
3) Access View: This view launches Microsoft Access so users can create forms and reports based on the list’s data.
4) Datasheet View: This view renders data in an editable spreadsheet format (such as Excel), which is convenient for bulk editing.
5) Gantt View: This option creates a view that renders data in a Gantt chart. It is useful primarily when rendering the tasks of a project.
6) Custom View In SharePoint Designer: This option launches Microsoft SharePoint Designer 2010, in which you can design a new view by taking advantage of the full set of capabilities provided by SharePoint Designer 2010.

Content Types
A Content type is a set of columns that define what type of contents are going to be stored in a list or library. A Content Type is a formal definition of a data template or item template.Each time you create a new item in a list or a new document in a library, you are creating an instance of a Content Type. 


Views
You can create a view for a list or a library to manage how data is shown. You can define which all columns need to be shown, specify column order, add filters and sorting, etc. The default view is "All Items" for lists and "All Document" for libraries. You can create create your own custom views too.

The option for creating or modifying view is on the ribbon. Click "Modify View"

The Edit View page pops up and you can make necessary changes in the view.









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

Monday, January 14, 2013

SharePoint 2010 - The content databases, tables and SQL queries

Today we will take a closer look at the content database associated with a SharePoint 2010 Web application and also discuss about some of the important tables, their relationships and some important SQL queries relating them.

The Content Database - Server
Open SQL Server Management Studio and connect to the DB Server configured for SharePoint 2010. You will see a number of databases as shown in the following figure. The databases for SharePoint internal configurations are highlight in red. While other databases are associated with each web application created in SharePoint server including Central Administration Site.


The Content Database - Associated Web application
Lets take an example of the web application("http://home:3000/") we create in the previous post to understand the content DB structure associated with it.

The Content DB associated with our web application is "WSS_Content_3000". As shown in the following figure a content db consist of numerous tables that are internal managed by SharePoint.


The Content Database - Tables
We will discuss a few important tables that exist in every content database.

1) Sites: Holds information about all the site collections for this content database.

2) Webs: Holds information about all the specific sites (webs) in each site collection.

3) Features: Holds information about all the activated features for each site collection or site.

4) UserInfo: Holds information about all the users for each site collection.

5) Groups: Holds information about all the SharePoint groups in each site collection.

6) Roles: Holds information about all the SharePoint roles (permission levels) for each site.

7) AllLists: Holds information about lists for each site.

8) GroupMembership: Holds information about all the SharePoint group members.

9) AllUserData: Holds information about all the list items for each list.

10) AllDocs: Holds information about all the documents (and all list items) for each document library and list.

11) RoleAssignment: Holds information about all the users or SharePoint groups that are assigned to roles.

12) SchedSubscriptions: Holds information about all the scheduled subscriptions (alerts) for each user.
13) ImmedSubscriptions: Holds information about all the immediate subscriptions (alerts) for each user.


The Content Database - Relationships
Following diagram shows the high level relationship between the tables in the content database.


The Content Database - Important SQL Queries
Following are some of the important sql queries that can be used to view the data in Content DB.


1) Query to get all the top level site collections
SELECT SiteId AS SiteGuid, Id AS WebGuid, FullUrl AS Url, Title, Author, TimeCreated
FROM dbo.Webs
WHERE (ParentWebId IS NULL)

2) Query to get all the child sites in a site collection
SELECT SiteId AS SiteGuid, Id AS WebGuid, FullUrl AS Url, Title, Author, TimeCreated
FROM dbo.Webs
WHERE (NOT (ParentWebId IS NULL))

3) Query to get all the SharePoint groups in a site collection
SELECT dbo.Webs.SiteId, dbo.Webs.Id, dbo.Webs.FullUrl, dbo.Webs.Title, dbo.Groups.ID AS Expr1, 
dbo.Groups.Title AS Expr2, dbo.Groups.Description
FROM dbo.Groups INNER JOIN
dbo.Webs ON dbo.Groups.SiteId = dbo.Webs.SiteId

4) Query to get all the users in a site collection
SELECT dbo.Webs.SiteId, dbo.Webs.Id, dbo.Webs.FullUrl, dbo.Webs.Title, dbo.UserInfo.tp_ID, 
dbo.UserInfo.tp_DomainGroup, dbo.UserInfo.tp_SiteAdmin, dbo.UserInfo.tp_Title, dbo.UserInfo.tp_Email
FROM dbo.UserInfo INNER JOIN
dbo.Webs ON dbo.UserInfo.tp_SiteID = dbo.Webs.SiteId

5) Query to get all the members of the SharePoint Groups
(i) All the members in all the SharePoint Groups in a web application.
SELECT dbo.Groups.ID, dbo.Groups.Title, dbo.UserInfo.tp_Title, dbo.UserInfo.tp_Login
FROM dbo.GroupMembership INNER JOIN
dbo.Groups ON dbo.GroupMembership.SiteId = dbo.Groups.SiteId INNER JOIN
dbo.UserInfo ON dbo.GroupMembership.MemberId = dbo.UserInfo.tp_ID

(ii)All the members in each SharePoint Group in a web application.
SELECT dbo.Groups.ID, dbo.Groups.Title, dbo.UserInfo.tp_Title, dbo.UserInfo.tp_Login
FROM dbo.GroupMembership with (nolock) 
INNER JOIN dbo.Groups with (nolock) 
ON dbo.GroupMembership.GroupId = Groups.ID 
INNER JOIN dbo.UserInfo 
ON dbo.GroupMembership.MemberId = dbo.UserInfo.tp_ID

6) Query to get all the sites where a specific feature is activated
SELECT dbo.Webs.Id AS WebGuid, dbo.Webs.Title AS WebTitle, dbo.Webs.FullUrl AS WebUrl, dbo.Features.FeatureId, 
dbo.Features.TimeActivated
FROM dbo.Features INNER JOIN
dbo.Webs ON dbo.Features.SiteId = dbo.Webs.SiteId AND dbo.Features.WebId = dbo.Webs.Id
WHERE (dbo.Features.FeatureId = '00DGEA71-E2FE-42de-9DF3-A44065BE0104')

7) Query to get all the users assigned to roles
SELECT dbo.Webs.Id, dbo.Webs.Title, dbo.Webs.FullUrl, dbo.Roles.RoleId, dbo.Roles.Title AS RoleTitle, 
dbo.UserInfo.tp_Title, dbo.UserInfo.tp_Login
FROM dbo.RoleAssignment INNER JOIN
dbo.Roles ON dbo.RoleAssignment.SiteId = dbo.Roles.SiteId AND 
dbo.RoleAssignment.RoleId = dbo.Roles.RoleId INNER JOIN
dbo.Webs ON dbo.Roles.SiteId = dbo.Webs.SiteId AND dbo.Roles.WebId = dbo.Webs.Id INNER JOIN
dbo.UserInfo ON dbo.RoleAssignment.PrincipalId = dbo.UserInfo.tp_ID

8) Query to get all the SharePoint groups assigned to roles
SELECT dbo.Webs.Id, dbo.Webs.Title, dbo.Webs.FullUrl, dbo.Roles.RoleId, dbo.Roles.Title AS RoleTitle, 
dbo.Groups.Title AS GroupName
FROM dbo.RoleAssignment INNER JOIN
dbo.Roles ON dbo.RoleAssignment.SiteId = dbo.Roles.SiteId AND 
dbo.RoleAssignment.RoleId = dbo.Roles.RoleId INNER JOIN
dbo.Webs ON dbo.Roles.SiteId = dbo.Webs.SiteId AND dbo.Roles.WebId = dbo.Webs.Id INNER JOIN
dbo.Groups ON dbo.RoleAssignment.SiteId = dbo.Groups.SiteId AND 
dbo.RoleAssignment.PrincipalId = dbo.Groups.ID

Note:- It is highly recommended that you never make any changes through SQL interface because improper use might crash SharePoint Site.