Category: Webparts

Ajax Webpart displays Webservice data

In this post I want to show how to create an Ajax Webpart, which receives its data from a Webservice – and until the data arrived – shows a status bar.

As base for the Webpart, I took the one from Mark Collins and his great article

The approach is to render the Webpart with only a <DIV>, and let the client – after it finishes querying the Webservice – fill the data into the <DIV> previously created.

The original version from Mark Collins comes without server side controls. I created the <DIV> as a HTMLGenericControl, because I wanted to have more control over it (and I was curious if it worked).

The basic stays the same. Long running operations are moved from your normal Webpart to the RaiseCallbackEvent method.

string GetCallbackResult()





void RaiseCallbackEvent(string eventArgument)


this._AjaxData = CalculateContent();


The content returned by the CalculateContent Method is a simple string, which the clients renders later into the <DIV> element.

string CalculateContent()


string returnString = string.Empty;




TextWriter tw = new

HtmlTextWriter _TxtWriter = new


_Grid = new

_Grid.DataSource = GetGridDataSource();


// catch if the grid datasource is empty

if (_DS == null)


"<IMG src=\"/_layouts/images/BROKENLINK.GIF\" border=\"0\"/> no data received";





returnString = _TxtWriter.InnerWriter.ToString();


catch (Exception ex)


_ErrorText += "Error in CalculateContent:\r\n:" + ex.ToString() + "\r\n";

returnString = _ErrorText;



return returnString;


This approach has a big disadvantage. You cannot use sorting, paging and filtering in the SPGridView, because it is created on the client side. You can use grouping, though. So what can we do about sorting and paging?

  • Sorting can be realized with a Webpart property, which takes the sort field an order, and sorts the underlying DataSet/DataView.

if (!String.IsNullOrEmpty(_SortString))


string[] sortArray = _SortString.Split(‘;’);

if (sortArray.Length == 2)


SortExpression = sortArray[0];

SortDirection = sortArray[1];

if (DataSetContainsField(_DS, SortExpression))


_DS.Tables[0].DefaultView.Sort = SortExpression + " " + SortDirection;




  • Filtering is also realized with a Webpart property, and modifying the DataSet/DataView

if (!String.IsNullOrEmpty(_FilterString) && _FilterString.Contains("="))


string filterColumnName = _FilterString.Substring(0, _FilterString.IndexOf(‘=’));


// catch typos in the filter

if (DataSetContainsField(_DS, filterColumnName))


_DS.Tables[0].DefaultView.RowFilter = _FilterString;



  • Paging: As soon, as I find a better solution, I will tell you about it J

Download the code here.

Webpart Development

Visual Studio Extensions

If you want to write your own Webpart, you can start from scratch with a Class Library, or use the templates from

The downside of this VS templates is, that they can only be used on a computer, which has SharePoint installed, and you cannot open a project created with the VS templates with a VS on which the templates are not installed.

Server side controls

Ishai Sagi wrote a great article about Webpart development. His article is about server side controls and data binding in Webparts.

Here is the link to his great article:


Mike Ammerlaan shows in his article how to integrate Ajax in SharePoint, and how to create a simple Ajax Webpart.

He also explains how to use UpdatePanels with Ajax, and how to disable the default SharePoint form action.

Ajax #2


In this post I’m going to explain how to start using ajax in your web parts. The goal of this article is to reproduce functionality similar to the KPI and BDC web parts in MOSS 2007. If you don’t know what ajax is or the basics of how it works this article is probably not for you.

Extend the simple Webpart

Now that we know how to create a simple Webpart, we want to add more functionality to it. Let us start with some Controls.

  1. Declare a Control as class variable
  2. Create it in CreateChildControls
  3. Modify the Control in OnPreRender
  4. Render the Control with its content

Declare a Control



HtmlGenericControl _MyDiv;


This method creates the control. After the creation, we will be able to access the control from elsewhere, to modify its properties or its content.

void CreateChildControls()




// Create a new instance, and add it to the Controls

_MyDiv = new



Modify the Control

After the control exists, we can modify it.

void OnPreRender(EventArgs e)




_MyDiv.Attributes.Add("style", "padding: 20px; margin: 20px; border-style: groove; background-color: #FFFFFF;");

_MyDiv.InnerHtml = "I like SharePoint";



Finally we render our controls, so that we actually see what we created. If we forget to do so, the controls will be generated, but not visible.

void Render(HtmlTextWriter writer)


// Determines whether the server control contains child controls.

// If it does not, it creates child controls.



// Renders the ChildControls



Deploy and Debug a Webpart to your SharePoint Server

To deploy a Webpart to a SharePoint Installation, complete the 3 steps beneath:

  1. Copy the dll from your Webpart to the bin folder of a webapplication
  2. Register the dll in the web.config as safe
  3. Add the Webpart to the Webpartgallery of a sitecollection
  4. Debug the Webpart

Copy the dll from your Webpart to the bin folder of a webapplication

Copy your dll to the bin folder of your IIS virtual server directory. In my case this is "C:\Inetpub\wwwroot\wss\VirtualDirectories\45079\bin".

If you don’t know where this directory might be, look it up in the IIS Manager.

Register the dll in the web.config

Open the web.config (e.g. "C:\Inetpub\wwwroot\wss\VirtualDirectories\45079\web.config"). Find the <SafeControls> section, and add a line like:

Assembly="simple Webpart HOWTO, Version=, Culture=neutral, PublicKeyToken=2e6fe95c9937e6f4"
Safe="True" />

The Assembly Name and the Namespace can be found in the properties of your project:

Add the Webpart to the Webpartgallery

Go to the Webpartgallery from your sitecollection, and add the new Webpart to your Webpartgallery.

Now you are done J You can add the new Webpart to every site in your sitecollection.

Debug the Webpart

To be able to debug a Webpart, you have to copy the dll (which was compiled in debug mode) and the pdb to the bin folder of your virtual server.

The easiest way is to set the output path for your debug configuration in the VS to the bin folder (step one from this post).

  1. Set the output path

  1. Build your Webpart
  2. Attach the VS to the Application Pool which the SharePoint site uses
    If you are unsure which w3wp you should attach the VS to, you can look it up in the IIS Manager. You can find the user in the application settings from your virtual server.





  1. Set a breakpoint and reload the site in your browser


  • Every time you deploy your Webpart, the application pool will recycle. So deploy with care, or – better – use a testsystem to develop and test your webparts.
  • While your breakpoint is active, the whole application pool will stop executing requests to every website, which uses that application pool.

Create a simple Webpart HOWTO

In this blog post, I want to show you how to create a simple Webpart. All you need is a Visual Studio 2005 (e.g. the express version) and of course SharePoint.

  1. Start your VS and create a new "Class Library"
  2. Add a reference to the Microsoft.SharePoint.dll. We will create a SharePoint Webpart, to be able to add Properties.
  3. To display some text, override the render method. You have to create a reference to the Microsoft.Web.dll, and type using System.Web.UI;

namespace simple_Webpart_HOWTO


public class Class1:WebPart


protected override void Render(HtmlTextWriter writer)


writer.Write("I like SharePoint.");




  1. (optional) Rename Class1 to some better name like "simpleWebpart". In the solution Explorer you can rename Class1.dll to simpleWebpart.dll
  2. Add [assembly: AllowPartiallyTrustedCallers()] to the AssemblyInfo.cs
  3. Next, we will create a Key, to sign our Assembly and give it a strong name. Open the "Visual Studio 2005 Command Prompt" from the Startmenu.
    sn -k 1024 c:\temp\keypair.snk
  4. Add the created Keypair to your project, and configure it to be signed

    After you build your project, you can extract your public key token with:
    sn -T "C:\PathToYourProject\bin\debug\simple Webpart HOWTO.dll"
    In my case the token is 2e6fe95c9937e6f4


  • ALWAYS put a try/catch block around your code, if it might generate an error. If you don’t, the whole page will display an error, instead of just your Webpart.

catch (Exception ex)


HtmlGenericControl errorControl = new HtmlGenericControl("DIV");

errorControl.Attributes.Add("style", "padding: 20px; margin: 20px; border-style: groove; background-color: #FFFFFF;");

errorControl.InnerHtml = "<IMG src=\"/_layouts/images/error16by16.gif\" border=\"0\"/>" + ex.ToString();



You can download the solution here.

Wiki mit Bildern Update

Falls bei der Benutzung des Webparts ein Fehler wie:

Fehler bei der Anforderung des Berechtigungstyps Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c.

auftritt, muss der Trustlevel in der web.config auf Full gesetzt werden.

<trust level="Full" originUrl="" />

Zum vollständigen Beitrag:

Update 23. Apr 2008:

Ich habe eine neue Version bereitgestellt.

Webpart, Properties and default value

If you write a Webpart with custom properties, you have to take care of the default value.

WebDisplayName("some property"),
WebDescription("Description of the property")]
string PropertyName
get { return _ PropertyName; }
set { _ PropertyName = value; }

Please do not specify a default value, which you might actually use. The default property value will not be saved, if you choose to configure it with the default value!

InfoPath Forms Services – Webpart

Patrick Tisseghem hat in seinem Blog einen interessanten Beitrag zum Thema Office Forms Server gemacht. Zu finden ist der Artikel hier:

Hier die Zusammenfassung:

Um ein Formular auf einer SharePoint Webseite anzuzeigen, muss man nicht erst ein Webpart entwickeln. Die Forms Services nutzen ein ASP.Net Webpart, dass durch den Eintrag

<SafeControl Assembly="Microsoft.Office.InfoPath.Server, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.Office.InfoPath.Server.Controls" TypeName="*" Safe="True" />

in der Web.Config Importiert, und genutzt werden kann.

Genehmigung ausstehend…

Über ein Portal sind diverse Dokumentenbibliotheken – in den Dokumente auf eine Genehmigung warten – verteilt.

Dieses Szenario wird vielen bekannt vorkommen. Ein Lösung habe ich vor einige Zeit geschrieben. Das Webpart zeigt alle die Dokumente an

  1. die auf eine Genehmigung warten
  2. bei denen der Besucher das Recht hat die Genehmigung durchzuführen

Die Lösung ist nicht die schönste, aber sie hat bei mir funktioniert. Und das übrigens für Windows SharePoint Services V2 und den SharePoint Portal Server.

  • In der Konfiguration des Webparts sollte der Account eingetragen werden, unter dem auch der Application Pool läuft
  • Die Installation des Webparts muss mit der Option "-globalinstall" erfolgen

Zum Download: NetatWork.notApproved.CAB