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>

Geen opmerkingen:

Een reactie posten