Skip to main content

Webpart

Go Search
Home
About Us
MOSS 2007
MOSS 2007 Developer
SharePoint 2010
News
Resources
Tools
White Papers
SharePoint Jobs
SetFocus
  

Other Blogs
There are no items in this list.
SharePoint Proficient - SharePoint Community Site > MOSS 2007 Developer > Webpart

 All Blogs Info

Object Hierarchy of WSSUse SHIFT+ENTER to open the menu (new window).
1/3/2010 1:18 PMCategory 2
What is Feature in SharePoint?Use SHIFT+ENTER to open the menu (new window).
1/3/2010 1:53 PM
IIS Application Pool, SharePoint Logical ArchitectureUse SHIFT+ENTER to open the menu (new window).
1/3/2010 3:46 PM
How to: Add or Delete a List in Multiple Web SitesUse SHIFT+ENTER to open the menu (new window).
1/26/2010 5:51 PM
How to Work on the Event HandlerUse SHIFT+ENTER to open the menu (new window).
1/26/2010 5:52 PMCategory 2
Determining Where to Build a Custom ApplicationUse SHIFT+ENTER to open the menu (new window).
1/26/2010 5:55 PMCategory 2

 MOSS Devlopment Blog

Determining Where to Build a Custom Application

You may want to create custom .aspx pages and Web applications and store them in a location that is accessible from all Web sites in your Windows SharePoint Services deployment. You may also want to create Web applications that contain custom code that works with the global settings for your deployment.

 Location for Custom ASPX Pages and Web Applications

You can build and store custom .aspx pages and Web applications in the following directory, which supports the _layouts virtual directory:

Local_Drive :\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS

Pages in this directory are accessible from all Web sites in the Windows SharePoint Services deployment through a URL in the following form:

http:// Server /[ sites/ ][ Site ]/[ SubSite ]/[.../]_layouts/File_Name.aspx

 Location for Custom Code that Works with Global Settings

For code that involves use of only the Microsoft.SharePoint.Administration namespace for working with global settings in a Windows SharePoint Services deployment, it is recommended that you create the Web application on the administrative port. Build and store .aspx pages and Web applications for the administrative port in the following directory:

Local_Drive :\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\ADMIN

Pages in the \ADMIN directory are accessible through a URL in the following form:

http:// Server:Port_# /_admin/ File_Name .aspx

How to Work on the Event Handler

Creating a Basic Event Handler

The following example shows the basic steps of creating an event handler that executes code before a list item is deleted or after an item is added. The example works on announcement lists, adding text to the body of new items, but cancelling attempts to delete existing items.

You create an event handler assembly in Microsoft Visual Studio 2005 by creating a class library. You add the reference to Microsoft.SharePoint.dll and inherit from the Microsoft.SharePoint.SPItemEventReceiver base class, as shown in the following example.

C#

Copy Code

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

 

namespace MyEventHandlers

 

{

    public class SimpleEventHandler : SPItemEventReceiver    {

    }

}

Windows SharePoint Services 3.0 instantiates an object of your class when actions occur within the list. As a developer, you override the methods of the SharePoint base class for the events you are interested in handling. The methods of the SPItemEventReceiver class that you can override are the following:

The example overrides two methods: ItemDeleting and ItemAdded. Remember that the suffix "ing" indicates that we are handling the event in a synchronous way before the action actually occurs, and the suffix "ed" indicates that we are handling the event in an asynchronous way after the action occurs.

C#

Copy Code

public override void ItemDeleting(SPItemEventProperties properties)

{

    properties.Cancel = true;

    properties.ErrorMessage = "Deleting is not supported.";

}

You have access to the data associated with the SPListItem object through an object that is provided as an input parameter when your method is called. This object is of type SPItemEventProperties. Through the Cancel property of the SPEventPropertiesBase class you can cancel the event, and through the ErrorMessage property you can display a custom error message on a SharePoint page.

The second method to override is ItemAdded. The following example uses the ListItem property to return an object that represents the new list item, and then modifies the body text of the item.

C#

Copy Code

public override void ItemAdded(SPItemEventProperties properties)

{

    SPListItem oItem = properties.ListItem;

    oItem["Body"] = "Body text maintained by the system.";

    oItem.Update();

}

You must register both the ItemDeleting and ItemAdded event receivers as described in Registering an Event Handler.

 

 

 

 

 

 

Registering an Event Handler

Event handlers are registered differently in Windows SharePoint Services 3.0 because of new concepts like content types and Features that it introduces. For backward compatibility reasons, however, Windows SharePoint Services 3.0 supports the existing registration of library events. The EventSinkAssembly, EventSinkClass, and the EventSinkData properties continue to function and are exposed in the user interface.

In Windows SharePoint Services 3.0, there are three fundamental ways to register an event handler:

  • Through the object model, as the SPWeb and SPList classes now each provide an EventReceivers property through which to access the collection of event receiver definitions for the Web site or list. You can add new event receivers by calling the Add method.
  • Declaratively by list type, for example, to register an event handler for all announcements lists. In a Feature.xml file, you can register an event handler by list template ID. When the containing feature is activated per SPWeb object, you can register the event handler for any list of the specified type.
  • Declaratively by content type, for example, to register an event handler for all documents of a specific type. Within the XML for a content type definition, you can register event receivers.

Note The assembly containing your event handler must be strongly named and registered in the global assembly cache (GAC) to be used. You cannot operate event receiver assemblies from the \_app_bin folder (Local_Drive:\Inetpub\wwwroot\wss\VirtualDirectories\GUID\_app_bin).

Content Types

Windows SharePoint Services 3.0 introduces the concept of content types in the data store. In short, content types introduce the notion of reusability to Web designers working with Windows SharePoint Services. Web designers now have the ability to create classes of objects with specific definitions and possible associated behavior, such as type name, fields, format, business processes, retention, auditing, and event handling. You can now activate SharePoint lists and libraries to support multiple content types. When you do that, you can attach one or more of these classes to your list or library and thus extend it with additional functionality and behavior. Think of extending a customer list with a Contact content type. The Contact content type can provide the Customer list with a set of new fields, like Contact Name, Function, Telephone, and so forth, and also with new behavior.

You can now define event handlers for a specific content type. You can, for example, define the content type "Customer", and within its behavior, you can define the metadata for the event handler.

Features

You define content types by using a feature. When you define a content type with a feature, you create two XML files as shown below:

  • Feature.xml   You use this XML file to define the metadata for the new feature. The following example code scopes the feature at the level of the site and defines a unique identifier for the new feature. Using the ElementManifests element, it then points to the location of the second XML file storing all of the detailed information on the feature itself.

Xml

Copy Code

<?xml version="1.0" encoding="utf-8"?>

<Feature Scope="Web"

  Title="Simple Event Handler Registration"

  Id="A6B8687A-3200-4b01-AD76-09E8D163FB9A"

  xmlns="http://schemas.microsoft.com/sharepoint/">

  <ElementManifests>

    <ElementManifest Location="elements.xml"/>

  </ElementManifests>

</Feature>

  • Elements.xml   You use this file to define the assembly that encapsulates the event handler, the class itself, and also a sequence number that specifies the order, if multiple event handlers are associated with the feature. The following example registers event receivers for deleting and adding items.

Xml

Copy Code

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <Receivers ListTemplateId="104">

    <Receiver>

      <Name>MyEventHandlers</Name>

      <Type>ItemDeleting</Type>

      <SequenceNumber>10000</SequenceNumber>

      <Assembly>MyEventHandlers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4358f2a5344ff0dc</Assembly>

      <Class>MyEventHandlers.SimpleEventHandler</Class>

      <Data></Data>

      <Filter></Filter>

    </Receiver>

    <Receiver>

      <Name>MyEventHandlers</Name>

      <Type>ItemAdded</Type>

      <SequenceNumber>10000</SequenceNumber>

      <Assembly>MyEventHandlers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4358f2a5344ff0dc</Assembly>

      <Class>MyEventHandlers.SimpleEventHandler</Class>

      <Data></Data>

      <Filter></Filter>

    </Receiver>

  </Receivers>

</Elements>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Registering Event Handlers as Content Types

Content types are your reusable building blocks within the Windows SharePoint Services data store. Because of this, the event handlers you register at this level are specific to a certain behavior you want to support. Take, for example, a content type like Product Specification, which you might add to a Shared Documents document library. You could create event handlers and register them at the level of the content type, Product Specification, which takes care of very specific processing regarding a specification. When users use this content type, they immediately also get this behavior attached to their list or library.

If your need is to register an event handler for a specific list or library, or for a specific set of lists or libraries, you do it at the level of Features. With regard to lists and libraries, Features are a new, atomic Windows SharePoint Services concept representing specific Collaboration Markup Language (CAML) sections that were previously all consolidated within one file (SCHEMA.XML or ONET.XML). In Windows SharePoint Services 3.0, these CAML sections are now isolated, which means that you can reuse them in different places. You now create the structure and the field definition of a list through a Feature.

With regard to our event handler registration, you can use the concept of the Feature to register your assembly for one specific list or library (by specifying the GUID of the list or library) or for a certain type of list or library (such as all the document libraries or all the form libraries). You define a Feature by creating the same two types of XML files (Feature.xml and Element.xml), as described in Registering an Event Handler.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Event Troubleshooting

Programming events can cause exceptional behaviors, depending on the contexts in which you implement the event handlers. The following table describes event behaviors related to specific contexts that you might encounter when writing code.

Context

Description

Document libraries and content types

You create an .aspx page of a particular content type in a document library, and the page has associated ItemAdding and ItemAdded events, but the events do not fire.

Only default content type properties are present in the Add phase. Additional properties (fields) of the specified content type are added only in the Update phase. Therefore, best practice is to avoid firing Add events with a specified content type ID. Instead, set the content type to the default content type in the Add phase. The content type can subsequently be changed in the Update phase. An alternative is to register the events at the list level.

Document libraries and content types

An ItemAdding event that is bound to a content type fires even when a document that is not of that type is uploaded.

When you first add a document to a library, the content type is always the default content type associated with the list. The content type of the document can be changed during the Update phase and the content type ID is adjusted accordingly.

Document libraries and content types

A request to delete an item through a list form does not have an associated content type ID, but this causes an ItemDeleting or ItemDeleted event to fire on all items, not just on items of a specific content type, even though the event was registered only for the content type.

By design, Windows SharePoint Services fires events for all items in a list when the request is not bound to a content type to allow firing an event for all items when the event receiver is registered for all items in the list.

This behavior affects policies that involve Delete events. If you implement a policy that involves deletion, apply the policy to a content type, and then bind the content type to a list, the policy will apply to all items in the list, not only to the items of the content type to which the policy is applied.

Lists and content types

You register ItemUpdating and ItemUpdated events on a content type that is bound to a list, but the events fire even when items that are not of that content type are updated through the object model.

Windows SharePoint Services returns 0 (zero) as the content type ID, not the content type ID of the item.

Lists

The BeforeProperties property applies only to DocumentLibrary type lists.

The workaround is to return the properties by using the object model and the given list item ID.

Document libraries

You add a custom content type to a document library. ItemAdding, ItemAdded, and ItemUpdating events fire, but not ItemUpdated events.

This behavior occurs only for the Shared Documents document library and not for custom document libraries. For Shared Documents, adding a content type creates a Forms/<Content Type> folder and copies a Template.doc file into that folder, which causes the events to fire.

Document libraries and content types

For folders, you get the content type and content type ID through the AfterProperties property in the ItemAdding and ItemAdded, events, but for documents, you get the content type ID only in the ItemAdded event and nothing in the ItemAdding event.

The Windows SharePoint Services parser for Microsoft Office system documents does not set the content type name in a document dictionary. Document metadata does not set a content type name.

Lists

List events do not fire on the UserInfo list.

Lists

An ItemAdded event fires on a folder type item, but the list item ID is not returned.

Document libraries

Events do not fire when unlinking a document copy from the original document.

Document libraries

List item IDs always equal 0 when events fire on documents in the Forms folder. If you register an ItemUpdating event in a document library and then modify EditForm.aspx, the event fires, but the ID equals 0 (zero) because the item is not a regular list item.

Lists

Event receivers do not bind to a list when the list is provisioned through Onet.xml and the list type has an associated Feature that binds a receiver to the list. You create a Feature that binds a receiver to a list type, create a list of that type through the site definition, but the receiver is not bound to the list when a site is provisioned. A workaround is to bind the receiver to a content type instead, and then bind the content type to the list.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Walkthrough: Handling Document Library Events

Windows SharePoint Services provides document library events that enable developers to build upon the SharePoint platform. Developers can create managed code assemblies that define handlers for these events and then bind the handlers to document libraries. The event handlers can call into the SharePoint object model to access the configuration and content databases directly, or they can invoke external services, using Windows SharePoint Services as a user interface for other systems.

Note:

This walkthrough describes a procedure that is maintained for backward compatibility with Windows SharePoint Services 2.0 event handling.

 Prerequisites

The following table describes the events for document libraries that Windows SharePoint Services provides.

Event

Description

Undo Check Out

Changes made to a checked-out document are undone.

Check In

A document is checked in to the library.

Check Out

A document is checked out from the library.

Copy

A document in the library is copied.

Delete

A document is deleted from the library.

Insert

A new document is saved to the library.

Move or Rename

A document is moved or renamed.

Update

An existing document or the value of a custom column in the library is edited.

In the context of Windows SharePoint Services, an event handler is a Microsoft .NET class that implements the IListEventSink interface, whose one method, OnEvent, is used within the handler. The SPListEvent object contains information about an event that occurs, and you can return the type of event through the Type property. Use the Site property to access the object model of the Microsoft.SharePoint namespace within the handler.

You must install the managed assembly that defines an event handler in the global assembly cache. In a server farm configuration, you must install this managed assembly in the global assembly cache of each front-end Web server.

To deploy an event handler on a server, event handling must be enabled on the Virtual Server General Settings page in SharePoint Central Administration.

Only users with full permissions for a document library can add event handlers.

 Event Settings

The list metadata for a document library binds the class of an event handler to a library by means of the following properties. The metadata can be set on the Document Library Advanced Settings page for the document library through code that implements the EventSinkAssembly, EventSinkClass, and EventSinkData properties of the SPList class, or through definitions contained in front-end site templates. The following table summarizes the event settings.

Setting

Type

Description

Assembly Name

String

The strong name of the event handler assembly file that lives in the global assembly cache.

Class Name

String

The fully qualified, case-sensitive name of the class within the assembly.

Properties

String

An arbitrary string of custom properties for use by the event handler. The length of the string cannot exceed 255 characters.

After you install the event handler assembly, on the Document Library Advanced Settings page for the document library, specify the strong name of the assembly in the Assembly Name box. The strong name must be in the format Assembly_Name, Version=Version, Culture=Culture, PublicKeyToken=Public_Key_Token. You can obtain these values by browsing to %windir%\assembly in Windows Explorer. As an example, the strong name for the Microsoft.SharePoint assembly resembles Microsoft.SharePoint, Version=12.0.0.0, Culture=Neutral, PublicKeyToken=71e9bce111e9429c.

The value that you specify in the Class Name box must be the full, case-sensitive name of a class defined in the specified assembly that implements the IListEventSink interface. For example, the full name of the class in the following example would be myNamespace.myClass.

Visual Basic

Copy Code

Namespace myNamespace

 

    Public Class myClass

 

        Inherits Microsoft.SharePoint.IListEventSink

 

        Public Sub OnEvent(evt As Microsoft.SharePoint.SPListEvent)

 

            'Add an announcement

            AddAnnouncement(evt)

 

        End Sub 'OnEvent

 

        Public Sub AddAnnouncement(evt As

           Microsoft.SharePoint.SPListEvent)

        .

        .

        .

        End Sub 'AddAnnouncement

 

    End Class 'myClass

 

End Namespace 'myNamespace

C#

Copy Code

namespace myNamespace

{

    public class myClass : Microsoft.SharePoint.IListEventSink

    {

        public void OnEvent(Microsoft.SharePoint.SPListEvent evt)

        {

            //Add an announcement

            AddAnnouncement(evt);

        }

 

        public void AddAnnouncement

           (Microsoft.SharePoint.SPListEvent evt)

        {

            .

            .

            .

        }

    }

}

Typing a value in the Properties box is optional. This value can contain up to 255 characters for use by the event handler.

 Events in Relation to Other Events

An event handler running in the context of Windows SharePoint Services cannot generate other events. To program side effects for an event, you must provide the code within the event handler. The event handler is called asynchronously from the actual request.

A new instance of an event handler class is created for each event. Consequently, you cannot store state in your event handler class and expect it to persist across multiple events. You can, however, create a base class for an event handler or for multiple event handlers that caches state so that the same sink object can be used for all events on a document library.

 Caching Credentials

Event handlers run in the context of the Internet Information Services (IIS) Application Pool Identity, an account that typically has no permissions in Windows SharePoint Services. If your handler needs to interact with Windows SharePoint Services through the object model, you must establish and cache credentials through impersonation of a user. Accessing the object model in an event handler without impersonation is not supported. For information, see Impersonating and Reverting in the .NET Framework Developer's Guide on MSDN.

 Security Context

The event handler thread runs within the same application pool account as the SharePoint Web application. If, however, the event handler needs to run in a different account to manipulate Windows SharePoint Services or an external service, the developer must maintain his or her own user credentials and manage his or her own security context.

 Exceptions and Errors

Exceptions for event handlers used in Windows SharePoint Services are thrown in the following conditions, for which a Microsoft Windows NT event log entry is created:

  • The assembly for the handler cannot be loaded.
  • The class defining the handler is not found.
  • The class does not implement the IlistEventSink interface.
  • The OnEvent method throws an exception.

Note:

When you restart IIS, each IIS worker process terminates only after all its queued work items, including HTTP requests and document library events, complete their tasks.

 Definitions and Templates

Developers can define event handler assemblies within list definitions, which provides a useful means for deploying solutions such as workflow-enabled document libraries in which events are already bound to the appropriate handlers. An event handler can be bound to a document library through the EventSinkAssembly, EventSinkClass, and EventSinkData attributes of the List element in the Schema.xml file for the list type. When an end user creates a library through the user interface (UI) from a list definition that specifies an event handler, list event settings are automatically set to the values specified in the definition. When an end user saves a document library as a list template, event settings specified through the UI are preserved in the template.

For information about definitions and templates for sites or lists, see Working with Site Templates and Definitions.

 Event handler example

The following programming task creates an event handler that deletes the oldest version of a file in a document library when the number of versions for the file reaches a specified number. To establish credentials for the handler, a method returns a token to the event handler for impersonation of a user.

 Procedure

To create a document library event handler

1.     On the File menu in Visual Studio 2005, point to New and then click Project.

2.     In the New Project dialog box, select Visual Basic Projects or Visual C# Projects in the Project Types box.

3.     In the Templates box, select Class Library.

4.     In the Name box, type the name of the project, which in this task is "DocLibHandler".

5.     In the Location box, type the path for the project, and then click OK.

6.     In Solution Explorer, right-click the References node, and click Add Reference on the shortcut menu.

7.     On the .NET tab of the Add Reference dialog box, select Windows SharePoint Services in the list of components, click Select, and then click OK.

8.     Add the following directives to the Class1.cs or Class1.vb file of the DocLibHandler project after the System directive that is included by default.

Visual Basic

Copy Code

Imports System.Security.Principal

Imports System.Runtime.InteropServices

Imports Microsoft.SharePoint

C#

Copy Code

using System.Security.Principal;

using System.Runtime.InteropServices;

using Microsoft.SharePoint;

9.     Change the namespace and class name in the Class1.cs or Class1.vb file to be DocLibEventHandler and DocVersionHandler, as follows.

Visual Basic

Copy Code

Namespace DocLibEventHandler

  

   Public Class DocVersionHandler

      Implements IlistEventSink

C#

Copy Code

namespace DocLibEventHandler

{

    public class DocVersionHandler : IListEventSink

    {

10.  Add the OnEvent method of the IListEventSink interface to the DocVersionHandler class, as follows.

Visual Basic

Copy Code

Private maxVersions As Integer = 5

 

Sub IListEventSink.OnEvent(listEvent

    As Microsoft.SharePoint.SPListEvent)

 

    ' TODO: ***** PROVIDE YOUR IMPLEMENTATION HERE ****

    ' Get the credentials (User_Alias, Domain, Password) that this

    ' event sink instance should run as and initialize the wic

    ' object by calling the CreateIdentity method

 

    Dim wic As WindowsImpersonationContext

        = CreateIdentity(User_Alias, Domain, Password).Impersonate()

 

    If listEvent.Type = SPListEventType.Update OrElse listEvent.Type

        = SPListEventType.CheckIn Then

 

        Dim site As SPWeb = listEvent.Site.OpenWeb()

        Dim file As SPFile = site.GetFile(listEvent.UrlAfter)

        Dim nDocVersions As Integer = file.Versions.Count

 

        While maxVersions > 0 AndAlso nDocVersions > maxVersions - 1

 

            file.Versions.Delete(0)

            nDocVersions = file.Versions.Count

 

        End While

 

    End If

 

    wic.Undo()

 

End Sub 'IListEventSink.OnEvent

C#

Copy Code

private int maxVersions = 5;

 

void IListEventSink.OnEvent

    (Microsoft.SharePoint.SPListEvent listEvent)

{

    /* TODO: ***** PROVIDE YOUR IMPLEMENTATION HERE ****

    Get the credentials (User_Alias, Domain, Password) that this

    event sink instance should run as and initialize the wic object

    by calling the CreateIdentity method*/

 

    WindowsImpersonationContext wic

       = CreateIdentity(User_Alias, Domain, Password).Impersonate();

 

    if ((listEvent.Type == SPListEventType.Update) ||

        (listEvent.Type == SPListEventType.CheckIn))

    {

        SPWeb site = listEvent.Site.OpenWeb();

        SPFile file = site.GetFile(listEvent.UrlAfter);

        int nDocVersions = file.Versions.Count;

 

        while ((maxVersions > 0) && (nDocVersions

            > (maxVersions - 1)))

        {

            file.Versions.Delete(0);

            nDocVersions = file.Versions.Count;

        }

    }

 

    wic.Undo();

}

11.  The OnEvent method calls the following method to impersonate an account with administrative permissions.

Important:

Do not pass credentials in clear-text, because doing so presents a security risk. To impersonate a user more securely, you can return the information programmatically with functions provided by the operating system for getting secret data from the user, such as the CryptProtectData and CryptUnprotectData functions of the Data Protection API (DPAPI).

12.  Include the following method within the DocVersionHandler class.

13.  Visual Basic

  1. Copy Code

16.Protected Shared Function CreateIdentity(User As String, Domain

17.    As String, Password As String) As WindowsIdentity

18. 

19.    ' The Windows NT user token.

20.    Dim tokenHandle As New IntPtr(0)

21. 

22.    Const LOGON32_PROVIDER_DEFAULT As Integer = 0

23.    Const LOGON32_LOGON_NETWORK As Integer = 3

24. 

25.    tokenHandle = IntPtr.Zero

26. 

27.    ' Call LogonUser to obtain a handle to an access token.

28.    Dim returnValue As Boolean = LogonUser(User, Domain, Password,

29.       LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, tokenHandle)

30. 

31.    If False = returnValue Then

32. 

33.        Dim ret As Integer = Marshal.GetLastWin32Error()

34.        Throw New Exception("LogonUser failed with

35.            error code: " + ret)

36. 

37.    End If

38. 

39.    System.Diagnostics.Debug.WriteLine(("Created user token:

40.        " + tokenHandle))

41. 

42.    'The WindowsIdentity class makes a new copy of the token.

43.    'It also handles calling CloseHandle for the copy.

44.    Dim id As New WindowsIdentity(tokenHandle)

45.    CloseHandle(tokenHandle)

46.    Return id

47. 

48.End Function 'CreateIdentity

49.<DllImport("advapi32.dll", SetLastError := True)>  _

50.    Private Shared Function LogonUser(lpszUsername As String,

51.            lpszDomain As String, _

52.        lpszPassword As String, dwLogonType As Integer,

53.            dwLogonProvider As Integer, _

54.        ByRef phToken As IntPtr) As Boolean

55. 

56.<DllImport("kernel32.dll", CharSet := CharSet.Auto)>  _

57.    Private Shared Declare Auto Function CloseHandle Lib

58.        "kernel32.dll" (handle As IntPtr) As Boolean

59.  C#

  1. Copy Code

62.protected static WindowsIdentity CreateIdentity(string User,

63.    string Domain, string Password)

64.{

65.    // The Windows NT user token.

66.    IntPtr tokenHandle = new IntPtr(0);

67. 

68.    const int LOGON32_PROVIDER_DEFAULT = 0;

69.    const int LOGON32_LOGON_NETWORK = 3;

70. 

71.    tokenHandle = IntPtr.Zero;

72. 

73.    // Call LogonUser to obtain a handle to an access token.

74.    bool returnValue = LogonUser(User, Domain, Password,

75.    LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,

76.    ref tokenHandle);

77. 

78.    if (false == returnValue)

79.    {

80.        int ret = Marshal.GetLastWin32Error();

81.        throw new Exception("LogonUser failed with

82.            error code: " +  ret);

83.    }

84. 

85.    System.Diagnostics.Debug.WriteLine("Created user token:

86.        " + tokenHandle);

87. 

88.    //The WindowsIdentity class makes a new copy of the token.

89.    //It also handles calling CloseHandle for the copy.

90.    WindowsIdentity id = new WindowsIdentity(tokenHandle);

91.    CloseHandle(tokenHandle);

92.    return id;

93.}

94. 

95.[DllImport("advapi32.dll", SetLastError=true)]

96.private static extern bool LogonUser(String lpszUsername,

97.    String lpszDomain, String lpszPassword,

98.int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

99. 

100. [DllImport("kernel32.dll", CharSet=CharSet.Auto)]

101. private extern static bool CloseHandle(IntPtr handle);

102.                To create a strong name for the assembly, go to the Local_Drive:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin directory (Local_Drive:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin in Visual Studio .NET Version 7) through a command prompt, and type sn -k Local_Drive:\DocLibHandler.snk, which creates a key file for the assembly.

103.                Add the following attributes for the assembly version and key file to the AssemblyInfo file of the project, replacing the attributes that are provided by default.

Copy Code

[assembly: AssemblyVersion("1.0.0.0")]

[assembly: AssemblyKeyFile("Local_Drive:\\DocLibHandler.snk")]

104.                Click Build Solution on the Build menu.

105.                To install your solution in the global assembly cache, drag the dynamic-link library (DLL) of your assembly to the Local_Drive:\WINDOWS\assembly directory in Windows Explorer.

106.                On the Virtual Server General Settings page in SharePoint Central Administration, select On in the Event Handlers section to enable use of event handlers on the virtual server.

107.                From a view of the document library to which you want to attach the event handler assembly, click Modify settings and columns, and then click Change advanced settings on the page for customizing the document library.

108.                On the Document Library Advanced Settings page, type the strong name for the assembly in the Assembly Name box. (For example, DocLibHandler, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=0fafac2a0cc92888.) You can get the values used in the strong name by right-clicking the DLL of your assembly in the Local_Drive:\WINDOWS\assembly directory and then clicking Properties on the shortcut menu.

109.                Type the fully qualified, case-sensitive name of the class in the Class Name box, which in this example is DocLibEventHandler.DocVersionHandler.

110.                Reset IIS by typing iisreset at a command prompt.

 Next Steps

To implement the handler in a document library, versioning must be enabled on the Document Library Settings page for the library.

 

 

 

 

 

How to: Add or Delete a List in Multiple Web Sites

How to: Add or Delete a List in Multiple Web Sites

You can use one of the Add methods of the SPListCollection class to add a list to multiple Web sites across a site collection.

The following example creates a generic list on every Web site, based on the title and description that is passed from two text boxes to the code. The AllWebs property of the SPSite class is used to return the collection of all Web sites that exist on the site.

This example assumes the existence of two text boxes on the .aspx page that contains a form.

Visual Basic

Copy Code

Dim listTitle As String = TextBox1.Text.ToString()

Dim listDescription As String = TextBox2.Text.ToString()

 

Dim mySite As SPSite = SPContext.Current.Site

Dim allWebs As SPWebCollection = mySite.AllWebs

Dim web As SPWeb

 

For Each web In  allWebs

    Dim allLists As SPListCollection = web.Lists

    allLists.Add(listTitle, listDescription, SPListTemplateType.GenericList)

Next web

C#

Copy Code

string listTitle = TextBox1.Text.ToString();

string listDescription = TextBox2.Text.ToString();

 

SPSite mySite = SPContext.Current.Site;

SPWebCollection allWebs = mySite.AllWebs;

 

foreach (SPWeb web in allWebs)

{

    SPListCollection allLists = web.Lists;

    allLists.Add(listTitle,listDescription, SPListTemplateType.GenericList);

}

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

If you want to delete a list from every Web site in which it appears, use the Delete method of the SPListCollection class. The following example uses nested loops to drill down to a list that has a title matching the title specified in a text box. The example assumes the existence of a text box on the .aspx page that contains a form.

Visual Basic

Copy Code

Dim mySite As SPSite = SPContext.Current.Site

Dim allWebs As SPWebCollection = mySite.AllWebs

Dim web As SPWeb

 

For Each web In  allWebs

    Dim allLists As SPListCollection = web.Lists

    Dim i As Integer

 

    For i = 0 To allLists.Count - 1

        Dim list As SPList = allLists(i)

 

        If list.Title = TextBox1.Text Then

            Dim listGuid As Guid = list.ID

            allLists.Delete(listGuid)

        End If

    Next i

Next web

C#

Copy Code

SPSite mySite = SPContext.Current.Site;

SPWebCollection allWebs = mySite.AllWebs;

 

foreach (SPWeb web in allWebs)

{

    SPListCollection allLists = web.Lists;

 

    for (int i=0; i<allLists.Count; i++)

    {

        SPList list = allLists[i];

 

        if (list.Title == TextBox1.Text)

        {

            Guid listGuid = list.ID;

            allLists.Delete(listGuid);

        }

    }

}

In the example the Title property of the SPList class is used to identify a list in the collection of lists for each Web site that matches the specified title. The ID property returns the globally unique identifier (GUID) of the list, which is passed as the parameter for the Delete method.

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

 

 

 

 

 

 

How to: Return Items from a List

To return items from a list, you can instantiate an SPWeb object and drill down through the object model to the SPListItemCollection object for the list. After you return the collection of all items for a list, you can iterate through the collection and use indexers to return specific field values.

The following example returns all the items for a specified Events list. It assumes the existence of a text box that can be used to type the name of an Events list.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim listItems As SPListItemCollection = mySite.Lists(TextBox1.Text).Items

Dim i As Integer

 

For i = 0 To listItems.Count - 1

 

   Dim item As SPListItem = listItems(i)

 

   Response.Write(SPEncode.HtmlEncode(item("Title").ToString()) & " :: " _

      & SPEncode.HtmlEncode(item("Location").ToString()) & " :: " _

      & SPEncode.HtmlEncode(item("Begin").ToString()) & " :: " _

      & SPEncode.HtmlEncode(item("End").ToString()) & "<BR>")

 

Next i

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

 

for (int i=0;i<listItems.Count;i++)

{

   SPListItem item = listItems[i];

 

   Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " : " +

      SPEncode.HtmlEncode(item["Location"].ToString()) + " : " +

      SPEncode.HtmlEncode(item["Begin"].ToString()) + " : " +

      SPEncode.HtmlEncode(item["End"].ToString()) + "<BR>");

}

This example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

In the example, indexers are used both to return the list that is typed by the user and to return specific items from the list. To return the items, the indexers must specify the name of each column whose value is returned. In this case, all the field names pertain to a common Events list.

You can also use one of the GetItems methods of the SPList class to return a subset of items from a list. The following example returns only Title column values where the Stock column value surpasses 100.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim list As SPList = mySite.Lists("Books")

 

Dim query As New SPQuery()

query.Query = "<Where><Gt><FieldRef Name='Stock'/><Value Type='Number'>100</Value></Gt></Where>"

 

Dim myItems As SPListItemCollection = list.GetItems(query)

Dim item As SPListItem

 

For Each item In myItems

   Response.Write(SPEncode.HtmlEncode(item("Title").ToString()) & "<BR>")

Next item

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPList list = mySite.Lists["Books"];

 

SPQuery query = new SPQuery();

query.Query = "<Where><Gt><FieldRef Name='Stock'/><Value Type='Number'>100</Value></Gt></Where>";

 

SPListItemCollection myItems = list.GetItems(query);

 

foreach (SPListItem item in myItems)

{

   Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + "<BR>");

}

The previous example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

The example assumes the existence of a Books list that has a Stock column containing number values.

The previous example uses a constructor to instantiate an SPQuery object, and then assigns to the Query property of the query object a string in Collaborative Application Markup Language Core Schemas that specifies the inner XML for the query (in other words, the Where element). After the GetItems property is set, the query object is passed through the GetItems method to return and display items.

Cross-List Queries

You can perform cross-list queries to query more efficiently for data across multiple Web sites. The following example uses the SPSiteDataQuery class to define a query, and then uses the GetSiteData method to return items where the Status column equals "Completed".

Visual Basic

Copy Code

Dim webSite As SPWeb = SPContext.Current.Web

Dim query As New SPSiteDataQuery()

 

query.Lists = "<Lists ServerTemplate=""107"" />"

query.Query = "<Where><Eq><FieldRef Name=""Status""/>" + "<Value Type=""Text"">Completed</Value></Eq></Where>"

 

Dim items As System.Data.DataTable = webSite.GetSiteData(query)

Dim item As System.Data.DataRow

 

For Each item In items

   Response.Write((SPEncode.HtmlEncode(item("Title").ToString()) + "<BR>"))

Next item

C#

Copy Code

SPWeb webSite = SPContext.Current.Web;

SPSiteDataQuery query = new SPSiteDataQuery();

 

query.Lists = "<Lists ServerTemplate=\"107\" />";

query.Query =

   "<Where><Eq><FieldRef Name=\"Status\"/>" +

   "<Value Type=\"Text\">Completed</Value></Eq></Where>";

 

System.Data.DataTable items = webSite.GetSiteData(query);

 

foreach (System.Data.DataRow item in items)

{

   Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + "<BR>");

}

This example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

 

 

 

 

 

 

 

 

 

 

How to: Add or Delete List Items

To add items to a list, use the Add method of the SPListItemCollection class to create an item object, and then use the Update method of the SPListItem class to update the database with the new item.

The following example assumes the existence of five text boxes, one that specifies the name of the list to add to, and four others that are used to specify the values to add. Indexers are used to gather the input from all five sources.

Note:

The code examples in this topic use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list. Outside of an HTTP context, such as in a console application or a Windows application, you obtain references to key objects with a different method. For more information, see Getting References to Sites, Web Applications, and other Key Objects.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim listItems As SPListItemCollection

    = mySite.Lists(TextBox1.Text).Items

 

Dim item As SPListItem = listItems.Add()

 

item("Title") = TextBox2.Text

item("Stock") = Convert.ToInt32(TextBox3.Text)

item("Return Date") = Convert.ToDateTime(TextBox4.Text)

item("Employee") = TextBox5.Text

 

item.Update()

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

 

SPListItem item = listItems.Add();

 

item["Title"] = TextBox2.Text;

item["Stock"] = Convert.ToInt32(TextBox3.Text);

item["Return Date"] = Convert.ToDateTime(TextBox4.Text);

item["Employee"] = TextBox5.Text;

 

item.Update();

}

The example first creates an SPListItem object through the Add method of the collection. It then assign values to specific fields by using an indexer on the list item. For example, item["Title"] specifies the Title column value for the item. Finally, the example calls the Update method of the list item to effect changes in the database.

The previous example requires a using directive (Imports in Microsoft Visual Basic) for the Microsoft.SharePoint namespace.

To create list items with metadata that will be preserved, you can use the Author, Editor, Created, and Modified fields as indexers, where Author or Editor specify a Windows SharePoint Services user ID. For an example, see the SPListItem class.

To delete items from a list, use the Delete method of the SPListItemCollection class, which takes as its parameter an index into the collection.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim listItems As SPListItemCollection

    = mySite.Lists(TextBox1.Text).Items

Dim itemCount As Integer = listItems.Count

Dim k As Integer

 

For k = 0 To itemCount - 1

    Dim item As SPListItem = listItems(k)

 

    If TextBox2.Text = item("Employee").ToString() Then

        listItems.Delete(k)

    End If

Next k

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

int itemCount = listItems.Count;

 

for (int k=0; k<itemCount; k++)

{

    SPListItem item = listItems[k];

 

    if (TextBox2.Text==item["Employee"].ToString())

    {

        listItems.Delete(k);

    }

}

Based on input from two text boxes, the example iterates through the collection of items for the specified list and deletes an item if the Employee field value matches the specified value.

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

 

 

 

 

IIS Application Pool, SharePoint Logical Architecture

Imp tips about Application Pool: (Logical Architecture):

 

·         An application pool is a grouping of one or more URLs (or Web sites as they are represented in IIS) served by a worker process

·         Capacity Planning

1)      The memory overhead of an application pool is 30-50 megabytes (MB) plus any memory for the applications running in the application pool process space

2)      The limit for the number of application pools is influenced by the available memory on the system and size of application running in the application pool

3)      The general guideline for acceptable performance is to use eight or fewer application pools.

·         Sharing and Isolation: IIS Application Pool provides a way for multiple website to run on same computer but still have their own worker process and identity. This can help to prevent the attacker to inject the malicious code that can attack sites in different Application Pool.

·         Configurable Items: Use separate Application pool identity for each application pool

·         Planning Recommendations: You should use dedicated Application Pool for following:

1)      To separate Authenticated content from Anonymous content

2)      To isolate application that stores password and interact with external business application

What is Feature in SharePoint?

Features reduce the complexity involved in making simple site customizations, and are robust when upgrades are applied to a deployment. Features eliminate the need to copy large chunks of code to change simple functionality. Features thus reduce versioning and inconsistency issues that may arise among front-end Web servers. Features make it easier to activate or deactivate functionality in the course of a deployment, and administrators can easily transform the template or definition of a site by simply toggling a particular Feature on or off in the user interface.

What are Feature Capabilities?

Features provide the following capabilities:

·         Scoping semantics for determining where custom code runs

·         Pluggable behavior for installing or uninstalling Features within a deployment

·         Pluggable behavior for activating or deactivating Features at a given scope

·         A scoped property bag for storing data required by a Feature within its scope

·         The basis of a unified framework for distributed deployment of Windows SharePoint Services solutions

What is Process of SharePoint Feature Implementation?

Feature Implementation:

 

1)      Add Subfolder to 12 hives under Template\Feature. (Imp Tip – If create folder by right click and New and add new folder, the new folder does not have inherited permissions. So if you deploy feature in the folder, then some Windows SharePoint Services Pages such as Site Settings, list views throws exceptions. You can fix this problem by right client Property, Security Advance. On the permission tab delete inherited permission from the folder. Or else create folder in DOS  )

2)      This folder includes Feature.xml file. This file contains base properties of features and list elements bound to properties

3)      This subfolder may contain supporting files also - .aspx, .htm, .xsn, resx, .dll and other file types

 

4)      Install feature from Command line STSADM - stsadm –o installfeature –filename <path of the Feature.xml file relative to the 12\TEMPLATE\ FEATURES folder >

 

5)      Activate feature through user interface

 

6)      stsadm –o activatefeature –name < folder in FEATURES directory containing the Feature.xml file > -url http://Server/Site/Subsite

 

 

7)      Installing feature makes it definition and elements known through Server Farm

Object Hierarchy of WSS

 

 WSS 3.0 Object model is divided into three hierarchies:

1)     Physical Object Hierarchy

2)     Content Hierarchy

3)     Services Hierarchy

All object hierarchy contains classes and containers

Physical Object Hierarchy includes classes that represent Physical Entities such as Servers and files AND Containers of such entities such as Farms and Folders

Content Hierarchy includes classes that represent publishable items of data such as list items, and classes that represents nested containers of data such as lists, Content DB, websites, collections of websites, Web Applications

Service Hierarchy includes classes that represent services and instances

 

Physical Object Hierarchy: There are four major classes in this Hierarchy

 

SPFarm:

1)     WSS 3.0 farm is represented by SPFarm class.  Server farm is one or more WFE, Zero or more AS and SQL Server.

2)     The SPFarm class represents a farm of one or more physical servers, so it is included in the Physical Hierarchy. But it can also be considered the top level of the Content Hierarchy; for example, all the (non-configuration) content of a Windows SharePoint Services farm can be backed up and restored.

3)     SPFarm class can also be thought of as representing the configuration database that is associated with the farm because Windows SharePoint Services 3.0 has no class that represents the configuration database itself

4)     SPFarm OBJECT has three classes: SPServer, SPService and SPSolution

5)     SPFarm inherits from SPPersistedObject, which means that the object (there is only one) that instantiates the class persists in the configuration database.

6)     SPFarm has static members for creating farms and returning references to the local farm or a remote farm.

7)     SPFarm has many members that can be used for developing administration functionality. Some of the more important members can help in the administration of the following:

·         Backup and restoration of the farm

·         Upgrades of the farm

·         Migration of (moving) the farm

·         Error reporting

·         Caching

 

SPServer:

1)     A physical server is represented by the SPServer class.

2)     It has an Address property that holds the IP address of the server and a Role property that identifies the server's role in the farm

3)     If there is just one server, its Role is SingleServer. If there is more than one, the front-end servers have the role WebFrontEnd an

4)     d almost all other servers have the role Application

5)     However, the Role property of a server that is physically hosting a Windows SharePoint Services content database typically has the value Invalid. This is because such servers typically run only one Windows SharePoint Services service—the Database Service (which is a Windows service)—and this database service is really just an alias for the SQL Server Windows service which is not part of Windows SharePoint Services. Hence, it is not really running any Windows SharePoint Services code, and it does not really fit into the Application role.

6)     The SPServer class also has a ServiceInstances property that holds references to all the instances of Windows services and Web services that are running on the server

7)     SPServer inherits from SPPersistedObject

 

SPFolder: Notice that the entity represented by an SPFolder object or an SPFile object might be located in a Windows SharePoint Services content database instead of in the file system of a server. For example, a spreadsheet file in a Windows SharePoint Services document library is stored in a cell of a database, not in a folder on one of the servers.

1)     Represents a folder on a SharePoint Web site.

2)     Various folder properties in the Microsoft.SharePoint namespace return a folder object; however, the GetFile method of the SPWeb class returns any folder from within a site or subsite.

3)     Use the Folders property of the SPWeb class, or the SubFolders property of the SPFolder class, to return an SPFolderCollection object that represents the collection of folders for a site or folder. Use an indexer to return a single folder from the collection. For example, if the collection is assigned to a variable named collFolders, use collFolders[index] in C#, or collFolders(index) in Visual Basic, where index is either the index number of the folder in the collection or the display name of the folder.

SPFile:

1)     SPFile Class represents a file in a SharePoint Web site that can be a Web Part Page, an item in a document library, or a file in a folder.

2)     Use the GetFile or GetFileAsString method of the SPWeb class to return a single file object. Otherwise, use the Files property of either the SPWeb or SPFolder class to return an SPFileCollection object that represents the collection of files for a site or folder. Use an indexer to return a single file from the collection

Determining Where to Build a Custom Application

You may want to create custom .aspx pages and Web applications and store them in a location that is accessible from all Web sites in your Windows SharePoint Services deployment. You may also want to create Web applications that contain custom code that works with the global settings for your deployment.

 Location for Custom ASPX Pages and Web Applications

You can build and store custom .aspx pages and Web applications in the following directory, which supports the _layouts virtual directory:

Local_Drive :\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS

Pages in this directory are accessible from all Web sites in the Windows SharePoint Services deployment through a URL in the following form:

http:// Server /[ sites/ ][ Site ]/[ SubSite ]/[.../]_layouts/File_Name.aspx

 Location for Custom Code that Works with Global Settings

For code that involves use of only the Microsoft.SharePoint.Administration namespace for working with global settings in a Windows SharePoint Services deployment, it is recommended that you create the Web application on the administrative port. Build and store .aspx pages and Web applications for the administrative port in the following directory:

Local_Drive :\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\ADMIN

Pages in the \ADMIN directory are accessible through a URL in the following form:

http:// Server:Port_# /_admin/ File_Name .aspx

How to Work on the Event Handler

Creating a Basic Event Handler

The following example shows the basic steps of creating an event handler that executes code before a list item is deleted or after an item is added. The example works on announcement lists, adding text to the body of new items, but cancelling attempts to delete existing items.

You create an event handler assembly in Microsoft Visual Studio 2005 by creating a class library. You add the reference to Microsoft.SharePoint.dll and inherit from the Microsoft.SharePoint.SPItemEventReceiver base class, as shown in the following example.

C#

Copy Code

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

 

namespace MyEventHandlers

 

{

    public class SimpleEventHandler : SPItemEventReceiver    {

    }

}

Windows SharePoint Services 3.0 instantiates an object of your class when actions occur within the list. As a developer, you override the methods of the SharePoint base class for the events you are interested in handling. The methods of the SPItemEventReceiver class that you can override are the following:

The example overrides two methods: ItemDeleting and ItemAdded. Remember that the suffix "ing" indicates that we are handling the event in a synchronous way before the action actually occurs, and the suffix "ed" indicates that we are handling the event in an asynchronous way after the action occurs.

C#

Copy Code

public override void ItemDeleting(SPItemEventProperties properties)

{

    properties.Cancel = true;

    properties.ErrorMessage = "Deleting is not supported.";

}

You have access to the data associated with the SPListItem object through an object that is provided as an input parameter when your method is called. This object is of type SPItemEventProperties. Through the Cancel property of the SPEventPropertiesBase class you can cancel the event, and through the ErrorMessage property you can display a custom error message on a SharePoint page.

The second method to override is ItemAdded. The following example uses the ListItem property to return an object that represents the new list item, and then modifies the body text of the item.

C#

Copy Code

public override void ItemAdded(SPItemEventProperties properties)

{

    SPListItem oItem = properties.ListItem;

    oItem["Body"] = "Body text maintained by the system.";

    oItem.Update();

}

You must register both the ItemDeleting and ItemAdded event receivers as described in Registering an Event Handler.

 

 

 

 

 

 

Registering an Event Handler

Event handlers are registered differently in Windows SharePoint Services 3.0 because of new concepts like content types and Features that it introduces. For backward compatibility reasons, however, Windows SharePoint Services 3.0 supports the existing registration of library events. The EventSinkAssembly, EventSinkClass, and the EventSinkData properties continue to function and are exposed in the user interface.

In Windows SharePoint Services 3.0, there are three fundamental ways to register an event handler:

  • Through the object model, as the SPWeb and SPList classes now each provide an EventReceivers property through which to access the collection of event receiver definitions for the Web site or list. You can add new event receivers by calling the Add method.
  • Declaratively by list type, for example, to register an event handler for all announcements lists. In a Feature.xml file, you can register an event handler by list template ID. When the containing feature is activated per SPWeb object, you can register the event handler for any list of the specified type.
  • Declaratively by content type, for example, to register an event handler for all documents of a specific type. Within the XML for a content type definition, you can register event receivers.

Note The assembly containing your event handler must be strongly named and registered in the global assembly cache (GAC) to be used. You cannot operate event receiver assemblies from the \_app_bin folder (Local_Drive:\Inetpub\wwwroot\wss\VirtualDirectories\GUID\_app_bin).

Content Types

Windows SharePoint Services 3.0 introduces the concept of content types in the data store. In short, content types introduce the notion of reusability to Web designers working with Windows SharePoint Services. Web designers now have the ability to create classes of objects with specific definitions and possible associated behavior, such as type name, fields, format, business processes, retention, auditing, and event handling. You can now activate SharePoint lists and libraries to support multiple content types. When you do that, you can attach one or more of these classes to your list or library and thus extend it with additional functionality and behavior. Think of extending a customer list with a Contact content type. The Contact content type can provide the Customer list with a set of new fields, like Contact Name, Function, Telephone, and so forth, and also with new behavior.

You can now define event handlers for a specific content type. You can, for example, define the content type "Customer", and within its behavior, you can define the metadata for the event handler.

Features

You define content types by using a feature. When you define a content type with a feature, you create two XML files as shown below:

  • Feature.xml   You use this XML file to define the metadata for the new feature. The following example code scopes the feature at the level of the site and defines a unique identifier for the new feature. Using the ElementManifests element, it then points to the location of the second XML file storing all of the detailed information on the feature itself.

Xml

Copy Code

<?xml version="1.0" encoding="utf-8"?>

<Feature Scope="Web"

  Title="Simple Event Handler Registration"

  Id="A6B8687A-3200-4b01-AD76-09E8D163FB9A"

  xmlns="http://schemas.microsoft.com/sharepoint/">

  <ElementManifests>

    <ElementManifest Location="elements.xml"/>

  </ElementManifests>

</Feature>

  • Elements.xml   You use this file to define the assembly that encapsulates the event handler, the class itself, and also a sequence number that specifies the order, if multiple event handlers are associated with the feature. The following example registers event receivers for deleting and adding items.

Xml

Copy Code

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <Receivers ListTemplateId="104">

    <Receiver>

      <Name>MyEventHandlers</Name>

      <Type>ItemDeleting</Type>

      <SequenceNumber>10000</SequenceNumber>

      <Assembly>MyEventHandlers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4358f2a5344ff0dc</Assembly>

      <Class>MyEventHandlers.SimpleEventHandler</Class>

      <Data></Data>

      <Filter></Filter>

    </Receiver>

    <Receiver>

      <Name>MyEventHandlers</Name>

      <Type>ItemAdded</Type>

      <SequenceNumber>10000</SequenceNumber>

      <Assembly>MyEventHandlers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4358f2a5344ff0dc</Assembly>

      <Class>MyEventHandlers.SimpleEventHandler</Class>

      <Data></Data>

      <Filter></Filter>

    </Receiver>

  </Receivers>

</Elements>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Registering Event Handlers as Content Types

Content types are your reusable building blocks within the Windows SharePoint Services data store. Because of this, the event handlers you register at this level are specific to a certain behavior you want to support. Take, for example, a content type like Product Specification, which you might add to a Shared Documents document library. You could create event handlers and register them at the level of the content type, Product Specification, which takes care of very specific processing regarding a specification. When users use this content type, they immediately also get this behavior attached to their list or library.

If your need is to register an event handler for a specific list or library, or for a specific set of lists or libraries, you do it at the level of Features. With regard to lists and libraries, Features are a new, atomic Windows SharePoint Services concept representing specific Collaboration Markup Language (CAML) sections that were previously all consolidated within one file (SCHEMA.XML or ONET.XML). In Windows SharePoint Services 3.0, these CAML sections are now isolated, which means that you can reuse them in different places. You now create the structure and the field definition of a list through a Feature.

With regard to our event handler registration, you can use the concept of the Feature to register your assembly for one specific list or library (by specifying the GUID of the list or library) or for a certain type of list or library (such as all the document libraries or all the form libraries). You define a Feature by creating the same two types of XML files (Feature.xml and Element.xml), as described in Registering an Event Handler.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Event Troubleshooting

Programming events can cause exceptional behaviors, depending on the contexts in which you implement the event handlers. The following table describes event behaviors related to specific contexts that you might encounter when writing code.

Context

Description

Document libraries and content types

You create an .aspx page of a particular content type in a document library, and the page has associated ItemAdding and ItemAdded events, but the events do not fire.

Only default content type properties are present in the Add phase. Additional properties (fields) of the specified content type are added only in the Update phase. Therefore, best practice is to avoid firing Add events with a specified content type ID. Instead, set the content type to the default content type in the Add phase. The content type can subsequently be changed in the Update phase. An alternative is to register the events at the list level.

Document libraries and content types

An ItemAdding event that is bound to a content type fires even when a document that is not of that type is uploaded.

When you first add a document to a library, the content type is always the default content type associated with the list. The content type of the document can be changed during the Update phase and the content type ID is adjusted accordingly.

Document libraries and content types

A request to delete an item through a list form does not have an associated content type ID, but this causes an ItemDeleting or ItemDeleted event to fire on all items, not just on items of a specific content type, even though the event was registered only for the content type.

By design, Windows SharePoint Services fires events for all items in a list when the request is not bound to a content type to allow firing an event for all items when the event receiver is registered for all items in the list.

This behavior affects policies that involve Delete events. If you implement a policy that involves deletion, apply the policy to a content type, and then bind the content type to a list, the policy will apply to all items in the list, not only to the items of the content type to which the policy is applied.

Lists and content types

You register ItemUpdating and ItemUpdated events on a content type that is bound to a list, but the events fire even when items that are not of that content type are updated through the object model.

Windows SharePoint Services returns 0 (zero) as the content type ID, not the content type ID of the item.

Lists

The BeforeProperties property applies only to DocumentLibrary type lists.

The workaround is to return the properties by using the object model and the given list item ID.

Document libraries

You add a custom content type to a document library. ItemAdding, ItemAdded, and ItemUpdating events fire, but not ItemUpdated events.

This behavior occurs only for the Shared Documents document library and not for custom document libraries. For Shared Documents, adding a content type creates a Forms/<Content Type> folder and copies a Template.doc file into that folder, which causes the events to fire.

Document libraries and content types

For folders, you get the content type and content type ID through the AfterProperties property in the ItemAdding and ItemAdded, events, but for documents, you get the content type ID only in the ItemAdded event and nothing in the ItemAdding event.

The Windows SharePoint Services parser for Microsoft Office system documents does not set the content type name in a document dictionary. Document metadata does not set a content type name.

Lists

List events do not fire on the UserInfo list.

Lists

An ItemAdded event fires on a folder type item, but the list item ID is not returned.

Document libraries

Events do not fire when unlinking a document copy from the original document.

Document libraries

List item IDs always equal 0 when events fire on documents in the Forms folder. If you register an ItemUpdating event in a document library and then modify EditForm.aspx, the event fires, but the ID equals 0 (zero) because the item is not a regular list item.

Lists

Event receivers do not bind to a list when the list is provisioned through Onet.xml and the list type has an associated Feature that binds a receiver to the list. You create a Feature that binds a receiver to a list type, create a list of that type through the site definition, but the receiver is not bound to the list when a site is provisioned. A workaround is to bind the receiver to a content type instead, and then bind the content type to the list.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Walkthrough: Handling Document Library Events

Windows SharePoint Services provides document library events that enable developers to build upon the SharePoint platform. Developers can create managed code assemblies that define handlers for these events and then bind the handlers to document libraries. The event handlers can call into the SharePoint object model to access the configuration and content databases directly, or they can invoke external services, using Windows SharePoint Services as a user interface for other systems.

Note:

This walkthrough describes a procedure that is maintained for backward compatibility with Windows SharePoint Services 2.0 event handling.

 Prerequisites

The following table describes the events for document libraries that Windows SharePoint Services provides.

Event

Description

Undo Check Out

Changes made to a checked-out document are undone.

Check In

A document is checked in to the library.

Check Out

A document is checked out from the library.

Copy

A document in the library is copied.

Delete

A document is deleted from the library.

Insert

A new document is saved to the library.

Move or Rename

A document is moved or renamed.

Update

An existing document or the value of a custom column in the library is edited.

In the context of Windows SharePoint Services, an event handler is a Microsoft .NET class that implements the IListEventSink interface, whose one method, OnEvent, is used within the handler. The SPListEvent object contains information about an event that occurs, and you can return the type of event through the Type property. Use the Site property to access the object model of the Microsoft.SharePoint namespace within the handler.

You must install the managed assembly that defines an event handler in the global assembly cache. In a server farm configuration, you must install this managed assembly in the global assembly cache of each front-end Web server.

To deploy an event handler on a server, event handling must be enabled on the Virtual Server General Settings page in SharePoint Central Administration.

Only users with full permissions for a document library can add event handlers.

 Event Settings

The list metadata for a document library binds the class of an event handler to a library by means of the following properties. The metadata can be set on the Document Library Advanced Settings page for the document library through code that implements the EventSinkAssembly, EventSinkClass, and EventSinkData properties of the SPList class, or through definitions contained in front-end site templates. The following table summarizes the event settings.

Setting

Type

Description

Assembly Name

String

The strong name of the event handler assembly file that lives in the global assembly cache.

Class Name

String

The fully qualified, case-sensitive name of the class within the assembly.

Properties

String

An arbitrary string of custom properties for use by the event handler. The length of the string cannot exceed 255 characters.

After you install the event handler assembly, on the Document Library Advanced Settings page for the document library, specify the strong name of the assembly in the Assembly Name box. The strong name must be in the format Assembly_Name, Version=Version, Culture=Culture, PublicKeyToken=Public_Key_Token. You can obtain these values by browsing to %windir%\assembly in Windows Explorer. As an example, the strong name for the Microsoft.SharePoint assembly resembles Microsoft.SharePoint, Version=12.0.0.0, Culture=Neutral, PublicKeyToken=71e9bce111e9429c.

The value that you specify in the Class Name box must be the full, case-sensitive name of a class defined in the specified assembly that implements the IListEventSink interface. For example, the full name of the class in the following example would be myNamespace.myClass.

Visual Basic

Copy Code

Namespace myNamespace

 

    Public Class myClass

 

        Inherits Microsoft.SharePoint.IListEventSink

 

        Public Sub OnEvent(evt As Microsoft.SharePoint.SPListEvent)

 

            'Add an announcement

            AddAnnouncement(evt)

 

        End Sub 'OnEvent

 

        Public Sub AddAnnouncement(evt As

           Microsoft.SharePoint.SPListEvent)

        .

        .

        .

        End Sub 'AddAnnouncement

 

    End Class 'myClass

 

End Namespace 'myNamespace

C#

Copy Code

namespace myNamespace

{

    public class myClass : Microsoft.SharePoint.IListEventSink

    {

        public void OnEvent(Microsoft.SharePoint.SPListEvent evt)

        {

            //Add an announcement

            AddAnnouncement(evt);

        }

 

        public void AddAnnouncement

           (Microsoft.SharePoint.SPListEvent evt)

        {

            .

            .

            .

        }

    }

}

Typing a value in the Properties box is optional. This value can contain up to 255 characters for use by the event handler.

 Events in Relation to Other Events

An event handler running in the context of Windows SharePoint Services cannot generate other events. To program side effects for an event, you must provide the code within the event handler. The event handler is called asynchronously from the actual request.

A new instance of an event handler class is created for each event. Consequently, you cannot store state in your event handler class and expect it to persist across multiple events. You can, however, create a base class for an event handler or for multiple event handlers that caches state so that the same sink object can be used for all events on a document library.

 Caching Credentials

Event handlers run in the context of the Internet Information Services (IIS) Application Pool Identity, an account that typically has no permissions in Windows SharePoint Services. If your handler needs to interact with Windows SharePoint Services through the object model, you must establish and cache credentials through impersonation of a user. Accessing the object model in an event handler without impersonation is not supported. For information, see Impersonating and Reverting in the .NET Framework Developer's Guide on MSDN.

 Security Context

The event handler thread runs within the same application pool account as the SharePoint Web application. If, however, the event handler needs to run in a different account to manipulate Windows SharePoint Services or an external service, the developer must maintain his or her own user credentials and manage his or her own security context.

 Exceptions and Errors

Exceptions for event handlers used in Windows SharePoint Services are thrown in the following conditions, for which a Microsoft Windows NT event log entry is created:

  • The assembly for the handler cannot be loaded.
  • The class defining the handler is not found.
  • The class does not implement the IlistEventSink interface.
  • The OnEvent method throws an exception.

Note:

When you restart IIS, each IIS worker process terminates only after all its queued work items, including HTTP requests and document library events, complete their tasks.

 Definitions and Templates

Developers can define event handler assemblies within list definitions, which provides a useful means for deploying solutions such as workflow-enabled document libraries in which events are already bound to the appropriate handlers. An event handler can be bound to a document library through the EventSinkAssembly, EventSinkClass, and EventSinkData attributes of the List element in the Schema.xml file for the list type. When an end user creates a library through the user interface (UI) from a list definition that specifies an event handler, list event settings are automatically set to the values specified in the definition. When an end user saves a document library as a list template, event settings specified through the UI are preserved in the template.

For information about definitions and templates for sites or lists, see Working with Site Templates and Definitions.

 Event handler example

The following programming task creates an event handler that deletes the oldest version of a file in a document library when the number of versions for the file reaches a specified number. To establish credentials for the handler, a method returns a token to the event handler for impersonation of a user.

 Procedure

To create a document library event handler

1.     On the File menu in Visual Studio 2005, point to New and then click Project.

2.     In the New Project dialog box, select Visual Basic Projects or Visual C# Projects in the Project Types box.

3.     In the Templates box, select Class Library.

4.     In the Name box, type the name of the project, which in this task is "DocLibHandler".

5.     In the Location box, type the path for the project, and then click OK.

6.     In Solution Explorer, right-click the References node, and click Add Reference on the shortcut menu.

7.     On the .NET tab of the Add Reference dialog box, select Windows SharePoint Services in the list of components, click Select, and then click OK.

8.     Add the following directives to the Class1.cs or Class1.vb file of the DocLibHandler project after the System directive that is included by default.

Visual Basic

Copy Code

Imports System.Security.Principal

Imports System.Runtime.InteropServices

Imports Microsoft.SharePoint

C#

Copy Code

using System.Security.Principal;

using System.Runtime.InteropServices;

using Microsoft.SharePoint;

9.     Change the namespace and class name in the Class1.cs or Class1.vb file to be DocLibEventHandler and DocVersionHandler, as follows.

Visual Basic

Copy Code

Namespace DocLibEventHandler

  

   Public Class DocVersionHandler

      Implements IlistEventSink

C#

Copy Code

namespace DocLibEventHandler

{

    public class DocVersionHandler : IListEventSink

    {

10.  Add the OnEvent method of the IListEventSink interface to the DocVersionHandler class, as follows.

Visual Basic

Copy Code

Private maxVersions As Integer = 5

 

Sub IListEventSink.OnEvent(listEvent

    As Microsoft.SharePoint.SPListEvent)

 

    ' TODO: ***** PROVIDE YOUR IMPLEMENTATION HERE ****

    ' Get the credentials (User_Alias, Domain, Password) that this

    ' event sink instance should run as and initialize the wic

    ' object by calling the CreateIdentity method

 

    Dim wic As WindowsImpersonationContext

        = CreateIdentity(User_Alias, Domain, Password).Impersonate()

 

    If listEvent.Type = SPListEventType.Update OrElse listEvent.Type

        = SPListEventType.CheckIn Then

 

        Dim site As SPWeb = listEvent.Site.OpenWeb()

        Dim file As SPFile = site.GetFile(listEvent.UrlAfter)

        Dim nDocVersions As Integer = file.Versions.Count

 

        While maxVersions > 0 AndAlso nDocVersions > maxVersions - 1

 

            file.Versions.Delete(0)

            nDocVersions = file.Versions.Count

 

        End While

 

    End If

 

    wic.Undo()

 

End Sub 'IListEventSink.OnEvent

C#

Copy Code

private int maxVersions = 5;

 

void IListEventSink.OnEvent

    (Microsoft.SharePoint.SPListEvent listEvent)

{

    /* TODO: ***** PROVIDE YOUR IMPLEMENTATION HERE ****

    Get the credentials (User_Alias, Domain, Password) that this

    event sink instance should run as and initialize the wic object

    by calling the CreateIdentity method*/

 

    WindowsImpersonationContext wic

       = CreateIdentity(User_Alias, Domain, Password).Impersonate();

 

    if ((listEvent.Type == SPListEventType.Update) ||

        (listEvent.Type == SPListEventType.CheckIn))

    {

        SPWeb site = listEvent.Site.OpenWeb();

        SPFile file = site.GetFile(listEvent.UrlAfter);

        int nDocVersions = file.Versions.Count;

 

        while ((maxVersions > 0) && (nDocVersions

            > (maxVersions - 1)))

        {

            file.Versions.Delete(0);

            nDocVersions = file.Versions.Count;

        }

    }

 

    wic.Undo();

}

11.  The OnEvent method calls the following method to impersonate an account with administrative permissions.

Important:

Do not pass credentials in clear-text, because doing so presents a security risk. To impersonate a user more securely, you can return the information programmatically with functions provided by the operating system for getting secret data from the user, such as the CryptProtectData and CryptUnprotectData functions of the Data Protection API (DPAPI).

12.  Include the following method within the DocVersionHandler class.

13.  Visual Basic

  1. Copy Code

16.Protected Shared Function CreateIdentity(User As String, Domain

17.    As String, Password As String) As WindowsIdentity

18. 

19.    ' The Windows NT user token.

20.    Dim tokenHandle As New IntPtr(0)

21. 

22.    Const LOGON32_PROVIDER_DEFAULT As Integer = 0

23.    Const LOGON32_LOGON_NETWORK As Integer = 3

24. 

25.    tokenHandle = IntPtr.Zero

26. 

27.    ' Call LogonUser to obtain a handle to an access token.

28.    Dim returnValue As Boolean = LogonUser(User, Domain, Password,

29.       LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, tokenHandle)

30. 

31.    If False = returnValue Then

32. 

33.        Dim ret As Integer = Marshal.GetLastWin32Error()

34.        Throw New Exception("LogonUser failed with

35.            error code: " + ret)

36. 

37.    End If

38. 

39.    System.Diagnostics.Debug.WriteLine(("Created user token:

40.        " + tokenHandle))

41. 

42.    'The WindowsIdentity class makes a new copy of the token.

43.    'It also handles calling CloseHandle for the copy.

44.    Dim id As New WindowsIdentity(tokenHandle)

45.    CloseHandle(tokenHandle)

46.    Return id

47. 

48.End Function 'CreateIdentity

49.<DllImport("advapi32.dll", SetLastError := True)>  _

50.    Private Shared Function LogonUser(lpszUsername As String,

51.            lpszDomain As String, _

52.        lpszPassword As String, dwLogonType As Integer,

53.            dwLogonProvider As Integer, _

54.        ByRef phToken As IntPtr) As Boolean

55. 

56.<DllImport("kernel32.dll", CharSet := CharSet.Auto)>  _

57.    Private Shared Declare Auto Function CloseHandle Lib

58.        "kernel32.dll" (handle As IntPtr) As Boolean

59.  C#

  1. Copy Code

62.protected static WindowsIdentity CreateIdentity(string User,

63.    string Domain, string Password)

64.{

65.    // The Windows NT user token.

66.    IntPtr tokenHandle = new IntPtr(0);

67. 

68.    const int LOGON32_PROVIDER_DEFAULT = 0;

69.    const int LOGON32_LOGON_NETWORK = 3;

70. 

71.    tokenHandle = IntPtr.Zero;

72. 

73.    // Call LogonUser to obtain a handle to an access token.

74.    bool returnValue = LogonUser(User, Domain, Password,

75.    LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,

76.    ref tokenHandle);

77. 

78.    if (false == returnValue)

79.    {

80.        int ret = Marshal.GetLastWin32Error();

81.        throw new Exception("LogonUser failed with

82.            error code: " +  ret);

83.    }

84. 

85.    System.Diagnostics.Debug.WriteLine("Created user token:

86.        " + tokenHandle);

87. 

88.    //The WindowsIdentity class makes a new copy of the token.

89.    //It also handles calling CloseHandle for the copy.

90.    WindowsIdentity id = new WindowsIdentity(tokenHandle);

91.    CloseHandle(tokenHandle);

92.    return id;

93.}

94. 

95.[DllImport("advapi32.dll", SetLastError=true)]

96.private static extern bool LogonUser(String lpszUsername,

97.    String lpszDomain, String lpszPassword,

98.int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

99. 

100. [DllImport("kernel32.dll", CharSet=CharSet.Auto)]

101. private extern static bool CloseHandle(IntPtr handle);

102.                To create a strong name for the assembly, go to the Local_Drive:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin directory (Local_Drive:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin in Visual Studio .NET Version 7) through a command prompt, and type sn -k Local_Drive:\DocLibHandler.snk, which creates a key file for the assembly.

103.                Add the following attributes for the assembly version and key file to the AssemblyInfo file of the project, replacing the attributes that are provided by default.

Copy Code

[assembly: AssemblyVersion("1.0.0.0")]

[assembly: AssemblyKeyFile("Local_Drive:\\DocLibHandler.snk")]

104.                Click Build Solution on the Build menu.

105.                To install your solution in the global assembly cache, drag the dynamic-link library (DLL) of your assembly to the Local_Drive:\WINDOWS\assembly directory in Windows Explorer.

106.                On the Virtual Server General Settings page in SharePoint Central Administration, select On in the Event Handlers section to enable use of event handlers on the virtual server.

107.                From a view of the document library to which you want to attach the event handler assembly, click Modify settings and columns, and then click Change advanced settings on the page for customizing the document library.

108.                On the Document Library Advanced Settings page, type the strong name for the assembly in the Assembly Name box. (For example, DocLibHandler, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=0fafac2a0cc92888.) You can get the values used in the strong name by right-clicking the DLL of your assembly in the Local_Drive:\WINDOWS\assembly directory and then clicking Properties on the shortcut menu.

109.                Type the fully qualified, case-sensitive name of the class in the Class Name box, which in this example is DocLibEventHandler.DocVersionHandler.

110.                Reset IIS by typing iisreset at a command prompt.

 Next Steps

To implement the handler in a document library, versioning must be enabled on the Document Library Settings page for the library.

 

 

 

 

 

How to: Add or Delete a List in Multiple Web Sites

How to: Add or Delete a List in Multiple Web Sites

You can use one of the Add methods of the SPListCollection class to add a list to multiple Web sites across a site collection.

The following example creates a generic list on every Web site, based on the title and description that is passed from two text boxes to the code. The AllWebs property of the SPSite class is used to return the collection of all Web sites that exist on the site.

This example assumes the existence of two text boxes on the .aspx page that contains a form.

Visual Basic

Copy Code

Dim listTitle As String = TextBox1.Text.ToString()

Dim listDescription As String = TextBox2.Text.ToString()

 

Dim mySite As SPSite = SPContext.Current.Site

Dim allWebs As SPWebCollection = mySite.AllWebs

Dim web As SPWeb

 

For Each web In  allWebs

    Dim allLists As SPListCollection = web.Lists

    allLists.Add(listTitle, listDescription, SPListTemplateType.GenericList)

Next web

C#

Copy Code

string listTitle = TextBox1.Text.ToString();

string listDescription = TextBox2.Text.ToString();

 

SPSite mySite = SPContext.Current.Site;

SPWebCollection allWebs = mySite.AllWebs;

 

foreach (SPWeb web in allWebs)

{

    SPListCollection allLists = web.Lists;

    allLists.Add(listTitle,listDescription, SPListTemplateType.GenericList);

}

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

If you want to delete a list from every Web site in which it appears, use the Delete method of the SPListCollection class. The following example uses nested loops to drill down to a list that has a title matching the title specified in a text box. The example assumes the existence of a text box on the .aspx page that contains a form.

Visual Basic

Copy Code

Dim mySite As SPSite = SPContext.Current.Site

Dim allWebs As SPWebCollection = mySite.AllWebs

Dim web As SPWeb

 

For Each web In  allWebs

    Dim allLists As SPListCollection = web.Lists

    Dim i As Integer

 

    For i = 0 To allLists.Count - 1

        Dim list As SPList = allLists(i)

 

        If list.Title = TextBox1.Text Then

            Dim listGuid As Guid = list.ID

            allLists.Delete(listGuid)

        End If

    Next i

Next web

C#

Copy Code

SPSite mySite = SPContext.Current.Site;

SPWebCollection allWebs = mySite.AllWebs;

 

foreach (SPWeb web in allWebs)

{

    SPListCollection allLists = web.Lists;

 

    for (int i=0; i<allLists.Count; i++)

    {

        SPList list = allLists[i];

 

        if (list.Title == TextBox1.Text)

        {

            Guid listGuid = list.ID;

            allLists.Delete(listGuid);

        }

    }

}

In the example the Title property of the SPList class is used to identify a list in the collection of lists for each Web site that matches the specified title. The ID property returns the globally unique identifier (GUID) of the list, which is passed as the parameter for the Delete method.

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

 

 

 

 

 

 

How to: Return Items from a List

To return items from a list, you can instantiate an SPWeb object and drill down through the object model to the SPListItemCollection object for the list. After you return the collection of all items for a list, you can iterate through the collection and use indexers to return specific field values.

The following example returns all the items for a specified Events list. It assumes the existence of a text box that can be used to type the name of an Events list.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim listItems As SPListItemCollection = mySite.Lists(TextBox1.Text).Items

Dim i As Integer

 

For i = 0 To listItems.Count - 1

 

   Dim item As SPListItem = listItems(i)

 

   Response.Write(SPEncode.HtmlEncode(item("Title").ToString()) & " :: " _

      & SPEncode.HtmlEncode(item("Location").ToString()) & " :: " _

      & SPEncode.HtmlEncode(item("Begin").ToString()) & " :: " _

      & SPEncode.HtmlEncode(item("End").ToString()) & "<BR>")

 

Next i

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

 

for (int i=0;i<listItems.Count;i++)

{

   SPListItem item = listItems[i];

 

   Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " : " +

      SPEncode.HtmlEncode(item["Location"].ToString()) + " : " +

      SPEncode.HtmlEncode(item["Begin"].ToString()) + " : " +

      SPEncode.HtmlEncode(item["End"].ToString()) + "<BR>");

}

This example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

In the example, indexers are used both to return the list that is typed by the user and to return specific items from the list. To return the items, the indexers must specify the name of each column whose value is returned. In this case, all the field names pertain to a common Events list.

You can also use one of the GetItems methods of the SPList class to return a subset of items from a list. The following example returns only Title column values where the Stock column value surpasses 100.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim list As SPList = mySite.Lists("Books")

 

Dim query As New SPQuery()

query.Query = "<Where><Gt><FieldRef Name='Stock'/><Value Type='Number'>100</Value></Gt></Where>"

 

Dim myItems As SPListItemCollection = list.GetItems(query)

Dim item As SPListItem

 

For Each item In myItems

   Response.Write(SPEncode.HtmlEncode(item("Title").ToString()) & "<BR>")

Next item

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPList list = mySite.Lists["Books"];

 

SPQuery query = new SPQuery();

query.Query = "<Where><Gt><FieldRef Name='Stock'/><Value Type='Number'>100</Value></Gt></Where>";

 

SPListItemCollection myItems = list.GetItems(query);

 

foreach (SPListItem item in myItems)

{

   Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + "<BR>");

}

The previous example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

The example assumes the existence of a Books list that has a Stock column containing number values.

The previous example uses a constructor to instantiate an SPQuery object, and then assigns to the Query property of the query object a string in Collaborative Application Markup Language Core Schemas that specifies the inner XML for the query (in other words, the Where element). After the GetItems property is set, the query object is passed through the GetItems method to return and display items.

Cross-List Queries

You can perform cross-list queries to query more efficiently for data across multiple Web sites. The following example uses the SPSiteDataQuery class to define a query, and then uses the GetSiteData method to return items where the Status column equals "Completed".

Visual Basic

Copy Code

Dim webSite As SPWeb = SPContext.Current.Web

Dim query As New SPSiteDataQuery()

 

query.Lists = "<Lists ServerTemplate=""107"" />"

query.Query = "<Where><Eq><FieldRef Name=""Status""/>" + "<Value Type=""Text"">Completed</Value></Eq></Where>"

 

Dim items As System.Data.DataTable = webSite.GetSiteData(query)

Dim item As System.Data.DataRow

 

For Each item In items

   Response.Write((SPEncode.HtmlEncode(item("Title").ToString()) + "<BR>"))

Next item

C#

Copy Code

SPWeb webSite = SPContext.Current.Web;

SPSiteDataQuery query = new SPSiteDataQuery();

 

query.Lists = "<Lists ServerTemplate=\"107\" />";

query.Query =

   "<Where><Eq><FieldRef Name=\"Status\"/>" +

   "<Value Type=\"Text\">Completed</Value></Eq></Where>";

 

System.Data.DataTable items = webSite.GetSiteData(query);

 

foreach (System.Data.DataRow item in items)

{

   Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + "<BR>");

}

This example requires using directives (Imports in Visual Basic) for both the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

 

 

 

 

 

 

 

 

 

 

How to: Add or Delete List Items

To add items to a list, use the Add method of the SPListItemCollection class to create an item object, and then use the Update method of the SPListItem class to update the database with the new item.

The following example assumes the existence of five text boxes, one that specifies the name of the list to add to, and four others that are used to specify the values to add. Indexers are used to gather the input from all five sources.

Note:

The code examples in this topic use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list. Outside of an HTTP context, such as in a console application or a Windows application, you obtain references to key objects with a different method. For more information, see Getting References to Sites, Web Applications, and other Key Objects.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim listItems As SPListItemCollection

    = mySite.Lists(TextBox1.Text).Items

 

Dim item As SPListItem = listItems.Add()

 

item("Title") = TextBox2.Text

item("Stock") = Convert.ToInt32(TextBox3.Text)

item("Return Date") = Convert.ToDateTime(TextBox4.Text)

item("Employee") = TextBox5.Text

 

item.Update()

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

 

SPListItem item = listItems.Add();

 

item["Title"] = TextBox2.Text;

item["Stock"] = Convert.ToInt32(TextBox3.Text);

item["Return Date"] = Convert.ToDateTime(TextBox4.Text);

item["Employee"] = TextBox5.Text;

 

item.Update();

}

The example first creates an SPListItem object through the Add method of the collection. It then assign values to specific fields by using an indexer on the list item. For example, item["Title"] specifies the Title column value for the item. Finally, the example calls the Update method of the list item to effect changes in the database.

The previous example requires a using directive (Imports in Microsoft Visual Basic) for the Microsoft.SharePoint namespace.

To create list items with metadata that will be preserved, you can use the Author, Editor, Created, and Modified fields as indexers, where Author or Editor specify a Windows SharePoint Services user ID. For an example, see the SPListItem class.

To delete items from a list, use the Delete method of the SPListItemCollection class, which takes as its parameter an index into the collection.

Visual Basic

Copy Code

Dim mySite As SPWeb = SPContext.Current.Web

Dim listItems As SPListItemCollection

    = mySite.Lists(TextBox1.Text).Items

Dim itemCount As Integer = listItems.Count

Dim k As Integer

 

For k = 0 To itemCount - 1

    Dim item As SPListItem = listItems(k)

 

    If TextBox2.Text = item("Employee").ToString() Then

        listItems.Delete(k)

    End If

Next k

C#

Copy Code

SPWeb mySite = SPContext.Current.Web;

SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

int itemCount = listItems.Count;

 

for (int k=0; k<itemCount; k++)

{

    SPListItem item = listItems[k];

 

    if (TextBox2.Text==item["Employee"].ToString())

    {

        listItems.Delete(k);

    }

}

Based on input from two text boxes, the example iterates through the collection of items for the specified list and deletes an item if the Employee field value matches the specified value.

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

 

 

 

 

IIS Application Pool, SharePoint Logical Architecture

Imp tips about Application Pool: (Logical Architecture):

 

·         An application pool is a grouping of one or more URLs (or Web sites as they are represented in IIS) served by a worker process

·         Capacity Planning

1)      The memory overhead of an application pool is 30-50 megabytes (MB) plus any memory for the applications running in the application pool process space

2)      The limit for the number of application pools is influenced by the available memory on the system and size of application running in the application pool

3)      The general guideline for acceptable performance is to use eight or fewer application pools.

·         Sharing and Isolation: IIS Application Pool provides a way for multiple website to run on same computer but still have their own worker process and identity. This can help to prevent the attacker to inject the malicious code that can attack sites in different Application Pool.

·         Configurable Items: Use separate Application pool identity for each application pool

·         Planning Recommendations: You should use dedicated Application Pool for following:

1)      To separate Authenticated content from Anonymous content

2)      To isolate application that stores password and interact with external business application

What is Feature in SharePoint?

Features reduce the complexity involved in making simple site customizations, and are robust when upgrades are applied to a deployment. Features eliminate the need to copy large chunks of code to change simple functionality. Features thus reduce versioning and inconsistency issues that may arise among front-end Web servers. Features make it easier to activate or deactivate functionality in the course of a deployment, and administrators can easily transform the template or definition of a site by simply toggling a particular Feature on or off in the user interface.

What are Feature Capabilities?

Features provide the following capabilities:

·         Scoping semantics for determining where custom code runs

·         Pluggable behavior for installing or uninstalling Features within a deployment

·         Pluggable behavior for activating or deactivating Features at a given scope

·         A scoped property bag for storing data required by a Feature within its scope

·         The basis of a unified framework for distributed deployment of Windows SharePoint Services solutions

What is Process of SharePoint Feature Implementation?

Feature Implementation:

 

1)      Add Subfolder to 12 hives under Template\Feature. (Imp Tip – If create folder by right click and New and add new folder, the new folder does not have inherited permissions. So if you deploy feature in the folder, then some Windows SharePoint Services Pages such as Site Settings, list views throws exceptions. You can fix this problem by right client Property, Security Advance. On the permission tab delete inherited permission from the folder. Or else create folder in DOS  )

2)      This folder includes Feature.xml file. This file contains base properties of features and list elements bound to properties

3)      This subfolder may contain supporting files also - .aspx, .htm, .xsn, resx, .dll and other file types

 

4)      Install feature from Command line STSADM - stsadm –o installfeature –filename <path of the Feature.xml file relative to the 12\TEMPLATE\ FEATURES folder >

 

5)      Activate feature through user interface

 

6)      stsadm –o activatefeature –name < folder in FEATURES directory containing the Feature.xml file > -url http://Server/Site/Subsite

 

 

7)      Installing feature makes it definition and elements known through Server Farm

Object Hierarchy of WSS

 

 WSS 3.0 Object model is divided into three hierarchies:

1)     Physical Object Hierarchy

2)     Content Hierarchy

3)     Services Hierarchy

All object hierarchy contains classes and containers

Physical Object Hierarchy includes classes that represent Physical Entities such as Servers and files AND Containers of such entities such as Farms and Folders

Content Hierarchy includes classes that represent publishable items of data such as list items, and classes that represents nested containers of data such as lists, Content DB, websites, collections of websites, Web Applications

Service Hierarchy includes classes that represent services and instances

 

Physical Object Hierarchy: There are four major classes in this Hierarchy

 

SPFarm:

1)     WSS 3.0 farm is represented by SPFarm class.  Server farm is one or more WFE, Zero or more AS and SQL Server.

2)     The SPFarm class represents a farm of one or more physical servers, so it is included in the Physical Hierarchy. But it can also be considered the top level of the Content Hierarchy; for example, all the (non-configuration) content of a Windows SharePoint Services farm can be backed up and restored.

3)     SPFarm class can also be thought of as representing the configuration database that is associated with the farm because Windows SharePoint Services 3.0 has no class that represents the configuration database itself

4)     SPFarm OBJECT has three classes: SPServer, SPService and SPSolution

5)     SPFarm inherits from SPPersistedObject, which means that the object (there is only one) that instantiates the class persists in the configuration database.

6)     SPFarm has static members for creating farms and returning references to the local farm or a remote farm.

7)     SPFarm has many members that can be used for developing administration functionality. Some of the more important members can help in the administration of the following:

·         Backup and restoration of the farm

·         Upgrades of the farm

·         Migration of (moving) the farm

·         Error reporting

·         Caching

 

SPServer:

1)     A physical server is represented by the SPServer class.

2)     It has an Address property that holds the IP address of the server and a Role property that identifies the server's role in the farm

3)     If there is just one server, its Role is SingleServer. If there is more than one, the front-end servers have the role WebFrontEnd an

4)     d almost all other servers have the role Application

5)     However, the Role property of a server that is physically hosting a Windows SharePoint Services content database typically has the value Invalid. This is because such servers typically run only one Windows SharePoint Services service—the Database Service (which is a Windows service)—and this database service is really just an alias for the SQL Server Windows service which is not part of Windows SharePoint Services. Hence, it is not really running any Windows SharePoint Services code, and it does not really fit into the Application role.

6)     The SPServer class also has a ServiceInstances property that holds references to all the instances of Windows services and Web services that are running on the server

7)     SPServer inherits from SPPersistedObject

 

SPFolder: Notice that the entity represented by an SPFolder object or an SPFile object might be located in a Windows SharePoint Services content database instead of in the file system of a server. For example, a spreadsheet file in a Windows SharePoint Services document library is stored in a cell of a database, not in a folder on one of the servers.

1)     Represents a folder on a SharePoint Web site.

2)     Various folder properties in the Microsoft.SharePoint namespace return a folder object; however, the GetFile method of the SPWeb class returns any folder from within a site or subsite.

3)     Use the Folders property of the SPWeb class, or the SubFolders property of the SPFolder class, to return an SPFolderCollection object that represents the collection of folders for a site or folder. Use an indexer to return a single folder from the collection. For example, if the collection is assigned to a variable named collFolders, use collFolders[index] in C#, or collFolders(index) in Visual Basic, where index is either the index number of the folder in the collection or the display name of the folder.

SPFile:

1)     SPFile Class represents a file in a SharePoint Web site that can be a Web Part Page, an item in a document library, or a file in a folder.

2)     Use the GetFile or GetFileAsString method of the SPWeb class to return a single file object. Otherwise, use the Files property of either the SPWeb or SPFolder class to return an SPFileCollection object that represents the collection of files for a site or folder. Use an indexer to return a single file from the collection

 ‭(Hidden)‬ Admin Links