woensdag 10 november 2010

Building web parts in SharePoint 2010

Introduction

A typical ASP.NET developer will surely know what web parts are. It are reusable components that can be placed on a page and do basically what ever you want. If you really want to get a feel of what web parts are, just open a page in SharePoint, edit it and insert a web part. Just select one from the list and look how it behaves.

Untitled Untitled

When you look at the list of web parts, you will see that you can place any list in the current site as a template on the page. This means that it will show you the contents of that list and you can now completely configure it. Add/Remove the tool bar, change the title, change the view so only items following certain criteria are shown, … .

In SharePoint 2007, you could only add web parts to a so called web part zone. This was a zone added in the page layout in which you could add web parts under each other. You were free to place these zones where ever you liked.
In SharePoint 2010, you have much more freedom. You can place a web part in a web zone as before or you can add a web part in every spot where you can type text. This makes it very easy and fast to build a page.

Types of web parts

Basically you have two types of web parts. In one of the types, you do your visual stuff completely with code. This means you have to position, style and render each and every control in the web part. For very simple ones this could be enough, if you want to do more on the GUI side, this is not the best option.
You can also make use of an ascx user control file in which you can do all your stuff in ASPX. The logic you do in the code behind and the user control is loaded in the web part code file. This allows you to do far more complicated stuff at the GUI side and of course this will be much easier and cleaner.

Creating a visual web part

In Visual Studio 2010, create a new project and select ‘Visual Web part’.

Untitled

In the next step, confirm the location of your test site collection.

Untitled

From now on it’s almost just like ASP.NET. IN the ascx file you can add ASP.NET or your own controls, AJAX, JQuery, … .

If you take a look in the VisualWebPart1.cs file, you will see that the the actual ascx user control will be deployed in the CONTROLTEMPLATES folder in the 14 hive. It is then loaded into the main web part. This technique could of course already be used in SharePoint 2007.

   1: using System;
   2: using System.ComponentModel;
   3: using System.Web;
   4: using System.Web.UI;
   5: using System.Web.UI.WebControls;
   6: using System.Web.UI.WebControls.WebParts;
   7: using Microsoft.SharePoint;
   8: using Microsoft.SharePoint.WebControls;
   9:  
  10: namespace VisualWebPartProject1.VisualWebPart1
  11: {
  12:     [ToolboxItemAttribute(false)]
  13:     public class VisualWebPart1 : WebPart
  14:     {
  15:         // Visual Studio might automatically update this path when you change the Visual Web Part project item.
  16:         private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPartProject1/VisualWebPart1/VisualWebPart1UserControl.ascx";
  17:  
  18:         protected override void CreateChildControls()
  19:         {
  20:             Control control = Page.LoadControl(_ascxPath);
  21:             Controls.Add(control);
  22:         }
  23:     }
  24: }

If you look closely, the visual web part class is inheriting from System.Web.UI.WebControls.WebParts.WebPart. In some code, you might also see web parts that inherit from Microsoft.SharePoint.WebPartPages.WebPart. This class actually extends the ASP.NET web part class with some very specific SharePoint features. Keep in mind it’s recommended you use the ASP.NET web part as a base class. The SharePoint one is only there for backwards compatibility and, as said, some SharePoint specific features:

  • Cross page connections

  • Connections between Web Parts that are outside of a zone

  • Client-side connections (Web Part Page Services Component)

  • Data caching infrastructure, including the ability to cache to the database

If you try to edit a web part, the ‘tool part’ will open on the right side of the screen. In here you can configure each instance of the web part.

Untitled

When building your own web parts, you can add your own variables here. In the VisualWebPart1.cs file, you can add something like this.

   1: [Personalizable(), WebBrowsable]
   2: public String MyProperty { get; set; }

The kind properties you can add in this way are rather limited to some primitive types. If you want to do more stuff (like dropdown boxes), you must create a custom tool part.

Deploying a web part

To deploy a web part, all that is done is placing a ‘web part’ file in the web part gallery. It contains some information about the web part (name, description), which assembly its logic is in and can also define default values for variables contained in the tool part.

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <webParts>
   3:   <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
   4:     <metaData>
   5:       <type name="VisualWebPartProject1.VisualWebPart1.VisualWebPart1, $SharePoint.Project.AssemblyFullName$" />
   6:       <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
   7:     </metaData>
   8:     <data>
   9:       <properties>
  10:         <property name="Title" type="string">VisualWebPart1</property>
  11:         <property name="Description" type="string">My Visual WebPart</property>
  12:       </properties>
  13:     </data>
  14:   </webPart>
  15: </webParts>

In theory, it’s not really necessary to provision this web part file. You can always go to the web part gallery and click ‘New Document’. There you will get a list of all the safe (safe control in web.config) web part assemblies. If you select your custom web part’s assembly, such a web part file will be generated automatically.

Untitled Untitled


Mass updating web parts

A common problem is mass updating web parts when the assembly version changes. When you add a web part to a page, what’s actually saved in that page is a reference to the assembly as defined in the web part file (from the web part gallery).

Now, if at a later time, the version of your web part’s assembly changes, all pages that already had the web part are still referring to the old version. You could of course write a console application that will replace each old web part with the new version but there is am much easier way called ‘assembly redirecting’. In the web.config you can easily define which version of an assembly should be used when the given version is requested.
   1: <configuration>
   2:    <runtime>
   3:       <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
   4:        <dependentAssembly>
   5:          <assemblyIdentity name="myAssembly"
   6:                            publicKeyToken="32ab4ba45e0a69a1"
   7:                            culture="en-us" />
   8:          <!-- Assembly versions can be redirected in application, publisher policy, or machine configuration files. -->
   9:          <bindingRedirect oldVersion="1.0.0.0"
  10:                           newVersion="2.0.0.0"/>
  11:        </dependentAssembly>
  12:        <dependentAssembly>
  13:          <assemblyIdentity name="mySecondAssembly"
  14:                            publicKeyToken="32ab4ba45e0a69a1"
  15:                            culture="en-us" />
  16:           <!-- Publisher policy can be set only in the application configuration file. -->
  17:           <publisherPolicy apply="no">
  18:        </dependentAssembly>
  19:       </assemblyBinding>
  20:    </runtime>
  21: </configuration>

maandag 1 november 2010

Overview of SharePoint features

Features in SharePoint are one of the most import aspects and is surely something you really need to master. You can see features as the building blocks of SharePoint and your custom solutions. Most of the times your solution will be deployed as a (combination of) feature adding extra functionality to the platform.

- Features are the building blocks of your solution
- Features can contain elements like extra menu items, custom list templates, content types, site columns, …
- Features can contain event handlers: in SharePoint you can react on certain events and then do your own stuff. Some of the events you can use: item created, item updated, site created, … . There is a dedicated post for this.
- Features can depend on other features: this means that you can make one big main feature, make your ‘sub features’ hidden and activate them all at once by activating that main feature.
- Features can be stapled: this means that you can link features to certain site templates. If a site based on such a template is created, the features will be activated as well. This technique is mainly used to customize the ‘my site’.

Features are located in the FEATURES folder (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES) on the hard disk of each farm server to which they are deployed. It’s always a good idea to take a peak there and see how the out of the box features are built.

How to create a feature

A feature almost always exists of a feature.xml file which tells something about the feature and a second (collection of) xml file referred to in the feature.xml file which tells what the feature should do exactly. The most important attributes are:

- Title and description
- Scope: your feature can be available on farm, web application, site collection or web level
- Hidden
- ImageUrl: provides a custom icon image in the list of features in SharePoint
- Version

In SharePoint 2007 / Visual Studio 2008 you had to manually create these XML files. With Visual Studio 2010 this has all changed as the development support for building SharePoint solutions has become much better.

To create a new feature in Visual Studio 2010:

- I started from an empty SharePoint project:
Untitled

- Right click on ‘Features’ –> ‘Add feature’
Untitled

- Name the feature and select your scope. The scope depends on which level of the farm the feature needs to be active
Untitled

- Add an elements file by right clicking on your project –> Add –> New item –> in the SharePoint 2010 category –> Empty element
Untitled

The feature.xml file

Here is the feature element definition:

   1: <Feature
   2:   ActivateOnDefault = "TRUE" | "FALSE"
   3:   AlwaysForceInstall = "TRUE" | "FALSE"
   4:   AutoActivateInCentralAdmin = "TRUE" | "FALSE"
   5:   Creator = "Text" 
   6:   DefaultResourceFile =  "Text"
   7:   Description = "Text" 
   8:   Hidden = "TRUE" | "FALSE"
   9:   Id = "Text"
  10:   ImageUrl = "Text"
  11:   ImageUrlAltText = "Text"
  12:   ReceiverAssembly = "Text"
  13:   ReceiverClass = "Text"
  14:   RequireResources = "TRUE" | "FALSE"
  15:   Scope = "Text"
  16:   SolutionId = "Text"
  17:   Title = "Text"
  18:   UIVersion = "Text"
  19:   Version = "Text" >
  20: </Feature>

Please read this MSDN page to explain you what each property means.

The element.xml file

Because there is a lot you can do to extend the SharePoint platform there is not real one single element xml definition. Therefore I thought it would be better to provide you with a list of some of the things you can do with features.

- ListTemplate
- ListInstance
- Module
- ContentType
- Field
- CustomAction
- Receivers
- Control
- FeatureSiteTemplateAssociation
- Workflow
- ContentTypeBinding
- DocumentConverter

Deploying features

In Visual Studio this is all done for you behind the scenes but of course it’s also important to understand a little bit better what is going on. When you are deploying a solution with features via Visual Studio what is actually happening is that the files are copied to the correct location on all necessary servers. This is called ‘installing the feature’. The next step is to activate them and this will actually make your new functionality available.

Activation can happen in different ways:

- Via the GUI
- PowerShell or STSADM command line
- Object Model
- Site definition reference: you can build site templates in XML that reference certain features and activate them when a site based on that template is created
- Feature activation dependency
- Feature stapling