Pages

Friday, 8 April 2011

Create a Custom WebPart in SharePoint(WSS 3.0)

In this post we will learn how to Create a Custom WebPart in SharePoint

Step 1: Create the Webpart

The first step is to create the WebPart. Below is the code snippet of a webPart. So we need to reference the ‘WebParts’ , the custom webpart class should inherit from ‘WebPart’ class and finally we need to override the ‘CreateChildControls’ method with our custom implementation.


using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;------>Refer to "WebParts" namespace

namespace ClassLibraryWebpart
{
    [Guid("fe3f223e-1646-4398-b759-57992fc9436e")]
    public class SimpleLabelWebPart:WebPart---->Inherit from "WebParts" class
    {
        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()---->Override the                                                                                                                                        "CreateChildControls" methods
        {
            base.CreateChildControls();
//we have implemented a simple logic by creating a lable and adding it to controls collection
            Label lbl = new Label();
            lbl.Text = "Hey this is the lable";
            this.Controls.Add(lbl);
        }
    }

}

Step 2 : Copy the compile DLL to the virtual directory in the BIN folder.

The second step is to copy the compiled DLL in the virtual directory of the sharepoint site.

You can get the virtual directory from the IIS from home directory tab in IIS. For instance the current website is hosted on the sharepoint 80 virtual site which is actually located at ‘C: \Inetpub\wwwroot\wss\VirtualDirectories\80’.

So now let’s browse to ‘C: \Inetpub\wwwroot\wss\VirtualDirectories\80\bin’ directory and copy the DLL in the bin folder.

Step 3: Make entry of the WebPart in to web.config file.

Now that we have copied the DLL to ‘bin’ folder , we need to make a ‘SafeControl’ entry in the ‘Web.Config’ file of the virtual directory.

So now let’s browse to ‘C:\Inetpub\wwwroot\wss\VirtualDirectories\80’ , open the web.config file and add the class library name in the ‘SafeControls’ section of the web.config file. Below code snippet shows the same in a visual manner.

<SafeControl Assembly="ClassLibraryWebpart" Namespace="ClassLibraryWebpartVersion=1.0.0.0, Culture=neutral, PublicKeyToken=d488f7bf0d4a4166" TypeName="*" Safe="True" />

Step 4: Add it to the WebPart gallery

Now that we have added the WebPart in the ‘web.config’ file its time to make it available in the web part gallery. So click on Site settings à then click webparts à Click new button, you should see the figure shown below.

You can also see the webpart which you recently added is seen the gallery. To make it available click the check box and click populate gallery.



You should now see your webpart ( for this context it is SimpleLabelWebPart) in the WebPart gallery.

Step 5: Add the WebPart to site pages.

Ok so now that our WebPart is available in the gallery it’s time to add this WebPart to a SharePoint page. So goto the page where you want to add this WebPart , click on the site action menu and click edit page as shown in the below figure.

On the page you should see a ‘Add a webpart’ button , click on it and it will populate with the existing web parts. Browse to your web part and click add.

Once done your webpart is now added to the site page. You can edit the default webpart properties by clicking on ‘Modify Shared WebPart’. For simplicity sake we have changed the title.

Step 6: View the WebPart

You can see the changed title display when view the page normally. So with a few lines of coding you can see how we have achieved huge customization.

Thursday, 7 April 2011

Server and Site Architecture: SharePoint Object Model Overview

Microsoft SharePoint Foundation offers a highly structured server-side object model that makes it easy to access objects that represent the various aspects of a SharePoint Web site. From higher-level objects, you can drill down through the object hierarchy to obtain the object that contains the members you need to use in your code.

The following diagram shows the SharePoint Foundation server architecture in relation to the collections and objects of the Microsoft.SharePoint.Administration namespace.




  1. The SPFarm object is the highest object within the SharePoint Foundation object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.
  2. Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.
  3. Each SPService object represents a logical service installed in the server farm. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, the database service, etc. and also objects for Web services, such as the basic content publishing Web service which supports the Web applications.
  4. An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.
  5. If the service implements the Service Application Framework of SharePoint Foundation, then it can be split into multiple configured farm-scoped instantiations (CFSIs). Each of these provides the functionality of the service but each has its own individual permission and provisioning settings.
  6. Each instance of a service, or a CFSI, that is running on a specific server is represented by an SPServiceInstance object.
  7. An SPDatabaseServiceInstance object represents a single instance of a database service running on the database server computer. TheSPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.
  8. Each SPWebApplication object represents a Web application hosted in an Internet Information Services (IIS) Web site. The SPWebApplication object provides access to credentials and other farm-wide application settings. 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.
  9. An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a Web application. The Sitesproperty gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.
  10. An SPSiteCollection object represents the collection of site collections within the Web application.

The following diagram shows the SharePoint Foundation site architecture in relation to the collections and objects of the Microsoft.SharePoint namespace.




  1. Each SPSiteobject, despite its singular name, represents a set of logically related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The SPSite.OpenWebmethod of the SPSite class returns a specific Web site.
  2. Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.
  3. Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.
  4. Each SPField object has members that contain settings for the field.
  5. Each SPListItem object represents a single row in the list.

Important Classes In SharePoint Object Model

Here are some of the important classes in the Object Model:

SPFarm:

The SPFarm object is the highest object within the Windows SharePoint Services object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.


SPServer:

Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.


SPService:

Each SPService object represents a logical service or application installed in the server farm. A service object provides access to server farm-wide settings of the load-balanced service that a respective service instance implements. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, Microsoft SQL Server, the database service, etc. and also objects for Web services, such as Windows SharePoint Services or services in the Microsoft Office system.


SPWebService:

An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.


SPDatabaseServiceInstance:

An SPDatabaseServiceInstance object represents a single instance of a database service running on the server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.


SPWebApplication:

Each SPWebApplication object represents a load-balanced Web application based in Internet Information Services (IIS). The SPWebApplication object provides access to credentials and other server farm wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property collection of content databases used in the Web application. The SPWebApplication class replaces the obsolete SPVirtualServer class; but it can still be helpful to think of a SPWebApplication object as a virtual server; that is, a set of one or more physical servers that appear as a single server to users.


SPContentDatabase:

An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a SharePoint Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.


SPSiteCollection:

An SPSiteCollection object represents the collection of site collections within the Web application. The Item property or indexer gets a specified site collection from the collection, and the Add method creates a site collection within the collection.


SPSite:

Each SPSite object, despite its singular name, represents a set of logically related SPWeb objects. Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The Microsoft.SharePoint.SPSite.OpenWeb method of the SPSite class returns a specific Web site.


SPWeb:

Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.


SPList:

Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.


SPField:

Each SPField object has members that contain settings for the field.


SPListItem:

Each SPListItem object represents a single row in the list.

Writing a simple Event Receiver in SharePoint


What is Event handling ?
The ability to catch certain user actions in code and respond programmmatically. These are the classes which we can inherit and write event handlers or receivers against them.


SPItemEventReceiver
SPListEventReceiver
SPWebEventReceiver
Which user actions you can catch?
ItemFileMove,IFMoving, ItemUpdated,ItemUpdating, ItemCheckedIn/Out, ItemCheckingIn/ItemChecingOut,ItemAdded,IAdding, ItemAttachementAdded/Adding, ItemDeleted/Deleting.
What is template id for customlist, document library, survey?
100 Custom List 101 Document Library 102 Survey 103 Links List 104 Announcements 105 Contacts
106 Events List 107 Tasks List 108 Discussion Board 109 Picture Library
Explain the steps for creating event handlers?
1) Create a class library project.
2) Add reference to Microsoft.Sharepoint.dll
3) Inherit the class SPItemEventReceiver
4) Override the method against which you want to attach the event handler.
e.g. for itemdeleting
namespace MyEventHandler{
public class ItemDeletingHandler : SPItemEventReceiver{
public override void ItemDeleting(SPItemEventProperties properties){
// We want to attach the eventhandler against a document library
// named MyDocumentLibrary
if(properties.ListTitle == “MyDocumentLibrary”){
// only the admin user has right to delete the uploaded document
if (!properties.UserLoginName.Contains(“domainnameadminUserName”)){
properties.ErrorMessage = “You don’t have sufficient privelege to delete on list “+properties.ListTitle;
properties.Cancel = true;}}}}}
5) Sign the assembly and put it in GAC i.e. c:windowsassembly
6) Create a new folder with the same name as your eventhandler at the following path
c:program filescommon filesmicrosoft sharedweb server extension12templateFeatures folder
7) Create two files feature.xml and elements.xml at the newly created folder.
8) Take feature.xml file of announcement and make the necessary changes to it.
<?xml version=1.0 encoding=utf-8?>
<Feature Id=C50FF499-B52A-471f-A9FB-36A49E2FA49F
Title=MyEventHandler
Description=For restricting delete of a list
Scope=Web
<ElementManifests>
<ElementManifest Location=Elements.xml/>
</ElementManifests>
</Feature>
9) Within elements.xml specify
<?xml version=1.0 encoding=utf-8?>
<Receivers ListTemplateId=101>
<Receiver>
<Name>MyEventHandler</Name>
<Type>ItemDeleting</Type>
<SequenceNumber>20000</SequenceNumber>
<Assembly>
MyEventHandler, Version=1.0.0.0,
culture=neutral, PublicKeyToken=e185cb2eba5d0774
</Assembly>
<Class>MyEventHandler.ItemDeletingHandler</Class>
<Data></Data>
<Filter></Filter>
</Receiver>
</Receivers>
</Elements>
Get the values for assembly tag by right clicking the assembly and selecting properties within the GAC.
If we have multiple eventhandler attached to a same event we can specify which handler should be executed first through SequenceNumber tag. It’s value should start from 20000
10) Now install the feature
stsadm.exe -o installfeature -filename MyEventHandlerfeature\Feature.xml
11) Activate the feature
stsadm -o activatefeature -filename MyEventHandlerfeature\Feature.xml -URL http://localhost.

That’s it…