Writing Event Handlers and Attaching/Detaching using Features Tuesday, Sep 28 2010 

In this post, I am going to write an event handler that:

  1. is triggered when an item is added to a document library (i.e. ItemAdded)
  2. sends an email to some email address notifying that an item has been added to the document library
  3. is deployed to a List using SharePoint Features

Okey, lets get started. Create a subsite under your site collection. In the subsite create a Document Library named AlertMe.

JumpStart – > JumpStartWeb -> AlertMe

homepage show

Create the Event Handler:

Go to Visual Studio 2008. Click File -> New -> Project …..and select Class Library:

create proj scr1

Give any name to your project e.g. ”EventHandler.SharePoint.SendEmail.Feature”. This will also become the name of your namespace

enter proj name

Add the directives as shown below:

add reference 4 with all screen changes

Top four directives will already be there.

  1. “Microsoft.SharePoint” is to use sharepoint object model.
  2. “System.Reflection” is to get assembly information as we will need that to register the event handler with the document library.
  3. “Microsoft.SharePoint.Utilities” is to send email from SharePoint.

Your namespace name is the name you selected for your project. Rename Class1 to “EmailAlertsEventHandler” and make it to inherit from SPItemEventReceiver class. Rename the class in Solution Explorer window as well:

You might have noted that SPItemEventReceiver class name appears in black coloured font, that’s because we are missing a reference to Windows SharePoint Services.

Lets add the reference as shown below:


Right click “References” -> in the Solution Explorer window and click Add Reference.

Select Windows SharePoint Services as shown below:

select WSS

As soon as you will add this reference, Microsoft.SharePoint will appear under References and SPItemEventReceiver will change its colour to green which means that it is recognized as a class now.

If you want to see what SPItemEventReceiver contains, press Alt+Cntrl+j, Object Browser window will open. Expand Microsoft.SharePoint -> Microsoft.SharePoint -> SPItemEventReceiver. You will see all the methods in this class in the right hand pane. You will also see the ItemAdded method which we are going to use for our event handler.

obj browser

Alright, lets add a few methods to our class. As you will write “public override” and press space, intellisence will provide for you the list of all methods available in SPItemEventReceiver, as we saw in the Object Browser:

methods auto appear

Select ItemAdded from the list and enjoy the intelligence of VS, you will find a few things automatically done for you:

auto para and base call

Here is the  code for “EmailAlertsEventHandler.cs”:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;
using Microsoft.SharePoint.Utilities;

namespace EventHandler.SharePoint.SendEmail.Feature
public class EmailAlertsEventHandler : SPItemEventReceiver
public override void ItemAdded(SPItemEventProperties properties)

SPListItem myItem = properties.ListItem;
using (SPSite site = new SPSite(properties.WebUrl))
using (SPWeb web = site.OpenWeb())
string emailSubject = "New Items Added to JumpStart";
string emailBody = myItem.Name.ToString() +
" has been added to AlertMe Document Library for your review." + "\n" +
"\n" + "Thanks," + "\n" + "JumpStart EmailAlertsEventHandler!";
SPUtility.SendEmail(web, true, true, "rehman.gul@hotmail.com", emailSubject, emailBody);
catch (Exception ex)


public static void AddOrRemoveEventHandler(SPList list, bool doAdd)
Assembly asm = Assembly.GetExecutingAssembly();
string className = typeof(EmailAlertsEventHandler).FullName;

if (doAdd)
SPEventReceiverDefinition eventDef = list.EventReceivers.Add();
eventDef.Type = SPEventReceiverType.ItemAdded;
eventDef.Assembly = asm.FullName;
eventDef.Class = className;
eventDef.Name = className + "." + eventDef.Type.ToString();
eventDef.SequenceNumber = 10001;
eventDef.Data = null;
List<SPEventReceiverDefinition> eventsToDelete = new List<SPEventReceiverDefinition>();
foreach (SPEventReceiverDefinition eventDef in list.EventReceivers)
if (eventDef.Assembly == asm.FullName && eventDef.Class == className)
foreach (SPEventReceiverDefinition eventDef in eventsToDelete)

As you can see in the code above, there are only two functions ItemAdded and AddOrRemoveEventHandler. ItemAdded opens the web, gets the name of the item which invokes the event handler and sends an email to the specified address. AddOrRemoveEventHandler adds the event handler to the list or removes it, depending on the bool value “doAdd”.

Create the Feature Receiver:

Now how do we attach this Event Handler with a specific list. For that we said we will use Features, such that when the feature is activated, the event handler is attached to our list, and when the feature is deactivated, the event handler is detached from the list.

So, we have to write some code to capture Activate and Deactivate events of the feature. Right click on your project in the solution explorer -> Add -> Class ………..as shown below:

add new class

Select Class, give it a name like EmailAlertsFeatureInstaller:

Add the directives Microsoft.SharePoint, System.Reflection and Microsoft.SharePoint.Utilities on the top as shown below. Inherit the class EmailAlertsFeatureInstaller from SPFeatureReceiver. You can open the Object Browser to see all the methods available in SPFeatureReceiver..

new class with intelli and func

Before I move to add methods to this class, lemme explain what is SPFeatureReceiver doing here. Every feature can have four events i.e Feature Activation, Feature Deactivation, Feature Installation and Feature Uninstallation. Against these four events, SPFeatureReceiver class provides us with four methods respectively i.e. FeatureActivated, FeatureDeactivating, FeatureInstalled and FeatureUninstalling. These methods will be executed as the events take place. So, if we override these methods and put our custom code inside, our custom code will be executed whenever a feature is activated, deactivated, installed or uninstalled.

And thats what we wanted i.e. when a feature is Activated, our event handler gets attached to our AlertMe document library. And when the feature is Deactivated, our event handler is detached from our AlertMe document library.

Here is the full code for EmailAlertsFeatureInstaller.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;
using Microsoft.SharePoint.Utilities;

namespace EventHandler.SharePoint.SendEmail.Feature
class EmailAlertsFeatureInstaller : SPFeatureReceiver
public override void FeatureActivated(SPFeatureReceiverProperties properties)
using (SPWeb web = (SPWeb)properties.Feature.Parent)
SPList list = web.Lists["AlertMe"];
EmailAlertsEventHandler.AddOrRemoveEventHandler(list, true);

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
using (SPWeb web = (SPWeb)properties.Feature.Parent)
List<SPList> webLists = new List<SPList>();
foreach (SPList list in web.Lists)

foreach (SPList list in webLists)
EmailAlertsEventHandler.AddOrRemoveEventHandler(list, false);

public override void FeatureInstalled(SPFeatureReceiverProperties properties)

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)


As you can see we have overriden only two methods of SPFeatureReceiver class i.e. FeatureActivated and FeatureDeactivating. On FeatureActivated we get to our list AlertMe and call AddOrRemoverEventHandler with a ‘true’ value i.e. attach the event handler. On FeatureDeactivating we iterate through all the lists and call AddOrRemoveEventHandler with a ‘false’ value i.e. detach the event handler.

Also, you can see above in the code that we have added FeatureInstalled and FeatureUninstalling methods though there is no functionality added to them. This is mandatory, if you will not add these methods you will receive an error message because these are abstract members of SPFeatureReceiver class and we must implement them in our class.

Alright we are ready to build our project. Try building and it should work.

Put your assembly in the GAC:

Now lets put our assembly (dll) in Global Assembly Cache (GAC) so that it is available to SharePoint. For that we have to strongly name our assembly as it will be placed in a shared location (GAC).

To strongly name your assembly, right click on your project in Solution Explorer window and click Properties:

sign 1

Select Signing at the bottom and fill the check box saying “Sign the assembly”. In “Choose a stong name key file” drop down, select <New…>. In “Key file name” text box, give name of your project (assembly) like “EventHandler.SharePoint.SendEmail.Feature”……..click OK…….as shown below:

sign 2

You will that a file named “EventHandler.SharePoint.SendEmail.Feature.snk” has been added to our project. If you click the file, you will see something similar:

key code

Now our assembly is ready to go to GAC. Go to your working directory on the file system, move to \bin\Debug folder e.g.


Here you will find your assembly i.e. EventHandler.SharePoint.SendEmail.Feature.dll

Open GAC i.e. c:\windows\assembly and drag and drop your dll in the GAC as shown below:



Create the Feature:

Now comes the second part of our project i.e. to create the Feature. Remember, we have created a Feature Receiver until now, Feature itself is still to be created.

All Features in SharePoint lies in 12 hive under Features directory:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES

Browse through a few Feature directories and you will find that all of them have a feature.xml file……and some will also have an elements.xml.

Lets create a Feature of our own. Create a folder under Features directory and name it EventHandler.SharePoint.SendEmail.Feature………..could be any name..

Go inside the folder, right click -> New -> Text Document and rename the text document as feature.xml file. Create another file in the same manner and save it as elements.xml:

feature start

Right click feature.xml file and Open With -> Notepad. Paste the following xml in the file and save:

<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="F2F6FE98-7A4C-4db7-B1E3-BC9C6E5CC9D7"
Title="EventHandler SharePoint SendEmail Feature"
Description="Email Alerts for AlertMe Library"
ReceiverAssembly="EventHandler.SharePoint.SendEmail.Feature, Version=, Culture=neutral, PublicKeyToken=74b4a55dc039bd07"
<ElementManifest Location="elements.xml"/>

Note that you have to be careful about four items in this xml. Feature Id, ReceiverAssembly, PublicKeyToken and ReceiverClass. They could be different in your case, so use the ones that you have.

For PublikKeyToken, go to GAC, take properties of your assembly and copy/paste into your feature.xml.

Feature Id is just a GUID. Here is how you can get one of your own:

Go to Visual Studio, click Tools ->Create GUID. If Create GUID option is greyed out, click Tools -> External Tools. Make the following settings as shown in the figure below and click OK. This will enable Create GUID option.

“Initial directory” in VS 2008 will be
C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\

generate GUID

Click Create GUID and you will receive it as under:

Click copy and paste it into Feature Id in feature.xml as shown above.

Open elements.xml and paste the following xml into it:

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

Install and Activate the Feature:

Alright, coool, our feature is ready to be installed now.

Open the command prompt and move to the Features directory. Enter the following command:

stsadm -o installfeature -name EventHandler.SharePoint.SendEmail.Feature

feature install scr

After you have received the “Operation completed successfully” message, navigate to your site in SharePoint. In my case the heirarchy was JumpStart -> JumpStartWeb -> AlertMe.

So, I’ll move to JumpStartWeb -> Site Actions -> Site Settings ->  under Site Administration click Site Features. You will see your feature available there as shown below:

Click Activate button in front of your feature to Activate the feature:

feature scr activate

Test your Event Handler:

Go to your document library, in my case it is AlertMe and upload a document:

As soon as you upload the file, you should receive an email to the address specified in your event handler:

Hope this helps–

New Features in SharePoint 2010 at a glance Thursday, Sep 16 2010 

Microsoft is releasing a slew of new technologies in 2010, and one of the most important of them is SharePoint 2010. Previously known by the code name SharePoint 14, SharePoint 2010 marks a significant upgrade to the SharePoint product. Here are ten of the most important things about the SharePoint 2010 release, which is expected to be available in the first half of 2010.

10. New SharePoint editions—In an effort to better unify the SharePoint lineup, Microsoft will make some big changes to the SharePoint editions with the 2010 release. Windows SharePoint Server (WSS) is gone, and so is Microsoft Office SharePoint Server (MOSS). The free WSS has been replaced by the new SharePoint Foundation 2010. MOSS is replaced by SharePoint Server 2010, which will be available in either the Standard or Enterprise edition as well as in editions for strictly internal sites and for Internet or extranet sites.

9. New hardware requirements—Like the majority of new Microsoft servers, SharePoint 2010 will ship only as a 64-bit product. If you’re deploying SharePoint on new hardware, this situation shouldn’t be a problem, but it’s definitely a consideration if you’re planning to upgrade an existing SharePoint server.

8. New software requirements—In addition to new hardware requirements, SharePoint 2010 will require an x64 edition of either Windows Server 2008 or Server 2008 R2. It also requires a 64-bit version of Microsoft SQL Server 2008 or SQL Server 2005.

7. SharePoint Best Practices Analyzer—With the SharePoint 2010 release, SharePoint Best Practices Analyzer will be incorporated as part of the base SharePoint product. This tool provides Microsoft’s guidance for SharePoint implementation and troubleshooting. A Problems and Solutions page in the analyzer helps you solve common implementation problems.

6. FAST Search—The new SharePoint release will incorporate the FAST Search technology that Microsoft acquired from the Norway-based Fast Search & Transfer company. The FAST technology provides a superset of the original SharePoint search capabilities. As its name implies, FAST Search is designed for high-end scalability. It supports a number of enhanced capabilities, including a content-processing pipeline, metadata extraction, visual search, and advanced linguistics.

5. Usage reporting and logging—SharePoint 2010 includes a newdatabase designed to support usage reporting and logging. The usage database is extensible, allowing third-party vendors to create custom reports based on the information it contains.

4. Visio Services—Visio Services in SharePoint 2010 lets users share and collaborate on Visio diagrams. A built-in viewer lets SharePoint users view Visio files in their browser without having Visio installed on their system. Visio Services also retrieves and renders any external data used in the Visio diagrams.

3. Enhanced collaboration features—SharePoint 2010 supports tagging content as well as providing enhanced blog authoring capabilities. There’s a new group authentication feature that’s based on distribution list or organization and a new rich text editor for creating wikis. In addition, calendars from Microsoft Exchange Server can be merged with SharePoint calendars.

2. New browser support—SharePoint 2010 supports an extended set of browsers. It’s designed to support XHTML 1.0–compliant browsers and will support Internet Explorer (IE) 8.0 and IE 7.0, Firefox, and Safari. Notably, IE 6.0 isn’t supported. So far, there’s been no official mention of Google Chrome or Opera.

1. Enhanced SharePoint Designer—Microsoft SharePoint Designer 2010 sports a new UI, improved workflow, and improved integration between designers. Although there were doubts about the Office 2007 ribbon-style interface when it was first released, Microsoft has been steadily putting the ribbon UI in many of its products, including SharePoint 2010. The new designer also has a tabbed interface and provides breadcrumb navigation.

Refernce: http://www.windowsitpro.com/article/hardware/new-features-in-sharepoint-2010.aspx

Deleting List Items in a SharePoint List Using C# Thursday, Sep 16 2010 

method for deleting list items.  The trick is to use a decrementing For loop.  The For loop in the following example counts downward (i–) instead of upward (i++), because items are being deleted and the number of items decreases with each increment:

for (int i = list.Items.Count - 1; i >= 0; i--) {

Which produces:


What about deleting an item based on a condition?:

for (int i = list.Items.Count - 1; i >= 0; i--) {
    if (list.Items[i].Title == "Sample Item 5") {
        Console.WriteLine("Deleting {0}", list.Items[i].Title);

It works!:





Hopefully you will always remember to delete list items (actually, the same goes for most other SharePoint collections too, such as SPFieldCollection, SPWebCollection, etc.) using a decrementing counter.  

Happy coding!

For complete article go to: http://www.devexpertise.com/2009/02/04/deleting-list-items-in-a-sharepoint-list/


Sharepoint Object Model Tuesday, Aug 10 2010 

There are several namespaces(around 50) that house the SharePoint object model. Out of these 50 namespaces we are using only 16 namespaces, rest of the namespaces are reserved for Microsoft internal use.

1. Document Library

Document libraries are a special type of list designed to store documents.To access a document library through object model we need to use Microsoft.Sharepoint namespace. To use this namespace in ASP.net we need to add a reference of Microsoft.Sharepoint.dll. This dll we can find from the below mentioned path:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

Let’s take each and every class in this namespace:

  • SPDocumentLibrary Class:This class represents a document library in Windows Sharepoint Services.
    In C# code: SPDocumentLibrary obj = (DocumentLibrary)oList
    oList is an object for list. The above code will cast the list object into Document Library.
  • SPPictureLibrary Class:This class represents a picture library in Windows Sharepoint Services. Both classes are used in the sane manner. The only difference is: As the name indicates SPDocumentLibrary is used for Document Library and SPPictureLibrary is used for Picture Library.

2. Features:

For using the features through Sharepoint object model we need Microsoft.Sharepoint dll and you can get the dll from the above mentioned path.

  • SPFeatureDefinition Class: Contains the base definition of an SPFeature, including its name, identifier, scope, and version
  • SPFeatureScope Class : Specifies the scope to which the feature applies.
  • SPElementDefinition Class: Serves as the base class for implementing element types within Windows SharePoint Services
  • SPFeature Class: Represents the state of a feature at its corresponding scope
  • SPFeatureProperty Class: Represents a single Feature property.

Code Example:

SPSite oSpSite = new SPSite(“http://YourServer&#8221;);
SPFeatureCollection oSPfeatureCollection = oSpSite.Features;

foreach (SPFeature oSPFeature in oSPfeatureCollection)
SPFeatureDefinition featureDefinition = oSPFeature.Definition;
SPElementDefinitionCollection elementDefinitionCollection =

foreach (SPElementDefinition elementDefinition in elementDefinitionCollection)

Ref: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfeatureproperty.aspx


For using meetings through object model we need to add Microsoft.Sharepoint dll as mentioned above. The classes under this category are explained as below:

SPMeeting Class:- Provides methods and properties that can be used to work with a Meeting Workspace. Suppose if you want to create a meeting workspace through object model then we need to use this class. There are different kind of meeting template that can be handled like Basic meeting, Decision Meeting, Multiple meeting etc.

MtgUtility:- Initialize a new instance of the MtgUtility class. To access the MtgUtility service and its methods, set a Web reference tohttp://Server_Name/[sites/][Site_Name/]_vti_bin/xxx.asmx.

Microsoft.SharePoint.Meetings.MtgUtility – System.Object


Sites objects are used to access the sharepoint site, The classes under this category of Sharepoint Object model are explained as below:

SPSite: . Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.

SPWeb: Represents a Windows SharePoint Services Web site.

CODE Example:

using(SPSite oSite = new SPSite(“http://Server_Name&#8221;))
using(SPWeb oWebsite = oSite.OpenWeb(“Website_URL”))
using(SPWeb oWebsiteRoot = oSite.RootWeb)
…//Your Code


Provides administrative types and members for managing a Windows SharePoint Services deployment. There are so many classes, delegates, interface under this namespace but only few classes I am going to explain.

SPSolution : Represents a solution on a farm.

Namespace: Microsoft.SharePoint.Administration

Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)


Base abstract class that can be overridden to trap the activation, deactivation, installation, or uninstallation of a Feature.

Namespace: Microsoft.SharePoint

Assembly: Microsoft.SharePoint

Use the SPFeatureReceiver class to trap events that are raised after the Feature installation, uninstallation, activation, or deactivation action has been performed.

It is not possible to cancel an installation or uninstallation through Feature events.


Represents a collection of SPSolution objects.

Namespace: Microsoft.SharePoint.Administration

Assembly: Microsoft.SharePoint


SPList object represent a List, SPListItem represent a List Item in the List and SPListItemCollection object represent a full item collection in the SPLIST.

Code Example:

SPList mylist_Name = myweb.Lists[“Category”];
SPListItemCollection itmcln = mylist_Name.Items;
foreach (SPListItem itm in itmcln)
if (itm[“ItemCategory”] != null)




This is all about Sharepoint Object Model.

Reference: http://www.c-sharpcorner.com/UploadFile/Ravish001/1376/

Creating Managed-Code UDFs for Excel Services Thursday, Aug 5 2010 

Much like previous versions of Microsoft Office Excel, Microsoft Office Excel 2007 provides support for user-defined functions (UDFs). UDFs are custom functions that extend the calculation and data-import capabilities of Excel 2007. You can use UDFs to:

  • Provide functionality that is not available with the native Excel function library.
  • Build custom data feeds for legacy or unsupported data sources, and application-specific data flows.

In the 2007 Microsoft Office system, you can use Excel Services to build UDFs based on the .NET Framework and deploy these UDFs to Microsoft Office SharePoint Server 2007. These UDFs can be called by Excel workbooks deployed to Excel Services. UDFs can be created to:

  • Call custom mathematical functions.
  • Get data from unsupported data sources such as legacy databases, Microsoft Office Access, and Microsoft SQL Server into worksheets.
  • Call Web services.

Code ItDownload the Code Sample

This section walks through five major steps to illustrate how to create managed-code UDFs for Excel Services:

  1. Create a managed-code UDF project in Microsoft Visual Studio 2005.
  2. Add a reference to the Excel Services UDF assembly.
  3. Create custom functions.
  4. Configure Excel Services to allow UDFs to be used.
  5. Create and publish an Excel workbook that calls UDFs.

1. Create a Managed-Code UDF Project in Visual Studio 2005

You can use the Visual Studio 2005 class library template to easily create an Excel Services managed-code UDF assembly.

To create a managed-code class library project in Visual Studio 2005

  1. Start Visual Studio 2005.
  2. On the File menu, select New, and then click Project. The New Project dialog box appears.
  3. In the Project Types pane, select Visual C# or Visual Basic.
  4. In the Templates pane, click Class Library.
  5. Specify a Name and Location for the project and click OK.

Visual Studio 2005 generates a class library project with a single source file in it called either Class1.cs or Class1.vb, depending on the language selected in step 3.

2. Add a Reference to the Excel Services UDF Assembly

Next, add a reference to the Excel Services UDF assembly. If Visual Studio 2005 is running on a computer that has SharePoint Server 2007 installed, do the following:

  1. Right-click the project in the Visual Studio Solution Explorer and select the Add Reference… menu item.
  2. Select the .NET tab in the Add Reference dialog box, then scroll down to the Excel Services UDF Framework component, select it, and then click OK to add the reference.

If Visual Studio 2005 is running on a computer that does not have SharePoint Server 2007 installed on it, the Excel Services UDF assembly is not available. In this case, you can copy the Excel Services UDF assembly from a computer that has SharePoint Server 2007 installed on it to a local project folder on the development computer. The Excel Services UDF assembly is called Microsoft.Office.Excel.Server.UDF.dll and by default is located in the following folder on a computer that has SharePoint Server 2007 installed:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

After you make a local copy of the Excel Services UDF assembly, you can add a reference to it by browsing for the local file. To add a reference to a local copy of the assembly do the following:

  1. Right-click the project in the Visual Studio Solution Explorer and select the Add Reference menu item.
  2. Select the Browse tab in the Add Reference dialog box and then navigate to the local folder that contains the copy of the Excel Services UDF assembly. Select it, and then click OK to add the reference.

Note that the Microsoft.Office.Excel.Server.UDF.dll is compiled using Microsoft .NET Framework 2.0 assemblies. For this reason, you cannot use Microsoft Visual Studio 2003 to create a managed-code UDF because it is not possible for assemblies created with an older version of the .NET Framework to include a reference to an assembly created with .NET Framework 2.0.

3. Create Custom Functions

After adding the reference to the Excel Services UDF assembly, the next step is to create the custom functions and mark them with the Excel Services UDF attributes. You must mark the class that implements UDF methods with theMicrosoft.Office.Excel.Server.UDF.UDFClass attribute and mark the UDF methods with theMicrosoft.Office.Excel.Server.UDF.UDFMethod attribute. Next, add the following line to the source file for the UDF assembly project to allow these attributes to be used without having to specify the fully qualified namespace path:

using Microsoft.Office.Excel.Server.Udf;

The next step is to mark the class that contains the methods that implement the UDFs with the UdfClass attribute.

public class Class1

The final step is to create the methods that implement the UDFs. Add the following methods to the class just marked with the UdfClass attribute.

public double MyDouble(double d)
    return (d * 9);

[UdfMethod(IsVolatile = true)]
public DateTime ReturnDateTimeToday()
    return (DateTime.Today);

The MyDouble method accepts a parameter of type double and returns the result of that value multiplied by 9. TheReturnDateTimeToday method returns the current date. Both methods are marked with the UdfMethod attribute. Any methods in the UDF assembly that are not marked with the UdfMethod attribute are ignored because they are not considered UDF methods. The UdfMethod attribute has a Boolean IsVolatile property that you can use to specify a UDF method as volatile or nonvolatile. The default value is FALSE, which means that a UDF method is nonvolatile.

4. Configure Excel Services

Configuring Excel Services to work with a managed-code UDF assembly involves two steps:

  1. Create a trusted file location.
  2. Register the UDF assembly.
  3. A trusted file location is a Microsoft Windows SharePoint Services location, network file share, or Web folder from which a server running Excel Services is permitted to access workbooks. To create a trusted Windows SharePoint Services location, do the following on a computer that has SharePoint Server 2007 installed.

To create a trusted Windows SharePoint Services location

  1. On the Start menu, click All Programs.
  2. Point to Microsoft Office Server and click SharePoint 3.0 Central Administration.
  3. On the Quick Launch, click the shared services provider (SSP) link—for example, “SharedServices1“—to view the Shared Services home page for that particular SSP.
  4. On the Shared Services home page, in the Excel Services Settings section, click Trusted file locations.
  5. On the Excel Services Trusted File Locations page, click Add Trusted File Location.
  6. On the Excel Services Add Trusted File Location page, in the Address box, type the location where the Excel workbook that calls UDFs will be saved to—for example, http://MyServer002/Shared%20Documents.
  7. Under Location type, click the appropriate location type. In this example, select Windows SharePoint Services.
  8. Under Trust Children, select Children trusted to trust child libraries or directories.
  9. Under Allow User-Defined Functions, select User-defined functions allowed to allow UDFs to be called from workbooks stored in this trusted location.
  10. Click OK.

Excel Services maintains a list of registered UDF assemblies. You can enable or disable each assembly for loading and calling by Excel Services. To register a UDF assembly with Excel Services, do the following on a computer that has SharePoint Server 2007 installed.

To register a UDF assembly with Excel Services

  1. On the Start menu, click All Programs.
  2. Point to Microsoft Office Server and click SharePoint 3.0 Central Administration.
  3. On the Quick Launch, click the shared services provider (SSP) link—for example, “SharedServices1“—to view the Shared Services home page for that particular SSP.
  4. Under Excel Services Settings, click User-defined function assemblies.
  5. On the Excel Services User-Defined Functions page, click Add User-Defined Function Assembly to open the Excel Services Add User-Defined Function Assembly page.
  6. In the Assembly box, type the path to the UDF assembly that contains the code created previously in the Create Custom Functions section.
  7. Under Assembly Location, select the appropriate location type.
  8. Under Enable Assembly, the Assembly enabled check box should be selected by default.
  9. Click OK.

When you register a UDF assembly with Excel Services, one of the Assembly Location options is a file path. A file path location can be a local folder or a network share. To enable the local folder file path option to work in all situations, specifically in a server farm environment where many computers would need to locate the UDF assembly, you can create a SharePoint Services solution package to deploy the UDF assembly to each server computer. For more information regarding creating a SharePoint Services solution package, see How to: Deploy UDFs Using Windows SharePoint Services Solutions.

5. Create and Publish an Excel Workbook That Calls UDFs

Create an Excel workbook that calls the UDFs implemented in the previous section, Create Custom Functions, by doing the following.

Create an Excel workbook that calls UDFs

  1. Start Excel 2007.
  2. In cell A1, type the formula to call the MyDouble UDF. The MyDouble function takes an argument of type double. This example takes the argument from cell B1. In cell A1, type =MyDouble(B1).
  3. In cell B1, type the number 8.
  4. Make cell B1 a named range. First click the Formulas tab. Then click cell B1 to select it. On the Formulas tab, in the Defined Named group, click Define. In the New Name dialog box, in the Name box, typeMyDoubleParam.
  5. In cell A2, type the formula to call the ReturnDateTimeToday UDF. Type =ReturnDateTimeToday().
  6. In cell A3, type the formula to call the ReturnDateTimeToday UDF. Type =ReturnDateTimeToday(). Next, right-click cell A3 to display the menu. Click Format Cells.
  7. In the Format Cells dialog box, on the Number tab, select Date. Select a date format type from the Type list—for example, *3/4/2001.
  8. Click OK.
  9. Save the workbook to a folder on a local drive. Name the workbook “TestSampleUdf.xlsx”.

Cells A1, A2, and A3 will evaluate to “#NAME?” in Excel. This is because Excel cannot resolve the calls to theMyDouble UDF and ReturnDateTimeToday UDF. The formulas are evaluated correctly when the workbook is displayed using Excel Services. For more information regarding the options for creating UDF solutions that work across both client and server, see Developing User-Defined Functions for Excel 2007 and Excel Services.

The final step is to publish the workbook created previously to Excel Services by doing the following.

To publish the workbook

  1. Click the Microsoft Office Button, point to Publish, and click Excel Services.
  2. In the Save As dialog box, click Excel Services Options.
  3. In the Excel Services Options dialog box, on the Show tab, make sure that Entire Workbook is selected.
  4. Click the Parameters tab.
  5. Click the Add button.
  6. In the Add Parameters dialog box, select the MyDoubleParam check box.
  7. Click OK. “MyDoubleParam” is now listed in the Parameters list.
  8. Click OK.
  9. In the Save As dialog box, make sure that the Open in Excel Services check box is selected.
  10. In the File name box, type the path to the trusted SharePoint document library where this workbook will be stored. For example, http://MyServer002/Shared%20Documents/TestSampleUdf.xlsx.
  11. Click Save.

The TestSampleUdf.xlsx workbook loads in Excel Web Access. Cell A1 displays the number “72” because cell B1 * 9 = 8 * 9, which is 72. Cell A2 displays a number and cell A3 displays the current date. The number in cell A2 represents the number of days since 1/1/1900 (or 1/1/1904 if Excel is configured to “Use 1904 Date System”). To change the value passed to the MyDouble UDF that is called in cell A1, specify a different value in the Parameterspane, and then click the Apply button. Excel Services recalculates the workbook.

Read ItWith the introduction of Excel Services in the 2007 Microsoft Office system, you have a great opportunity to integrate Excel 2007 as a key component to business applications. This article explores how to create managed-code UDFs for Excel Services. The key steps include:

  1. Create a managed-code UDF project in Visual Studio 2005.
  2. Add a reference to the Excel Services UDF Framework.
  3. Create custom functions that provide the UDF implementation.
  4. Configure Excel Services to allow UDFs to be used.
  5. Create and publish an Excel workbook that calls UDFs.

Source taken from: http://msdn.microsoft.com/en-us/library/bb428649(office.12).aspx

Creating a Custom Web Service for SharePoint Thursday, Aug 5 2010 

This article will guide you through the process of creating a custom web service for SharePoint. This web service will work with new versions of SharePoint, Office SharePoint Server 2007 and Windows SharePoint Service 3.0. We will create a simple service that will upload documents to SharePoint. We will call it UploadService. Remember, there are steps in the Microsoft articles that are confusing especially for the beginners, I have taken care of that as well. I have tried to include as much information as possible including screenshots and code snippets to make the job easier for the developer. I have used Microsoft articles as a base for this article. There are some mistakes in the Microsoft articles that have been corrected in this article.

Basic Steps for Creating a Web Service

Create an ASP.NET web service in Microsoft Visual Studio 2005. There are two ways to do this. You can develop a web service on the server machine that hosts SharePoint or you can develop it on a remote machine that does not host SharePoint and later deploy the service on the machine that hosts SharePoint. We will discuss the second method in this article.

Add .ASMX file to your project if it’s not already there. This file will contain the programming logic for the web service. Note, you can add programming logic to the markup page as well as the code behind. The choice is yours.
Generate a static discovery file (disco) and a Web Services Description Language (WSDL) file.
Modify the disco and wsdl files for SharePoint.

Deploy the web service files to the SharePoint server.

Create a client application to consume the web service.

You can download the sample application (web service) here. Download size is 361 KB.

The zip file contains the web service and its related files. It also contains an installer to help you install the service easily on your server. Unzip the file to your hard disk. It will create a “WSUploadService” folder. You can unzip the file anywhere on your hard disk. There is no restriction on unzipping it to a particular folder. Run “UploadServiceCopier.exe” to install the service. Installer will ask you to select a SharePoint site where this service should be installed. Select your site from the drop down and keep the folder name as “bin” (second field: textbox) and click “Next”.

To uninstall, run the “UploadServiceCopier.exe” again. It will give you the following message:

“Service is already installed. Do you want to uninstall it?”

Select “Yes” and then select “Remove WSUploadService” and click “Finish” to uninstall the service. Uninstall will remove all copied files from your hard disk.

Please run “UploadServiceCopier.exe” to install/uninstall the service. Do not run “setup.exe” directly as it will not install the service correctly.

Creating a Custom Web Service

1. The first step is to create an ASP.NET web service project in Visual Studio 2005. If you don’t find a web service project template in visual studio, that means that you are still running an old version of Visual Studio 2005, the one without the service pack. You will have to download and install the Visual Studio 2005 Service Pack 1 Beta from Microsoft here. It’s a 371.9 MB download and let me tell you in advance that the installation is very slow and takes a lot of time. On the File menu, click New Project.

2. In the Project Types box, select Visual C#.

3. In the Templates box, select ASP.NET Web Service Application.

4. In the Name box, type UploadService. In the Location box, type the following path: C:\WebService. You can also click the browse button to browse the folders and select the destination folder. This is the path where the project will be stored. In the Solution Name box, type UploadService and check Create directory for solution checkbox.

5. Click OK.

6. In the Solution Explorer, right-click Service1.asmx and rename the file Files.asmx and then right click Files.asmx and click View Code.

7. Add a reference to the assembly for Microsoft Office SharePoint Server 2007 (Microsoft.SharePoint.dll). This assembly is located in the following directory: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI. Please note that if you are developing on a machine that does not have SharePoint installed then you can copy the required files from the SharePoint machine to your development machine.

8. Make sure following using directives are included at the top:

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Net;

9. Change your class name from Service1 to Files.

public class Files : System.Web.Services.WebService

10. Comment out the web method definition. The commented out web method code will look like as follows:

//public string HelloWorld()
//return “Hello World”;

11. Add following code (web method) in the class:

public string UploadDocument(string fileName, byte[] fileContents, string pathFolder)
if (fileContents == null)
return "Null Attachment";

int iStartIndex = pathFolder.LastIndexOf("/");
string sitePath = pathFolder.Remove(iStartIndex);
string folderName = pathFolder.Substring(iStartIndex + 1);

SPSite site = new SPSite(sitePath);
SPWeb web = site.OpenWeb();

SPFolder folder = web.GetFolder(folderName);

string fileURL = fileName;

folder.Files.Add(fileURL, fileContents);

if (folder.Files[fileURL].CheckedOutBy.Name != "")
folder.Files[fileURL].CheckIn("File Checked In");

return "File added successfully!";

catch (System.Exception ex)
return "Error: " + ex.Source + " - " + ex.Message;

12. Open Files.asmx markup page. In Solution Explorer, right-click Files.asmx and select View Markup. You will notice that the markup page has following line:

<%@ WebService Language=”C#” CodeBehind=”Service1.asmx.cs” %>

Change it to the following line:

<%@ WebService Language=”C#” %>

13. Create a strong name for the class library. In Solution Explorer, right-click the web service project, and in the Properties dialog box, click Signing, select Sign the assembly, and select in the box for choosing a strong name key file.

14. In the Create Strong Name Key dialog box, provide a file name for the key, deselect Protect my key file with a password, and click OK.

This was the easy way. You can also strong name your assembly using the command line utility called as sn.exe. Use following steps if you want to strong name your assembly manually:

1. Strong naming utility (sn.exe) can be found in the following folder: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

Copy the sn.exe utility to the folder where your assembly is located and run the following command to strong name your assembly:

sn.exe -k key.snk

Resulting key will be written to the key.snk file.

2. Go to your project’s properties (right-click project name in the Solution Explorer and select Properties from the menu) and select Signing from the menu that appears on the left. This will open a form.

3. Check Sign the assembly checkbox and choose the key file from the drop down (Click the Browse… button in the drop down to locate the key.snk file that you generated in the previous step).

4. Re-compile your assembly.

15. Compile the web service project.

16. As we are developing this web service on a machine that does not host SharePoint, therefore, we need to create a virtual directory in IIS. Click Start, point to Administrative Tools (You may have to go to the Control Panel first to select Administrative Tools), and then click Internet Information Services (IIS) Manager.

Note: In case you are developing the service on a SharePoint server, then skip steps 17-20 and use following instructions and then start with step 22:

1. Copy the Files.asmx to the following folder: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS

2. Run disco.exe at the command prompt from the LAYOUTS directory to generate .disco and .wsdl files.

Run a command in the following format to generate the files in LAYOUTS:

disco http://localhost/_layouts/Files.asmx

17. Expand the branch for the server computer to which you want to add a virtual directory. Under the server computer branch, expand the Web Sites folder, and right-click the Default Web Site and select New and then Virtual Directory…. If you don’t want to use Default Web Site, you can create a new web site.

18. Click Next and enter an alias in the text box, for example, for this service you can enter UploadService.

19. Click Next and then click Browse… button to browse to the project folder (containing the .asmx file) and click Next.

20. Click Next again and then click Finish.

Generating and Modifying Static Discovery and WSDL Files

21. Use Disco.exe to generate .disco and .wsdl files. This command line utility is located in the following directory:

C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

Open command prompt and type the following line and press Enter:

Disco http://localhost/uploadservice/Files.asmx

Make sure you have entered the correct path in the command above otherwise you will get an error. If you created a virtual directory on a port other than the port 80, then you must mention the port number in the path (For example, http://localhost:8080/uploadservice/Files.asmx). This will generate the .disco and .wsdl files.

22. To register namespaces of the Windows SharePoint Services object model, open both the .disco and .wsdl files and replace the opening XML processing instruction — — with instructions such as the following:

<%@ Page Language="C#" Inherits="System.Web.UI.Page"%>
<%@ Assembly Name="Microsoft.SharePoint, Version=,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Import Namespace="Microsoft.SharePoint.Utilities" %> 
<%@ Import Namespace="Microsoft.SharePoint" %>
<% Response.ContentType = "text/xml"; %>

23. In the .disco file, modify the contract reference and SOAP address tags to be like the following example, which replaces literal paths with code generated paths through use of the Microsoft.SharePoint.Utilities.SPEncode class, and which replaces the method name that is specified in the binding attribute:

<contractRef ref=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request) + "?wsdl"),Response.Output=""); %&gt;
docRef=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt;
xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<soap address=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt;
xmlns:q1="http://tempuri.org" binding="q1:FilesSoap" xmlns=
"http://schemas.xmlsoap.org/disco/soap/" />
<soap address=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt;
xmlns:q2="http://tempuri.org" binding="q2:FilesSoap12" xmlns=
"http://schemas.xmlsoap.org/disco/soap/" />

24. In the .wsdl file, make the following, similar substitution for the SOAP address that is specified:

<soap:address location=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt; />

Make the following substitution for the SOAP12 address:

<soap12:address location=&lt;%SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt; />

25. Rename both files in the respective formats Filedisco.aspx and Fileswsdl.aspx so that your service is discoverable through SharePoint.

Deploying web service on the SharePoint server

Copy the Web service files to the _vti_bin virtual directory

26. Copy the web service files to the _vti_bin directory of the SharePoint server. Web service files that are to be copied are as following:


The _vti_bin virtual directory maps physically to the Local_Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI directory, which contains the default Web service files used in Windows SharePoint Services.

To include the Web service in the list of web services on the server

27. In Notepad, open the spsdisco.aspx file. spsdisco.aspx is located in the following directory (on the SharePoint server):

Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

28. Add the following lines to the end of the file within the discovery element and save the file:

<contractRef ref=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(spWeb.Url + "/_vti_bin/Files.asmx?wsdl"), Response.Output); %&gt;
docRef=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(spWeb.Url + "/_vti_bin/Files.asmx"), Response.Output)
; %&gt; xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<soap address=&lt;% 
(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/Files.asmx"),Response.Output)
; %&gt; xmlns:q1="http://schemas.microsoft.com/sharepoint/soap/directory/"
xmlns="http://schemas.xmlsoap.org/disco/soap/" />

Copying the assembly to the correct Bin folder

29. I have seen blogs and forums where people have recommended to copy the assembly to the following folder:

Local_Drive:\program files\common files\microsoft shared\web server extensions\12\isapi\

Some people say it should be copied to the following folder:


bin folder is not there by default and has to be created but safest place to copy the assembly is the bin folder of the virtual directory of the web application where you intend to use the web service. Following path contains the virtual directories of web applications that you have created on your SharePoint server.


For example, if you want to use the web service in web application at port 81, then you should copy the assembly to the following folder:


Similarly, if you want to use the web service in web application at port 17316, then you should copy the assembly to the following folder:


I am not saying that you can not copy the assembly to the _vti_bin folder or wwwroot folder, of course you can but I have often seen people struggling with the service deployment. People often ask me where they should copy the assembly and what is the best place to put the assembly in. I tested my web service by putting the assembly file in all the recommended places and I found that bin folder of the virtual directory of the web application is the safest place where your web service is guaranteed to work.

Copy the assembly to the bin folder of the virtual directory of the web application of your choice. You will have to create the bin folder yourself. It is not there by default.

Adding web service to the GAC

30. You must add your assembly in the GAC on your SharePoint server. This is necessary otherwise you will get permissions error on the server. There are three ways to avoid this permissions error. One way is to add the assembly in the GAC. Second way is to change the trust level to medium in the web.config file and the third is to create a custom trust policy of your own. There is an article on Microsoft site that has all the details of Code Access Security (CAS) and it also shows how to create a custom policy file. Here is the article if you are interested in exploring this topic.

Unfortunately, this is an old version and works only with SharePoint 2003. I am not sure if Microsoft has already released an updated version of this article or not. I intend to write an updated version of this article (at least the custom policy file part) for Office SharePoint Server 2007 and Windows SharePoint Services 3.0.

To add your assembly to the Global Assembly Cache (GAC), you can either drag and drop the assembly into the %windows%\assembly directory using 2 instances of Windows Explorer, or use the command line utility gacutil.exe that is installed with the .NET Framework SDK 2.0. This utility is located in the following folder:

C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

To use gacutil.exe to copy the class library DLL into the GAC

To open the Visual Studio command prompt, click Start, point to All Programs, point to Microsoft Visual Studio 2005, point to Visual Studio Tools, and click Visual Studio 2005 Command Prompt.
At the command prompt type a command in the following form, and press ENTER:
gacutil.exe -i “”.

You can also use “.NET Framework 2.0 Configuration” tool to add the assembly to the GAC.

1. Go to control panel, click Administrative Tools and select Microsoft .NET Framework 2.0 Configuration.

2. Click Manage the Assembly Cache and then select Add an Assembly to the Assembly Cache. Locate the assembly and click Open.

Creating a Windows Application to Consume the Web Service

After copying the Web services files to the _vti_bin directory, the next step is to create a Windows Application to consume the Web service.

31. Create a new C# Windows Application in Visual Studio 2005.

32. In Solution Explorer, right-click References, and then click Add Web Reference.

33. In the address bar of the Add Web Reference browser, type the URL for the site to which to apply the service, as follows, and then press ENTER:


If you installed the service on another port, for example, port 17316, then the url would be:


You can also browse all web services available on the server. Files.asmx will be listed in the web services available on the server. There will be multiple entries, each entry representing the service available for a different web application. Therefore, if you want to upload documents to a site on port 80, then you should select Files.asmx for port 80.

34. Include following using directives at the top:

using System.Net;
using System.IO;

35. Add following code to your application:

localhost.Files oUploader = new localhost.Files();

oUploader.PreAuthenticate = true;
oUploader.Credentials = CredentialCache.DefaultCredentials;

string strPath = @"C:\test.doc";
string strFile = strPath.Substring(strPath.LastIndexOf("\\") + 1);

string strDestination = "http://sp:17316/Docs";

FileStream fStream = new FileStream(strPath, System.IO.FileMode.Open);
byte[] binFile = new byte[(int)fStream.Length];
fStream.Read(binFile, 0, (int)fStream.Length);

string str = oUploader.UploadDocument(strFile, binFile, strDestination);

catch (Exception ex)
MessageBox.Show(ex.Source + " - " + ex.Message + " - 
" + ex.InnerException + " - " + ex.StackTrace);

localhost is the name of the web reference that you added in previous step. strPath contains the filename that is to be uploaded. This is just a sample to show you how the service works, that’s why i have hard coded the filename but in a real life situation you may want to add a text box and a browse button to select files from your hard disk. strDestination contains the destination path. This should be the path representing the document library where file is to be uploaded.

36. Finally, before testing the service, make sure the current user has privileges to upload documents in the destination document library. The user should have “Contributor” rights in the document library otherwise, you will get “401: Unauthorized” error. Run the application to test the service.

Frequently Asked Questions

Q: I get “Could not create type” error message. What could be the reason?

Make sure your .asmx file has correct class name definition. Open your .asmx file and if class name is myFiles, change it to myService.myFiles!



It’s better that you use correct format in the first place but you can change the .asmx file after deployment as well. Go to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI folder and open your .asmx file in notepad (or any editor of your choice) and make the changes as mentioned above.

Q: I get “Server did not recognize the value of HTTP Header SOAPAction: …” error?

This error occurs if you do not use correct web service namespace. Following three lines should be included in your code, just before the class defintion:

[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

This error can occur even if you omit the trailing slash of http://tempuri.org/, http://tempuri.org will result in an error.

Q: I get “File not found.” error?

This happens when SharePoint fails to find the assembly file. Make sure you have added the assembly in the correct bin folder. Also, make sure you have added the assembly in the GAC.

Q: I get “Unauthorized” error?

Make sure the user who is trying to use the web service has “Contributor” rights in the destination site or library. Also, make sure following lines are added to your client application:

oUploader.PreAuthenticate = true;
oUploader.Credentials = CredentialCache.DefaultCredentials;

Q: I get “SQL Server might not be started” error. I have double checked, my SQL Server is running. Why am i getting the error?

There could be several reasons for this. If you modified the web.config file, reverse the changes you made to the config file and then try again. The error has nothing to do with the SQL Server.

Q: I do not see my web service when i click “Web services on the local machine” in Add Web Reference?

Did you make changes in the spsdisco.aspx file? To include your web service in the list of web services on the SharePoint server, you must add reference to your web service in the spsdisco.aspx file (within the discovery element).

Q: Is it necessary to include the code in the code-behind?

No! You can write code in the myFiles.asmx (markup page) and delete the myFiles.asmx.cs file. Here is the myFiles.asmx code listing:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Net;

namespace myService
/// Summary description for Service1
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myFiles : System.Web.Services.WebService

//public string HelloWorld()
// return "Hello World";
public string UploadDocument(string fileName, byte
[] fileContents, string pathFolder)
if (fileContents == null)
return "Null Attachment";
int iStartIndex = pathFolder.LastIndexOf("/");
string sitePath = pathFolder.Remove(iStartIndex);
string folderName = pathFolder.Substring(iStartIndex + 1);

SPSite site = new SPSite(sitePath);
SPWeb web = site.OpenWeb();

SPFolder folder = web.GetFolder(folderName);

string fileURL = fileName;

folder.Files.Add(fileURL, fileContents);

if (folder.Files[fileURL].CheckedOutBy.Name != "")
folder.Files[fileURL].CheckIn("File Checked In");
return "File added successfully!";

catch (System.Exception ex)
return "Error: " + ex.Source + " - " + ex.Message;


Source is taken from: http://it.toolbox.com/blogs/sharepoint-blog/creating-a-custom-web-service-for-sharepoint-13553

Sharepoint Interview Questions with Answers Monday, May 31 2010 

What is a SharePoint Feature? What files are used to define a feature?
A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances, scope of which are defined as
1. Farm level 2. Web Application level 3. Site level 4. Web level
Features have their own receiver architecture, which allow you to trap events such as when a feature is
Installing, Uninstalling, Activated, or Deactivated.

The element types that can be defined by a feature include
menu commands, link commands, page templates, page instances, list definitions, list instances,
event handlers, and workflows.

The two files that are used to define a feature are the feature.xml and manifest file(elements.xml). The feature XML file defines the actual feature and will make SharePoint aware of the installed feature. The manifest file contains details about the feature such as functionality.

• Workflow can be applied to what all elements of SharePoint ?
Workflow associations are often created directly on lists and libraries, a workflow association can also be created on a content type that exists within the Content Type Gallery for the current site or content types defined within a list. In short, it can be applied …
At the level of a list/library
At the level of a content type defined at site scope
At the level of a content type defined at list scope

• What are the types of input forms that can be created for a workflow ?
You can create four different types of input forms including
1. An association form
2. An initiation form
3. A modification form
4. A task edit form.

Note that these forms are optional when you create a workflow template.

• What are ways to create input forms for workflow ?
1. You can create your forms by using custom application pages, which are standard .aspx pages deployed to run out of the _layouts directory. ( disadv: lot of code required when compared to Infopath approach)
2. Using Microsoft Office InfoPath 2007 (disadv: picks up a dependenct on MOSS, i.e. it cannot run in a standalone WSS environment)

• What is the difference between method activity and event activity in WorkFlow ?
A method activity is one that performs an action, such as creating or updating a task. An event activity is one that runs in response to an action occurring.

• What are content types?
A content type is a flexible and reusable WSS type definition (or we can a template) that defines the columns and behavior for an item in a list or a document in a document library. For example, you can create a content type for a leave approval document with a unique set of columns, an event handler, and its own document template and attach it with a document library/libraries.
• Can a content type have receivers associated with it?
Yes, a content type can have an event receiver associated with it, either inheriting from the SPListEventReciever base class for list level events, or inheriting from the SPItemEventReciever base class. Whenever the content type is instantiated, it will be subject to the event receivers that are associated with it.

What two files are typically (this is kept generally) included when developing a content type, and what is the purpose of each?
There is generally the main content type file that holds things like the content type ID, name, group, description, and version. There is also the ContentType.Fields file which contains the fields to include in the content type that has the ID, Type, Name, DisplayName, StaticName, Hidden, Required, and Sealed elements. They are related by the FieldRefs element in the main content type file.

What is an ancestral type and what does it have to do with content types?
An ancestral type is the base type that the content type is deriving from, such as Document (0x0101). The ancestral type will define the metadata fields that are included with the custom content type.

• Can a list definition be derived from a custom content type?
Yes, a list definition can derive from a content type which can be seen in the schema.XML of the list definition in the element.

• When creating a list definition, how can you create an instance of the list?
You can create a new instance of a list by creating an instance.XML file

What is a Field Control?
Field controls are simple ASP.NET 2.0 server controls that provide the basic field functionality of SharePoint. They provide basic general functionality such as displaying or editing list data as it appears on SharePoint list pages.

• What base class do custom Field Controls inherit from?
This varies. Generally, custom field controls inherit from the Microsoft.SharePoint.WebControls.BaseFieldControl namespace, but you can inherit from the default field controls.

Can multiple SharePoint installs point to the same DB?
Multiple SharePoint installs can use the same database server. Not literally the same database on that server. That server must be SQL Server 2000 or SQL Server 2005. It cannot be Oracle or another vendor.

• How to create links to the mapped network drives?
Creating links to mapped drives in WSS v3 or MOSS 2007 can be done via
the new content type for .lnk files.

• While creating a Web part, which is the ideal location to Initialize my new controls?
Override the CreateChildControls method to include your new controls. You can control the exact rendering of your controls by calling the .Render method in the web parts Render method.

What are the two base classes a WebPart you are going to use within SharePoint 2007 can inherit from?
There are two base classes that a WebPart which is going to be consumed by SharePoint can inherit from, either the
SharePoint WebPart Base class
or the
ASP.NET 2.0 WebPart base class.
When inheriting from the SharePoint WebPart Base class your derived WebPart class will inherit from Microsoft.SharePoint.WebPartPages.WebPart. When inheriting from the ASP.NET 2.0 WebPart base class your derived WebPart class will inherit from System.Web.UI.WebControls.WebParts.WebPart. It is considered good practice to use the ASP.NET WebPart base class since the old base class is meant for backwards compatibility with previous version of SharePoint, however there are four exception when it is better to leverage functionality from the SharePoint WebPart base class:
Cross page connections
Connections between Web Parts that are outside of a Web Part zone
Client-side connections (Web Part Page Services Component)
Data caching infrastructure

What are the differences between the two base classes and what are the inherit benefits of using one over another?
The difference is the Microsoft.SharePoint.WebPartPages.WebPart base class is meant for backward compatibility with previous versions of SharePoint. The benefit of using the SharePoint WebPart base class is it supported:
Cross page connections
Connections between Web Parts that are outside of a Web Part zone
Client-side connections (Web Part Page Services Component)
Data caching infrastructure
ASP.NET 2.0 WebParts are generally considered better to use because SharePoint is built upon the ASP.NET 2.0 web architecture. Inheriting from the ASP.NET 2.0 base class offers you features that inherit to ASP.NET 2.0, such as embedding resources as opposed to use ClassResources for deployment of said types.

• What is the WebPartManager sealed class? What is its purpose?
The WebPartManager sealed class is responsible for managing everything occurring on a WebPart page, such as the WebParts (controls), events, and misc. functionality that will occur in WebPartZones. For example, the WebPartManager is responsible for the functionality that is provided when you are working with moving a WebPart from WebPartZone to WebPartZone. It is known as the “the central class of the Web Part Control Set.”

• What does AllowUnsafeUpdates do ?
If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.

• What does RunWithElevatedPrivileges do?
There are certain object model calls model that require site-administration privileges. To bypass access-denied error, we use RunWithElevatedPrivileges property when request is initiated by a nonprivileged user. We can successfully make calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
• What does SPWeb.EnsureUser method do?
Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.
e.g SPUser usr = myWeb.EnsureUser(“hitenders”);

• What is a SPSite and SPWeb object, and what is the difference between each of the objects?
The SPSite object represents a collection of sites (site collection [a top level site and all its subsites]). The SPWeb object represents an instance SharePoint Web, and SPWeb object contains things like the actual content. A SPSite object contains the various subsites and the information regarding them.

• What does a SPWebApplication object represent?
The SPWebApplication objects represents a SharePoint Web Application, which essentially is an IIS virtual server. Using the class you can instigate high level operations, such as getting all the features of an entire Web Application instance, or doing high level creation operations like creating new Web Applications through code.

Would you use SPWebApplication to get information like the SMTP address of the SharePoint site?
Yes, since this is a Web Application level setting. You would iterate through each SPWebApplication in the SPWebApplication collection, and then use the appropriate property calls (OutboundMailServiceInstance) in order to return settings regarding the mail service such as the SMTP address.

• How do you return SharePoint List items using SharePoint web services?
In order to retrieve list items from a SharePoint list through Web Services, you should use the lists.asmx web service by establishing a web reference in Visual Studio. The lists.asmx exposes the GetListItems method, which will allow the return of the full content of the list in an XML node. It will take parameters like the GUID of the name of the list you are querying against, the GUID of the view you are going to query, etc.
Side Question: I got asked how I built queries with the lists.asmx web service. In order to build queries with this service, one of the parameters that the GetListItems method exposes is the option to build a CAML query. There are other ways to do this as well, but that was how I answered it.

• When retrieving List items using SharePoint Web Services, how do you specify explicit credentials to be passed to access the list items?
In order to specify explicit credentials with a Web Service, you generally instantiate the web service, and then using the credentials properties of the Web Service object you use the System.Net.NetworkCredential class to specify the username, password, and domain that you wish to pass when making the web service call and operations.

• What is CAML, and why would you use it?
CAML stands for Collaborative Application Markup Language. CAML is an XML based language which provides data constructs that build up the SharePoint fields, view, and is used for table definition during site provisioning. CAML is responsible for rending data and the resulting HTML that is output to the user in SharePoint. CAML can be used for a variety of circumstances, overall is used to query, build and customize SharePoint based sites. A general use would be building a CAML query in a SharePoint WebPart in order to retrieve values from a SharePoint list.

• What is impersonation, and when would you use impersonation?
Impersonation can basically provide the functionality of executing something in the context of a different identity, for example assigning an account to users with anonymous access. You would use impersonation in order to access resources on behalf of the user with a different account, that normally, that wouldn’t be able to access or execute something.

What are WebPart properties, and what are some of the attributes you see when declaring WebPart properties in code?
WebPart properties are just like ASP.NET control properties, they are used to interact with and specify attributes that should be applied to a WebPart by a user. Some of the attributes you see with ASP.NET 2.0 properties are WebDescription, WebDisplayName, Category, Personalizable, and WebBrowsable. Although most of these properties come from the System.Web.UI.WebControls.WebParts class, ones like Category come out of System.ComponentModel namespace.

• Why are properties important in WebPart development, and how have you exploited them in past development projects? What must each custom property have?
Properties are important because WebParts allow levels of personalization for each user. WebPart properties make it possible for a user to interact, adjust, and increase overall experience value with the programmatic assets that you develop without having the need to use an external editor or right any code. A very simple example of exploiting a property would be something like allowing the user to change the text on the WebPart design interface so that they can display whatever string of text they desire.
Each custom property that you have must have the appropriate get and set accessor methods.

• What are ClassResources? How do you reference and deploy resources with an ASP.NET 2.0 WebPart?
ClassResources are used when inheriting from the SharePoint.WebPart.WebPartPages.WebPart base class, and are defined in the SharePoint solution file as things that should be stored in the wpresources directory on the server. It is a helpful directory to use in order to deploy custom images. In ASP.NET 2.0, typically things such as images are referenced by embedding them as resources within an assembly. The good part about ClassResources is they can help to eliminate recompiles to change small interface adjustments or alterations to external JavaScript files.

• What is a SharePoint Solution File? How does it differ from WebPart .cab files in legacy development? What does it contain?
A SharePoint solution file is essentially a .cabinet file with all a developers ustom componets suffixed with a .wsp extension that aids in deployment. The big difference with SharePoint solution files is is that a solution:
allows deployment to all WFE’s in a farm
is highly manageable from the interface allowing deployment, retraction, and versioning
Can package all types of assets like site definitions, feature definitions (and associated components), Webparts, etc.
Can provide Code Access Security provisioning to avoid GAC deployments
And much more..

• What is a .ddf file and what does it have to do with SharePoint Solution creation?
A .ddf file is a data directive file and is used when building the SharePoint solution bundle specifying the source files and their destination locations. The important thing for someone to understand is that the .ddf file will be passed as a parameter to the MAKECAB utility to orchestrate construction of the SharePoint solution file.

• What file does a SharePoint solution package use to orchestrate (describe) its packaged contents?
The solution Manifest.XML file.

• What deployment mechanism can you use to instigate Code Access Security attributes for your WebParts?
SharePoint solution files can add in order to handle code access security deployment issues. This is done in the element in the SharePoint solution manifest.XML, which makes it easier to get assemblies the appropriate permissions in order to operate in the bin directory of the web application.

• What are event receivers?
Event receivers are classes that inherit from the SpItemEventReciever or SPListEventReciever base class (both of which derive out of the abstract base class SPEventRecieverBase), and provide the option of responding to events as they occur within SharePoint, such as adding an item or deleting an item.

• When would you use an event receiver?
Since event receivers respond to events, you could use a receiver for something as simple as canceling an action, such as deleting a document library by using the Cancel property. This would essentially prevent users from deleting any documents if you wanted to maintain retention of stored data.

• What base class do event receivers inherit from?
Event receivers either inherit from the SPListEventReciever base class or the SPItemEventReciever base class, both which derive from the abstract base class SPEventReceiverBase.

• If I wanted to not allow people to delete documents from a document library, how would I go about it?
You would on the ItemDeleting event set: properties.Cancel= true.

• What is the difference between an asynchronous and synchronous event receivers?
An asynchronous event occurs after an action has taken place, and a synchronous event occurs before an action has take place. For example, an asynchronous event is ItemAdded, and its sister synchronous event is ItemAdding

.What are Application Pages in SharePoint?
Unlike site pages (for example, default.aspx), a custom application page is deployed once per Web server and cannot be customized on a site-by-site basis. Application pages are based in the virtual _layouts directory. In addition, they are compiled into a single assembly DLL.

A good example of an Application Page is the default Site Settings page: every site has one, and it’s not customizable on a per site basis (although the contents can be different for sites).

With application pages, you can also add inline code. With site pages, you cannot add inline code.

Typically, you link custom application pages to application.master, the master page file that is used by the default application pages in Windows SharePoint Services. You should also write application pages to inherit from a base class defined inside the Microsoft.SharePoint assembly named LayoutsPageBase.

.When to use Diffrent Site Collections?

Ans. An Individual Site collection offers following :

For the Users:

Dedicated Recycle bins
Dedicated usage Reports
Distributed administration (site collection administrators)
Dedicated search scopes, keywords, and best-bets
Custom feature deployments
Dedicated language translation maintenance
Dedicated galleries for web parts, master pages, content types, site columns, site templates, and list templates
Dedicated shared libraries, such as site collection images and site collection styles
Dedicated real estate (Self Containment)

For the IT Administrators:

Site quota templates
Distributed administration
Site locking
Database maintenance options
Backup / Restore abilities
Content Deployments
InfoPath forms services global template targeting.

.What are Security methods(Authentication methods) available in sharepoint.

Ans :“Out of the box”, SharePoint 2007 supports nine authentication methods. NTLM (short for NT Lan Manager, which is simply the Windows authentication that everyone is familiar with) and Kerberos (also a Windows “standard” authentication) are offered during installation, but I recommend to get started with NTLM, as Kerberos requires “special configuration by the domain administrator”, while NTLM works without further hassle.

.What does AllowUnsafeUpdates do ?
If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting theAllowUnsafeUpdates property.

using(SPSite mySite = new SPSite(“yourserver”))
using(SPWeb myWeb = mySite.OpenWeb())
myWeb.AllowUnsafeUpdates = true;
SPList interviewList = myWeb.Lists[“listtoinsert”];
SPListItem newItem = interviewList.Items.Add();

newItem[“interview”] = “interview”;

.How Does SharePoint work?
The browser sends a DAV packet to IIS asking to perform a document check in. PKMDASL.DLL, an ISAPI DLL, parses the packet and sees that it has the proprietary INVOKE command. Because of the existence of this command, the packet is passed off to msdmserv.exe, who in turn processes the packet and uses EXOLEDB to access the WSS, perform the operation and send the results back to the user in the form of XML.

.What is the difference between Syncronous & Asyncronous events?
Syncronous calls ending with ‘ing’
E.g. ItemDeleting
Event Handler code execute BEFORE action is committed
WSS waits for code to return
Option to cancel and return error code

Asyncronous calls ending with ‘ed’
E.g. ItemDeleted
Event Handler code executes AFTER action is committed
WSS does not wait for code to return
Executed in its own Worker thread.

.What is ServerUpdate() ?
Any changes in the list, i.e. new addition or modification of an item.. the operation is complete by calling the Update method.

But if a List is set to maintain versions .. and you are editing an item, but don’t want to save it as a new version, then use the SystemUpdate method instead and pass in ‘false’ as the parameter.

.What is query.ViewAttributes OR How can you force SPQuery to return results from all the folders of the list?

If you use SPQuery on any SPlist .. it will bring back results from the current folder only.
If you want to get results from all the folders in the list.. then you need to specify the scope of the query by the use of ViewAttributes..
e.g. query.ViewAttributes = “Scope=\”Recursive\””;

Key Performance Indicators (KPIs) Monday, May 31 2010 

Key Performance Indicators (KPIs)

A Key Performance Indicator (KPI) is a visual signal that tells us the amount of progress made towards a goal. In this article lets see how to create and display KPIs by using Microsoft Office SharePoint Server 2007 KPI list.

KPIs are valuable resources to evaluate progress against measurable goals. To create and publish KPIs, there is a four step procedure.

  1. Create a KPI list
  2. Add the KPI to the list
  3. Add a Web Part to a Web page
  4. Link the KPI list to the Web Part.

First of all we need to choose a KPI Type:

KPI types:

Using data in SharePoint lists
When SharePoint lists contain items that you can count, items that are part of a workflow, or items that contain dates, you can use a KPI to track how long the issues or tasks have been open, how many are open, and what percentage of a task is complete.

Using data in Microsoft Office Excel workbooks
You can set up a KPI in an Excel workbook and link to the KPI from Office SharePoint Server 2007. As the data in the workbook changes, the KPI is automatically updated.

Using data from Microsoft SQL Server 2005 Analysis Services
Office SharePoint Server 2007 can use KPIs from Analysis Services, a component of Microsoft SQL Server 2005. A systems administrator or database analyst usually sets up these KPIs and registers the data connection with Office SharePoint Server. Then, anyone with the appropriate permissions can access the database and link to the Analysis Services KPIs.

Using manually entered information
In situations where there is no formal system set up or you have a one-time project to track, you can use this KPI and enter the criteria manually. This KPI is useful for displaying information that is communicated in e-mail or some other nonstructured system.

Create a KPI list:
You can create KPI lists in the Reports Library of the Reports Center in a team or organization site, so that other people easily can find them.

  1. In the site where you want to create the KPI list, on the default page of the Report Center, click Site Actions, and then select View All Site Content. Under the All Site Content heading, click Create.
  2. On the Create page, under Custom Lists, click KPI List.
  3. Type a name and an optional description for the KPI list.
  4. Click OK.

You now have a KPI list to which you can add one or more KPI types.

Add a KPI to the KPI list
1.On the KPI list toolbar, click the arrow next to New.

2. Select “Indicator using data in SharePoint list” KPI type.

3. On the New Indicator page, do the following:

  1. In the Name and Description boxes, type a name and optional description for the indicator.
  2. In the Comments box, type text to help people who are viewing the KPI understand what it represents.
  3. Under SharePoint List and View, in the List URL box, enter the URL of the list or library.
  4. In View, select the view that contains the items you want to use in the KPI.
  5. Under Value Calculation, select one of the following ways to calculate the goal of the KPI:
  • Number of list items: A count of the total number of items in the list.
  • Percentage of list items: A calculation that compares the value of a content type within a column or up to five columns in the list.
  • Calculation using all list items in the view: A computation of Total, Average, Maximum, or Minimum of a numerical column in the list. Note The Calucaltion using all list items in the view option is only available if your list includes a numerical field.

6.   In the Status Icon section, under Status Icon Rules, in the Better values are list, select higher or lower to indicate which range of numbers will be green.

7.   Type the values for the status indicators in the boxes. For example, to track the minimum percentage complete for a set of tasks, you can set the green indicator at the goal value and the warning value to be one less than the goal value. In that case, if you want to see when the minimum percentage complete drops below 25 percent, you set the green indicator to 25 and the yellow indicator to 24.

After you add all of the KPIs that you want to the KPI list, you can publish them on a Web page by using one of two KPI Web Parts.

Publish the KPI on a Web page
After you add one or more KPI types to the KPI list, you can display the KPI list on My Site, a team site, or any other SharePoint page. In addition, the KPI list is available for use by anyone in your organization who has permissions to access it. You can use one or all of the KPIs that appear on the list. To display the KPIs, you edit the Web page where you want to display the KPI list and add a KPI Web Part. To display the entire KPI list, use the KPI List Web Part. To show only one of the KPIs from the list, use the KPI Details Web Part.

Add a Web Part to a page
1. On the page where you want to add the KPI, click Site Actions, and then select Edit Page.

2. In the zone in which you want to add the KPI, click Add a Web Part.

3. In the Add Web Parts dialog box, in the All Web Parts section, under Dashboard, do one of the following.

  • To insert the entire KPI list, select Key Performance Indicators.
  • To choose one KPI from the KPI list, select KPI Details.

4. Click Add.

Link the KPI list to the Web Part
1. In the Web Part, click Open the tool pane.

2. In the tool pane, under Indicator List, navigate to and double-click the KPI list that you created in the previous set of procedures. The list may be in the Report Center of the site.

3. Select one of the KPIs in the list. (If you selected the KPI List, the entire list is displayed.)

4. Click OK.

Hope this helps–

Source taken from: http://rehmangul.wordpress.com/2007/05/04/key-performance-indicators-kpis-in-moss-2007/

Site Templates Wednesday, May 26 2010 

Site Templates

Site templates are used to allow the rapid creation of web sites and basic content in a SharePoint system. Any number of new sites can be generated based on a site template, which is a set of basic content pages and schemas (which are themselves stored on the Web server as a set of HTML and XML files).  There can be an unlimited number of site templates, although typically there are basic types and a few templates customized to an organization’s specific requirements.

A site template provides the basic components and layout of a new site created under SharePoint. A site template contains specific design information about a site, including the lists that are part of that site, Web Part Pages used in the site, the site’s themes and borders, changes to the Quick Launch bar, as well as some site content (such as document libraries).

A site template creates a copy of the template contents in the new site’s directory location.  These template-created sites can still be modified, but a lot of the basic formatting of the site, as well as the site flow and logic, can be created quickly using a template instead of requiring manual coding.

Where are site templates kept?

When SharePoint Services is installed on a Web server, a default set of site definitions (including site templates and list templates) is created.  Customized versions of an existing site definition can be created, modifying one of the existing sites to more closely suit specific requirements. Typically, new site definitions are made by copying an existing site definition, and then editing that copy.  Modifying the default site templates is not recommended.

Site templates are stored in the SharePoint database and can be accessed through template galleries. Once a site template has been created, other users can use that template (or create copies of it for further modification). User-created site templates can be imported to the site collection level, adding them to the site template gallery. Site template files have an “.stp” extension.

Creating a Site Template

To create a site template, the Add Items right must be granted to the user for the site collection gallery. By default, this exists for the Designer and Administrator site groups, but any group can be given this right by an Administrator.  To create a site based on a site template, the site definition must be available either on the server or in the SharePoint central template gallery.

To create a new site template, follow these steps:

  1. Click on Site Settings
  2. Under the Administration option, click on Go to Site Administration:


  1. Under Management and Statistics, click on Save site as a template


  1. When prompted, enter the name of the site template file. In the Template title field, enter the title of the site template as it will appear in the gallery (a descriptive title works best)


  1. To include any existing site content, click the Include content check box
  2. Click OK

The new site template is added to the site gallery:


Clicking on the template name will initiate the process of creating a new site based on this site template.

Adding a Site Template to the Site Template Gallery

When a site template is created, it is automatically added to the site template gallery. If you are copying site templates from another location as a “.stp” file, you must manually add the site template to the gallery.

To add a site template to the site collection template gallery using the “.stp” file, follow these steps:

  1. From the top-level Web site, click on Site Settings
  2. Under the Administration link, click on Go to Site Administration
  3. Under Site Collection Galleries, click Manage site template gallery


  1. Click Upload Template


  1. Browse to the site template file, or enter the path and name of the file directly.  You can upload several site templates at once by clicking on Upload Multiple Files.


  1. Click Save

The new file templates will now be included in the site gallery.

Deleting a site template

To remove a site template from the site template gallery, follow these steps:

  1. From the top-level Web site, click on Site Settings
  2. Under the Administration link, click on Go to Site Administration
  3. Under Site Collection Galleries, click Manage site template gallery
  4. Click the Edit icon next to the site template you want to delete


  1. Click the Delete button


The site template will be removed from the gallery, although the “.stp” file will not be deleted.

Editing a site template

To edit a site template name or description in the site template gallery, follow these steps:

  1. From the top-level Web site, click on Site Settings
  2. Under the Administration link, click on Go to Site Administration
  3. Under Site Collection Galleries, click Manage site template gallery
  4. Click the Edit icon next to the site template you want to change
  5. Make any changes and click the Save button

Changes to the site template are made immediately.

Source URL:  http://www.datasprings.com/Resources/ArticlesInformation/SharePointMOSS2007SiteTemplates.aspx

User Profiles and Audience Targeting in SharePoint 2007 Wednesday, May 26 2010 

Within any organization, a user is more than just the account he or she uses to log in to the network and the unique ID (for example, CustomerID, VendorID, or EmployeeID) he or she is assigned. A user has a name, a phone number, an address, a title, and maybe even a photograph and food preferences. An organization usually maintains such information in disparate databases. For instance, HR would have information such as emergency contacts and mailing address, whereas payroll may have tax and salary information.

This valuable information usually is locked away in systems that do not talk very well with each other. If all this information could be stored in one system, specific content could be targeted to specific users. So, for example, a new law that applies only to offices in California would be viewed only by users whose PositionState field is CA.

Microsoft Office SharePoint Server 2007 (MOSS 2007), or simply SharePoint 2007, provides just such a solution by introducing the concept of User Profiles. User profiles allow you to associate metadata with every UserID. In MOSS 2007, this metadata can then be kept in sync with the other systems in the organization using BDC, an Active Directory domain controller, or an LDAP server. Having such metadata from disparate systems aggregated and synchronized into one single system.MOSS 2007.presents a very valuable proposition to any organization.

It is quite reasonable to expect that a MOSS User Profile would be an amalgamation of information from various sources. Thus, MOSS provides you with the means to fine-tune such information and its import. This article examines the SharePoint 2007 User Profile feature, beginning with a discussion of what it takes to set up metadata.

User Profiles Setup

Putting User Profiles to Use.Audience Targeting

User Profile information can be incredibly useful. You could write custom utilities on top of such information. For instance, you could provide an “Emergency Contact List” in the form of an Excel spreadsheet by simply reading user profile information. This list then could be interlinked with an emergency coverage schedule, thus allowing the end user to very easily track down the right individual for the right job, along with his contact information, just when he or she needs it.

Besides writing custom utilities to leverage User Profiles, a rather useful way to use user profiles out of the box is audience targeting. Audience targeting refers to the ability to create an audience based on a specific set of rules and then target content to a specific audience.

Before you can use audience targeting, you need to set up a rules-based audience first. Here is how you do so:

  1. Under the Shared Service provider for the web site, click the “Audiences” link under the “Audiences” section.
  2. You will see the number of audiences that exist in the system and a listing of relevant links to view or create audiences. Click “Create Audience.”
  3. Specify an audience, as shown in Figure 4.Source is taken from: http://www.codeguru.com/csharp/.net/net_data/sortinganditerating/article.php/c13255__1/User-Profiles-and-Audience-Targeting-in-SharePoint-2007.htm

Next Page »