Basic SharePoint Web Part and Feature - Step by Step

By Phill Duffy on Jul 21 2008 | 1 Comments

In this example we will be creating a very simple SharePoint Web Part and feature. It is going to touch on a lot of areas which will need further explanation, this setup is going to be purely functional with a bit of extra information. Areas which need explaining will have their own entry soon and linked from here.

I am going to be using Visual Studio 2005 and the code will be written in C#

OK, here goes...

Screen Shot

This is what we want to achieve. It may not look much but it is the basis to get you started 

image

The Steps - Part 1 - Setting it up

  • Open Visual Studio 2005

  • Create a new class project

    Visual C# > Windows > Class Library , Enter a name i.e 'TheWebPart', Click OK

    image 

  • Next add a reference to System.Web

  • The class created is named Class1, we will change this to something more appropriate. Rename the class to SimpleWebPart in both the code and the Class1.cs file

    image

  • We want to inherit from the Web Part class, add it to your main class like in the image. You can type in WebPart (case sensitive) and because we are reference the System.dll it will show you a little red tab which will add the using line in for you. If you are referencing the SharePoint dll then it will ask you which WebPart class you want to use, you should use the one from System.Web.

    image 

  • Lets add some code so it does something, this is a very basic 'Hello World' type example, in the next tutorial we will start getting to the more interesting things we can do with SharePoint and Web Parts.

  • Add the following code to override the CreateChildControls method and add our own LiteralControl so that we can display some text in the Web Part:

    	using System.Web.UI.WebControls.WebParts;
    	using System.Web.UI;
    	namespace TheWebPart
    	{
    	public class SimpleWebPart : WebPart
    	{
    	protected override void CreateChildControls()
    	{
    	LiteralControl literalControl = new LiteralControl();
    	literalControl.Text = "I am a WebPart";
    	Controls.Add(literalControl);
    	}
    	}
    	}
    	

    That is all it is going to do, it is going to say 'I am a WebPart'!
  • We are going to be deploying our Web Part dll to the Global Assembly Cache (GAC), this is purely for ease of demonstration, by placing the dll in the GAC we are effectively saying the Web Part can run any code it wants to. Usually you will want to add the dll to the Bin directory and, if required, use Code Access Security to only allow it to perform the required actions.

    To be able to add our dll to the GAC we need to sign our DLL. Take a look at this highly 'arrowed' image on how to do this.
    Right Click on your Class Library in the Solution Explorer > Properties
    Click the Signing Tab > Tick to sign the assembly > Choose 'New' from the drop down list
    Give your key a name i.e 'SimpleWebPart' > uncheck password protection > click OK

    image 

    This will create an SNK file in your solution, done. You can close the properties tab.

The Steps - Part 2 - The Feature

The feature will do most of the deployment work for us, the next step up in deployment is a solution which is a big topic in itself but worth investigating, I will produce a walk through in the near future. The feature we are going to create will be able to be installed using STSADM on our SharePoint Server and can be activated on the Site Collection.

  • Add a folder to your project called 'Features' and then under that folder add yet another folder called 'SimpleWebPartFeature'

  • In the SimpleWebPartFeature add a 'New Item' , that new Item should be an XML file called Features.xml, your solution should look like

    image

  • Open the Feature.xml file, head straight to the properties and make sure you have the WSS schema on, it will help out a lot here.

  • We want to enter our feature code like the following: in the ID you need to use the Create GUID app from the tools menu, it should be in registry format and make sure you remove the braces. example ID would be Id="1FF97ECC-19A0-44bd-9459-0110E0211394" . This unique ID is how your SharePoint will identify your feature, the title and description are easy. The scope has several options, the main two are Site (Site Collection) or Web (Individual site). The Element Manifest is to hold other information our feature deals with.

  • 	<?xml version="1.0" encoding="utf-8"?>
    	<Feature
    	Title="PhillDuffy.com Simple WebPart"
    	Description="An exciting PhillDuffy.com Simple WebPart"
    	Id="13EDED84-94B7-4960-839D-87B71A85A5ED"
    	Scope="Site"
    	Hidden="FALSE"
    	xmlns="http://schemas.microsoft.com/sharepoint/">
    	<ElementManifests>
    	<ElementManifest Location="WebPart.xml" />
    	<ElementFile Location="SimpleWebPart.webpart" />
    	</ElementManifests>
    	</Feature>
    	

  • Add a new xml file into the same folder and call it WebPart.xml, add the following code to it

  • 	<?xml version="1.0" encoding="utf-8" ?>
    	<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    	<Module Name="WebPartPopulation" Url="_catalogs/wp" RootWebOnly="TRUE">
    	<File Url="SimpleWebPart.webpart" Type="GhostableInLibrary">
    	<Property Name="Group" Value="PhillDuffy.com"></Property>
    	<Property Name="QuickAddGroups" Value="PhillDuffy.com" />
    	</File>
    	</Module>
    	</Elements>
    	

    This code adds our web part to the Web Part Gallery upon activation and provides information on which group it will appear in etc
     
  • Finally we want to add another xml file, this time it needs to be called SimpleWebPart.webpart, add the following code to it, with this file we need to add the full assembly name of our DLL. This can be found using the wonderful Reflector tool by Lutz Roeder. Find it, download it, add your dll and copy your assembly name into the type name section. You will need to build your solution before your dll is compiled

    The Type name is as following and is made up of 5 items.

    [NAMESPACE].[CLASS], [FULL NAME FROM REFLECTOR]

    TheWebPart.SimpleWebPart, TheWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c91d316a6fafcb9b

    image

  • 	<?xml version="1.0" encoding="utf-8" ?>
    	<webParts>
    	<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    	<metaData>
    	<type name="TheWebPart.SimpleWebPart, TheWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c91d316a6fafcb9b" />
    	<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    	</metaData>
    	<data>
    	<properties>
    	<property name="Title" type="string">PhillDuffy.com Simple WebPart</property>
    	<property name="Description" type="string">PhillDuffy.com Simple WebPart</property>
    	</properties>
    	</data>
    	</webPart>
    	</webParts>
    	


    Please note the Type will be unique to you. This XML based file holds simple information about our web part such as the dll to use and some display information.
     
  • Our Solution Explorer will look like this, with any luck :)

     image

The Steps - Part 3 - Safe Control

 

  •  
  • Navigate to your Web Applications web.config file and open it up in Visual Studio, here we want to add a Safe Control for our Web Part, this tells SharePoint that our Assembly is safe to use.

    Find the bottom of the SafeControl section and add your own like the following, my safe control entry looks like this, again the Assembly information can be taken from Reflector.

    <SafeControl Assembly="TheWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c91d316a6fafcb9b" Namespace="TheWebPart" TypeName="*" Safe="true" />

    image

  • Close the Web.config file

The Steps - Part 4 - Deployment, Installation and Activation

  • Add a post build command on your Class Library Project to copy our Feature structure to the 12 hive

    xcopy "$(ProjectDir)\Features" "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES" /y /s

    Now when you build your project the deployment files are in the correct location

  • In our Project we need to manually drag and drop our compiled and signed dll into the GAC, this can be done by bring up to explorer windows, one with your dll in from your Bin folder and the other one open in C:\Windows\Assembly, just drop your DLL into the assembly and make sure it has gone it. When you update your code all you need to do is replace the DLL in the GAC.

  • Next we Install the feature to our SharePoint server

  • Bring up a command prompt and type:

    cd "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN"

    Once you are here you can type the following to install our feature

    stsadm -o installfeature -name SimpleWebPartFeature

    This will add the feature so that it can be activated on a Site Collection, the Web Part will not be available to us until we actually activate the feature.

  • Navigate to your site collecion go to Site Actions > Site Sites > Site Collection Features

    Find our 'PhillDuffy.com Simple WebPart' and click activate it.

  • Navigate back to your Page

    Site Actions > Edit Page > Add Web Part > Find the Web Part and add it!!! We are done!!


    image image


    Please, please... If you find any mistakes, if anything does not make sense or needs explaining leave a comment. Also if you appreciate the effort, let me know too :)

Post info

Categories:

Comments

HariHaraDeep India on 7/21/2009 6:43 AM Hi Phill,

Fantastic blog post, Very much helpful for the beginners.

Good Job.

hariharadeep