Você está na página 1de 117

Namespaces in the Windows SharePoint Services Object Model The Windows SharePoint Services object model consists of forty-two

namespaces in ten assemblies that are used in SharePoint sites on the server that is running Windows SharePoint Services. Public Namespaces The following table lists the public namespaces, identifies their assemblies, and briefly describes namespaces that can be used to customize a deployment. Name Microsoft.HtmlTrans Assembly Microsoft HtmlTrans Interface (in Microsoft.HtmlTrans.Interface.dll) Description Provides an interface for custom conversion applications that deliver HTML versions of documents to users who do not have the required client application or viewer installed on their computers. Provides types and members for working with a top-level site and its subsites or lists. Provides administrati ve types and members for managing a Windows SharePoint Services deployment. Provides types and members for

Microsoft.SharePoint

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.Administration

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.Administration.Back up

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

performing backup and restore operations on SharePoint sites. Microsoft.SharePoint.ApplicationRuntime Microsoft.SharePoint.Deployment Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint (in Microsoft.SharePoint.dll) Provides types and members for importing and exporting content between Windows SharePoint Services Web sites. Provides the base class for the data retrieval service adapters used in Windows SharePoint Services.

Microsoft.SharePoint.Dsp

Microsoft.SharePoint.Dsp (in Microsoft.SharePoint.Dsp.dll)

Microsoft.SharePoint.Dsp.OleDb

Microsoft.SharePoint.Dsp.OleDb (in Provides the Microsoft.SharePoint.Dsp.OleDb.dll data ) retrieval service adapter for performing queries against OLE DB data sources. Microsoft.SharePoint.Dsp.SoapPT (in Microsoft.SharePoint.Dsp.SoapPT.d ll) Provides the data retrieval service adapter for performing passthrough

Microsoft.SharePoint.Dsp.SoapPT

queries against arbitrary Web services. Microsoft.SharePoint.Dsp.Sts Microsoft.SharePoint.Dsp.Sts (in Microsoft.SharePoint.Dsp.Sts.dll) Provides the data retrieval service adapter for performing queries against sites, lists, and document libraries in Windows SharePoint Services. Provides the data retrieval service adapter for performing queries against arbitrary XML data sources.

Microsoft.SharePoint.Dsp.XmlUrl

Microsoft.SharePoint.Dsp.XmlUrl (in Microsoft.SharePoint.Dsp.XmlUrl.dl l)

Microsoft.SharePoint.EmailIntegration Microsoft.SharePoint.Help Microsoft.SharePoint.Help.Constants Microsoft.SharePoint.Help.Search Microsoft.SharePoint.Meetings

Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint (in Microsoft.SharePoint.dll) Provides types and members that can be used to customize Meeting Workspace sites.

Microsoft.SharePoint.MobileControls

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Provides server controls for rendering the mobile forms and view pages used in SharePoint lists. Provides types and members for customizing the navigation structures and site maps of SharePoint Web sites.

Microsoft.SharePoint.Navigation

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.Search.Administratio Microsoft.SharePoint.Search (in n Microsoft.SharePoint.Search.dll) Microsoft.SharePoint.Search.Query Microsoft.SharePoint.Security Microsoft.SharePoint.Search (in Microsoft.SharePoint.Search.dll) Microsoft SharePoint Security (in Microsoft.SharePoint.Security.dll) Provides a set of code access permission and attribute classes designed to protect a specific set of resources and operations, such as access to the Windows SharePoint Services object model, the ability to do unsafe saving on HTTP Gets, and enabling point-to-

point Web Part connections. Microsoft.SharePoint.SoapServer Microsoft.SharePoint (in Microsoft.SharePoint.dll) Contains classes that implement the Windows SharePoint Services Web Service and Web services for working with Web Part pages and Web Parts. In most cases, the members of these classes are not designed to be called from the server but remotely from client applications. Provides an interface for creating custom operations to run at the command prompt in STSADM.EX E. Provides types and members for upgrading a Windows SharePoint Services deployment. Provides utilities for encoding strings and

Microsoft.SharePoint.StsAdmin

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.Upgrade

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.Utilities

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

processing user information. Microsoft.SharePoint.WebControls Microsoft.SharePoint (in Microsoft.SharePoint.dll) Provides server controls that are used on site and list pages in a SharePoint site. Provides classes, interfaces, and members for creating custom Web Parts and Web Part pages Provides a set of interfaces and their supporting classes and members that can be implemente d in the class of a custom Web Part to support creating connections with other Web Parts. Provides types and members for associating, initiating, and managing workflow templates and instances.

Microsoft.SharePoint.WebPartPages

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.WebPartPages.Com munication

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.Workflow

Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Microsoft.SharePoint.WorkflowActions

microsoft.sharepoint.WorkflowActi ons (in microsoft.sharepoint.WorkflowActi ons.dll)

Provides types that represent workflow activities. These activities can be assembled into workflow activities.

Internal Namespaces The types and members of namespaces listed in the following table support Windows SharePoint Services and are not intended to be used directly from your code. Namespace Microsoft.SharePoint.ApplicationPages Microsoft.SharePoint.ApplicationPages.WebControls N:Microsoft.SharePoint.DirectorySoap Microsoft.SharePoint.Search.Internal.Protocols Assembly Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint (in Microsoft.SharePoint.dll) Microsoft.SharePoint.Searc h (in Microsoft.SharePoint.Searc h.dll)

Microsoft.SharePoint.Search.Internal.Protocols.SharePoi Microsoft.SharePoint.Searc nt2001 h (in Microsoft.SharePoint.Searc h.dll) Microsoft.SharePoint.Search.Internal.Protocols.SharePoi Microsoft.SharePoint.Searc nt2003 h (in Microsoft.SharePoint.Searc h.dll) Microsoft.SharePoint.Search.Internal.Protocols.SharePoi Microsoft.SharePoint.Searc nt2006 h (in Microsoft.SharePoint.Searc h.dll) Microsoft.SharePoint.Search.Internal.Protocols.SharePoi Microsoft.SharePoint.Searc ntPortal2003 h (in Microsoft.SharePoint.Searc h.dll) Microsoft.SharePoint.Search.Internal.Protocols.SiteData Microsoft.SharePoint.Searc

h (in Microsoft.SharePoint.Searc h.dll) Microsoft.SharePoint.Search.Internal.Protocols.SPSCraw Microsoft.SharePoint.Searc l h (in Microsoft.SharePoint.Searc h.dll) Microsoft.SharePoint.Search.Internal.UI Microsoft.SharePoint.Searc h (in Microsoft.SharePoint.Searc h.dll) Microsoft.SharePoint.Searc h (in Microsoft.SharePoint.Searc h.dll)

N:Microsoft.SharePoint.Search.Internal.WebControls

Microsoft.SharePoint Namespace Provides types and members for working with a top-level site and its subsites or lists. Classes Class NameValuePair RecordsRepositoryProperty Description Defines a name/value pair that can be set or retrieved. A structure which represents properties of the records repository. The structure consists of four strings which include the name of the object, the value, the type of the object, and any other information. Represents an alert, which generates periodic email notifications sent to a user about the list, list item, document, or document library to which the alert applies. SPAlertprovides information about the alert, such as which alert template is used, the alert frequency, and the UserID of the user who created the alert. Represents a collection of SPAlert objects. The SPAlertCollection is available as a property of either SPWebor SPUser. Defines the template used for an alert. Represents a collection of alert templates. Represents the collection of attachments for a list

SPAlert

SPAlertCollection

SPAlertTemplate SPAlertTemplateCollection SPAttachmentCollection

item. SPAudit Enables auditing of how site collections, sites, lists, folders, and list items are accessed, changed, and used. Contains information about an audited event that is connected to a site collection, site, folder, list, or list item. Provides a container for SPAuditEntry objects. Defines a query of the audit entries of the SharePoint database. Provides the base functionality for collections in theMicrosoft.SharePoint andMicrosoft.SharePoint. Administration namespaces. A class that retrieves SPContentTypeId objects that represent identifiers (IDs) for built-in content types. A class that retrieves the values of preset (or noncustom) document fields, which in turn are obtained from Windows SharePoint Services Web page documents that have been checked into the document library. Many document types such as email messages, e-mail contacts, workflow events, and other objects can be represented by these fields. Represents a day, week, or month view style for a calendar. Represents a collection of SPCalendarViewStyle objects. Represents a change that has been made to objects or metadata within an item, list, Web site, or site collection scope, or a security policy change at the Web application scope that has been recorded in the Windows SharePoint Services change log. Represents a change to an alert. Represents a collection of SPChange objects. The maximum number of changes that can be represented in a collection is 1000. Represents a change to a content type. Represents a change to a site column.

SPAuditEntry

SPAuditEntryCollection SPAuditQuery SPBaseCollection

SPBuiltInContentTypeId SPBuiltInFieldId

SPCalendarViewStyle SPCalendarViewStyleCollection SPChange

SPChangeAlert SPChangeCollection

SPChangeContentType SPChangeField

SPChangeFile SPChangeFolder SPChangeGroup SPChangeItem SPChangeList SPChangeQuery SPChangeSecurityPolicy SPChangeSite SPChangeToken SPChangeTokenCollection SPChangeUser SPChangeView SPChangeWeb SPCheckedOutFile SPContentType SPContentTypeCollection SPContentTypeReadOnlyException SPContentTypeSealedException SPContentTypeUsage SPContext SPCopyDestination SPCopyDestinationCollection SPCopyFieldInformation

Represents a change to a file that is outside a list or to an attachment. Represents a change to a folder. Represents a change to a group. Represents a change to an item. Represents a change to a list. Defines a query that is performed against the change log in Windows SharePoint Services. Represents a change to a security policy. Represents a change to a site collection. Represents the unique sequential location of a change within the change log. Represents a collection of SPChangeToken objects. Represents a change to a user. Represents a change to a view. Represents a change to a Web site. Represents a checked-out file in a document library or workspace. Represents a site or list content type. Represents a collection of site or list content types. Represents an exception in Windows SharePoint Services. Represents an exception in Windows SharePoint Services. Used to track where a content type is used as the basis for another content type. Represents the context of an HTTP request in Windows SharePoint Services. Represents a copy destination for a document on a SharePoint Web site. Represents a collection of SPCopyDestination objects. Represents type information that is associated with

fields being copied across servers. SPCopyFieldMask SPCustomWebTemplate SPDailySchedule SPDataRetrievalServicesSettings Represents a field mask for a copied item. Represents a custom site template. Represents a daily schedule for a job definition. Obsolete. Use the SPDataRetrievalProvider class to access the data-retrieval service settings for a Web application instead. (In Windows SharePoint Services 2.0, theSPDataRetrievalServucesSettings class represented the data-retrieval service settings that are used on a virtual server.) Represents an en exception that occurs while performing an operation on a distribution list for a group. Holds information about an asynchronous Directory Management Service request. Represents all the discussions associated with a single document that has been discussed in a document library. Represents the collection of SPDocDiscussion objects associated with documents in a specific document library. Represents a document template used in a document library. Represents a collection of document templates. Represents a document library in Windows SharePoint Services. Provides a method for trapping the event when a list receives an e-mail message.

SPDistributionGroupException

SPDistributionGroupJobData SPDocDiscussion

SPDocDiscussionCollection

SPDocTemplate SPDocTemplateCollection SPDocumentLibrary SPEmailEventReceiver

SPEncodedResourceExpressionBuild Represents an expression builder for returning an er encoded resource. SPEvaluatorModeProvisioner Represents a provisioner for creating the default site and content in stand-alone installations of Windows SharePoint Services. Represents the class that implements evaluator mode provisioning for stand-alone installations of Windows SharePoint Services.

SPEvaluatorModeProvisioning

SPEventContext

Represents an Event Context in a list of receiver processes on a Windows SharePoint Services Web site. Base class that provides the event properties that are common to all event types. This class is never instantiated. Base class that provides methods for event receivers in the Windows SharePoint Services object model. This class is never instantiated. Abstract base class that defines general properties of an event receiver that will reside in theSPEventReceiverDefinitionCollection.

SPEventPropertiesBase

SPEventReceiverBase

SPEventReceiverDefinition

SPEventReceiverDefinitionCollection Represents a collection of SPEventReceiverDefinition objects that are used to enumerate the list of registered event receivers for Windows SharePoint Services objects that can have events. SPException SPExecutingConversionRequest SPExternalBinaryId Represents an exception in Windows SharePoint Services. Conveys the context of a document conversion. Provides the means to retrieve ID values that allow you to retrieve files that are stored in an External BLOB Store. A collection of BinaryID values provides using anSPExternalBinaryId object, and that correspond with binary files stored in an External BLOB Store. Represents the state of a feature at its corresponding scope. Represents a collection of SPFeature objects. Represents a Feature that is depended upon by another Feature. Represents a collection of Features that are depended upon by another Feature. Represents a single Feature property. Represents a collection of SPFeatureProperty objects. Base abstract class that can be overridden to trap

SPExternalBinaryIdCollection

SPFeature SPFeatureCollection SPFeatureDependency SPFeatureDependencyCollection SPFeatureProperty SPFeaturePropertyCollection SPFeatureReceiver

the activation, deactivation, installation, or uninstallation of a Feature. SPFeatureReceiverProperties SPField SPFieldAllDayEvent SPFieldAttachments SPFieldBoolean SPFieldCalculated SPFieldChoice SPFieldCollection SPFieldComputed SPFieldCrossProjectLink SPFieldCurrency SPFieldDateTime SPFieldFile SPFieldLink SPFieldLinkCollection SPFieldLookup SPFieldLookupValue SPFieldLookupValueCollection SPFieldModStat SPFieldMultiChoice SPFieldMultiChoiceValue Represents the properties of a Feature installation, uninstallation, activation, or deactivation event. Represents a field in a list on a Windows SharePoint Services Web site. Represents a Boolean field that specifies an all-day activity without a start or end time. Represents a field that contains attachments. Represents a Boolean field type. Represents a calculated field in a list. Represents a choice field. Represents a collection of SPField objects. Represents a computed field, which is a field that depends on another field for its contents. Represents a field that is used to connect a list event with a Meeting Workspace site. Represents a field that contains currency values. Represents a field that contains date and time values. Represents a field that contains a file. Represents a single column (also known as field) reference that is included in a content type. Represents the collection of column or field references in a content type. Represents a lookup field. Contains the value for an SPFieldLookup object. Contains the values for an SPFieldLookup object that can contain multiple values. Represents a field that contains content approval status. Represents a choice field that allows multiple values. Contains the value for an SPFieldLookup object.

SPFieldMultiColumn SPFieldMultiColumnValue SPFieldMultiLineText SPFieldNumber SPFieldPageSeparator SPFieldRatingScale SPFieldRatingScaleValue SPFieldRecurrence SPFieldText SPFieldTypeDefinition SPFieldTypeDefinitionCollection SPFieldUrl SPFieldUrlValue SPFieldUser SPFieldUserValue SPFieldUserValueCollection SPFieldValidationException SPFieldWorkflowStatus SPFile

Represents a multicolumn field type. Contains the value for an SPFieldMultiColumn object. Represents a text field that can contain multiple lines. Represents a field that contains numbers. Represents a field that is used to insert a page break in a survey list. Represents a rating scale field that is used in surveys. Contains the value for an SPFieldRatingScale object. Represents a field that contains a recurrence pattern in a Calendar list. Represents a field that contains a single line of text. Represents a field type definition. Represents a collection of SPFieldTypeDefinition objects. Represents a field that contains URL values. Contains the value for an SPFieldUrl object. Represents a user field. Contains the value for an SPFieldUser object. Contains the values for an SPFieldUser object that can contain multiple values. Represents an exception that is thrown when an error occurs during field value validation. Represents a workflow status field. 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. Represents a collection of SPFile objects. Exposes a Stream object around a SharePoint file. Represents a version of an SPFile object. Represents a collection of SPFileVersion objects.

SPFileCollection SPFileStream SPFileVersion SPFileVersionCollection

SPFolder SPFolderCollection SPForm SPFormCollection SPFormContext SPGroup SPGroupCollection SPHourlySchedule

Represents a folder on a SharePoint Web site. Represents a collection of SPFolder objects. Represents a form creating, displaying, or editing a list item in a list. Represents a collection of SPForm objects. Provides information about the context that is specific to a list item form. Represents a group on a Windows SharePoint Services Web site. Represents a collection of SPGroup objects. Represents an hourly schedule for a job definition.

SPHtmlEncodedResourceExpression Represents an expression builder for returning an Builder HTML-encoded resource string. SPInvalidPropertyException SPIssueList SPItem SPItemEventDataCollection Represents an exception that is thrown for invalid properties in a property bag. Represents an issues list. Abstract base class that constitutes the data transport item upon which forms operate. Holds the properties of an item in state, which can be the current properties of the item (for Before events), properties that the item will have (for updating events), or changed properties of the item (for After events). Contains properties for asynchronous list item event handlers, and serves as a base class for Before synchronous event handlers. Provides methods for trapping events that occur to items. This class is never instantiated. Represents a natural language used within the context of Microsoft Windows SharePoint Services. Represents a collection of SPLanguage objects. Describes a link to or from a document or regular list item. Represents a collection of Microsoft.SharePoint.SPLinkobjects.

SPItemEventProperties

SPItemEventReceiver SPLanguage SPLanguageCollection SPLink SPLinkCollection

SPList SPListCollection SPListEvent

Represents a list on a SharePoint Web site. Represents a collection of SPList objects. Represents an event that occurs within a document library. This class is maintained for backwardcompatibility with event handling in Windows SharePoint Services 2.0. Contains properties for list events. Provides methods to trap events that occur for lists. This class is never instantiated. Represents an item or row in a list. Represents a collection of SPListItem objects. Supports paging through data sets, storing the state that is required to get the next page of data for a specific view of a list. Represents a version of a list item. Represents a collection of SPListItemVersion objects. Represents a list definition or a list template, which defines the fields and views for a list. List definitions are contained in files within \\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES, but list templates are created through the user interface or through the object model when a list is saved as a template. Represents a collection of SPListTemplate objects. Represents the information for a locale that can be set in a SharePoint site, including the display name and locale identifier (LCID). Represents a collection of SPLocale objects. Defines the list of strings that represent localization countries, languages, or regions. Sets the web page image to the image used by the server to indicate a lengthy operation (typically, a rotating gear image with associated text). Represents the base class for the SPUser and SPGroupclasses.

SPListEventProperties SPListEventReceiver SPListItem SPListItemCollection SPListItemCollectionPosition

SPListItemVersion SPListItemVersionCollection SPListTemplate

SPListTemplateCollection SPLocale

SPLocaleCollection SPLocalizationCollection SPLongOperation

SPMember

SPMemberCollection SPMinuteSchedule SPMobileContext

An abstract class encapsulating the behavior of user collections and group collections. Represents a minute schedule for a job definition. Provides information about the current context that is needed for interaction between mobile devices and Windows SharePoint Services 3.0 Web sites. Provides information about the content approval status for an item in a list or a document library. Represents the collection of files and views that are used in a site template. Represents metadata for a module. Represents a collection of SPModule objects. Represents a monthly schedule for a job definition. Represents a schedule that specifies the time range during which the job will run. Use the new SPRoleDefinition and SPRoleAssignment classes instead, to define roles and to assign users to them. For more information, see Changes in the Authorization Object Model. (In Windows SharePoint Services 2.0, SPRole represented the permission assigned to a user or group for a list or a site and is maintained for backward compatibility.) Obsolete. Use the new SPRoleDefinition and SPRoleAssignmentcla sses instead, to define roles and to assign users to them. For more information, see Changes in the Authorization Object Model. (In Windows SharePoint Services 2.0, SPRolerepresented a collection of SPPermission objects and is maintained for backward compatibility.) Obsolete. Represents the detailed permissions and role assignments for a user at a given scope. Represents a document library that contains pictures. Represents a user or group that can be assigned permissions in Windows SharePoint Services to control security.

SPModerationInformation SPModule SPModule.SPModulePropertyBag SPModuleCollection SPMonthlySchedule SPOneTimeSchedule SPPermission

SPPermissionCollection

SPPermissionInfo SPPictureLibrary SPPrincipal

SPQuery SPRecycleBinItem SPRecycleBinItemCollection

Represents a query in a list view. Represents an item in the Recycle Bin for a Web site or a site collection. Represents a collection of SPRecycleBinItem objects.

SPRecycleBinItemCollectionPosition Stores information about the state that is required to get the next page of data for a recycle bin view. SPRecycleBinQuery SPRegionalSettings SPRequestContext SPResource SPResourceExpressionBuilder SPReusableAcl Evaluates expressions during Windows SharePoint Services page parsing. Represents an access control list (ACL) that is applied to a site collection, Web site, list, or list item. Use the new SPRoleDefinition and SPRoleAssignmentcla sses instead, to define roles and to assign users to them. For more information, see Changes in the Authorization Object Model. (In Windows SharePoint Services 2.0, SPRolerepresented a site group and is maintained for backward compatibility.) Obsolete. Defines the role assignments for a user or group on the current object. Represents a collection of SPRoleAssignment objects that defines all the role assignments for each securable object. Use the new SPRoleDefinition and SPRoleAssignmentcla sses instead, to define roles and to assign users to them. For more information, see Changes in the Authorization Object Model. (In Windows SharePoint Services 2.0,SPRoleCollection represented a collection of SPRole objects and is maintained for backward compatibility.) Obsolete. Represents a query against the Recycle Bin. Represents regional settings that are used on the server that is running Windows SharePoint Services. Manages a list of references to the SPSites that are being opened for a specific request.

SPRole

SPRoleAssignment SPRoleAssignmentCollection

SPRoleCollection

SPRoleDefinition

Defines a single role definition, including a name, description, management properties, and a set of rights. Defines the role definitions that are bound to a role assignment object. Represents the collection of SPRoleDefinition objects defining the role definitions that are available for use within the Web site. Abstract base class that supports the different schedule types that are used in job definitions. This class is deprecated. For Search, use the Executemethod of theMicrosoft.SharePoint.Search.Query.KeywordQuer y class or the Microsoft.SharePoint.Search.Query.FullTextSqlQ ueryclass. Represents the item returned as a result of a search performed on a list, document library, or site. This method is deprecated. For Search, use the Executemethod of theMicrosoft.SharePoint.Search.Query.Keywor dQueryclass or theMicrosoft.SharePoint.Search.Query.FullText SqlQueryclass. Represents a collection of SPSearchResult objects. Deprecated. For Search, use the Execute method of theMicrosoft.SharePoint.Search.Query.Keywor dQueryclass or theMicrosoft.SharePoint.Search.Query.FullText SqlQueryclass. Supports paging through the results of a search and storing the state that is required to get the next page of data. Provides static security management properties and methods.

SPRoleDefinitionBindingCollection SPRoleDefinitionCollection

SPSchedule SPSearchResult

SPSearchResultCollection

SPSearchResultCollectionPosition

SPSecurity

SPSimpleFormattingEncodedResourc Represents an expression builder that returns an eExpressionBuilder encoded resource string with simple text formatting. SPSimpleItem Provides the methods to add, modify, or delete an SPSimpleItem object and the fields that are

associated with that object. SPSite Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application. Represents a query that can be performed across multiple lists in multiple Web sites in the same Web site collection. Represents the time zone setting that is implemented on a SharePoint Web site. Represents a collection of SPTimeZone objects.

SPSiteDataQuery

SPTimeZone SPTimeZoneCollection SPTransformServer SPTransformUtilities SPUser SPUserCollection SPUserStorage

Represents a user in Microsoft Windows SharePoint Services. Represents a collection of SPUser objects. Maintains information about the user of a Web Part Page and the amount of space the user is consuming in bytes. Represents a collection of SPUserStorage objects used to maintain storage information for all users of a Web Part Page. Represents the token that identifies the authentication process applied to a user. Represents a view of the data that is contained in a list on a SharePoint site. Represents a collection of SPView objects. Provides specific information about the context of a view. Represents the collection of fields returned in a view. Represents a style for a view. Represents a collection of SPViewStyle objects.

SPUserStorageCollection

SPUserToken SPView SPViewCollection SPViewContext SPViewFieldCollection SPViewStyle SPViewStyleCollection

SPWeb SPWebCollection SPWebEventProperties SPWebEventReceiver SPWebPartCollection

Represents a Windows SharePoint Services Web site. Represents a collection of SPWeb objects. Contains properties for Web site events. Provides methods for trapping events that occur to Web sites. This class is never instantiated. Use the GetLimitedWebPartManager method of the SPFileclass to return an SPLimitedWebPartManager object to manage Web Parts instead. (In Windows SharePoint Services 2.0 the SPWebPartCollection class represented a collection of Web Parts.) Obsolete. Represents the properties of a Web site creation. Provides a handler for responding to Web site creation. Represents a site definition configuration or site template that is used to create SharePoint sites. Represents a collection of SPWebTemplate objects. Represents a weekly schedule for a job definition. Sets the Welcome Page URL for Windows SharePoint Services Web sites. Provides properties that control the characteristics and behaviors of work item object instances. This class is used in conjunction with theMicrosoft.SharePoint.SPWorkItemCollection class . A collection of SPWorkItem object instances. Derives fromMicrosoft.SharePoint.SPBaseCollection. The XML document collection that is associated with a specific site collection. Represents a yearly schedule for a job definition. This type or member supports Microsoft Windows SharePoint Services and is not intended to be used directly from your code.

SPWebProvisioningProperties SPWebProvisioningProvider SPWebTemplate SPWebTemplateCollection SPWeeklySchedule SPWikiWelcomeFeatureReceiver SPWorkItem

SPWorkItemCollection SPXmlDocumentCollection SPYearlySchedule Strings

Interfaces Interface IAlertNotifyHandler IAlertUpdateHandler IExternalSecurityWeb Description Provides a method for handling the sending of an alert. Provides synchronous methods for handling alert updates made through the user interface. Provides methods that return custom information about the security used in Microsoft Windows SharePoint Services for use in indexing by a search crawler on a portal.

IFileDialogPostProcessor Provides a method for customizing the Web views used in file dialog boxes and forms of document libraries. IListEventSink IRequestResources ISecurableObject ISPConversionProcessor Defines the interface that a list event handler must implement to respond to events within a document library. Specifies an interface that checks user permissions during operations that may potentially alter content on the Web site. Exposes the role assignments for an object and manages the permissions of the object. Provides methods for custom handling of transformed data, including preprocessing and postprocessing of data returned by the launcher. Defines event receivers for events associated with SharePoint objects (such as Web sites, lists, documents, content types, or specific SharePoint features.

ISPEventReceiversHost

Structures Structure Description

ExternalSecurityWebProperty Provides fields that contain custom information about security used in Microsoft Windows SharePoint Services. SPAlertEventData SPAlertHandlerParams SPContentTypeId SPSite.UsageInfo Provides information about an alert event. A structure containing a light weight SPAlert object and information needed to generate an alert message. Represents the identifier (ID) of a content type. Provides fields used to access information regarding site

collection usage. SPSystemTime SPTimeZoneInformation SPUserInfo Provides properties used to define system date and time values. Provides fields used to define a time zone. Defines information about a user who is not currently registered in the content database.

Delegates Delegate SPContext.GetCachedField SPContext.SetCachedField Description Implements a callback to check for a cached field value. Implements a callback to set cached field values.

SPFieldCollection.CreateSPFieldCallback Allows a callback to be established for a field within a collection. SPSecurity.CodeToRunElevated Represents methods that are passed to RunWithElevatedPrivileges, so that the methods can run with Full Control privileges even if the current user does not otherwise have Full Control.

Enumerations Enumeration DefaultItemOpen Description Specifies whether to use a rich client application or the browser to open a list item. Specifies the kind of user who can view the minor version of a document draft. An enumeration which returns the result of the file submission operation against a site object. Specifies the type of a form. Used to filter SharePoint page metadata, and to appropriately handle command

DraftVisibilityType OfficialFileResult

PAGETYPE RequestResources

data associated with SharePoint site pages. SPAddFieldOptions An enumerated list of options that are used to control settings that relate to default content types and content type views. The SPAlertFrequency enumeration specifies the time interval for sending an alert about changes to a specific list, list item, document library, or document. Specifies the status of an alert. Specifies the type of item that an alert applies to. Specifies whether an audited event occurred programmatically or as a result of user action through the Windows SharePoint Services 3.0 UI. Specifies types of events, for a particular site collection, site, list, folder, or list item, that are auditable by using the SPAuditclass. Specifies the types of object that can be audited. Specifies the actual location of a document in a SharePoint document library. Specifies what kind of actions and events are being audited for a particular site collection, site, list, folder, or list item object. Specifies the built-in permissions available in Windows SharePoint Services. Specifies the base type for a list. Specifies the order to use for day, month, and year in calendar dates. Specifies the calendar type. Specifies the scope at which a change log is retrieved.

SPAlertFrequency

SPAlertStatus SPAlertType SPAuditEventSource

SPAuditEventType

SPAuditItemType SPAuditLocationType

SPAuditMaskType

SPBasePermissions SPBaseType SPCalendarOrderType SPCalendarType SPChangeCollection.CollectionScope

SPChangeType SPCheckinType SPChoiceFormatType SPCopyDestinationType SPCopyErrorCode SPCurrencyFieldFormats SPCustomizedPageStatus SPDateTimeFieldFormatType SPDistributionGroupJobType

Specifies the type of change to return through a query against the change log. Specifies the type of check in for a file. Specifies how options for how to display selections in a choice field. Specifies the behavior used for updates of a document to a copy destination. Specifies copy-specific error codes. Specifies the format to use in currency fields. Obsolete. Specifies the customization status of a Windows SharePoint Services page. Specifies the format to use in displaying date and time fields. Describes a type of asynchronous operation that is performed on distribution groups. Specifies the type of object that is hosting the event. Specifies the status of trapping an event. Specifies the type of event that has occurred for a Windows SharePoint Services object. Specifies the type of event for a list, list item, document, or document library to which an alert responds. Specifies the scope to which the feature applies. Specifies a field type for a field. Specifies the selection mode for creating or editing column values. Specifies the check-out status for a file in a document library. Indicates the results of a file transform. Specifies the conversion state for a file

SPEventHostType SPEventReceiverStatus SPEventReceiverType

SPEventType

SPFeatureScope SPFieldType SPFieldUserSelectionMode SPFile.SPCheckOutStatus SPFileConversionResult SPFileConversionState

that is being transformed. SPFileLevel SPFileSystemObjectType SPIssueList.ReportType SPListCategoryType SPListEventType SPListTemplate.QuickLaunchOptions Specifies the level of publication for a document. Specifies a type of file system object. Specifies the kind of report to use in displaying data from an Issues list. Specifies a list template category type for use on the Create page. Specifies the type of an event that occurs in a document library. Specifies whether to display Quick Launch links to lists created through the list template. Specifies the type of a list definition or a list template. Specifies values for content approval status of items in lists and document libraries. Specifies criteria for how to move files. Specifies the number of decimal places to use in number and currency fields. Specifies the type of object. Provides values to pass when opening a binary stream file when using the OpenBinary or OpenBinaryStream me thods. Represents the permissions available for role definitions on a Web site. This enumeration is obsolete. Use theSPPermissionGroup64 enumeration instead. Represents the permissions available for role definitions on a Web site. Specifies the size of the preview value for a multiline text field. Specifies the Recycle Bin stage of the item.

SPListTemplateType SPModerationStatusType

SPMoveOperations SPNumberFormatTypes SPObjectType SPOpenBinaryOptions

SPPermissionGroup

SPPermissionGroup64 SPPreviewValueSize SPRecycleBinItemState

SPRecycleBinItemType SPRecycleBinOrderBy SPRecycleBinType SPRichTextMode SPRights

Specifies the type of Recycle Bin item. Specifies the column by which to order a Recycle Bin query. Specifies whether the Recycle Bin is the end-user or site-collection Recycle Bin. Specifies the rich text formatting of a field. Specifies the rights that apply to users, site groups, and cross-site groups. Obsolete. Specifies the types of roles that are available for users and groups.

SPRoleType SPSecurity.SPOperationCode SPSite.StorageManagementInformationType SPSite.StorageManagementSortedOn

Specifies the kind of storage management data to display. Specifies whether items on a page are sorted by size (increasing or decreasing) or by date (increasing or decreasing). Specifies the direction in which items are sorted on a page. Specifies the type of file that is created based on the site definition or template.

SPSite.StorageManagementSortOrder SPTemplateFileType SPTransformCacheType SPUrlFieldFormatType SPViewCollection.SPViewType SPViewScope SPWeb.WebAnonymousState

Specifies the format used for URL fields. Specifies the type of view implemented for a list. Specifies the recursive scope of a view for a document library. Specifies settings for anonymous access to a Web site.

SPWebTemplate.TeamCollaborationSiteConfig Specifies the type of team collaboration uration site definition. SPWebTemplate.WebTemplate SPWorkItemStatus Specifies the type of a site definition. Specifies the current processing status of an SPWorkItemobject instance. The

value is passed to the InternalStateproperty. WebASPXPageIndexMode Sets a value that indicates one of three indexing modes that can apply to a Web page. Specifies the type of file dialog box or form for a document library.

WffRequestType

Microsoft.SharePoint.Administration Namespace Provides administrative types and members for managing a Windows SharePoint Services deployment. Classes Class PersistedAttribute SPAce SPAcl SPActionLink Description Indicates that this property should be stored in the configuration database. Respresents an access control entry in an access control list (ACL). Represents an access control list (ACL). Represents an action that is displayed for a service on the Services on Server page in the SharePoint Central Administration Web site.

SPAdministrationServiceJobDefinition SPAdministrationWebApplication Represents an SPWebApplication object with additional settings that are specific to Windows SharePoint Services. Represents an incoming URL and the zone with which it is associated. Represents a collection of SPAlternateUrl objects. Provides methods that can be used to perform operations on all theSPAlternateUrlCollection objects in the farm. Represents a collection of antivirus settings. Represents an Internet Information Services

SPAlternateUrl SPAlternateUrlCollection SPAlternateUrlCollectionManager

SPAntivirusSettings SPApplicationPool

(IIS) application pool. SPApplicationPoolCollection SPAutoSerializingObject Represents a collection of SPApplicationPool objects. Serves as the base class for all topology objects that provide automatic serialization of fields with the appropriate attributes. Represents an exception that is thrown to prevent overwriting settings when changes made to administration on one computer within a server farm conflict with settings on another computer. Obsolete. Represents the configuration database in a Microsoft Windows SharePoint Services deployment. Provides data for the SPConfigurationChangeEventHandler event. Represents a content database that is part of a Windows SharePoint Services deployment. A collection of references to content databases that are used by a single Web application. Encapsulates access to Microsoft SQL Server databases. Represents a collection of SPDatabase objects. Represents a database exception that is thrown when Microsoft SQL Server returns an error of any kind, including errors that occur in Windows SharePoint Services business logic that is running in SQL Server. Represents a farm-wide service that stores settings for all instances of SQL Server. Represents a collection of SPDatabaseService objects. Represents a named SQL Server instance. Represents a collection of SPDatabaseServiceInstance objects. Represents data-retrieval service settings for a Web application.

SPConcurrencyException

SPConfigDatabase

SPConfigurationChangeEventArgs SPContentDatabase SPContentDatabaseCollection SPDatabase SPDatabaseCollection SPDatabaseException

SPDatabaseService SPDatabaseServiceCollection SPDatabaseServiceInstance SPDatabaseServiceInstanceCollection SPDataRetrievalProvider

SPDeletedConcurrencyException

Represents an exception that is thrown when attempting to update an object that has been deleted. Provides a diagnostic logging category manager for Windows SharePoint Services. Represents a document converter, or document transformer, that is installed in a SharePoint Web application. Represents a collection of SPDocumentConverter objects that are available to a Web application. Base class that supports property promotion and demotion for HTML documents. Represents an exception that is thrown when creating an object that has the same properties as another object. Serves as the base class for implementing element types within Windows SharePoint Services. Represents a collection of SPElementDefinition objects. Represents an encrypted string. Represents a collection of SPEncryptedString objects. Represents a Windows SharePoint Services farm. Contains the base definition of an SPFeature, including its name, identifier, scope, and version. Represents a collection of SPFeatureDefinition objects. Represents the settings that are related to Web page security validation. Use the new SPFarm and SPWebService classes instead, to manage a Windows SharePoint Services deployment. (In Windows SharePoint Services 2.0, SPGlobalAdmin represented the top-level object for administration of a

SPDiagnosticsService SPDocumentConverter

SPDocumentConverterCollection

SPDocumentParser SPDuplicateObjectException

SPElementDefinition

SPElementDefinitionCollection SPEncryptedString SPEncryptedStringCollection SPFarm SPFeatureDefinition

SPFeatureDefinitionCollection SPFormDigestSettings SPGlobalAdmin

deployment, and is maintained for backward compatibility.) Obsolete. SPGlobalConfig Use the new SPWebApplication and SPWebService c lasses instead, to define configuration settings. Obsolete. Represents a collection of HTML viewer settings. Represents the Internet Information Services (IIS) authentication settings that are shared across all front-end Web servers for a specific URL zone, which can be modified and propagated by re-provisioning the Web application. Represents an Internet Information Services (IIS) Web site. Represents the service that is used in Windows SharePoint Services for incoming e-mail timer jobs. Represents an instance of the incoming e-mail service that is used in Windows SharePoint Services for incoming e-mail timer jobs.

SPHtmlTransformSettings SPIisSettings

SPIisWebSite SPIncomingEmailService

SPIncomingEmailServiceInstance

SPInvalidCollationException SPIrmSettings Represents Information Rights Management (IRM) settings that are used in Windows SharePoint Services to help protect the use and distribution of documents. Represents a job definition. This member is reserved for internal use and is not intended to be used directly from your code. Base class that is used for load balancers in document conversions. Provides methods for managing the Internet Information Services (IIS) metabase. Represents an object that is persisted in the Internet Information Services (IIS) metabase. Represents a collection of site collections that can be migrated in a gradual upgrade from

SPJobDefinition SPJobDefinitionCollection

SPLoadBalancerServiceInstance SPMetabaseManager SPMetabaseObject SPMigratableSiteCollection

Windows SharePoint Services 2.0 to Windows SharePoint Services 3.0. SPOutboundMailService Represents a Simple Mail Transfer Protocol (SMTP) service that is used in Windows SharePoint Services to send outbound mail. Respresents an instance of a Simple Mail Transfer Protocol (SMTP) service that is used in Windows SharePoint Services to send outbound mail.

SPOutboundMailServiceInstance

SPOutboundMailServiceInstanceCollecti Represents a collection on of SPOutboundMailServiceInstance objects. SPPeoplePickerSearchActiveDirectoryDo Represents an Active Directory domain forest main that is searched by the People Picker control within the Windows SharePoint Services user interface. SPPeoplePickerSettings Represents settings that are used in the People Picker control to select users, distribution lists, and security groups within the Windows SharePoint Services user interface. Represents a collection of SPPersistedObject objects that have a common parent. Represents a custom Web template that is persisted.

SPPersistedChildCollection

SPPersistedCustomWebTemplate

SPPersistedCustomWebTemplateCollecti Represents a collection of persisted custom on Web templates that share a Web service or Web application as parent object. SPPersistedDependencyCollection SPPersistedFile Represents a collection of persisted objects that depend on a common object. Represents a file stored in the configuration store that is used for administration and deployment. Provides the methods for an object to automatically serialize its state, persist that state in a permanent store, retrieve it at a later time, and deserialize it back into an in-memory object. Provides a base class for collections that manage SPPersistedObjectobjects.

SPPersistedObject

SPPersistedObjectCollection

SPPersistedUpgradableObject SPPolicy SPPolicy.SPPolicyRoleBindingCollection SPPolicyCollection SPPolicyRole SPPolicyRoleCollection SPPrefix

Represents a persisted object that implements the IUpgradableinterface. Represents the policy that is assigned to a user or group. Represents the collection of policy roles through which each user or group is bound to a policy. Represents a collection of SPPolicy objects. Defines the rights granted and denied to a single policy role. Represents a collection of SPPolicyRole objects. Represents a specified relative URL that is used to determine whether Windows SharePoint Services or Microsoft Internet Information Services (IIS) handles the request. Represents a collection of SPPrefix objects. Represents a process identity, which specifies an Internet Information Services (IIS) application pool and Windows service account. Represents a collection of SPProcessIdentity objects. Represents a quota that limits the system resources that are allocated to users. Represents a reusable definition of a quota that is applied to SharePoint sites in the deployment. Represents a collection of SPQuotaTemplate objects. A running job object is created for every instance of the job that is executing, at the rate of one per server. Represents a collection of SPRunningJob objects. Represents a server binding for a site that uses Secure Socket Layer (SSL) and secure hypertext transfer protocol (HTTPS). Represents a physical computer in the server farm.

SPPrefixCollection SPProcessIdentity

SPProcessIdentityCollection SPQuota SPQuotaTemplate

SPQuotaTemplateCollection SPRunningJob

SPRunningJobCollection SPSecureBinding

SPServer

SPServerBinding

Represents a server binding for an Internet Information Services (IIS) Web site, which includes at least one of the following: IP address, port, or host name. Represents a collection of SPServer objects. Represents a farm-wide service. Represents a collection of SPService objects. Represents a single instance of a service that runs on a server. Represents a collection of SPServiceInstance objects.

SPServerCollection SPService SPServiceCollection SPServiceInstance SPServiceInstanceCollection

SPServiceInstanceDependencyCollectio Represents a collection of service instances that n are dependent on a service. SPServiceInstanceJobDefinition SPSiteAdministration Represents a SPJobDefinition that is associated with aSPServiceInstance object. Provides an abstraction for operations that require administrator access to the content space of a site collection. Represents a collection of SPSite objects or site collections on a virtual server. Represents a solution on a farm. Represents a collection of SPSolution objects. Represents a language pack for a solution or Web Part package. Represents a collection of language packs associated with a solution or Web Part package. Implements a timer service to support the use of timer jobs. Provides an instance of a timer service that runs on a server. This member is reserved for internal use and is not intended to be used directly from your code.

SPSiteCollection SPSolution SPSolutionCollection SPSolutionLanguagePack SPSolutionLanguagePackCollection SPTimerService SPTimerServiceInstance SPTimerServiceInstanceCollection

SPUncleanDatabaseException SPUpdatedConcurrencyException Represents an exception in Windows SharePoint

Services that occurs when running code on multiple front-end Web servers that modifies the same object, or when the servers use a mix of Windows SharePoint Services 3.0 and Windows SharePoint Services 2.0 object model code that modifies the same object. SPUpgradeJobDefinition SPUsage Represents an upgrade job definition. Provides a property to return the localized names of the report types that are used in usage reports. Defines the search string categories of identities of usage report components, for example, the browser or operating system. Encapsulates settings for usage analysis and logging in the Windows SharePoint Services deployment.

SPUsageIdentityTable

SPUsageSettings

SPUserMigratorElement SPVirtualServer Obsolete. Use the SPWebApplication class or the SPIisSettings class instead. (In Windows SharePoint Services 2.0, the SPVirtualServerclass represented the toplevel object for a virtual server in Windows SharePoint Services, and is maintained for backward compatibility.) Obsolete. Obsolete. Use the SPWebApplicationCollection class instead. (In Windows SharePoint Services 2.0, the SPVirtualServerCollectionclass represented a collection of SPVirtualServer objects, and is maintained for backward compatibility.) Obsolete. Obsolete. Use the SPWebApplication class or the SPIisSettings class instead. (In Windows SharePoint Services 2.0, theSPVirtualServerConfig class represented the configuration settings for a virtual server, and is maintained for backward compatibility.) Obsolete. Represents an Internet Information Services (IIS) load-balanced Web application that is

SPVirtualServerCollection

SPVirtualServerConfig

SPWebApplication

installed on the server farm. SPWebApplicationBuilder Creates an SPWebApplication object, providing default settings for all the required values and allowing the caller to change only those properties that need values that are different from the default. Represents a collection of SPWebApplication objects. Holds modifications that are made to the web.config. Represents a front-end Web server in a server farm. Represents a collection of SPWebServer objects. Represents a Web service that contains one or more Web applications. Represents a collection of SPWebService objects. Represents an instance of a Windows SharePoint Services Web service running on a particular server. Represents a collection of SPWebServiceInstance objects. Represents a Windows service that is installed on one or more servers in the server farm. Represents a collection of SPWindowsService objects. Represents an instance of a Windows service that runs on a particular server. Represents a collection of SPWindowsServiceInstance objects. Serves as the base class for deriving definitions of work-item timer jobs. This class works with the timer job (SPTimerService) to process work items (SPWorkItem).

SPWebApplicationCollection SPWebConfigModification SPWebServer SPWebServerCollection SPWebService SPWebServiceCollection SPWebServiceInstance

SPWebServiceInstanceCollection SPWindowsService SPWindowsServiceCollection SPWindowsServiceInstance SPWindowsServiceInstanceCollection SPWorkItemJobDefinition

Interfaces

Interface IDiagnosticsLevel

Description Provides an interface through which developers can expose to Windows SharePoint Services a single trace log category to assign to trace log messages for a given application.

IDiagnosticsManager Provides an interface through which developers can expose to Windows SharePoint Services the categories to assign to trace log messages for a given application. IMigratable Provides support for gradual upgrade by migrating paired objects from Windows SharePoint Services 2.0 to Windows SharePoint Services 3.0. Provides support for migrating user accounts from one login name to another. Provides members for managing an upgradable object.

ISPUserMigrator IUpgradable Delegates Delegate

Description

SPConfigurationChangeEventHandler Provides an event handler for when an object changes. Enumerations Enumeration EventSeverity HttpErrorsExistingResponseOptions Description Specifies the severity of events written to the Windows event log. Specifies whether Internet Information Services (IIS) overwrites Windows SharePoint Services error messages. Specifies the process identity type used by a Web application. Specifies the type of action provided for a service that is displayed on the Services on Server page within the SharePoint Central Administration Web site. Specifies a security policy to use for anonymous users Specifies a Microsoft SQL Server database option that is used in a Transact-SQL statement.

IdentityType SPActionLinkType

SPAnonymousPolicy SPDatabase.DatabaseOptions

SPIisWebSite.SPIisServerState SPJobLockType SPMembershipUserKeyType

Indicates the state of the server that runs Internet Information Services (IIS). Values for the lock type of a job definition. In Forms authentication mode, whether to use UserName orProviderUserKeyas the underlying mechanism to identify a user. Specifies the status of a service that runs within a Windows SharePoint Services deployment. Defines the base permissions (see SPBasePermissions) for the read and write permissions that are applied through policies to a SharePoint Web application. Specifies a policy role type to apply globally in a SharePoint Web application to a user or group. Specifies which part of a URL namespace that is used in this Web application belongs to Windows SharePoint Services. Contains values that specify the status of a solution deployment job. Specifies the role of the server with respect to the Windows SharePoint Services deployment. Provides values to specify the type of deployment operation. Contains values that indicate the deployment status of the solution. Describes the result of an operation that attempts to deploy or retract an SPSolution or SPSolutionLanguagePac k object. Specifies the originating zone of a request received by Windows SharePoint Services 2.0. Specifies the time interval on which a usage report for a Web site is based.

SPObjectStatus

SPPolicyPermissions

SPPolicyRoleType

SPPrefixType

SPRunningJobStatus SPServerRole

SPSolutionDeploymentJobType SPSolutionDeploymentState SPSolutionOperationResult

SPUrlZone

SPUsagePeriodType

SPUsageReportType SPVirtualServerState

Specifies the type of information returned in a usage report for a SharePoint site. Specifies the status of a virtual server relative to a deployment of Windows SharePoint Services.

SPWebConfigModification.SPWebConfigModific Specifies the type of web.config ationType modification. TraceSeverity Specifies the level of trace information that is written to the trace log file.

Server and Site Architecture: Object Model Overview Windows SharePoint Services offers a highly structured server-side object model that makes it easy to access objects that represent the various aspects of a SharePoint Web site. From higher-level objects, you can drill down through the object hierarchy to obtain the object that contains the members you need to use in your code. Entry Points Depending on the type of custom application or solution that you are creating, you use different entry points into the object model to obtain the appropriate object from which to start. For example, if you are customizing administration and configuration of a deployment, you can use the static ContentService property to return the current Web service object and its collection of Web applications. To modify settings in the administrative Web application, instead use the AdministrationService property. Collection classes that derive from the Microsoft.SharePoint.Administration.SPPersistedObjectCollection class inherit a GetValue method that you can use to return a specific object from a collection. Note: If you are creating a Web Part, custom Web service, or Web application to work with site collections, individual sites, or lists, you can use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list. When you create a Web application in the /_layouts virtual directory, its functionality becomes available to all sites on the Web server. Outside of an HTTP context, such as in a console application or a Windows application, use a constructor of the SPSite class to obtain a specific site collection and to reach various objects within the collection. For more information, see Getting References to Sites, Web Applications, and other Key Objects. Server Architecture The following diagram shows the Windows SharePoint Services server architecture in relation to the collections and objects of theMicrosoft.SharePoint.Administration namespace.

1. The SPFarm object is the highest object within the Windows SharePoint Services

object model hierarchy. The Serversproperty gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.

2. Each SPServer object represents a physical server computer.

3. Each SPService object represents a logical service or application installed in the


server farm. A service object provides access to server farm-wide settings of the load-balanced service that a respective service instance implements. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, Microsoft SQL Server, the database service, etc. and also objects for Web services, such as Windows SharePoint Services or services in the Microsoft Office system.

4. An SPWebService object provides access to configuration settings for a specific


logical service or application. TheWebApplications property gets the collection of Web applications that run the service.

5. An SPDatabaseServiceInstance object represents a single instance of a database


service running on the server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.

6. Each SPWebApplication object represents a load-balanced Web application based in


Internet Information Services (IIS). TheSPWebApplication object provides access to credentials and other server farm wide application settings. The Sitesproperty gets the collection of site collections within the Web application, and the ContentDatabases property collection of content databases used in the Web application. The SPWebApplication class replaces the obsolete SPVirtualServer class; but it can still be helpful to think of a SPWebApplication object as a virtual server; that is, a set of one or more physical servers that appear as a single server to users.

7. An SPContentDatabase object inherits from the SPDatabase class and represents a


database that contains user data for a SharePoint Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.

8. An SPSiteCollection object represents the collection of site collections within the Web
application. The Item property or indexer gets a specified site collection from the collection, and the Add method creates a site collection within the collection. Site Architecture The following diagram shows the Windows SharePoint Services site architecture in relation to the collections and objects of theMicrosoft.SharePoint namespace.

1. Each SPSiteobject, despite its singular name, represents a set of logically

related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast toSPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The Microsoft.SharePoint.SPSite.OpenWebmethod of the SPSite class returns a specific Web site. members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns anSPWebCollection object that represents all the subsites of a specified site, and the Lists property returns anSPListCollection object that represents all the lists in the site.

2. Each site collection includes any number of SPWeb objects, and each object has

3. Each SPList object has members that are used to manage the list or access items in
the list. The GetItems method can be used to perform queries that return specific

items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.

4. Each SPField object has members that contain settings for the field. 5. Each SPListItem object represents a single row in the list.
If you install "Infrastructure Update for Windows SharePoint Services 3.0 (KB951695)," custom solutions may fail if they call the SharePoint object model while impersonation is suspended. If you use Windows authentication and your code calls the SharePoint object model from an IIS worker process, the request must impersonate the calling users identity. Windows SharePoint Services configures ASP.NET to impersonate the calling user automatically, but your code may work unexpectedly, or fail, if you suspend impersonation-for example, by calling the RevertToSelf function of the Windows API, or by calling theSystem.Security.Principal.WindowsIdentity.Impersonate method and passing IntPtr.Zero as the value of the user token parameter. Even if your code does not explicitly revert to self, it might be called by ASP.NET after it reverts to self, such as happens when implementing a virtual path provider; if your code does not impersonate the calling user, it might not function properly.

Sample Object Model Tasks This section in the Windows SharePoint Services Software Development Kit (SDK) provides sample programming tasks that show how to use the Windows SharePoint Services object model to customize SharePoint sites and lists within a deployment. In This Section How to: Create a Web Application in a SharePoint Web Site How to: Create a Console Application How to: Implement the Object Model in a Custom Web Part How to: Return Sites and Site Collections How to: Create or Delete a Site or a Site Collection How to: Create or Delete Lists How to: Add or Delete a List in Multiple Web Sites How to: Return Items from a List How to: Add or Delete List Items How to: Access, Copy, and Move Files How to: Upload a File to a SharePoint Site from a Local Folder How to: Add a Recurring Event to Lists on Multiple Sites

How to: Create a Web Application in a SharePoint Web Site

This programming task describes how to create a custom Web application, or Web Site, in Visual Studio 2005 that operates within the context of Windows SharePoint Services. The example creates a tool that reports a list of all the SharePoint Web sites to which a specified user belongs, as well as a list of the groups to which the user belongs for each Web site. Note: The phrase "Web application" has varying meanings depending on the context. This topic concerns browser-based applications that run from an aspx page. It is not about Web applications in the sense of Internet Information Services (IIS) "Web sites" or "Application Pools". Hence, it is not about the things represented by the SPWebApplication class in the Windows SharePoint Services 3.0 object model. Procedure To create a tool for reporting a user's SharePoint Web sites and groups 1. In Visual Studio 2005, create a new Web application and set a reference to Microsoft.SharePoint.dll. For information about how to perform these steps, or about how to create a Web application on a front-end Web server from a remote computer that is not running Windows SharePoint Services, see Getting Started with Programmatically Customizing a SharePoint Web Site in Visual Studio.

2. In Design view, use the Toolbox to add a label, a text box, and a button to
Default.aspx. To open the Toolbox, click Toolboxon the View menu. Note: To create a Web application that modifies data in the content database, you need to add a FormDigest control and a page directive to the .aspx file that contains the form. For information about how to add this control, see Security Validation and Making Posts to Update Data. 3. To open the code-behind file named Default.aspx.cs, double-click the button you added in the previous step.

4. At the beginning of the file, add using directives (Imports statements in Visual
Basic) that reference theMicrosoft.SharePoint and Microsoft.SharePoint.Utilities, as follows: Visual Basic Imports Microsoft.SharePoint Imports Microsoft.SharePoint.Utilities C# using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; You must reference the Microsoft.SharePoint namespace in order to return the specified user and the groups to which the user belongs. You must reference

the Microsoft.SharePoint.Utilities namespace in order to encode strings that are displayed in the example. 5. At the beginning of the class definition return the site collection object for the current request context as follows: Visual Basic Partial Class _Default Inherits System.Web.UI.Page

Dim oSite As SPSite = SPContext.Current.Site ... C# public partial class _Default : System.Web.UI.Page { SPSite oSite = SPContext.Current.Site; ...

6. Create a method that uses the AllWebs property of the SPSite class,

the AllUsers property of the SPWeb class, and theGroups property of the SPUser class within nested foreach statements, in order to return a user object for the user name specified in the text box, as well as the list of groups to which that user belongs. Within the default class in Default.aspx.cs, add the following method to return the users and groups for each Web site in the current site collection: Visual Basic Protected Sub GetSitesAndGroups() Dim strUser As String = SPEncode.HtmlEncode(TextBox1.Text) _ & " is a user in the following groups:<BR>"

Dim collWebs As SPWebCollection = oSite.AllWebs

For Each oWebsite As SPWeb In collWebs Dim strGroups As String = ""

'Use AllUsers not Users to ensure you find the user

Dim collUsers As SPUserCollection = oWebsite.AllUsers

For Each oUser As SPUser In collUsers If oUser.LoginName.ToUpper() = TextBox1.Text.ToUpper() Then Dim collGroups As SPGroupCollection = oUser.Groups

For Each oGroup As SPGroup In collGroups strGroups += SPEncode.HtmlEncode(oGroup.Name) & " " Next oGroup

strUser = strUser _ & oWebsite.ServerRelativeUrl.ToString() _ & " -- " & strGroups & "<BR>" End If Next oUser

oWebsite.Dispose() Next oWebsite

Label1.Text = strUser End Sub C# protected void GetSitesAndGroups() { string strUser = SPEncode.HtmlEncode(TextBox1.Text) + " is a user in the following groups:<BR>";

SPWebCollection collWebs = oSite.AllWebs;

foreach (SPWeb oWebsite in collWebs) { string strGroups = "";

/*Use AllUsers not Users to ensure you find the user*/ SPUserCollection collUsers = oWebsite.AllUsers; foreach (SPUser oUser in collUsers) { if (oUser.LoginName.ToUpper() == TextBox1.Text.ToUpper()) { SPGroupCollection collGroups = oUser.Groups;

foreach (SPGroup oGroup in collGroups) { strGroups += SPEncode.HtmlEncode(oGroup.Name) + " "; }

strUser += oWebsite.ServerRelativeUrl.ToString() + " -- " + strGroups + "<BR>"; } }

oWebsite.Dispose(); }

Label1.Text = strUser; } The code example iterates through all the users of all the Web sites within the current site collection, and if the value of theLoginName property for a given user matches the user name that is entered in the text box, then the names of all the user's groups for the site are collected and displayed.

7. To run the code added in the previous step and avoid receiving an access denied

error message, the user implementing the GetSitesAndGroups method must have Full Control permission. Add the following code to the Button1_Click event handler, which uses the RunWithElevatedPrivileges method to allow the current user to iterate through the users and groups of each Web site within the current site collection. Visual Basic

Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim elevatedGetSitesAndGroups As New SPSecurity.CodeToRunElevated(AddressOf GetSitesAndGroups) SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups) End Sub C# protected void Button1_Click(object sender, EventArgs e) { SPSecurity.CodeToRunElevated elevatedGetSitesAndGroups = new SPSecurity.CodeToRunElevated(GetSitesAndGroups); SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups); }

8. On the Debug menu, click Start Debugging, or press F5. If a Debugging Not
Enabled dialog box appears, make sureAdd a new Web.config file with debugging enabled is selected, and click OK.

The browser opens the page. When you type the logon name of a user on a site within the current site collection, the label displays the Web sites and groups to which the specified user belongs.

9. To run the application after creating it in Visual Studio 2005, navigate


tohttp://Server_Name/_layouts/Web_Application_Name/Default.aspx.

How to: Create a Console Application This programming task describes how to create a console application in Microsoft Visual Studio 2005. The example displays the number of lists within a site collection. Users must be administrators on the computer where the script is executed in order to run a console application in the context of Windows SharePoint Services. To create a console application in Visual Studio 2005

1. On the File menu in Visual Studio 2005, point to New and then click Project. 2. In the New Project dialog box, select a language, and then select Windows in
the Project Types box.

3. In the Templates box, select Console Application. 4. In the Location box, type the path to where to create the application, and then
click OK.

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

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

7. In the .vb or .cs file, add a using directive for the Microsoft.SharePoint namespace,
as follows. Visual Basic Imports Microsoft.SharePoint C# using Microsoft.SharePoint;

8. Add the following code to the Main method in the .vb or .cs file.
Visual Basic Overloads Sub Main(args() As String)

Dim siteCollection As New SPSite("http://Server_Name") Dim sites As SPWebCollection = siteCollection.AllWebs Dim site As SPWeb

For Each site In sites

Dim lists As SPListCollection = site.Lists

Console.WriteLine("Site: " + site.Name + " Lists: " + lists.Count.ToString())

Next site

Console.WriteLine("Press ENTER to continue") Console.ReadLine()

End Sub 'Main

C# static void Main(string[] args) { SPSite siteCollection = new SPSite("http://Server_Name"); SPWebCollection sites = siteCollection.AllWebs;

foreach (SPWeb site in sites) { SPListCollection lists = site.Lists;

Console.WriteLine("Site: " + site.Name + " Lists: " + lists.Count.ToString()); }

Console.WriteLine("Press ENTER to continue"); Console.ReadLine(); }

9. Click Start on the Debug menu or press F5 to run the code.

How to: Implement the Object Model in a Custom Web Part You can create custom Web Parts to work with site or list data. This programming task shows how to create a simple Web Part that displays the titles and number of items for all lists that contain more than 10 items on subsites in the current Web site. To create a Web Part that displays titles and number of items for lists 1. Create a Web Part as described in Walkthrough: Creating a Basic SharePoint Web Part. This example assumes that you have created a SimpleWebPart application.

2. Open WebCustomControl1.cs or WebCustomControl1.vb for the SimpleWebPart


application, and add directives for theMicrosoft.SharePoint and Microsoft.SharePoint.Utilities, as follows: Visual Basic

Imports Microsoft.SharePoint Imports Microsoft.SharePoint.Utilities C# using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities;

3. Remove the HtmlControl objects used in the example, including declarations for

their variables, the _mybutton_click handler, and the CreateChildControls method.

4. Replace the contents of the RenderWebPart method with the following code block.
Visual Basic Dim mySite As SPWeb = SPContext.Current.Web

output.Write(SPEncode.HtmlEncode(mySite.Title))

Dim subSites As SPWebCollection = mySite.Webs Dim site As SPWeb

For Each site In subSites output.Write(SPEncode.HtmlEncode(site.Title) & "<BR>") Dim lists As SPListCollection = site.Lists Dim list As SPList

For Each list In lists

If list.ItemCount > 10 Then output.Write(SPEncode.HtmlEncode(list.Title) & " :: " & list.ItemCount & "<BR>") End If Next list Next site C# SPWeb mySite = SPContext.Current.Web;

output.Write(SPEncode.HtmlEncode(mySite.Title));

SPWebCollection subSites = mySite.Webs;

foreach(SPWeb site in subSites) {

output.Write(SPEncode.HtmlEncode(site.Title) + "<BR>");

SPListCollection lists=site.Lists;

foreach(SPList list in lists) {

if (list.ItemCount>10) { output.Write(SPEncode.HtmlEncode(list.Title) + " : " + list.ItemCount + "<BR>"); } } } The example first writes out the title of the current Web site. It then iterates through all the subsites to print their titles, and through all the lists in each subsite to print the list title and number of items for cases in which more than ten list items are in a list.

5. On the Build menu, click Build Solution. 6. Increase the trust level in Windows SharePoint Services from minimal (default) to
medium by opening the web.config file at\\Inetpub\wwwroot\wss\VirtualDirectories\80 and replacing the following line: <trust level="WSS_Minimal" originUrl="" /> with the following: <trust level="WSS_Medium" originUrl="" />

7. Reset Microsoft Internet Information Services (IIS) to make the changes in trust level take effect. The Web Part can be imported through the user interface into a Web Part Page or into the home page for viewing the list data.

How to: Return Sites and Site Collections You can return all the Web sites within a site collection, all the first-tier subsites beneath a Web site, all the subsites and lists for the current Web site, or the collection of site collections in a SharePoint Web application, as shown in the following examples. You can return all the Web sites within a site collection, including the top-level site and all subsites, by using the AllWebs property of the SPSite class. The following example displays the titles of all the sites and lists in the current site collection. Visual Basic Dim mySite As SPSite = SPContext.Current.Site Dim subSites As SPWebCollection = mySite.AllWebs Dim i As Integer

For i = 0 To subSites.Count - 1 Dim lists As SPListCollection = subSites(i).Lists Dim j As Integer

For j = 0 To lists.Count - 1 Response.Write(SPEncode.HtmlEncode(subSites(i).Title) & " :: " _ & SPEncode.HtmlEncode(lists(j).Title) & "<BR>") Next j Next i C# SPSite mySite = SPContext.Current.Site; SPWebCollection subSites = mySite.AllWebs;

for (int i=0;i<subSites.Count;i++) { SPListCollection lists = subSites[i].Lists;

for (int j=0;j<lists.Count;j++) { Response.Write(SPEncode.HtmlEncode(subSites[i].Title) + " :: " + SPEncode.HtmlEncode(lists[j].Title) + "<BR>"); } } The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint andMicrosoft.SharePoint.Utilities namespaces. To return a list of all the first-tier subsites beneath a Web site, use the Webs property of the SPWeb class. The following example displays a list of subsite titles. Visual Basic Dim mySite As SPWeb = SPContext.Current.Web Dim sites As SPWebCollection = mySite.Webs Dim subSite As SPWeb

For Each subSite In sites Response.Write(SPEncode.HtmlEncode(subSite.Title) & "<BR>") Next subSite C# SPWeb mySite = SPContext.Current.Web; SPWebCollection sites = mySite.Webs;

foreach (SPWeb subSite in sites) { Response.Write(SPEncode.HtmlEncode(subSite.Title) + "<BR>"); } The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint andMicrosoft.SharePoint.Utilities namespaces. Instead of using a foreach statement, the following example uses nested for statements to display a list of subsite URLs and list titles. Visual Basic Dim mySite As SPWeb = SPContext.Current.Web Dim sites As SPWebCollection = mySite.Webs

Dim i As Integer

For i = 0 To sites.Count - 1 Dim lists As SPListCollection = sites(i).Lists Dim j As Integer

For j = 0 To lists.Count - 1 Response.Write(sites(i).Url & " :: " & SPEncode.HtmlEncode(lists(j).Title) & "<BR>") Next j Next i C# SPWeb mySite = SPContext.Current.Web; SPWebCollection sites = mySite.Webs;

for (int i=0;i<sites.Count;i++) { SPListCollection lists = sites[i].Lists;

for (int j=0;j<lists.Count;j++) { Response.Write(sites[i].Url + " :: " + SPEncode.HtmlEncode(lists[j].Title) + "<BR>"); } } The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint andMicrosoft.SharePoint.Utilities namespaces. The next example displays all the subsites and lists for the current Web site, as well as the number of items in each list. The example uses nested foreach statements to iterate through the collections of Web sites and lists. Visual Basic Dim mySite As SPWeb = SPContext.Current.Web Dim sites As SPWebCollection = mySite.Webs

Dim subSite As SPWeb

For Each subSite In sites Response.Write("<B>" & SPEncode.HtmlEncode(subSite.Title) & "</B>" & "<BR>")

Dim lists As SPListCollection = subSite.Lists Dim list As SPList

For Each list In lists Response.Write(SPEncode.HtmlEncode(list.Title) & " :: " & list.ItemCount & "<BR>") Next list Next subSite C# SPWeb mySite = SPContext.Current.Web; SPWebCollection sites = mySite.Webs;

foreach (SPWeb subSite in sites) { Response.Write("<B>" + SPEncode.HtmlEncode(subSite.Title) + "</B>" + "<BR>");

SPListCollection lists = subSite.Lists;

foreach (SPList list in lists) { Response.Write(SPEncode.HtmlEncode(list.Title) + " :: " + list.ItemCount + "<BR>"); } } The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint andMicrosoft.SharePoint.Utilities namespaces.

To return the collection of site collections in a SharePoint Web application, use the Sites property of theMicrosoft.SharePoint.Administration.SPWebApplication class. Use properties of the Microsoft.SharePoint.SPContext class to return the current Web application. The following example displays the URLs of all the site collections in the current Web application. Visual Basic Dim webApplication As SPWebApplication = SPContext.Current.Site.WebApplication Dim siteCollections As SPSiteCollection = webApplication.Sites Dim siteCollection As SPSite

For Each siteCollection In siteCollections Response.Write(siteCollection.Url + "<BR>") Next siteCollection C# SPWebApplication webApplication = SPContext.Current.Site.WebApplication; SPSiteCollection siteCollections = webApplication.Sites;

foreach (SPSite siteCollection in siteCollections) { Response.Write(siteCollection.Url + "<BR>"); } The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint,Microsoft.SharePoint.Administration, and Microsoft.SharePoint.Utilities namespaces. The example assumes the existence of an .aspx page that contains a label control. How to: Create or Delete a Site or a Site Collection To create a site, use one of the Addmethods of the SPWebCollection class. To create a subsite beneath a site, use theWebs property of the SPWeb class to return the collection of subsites and then call one of the Add methods for the collection. The following example creates a new subsite that is based on the template of the current site and on information gathered from three text boxes. The text boxes specify the name to use in the new URL, the title to use for the site, and a description for the site. 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 Dim mySite As SPWeb = SPContext.Current.Web Dim subSites As SPWebCollection = mySite.Webs Dim currentTemplate As String = mySite.WebTemplate

Dim siteUrl As String = TextBox1.Text.ToString() Dim siteTitle As String = TextBox2.Text.ToString() Dim siteDescription As String = TextBox3.Text.ToString()

subSites.Add(siteUrl, siteTitle, siteDescription, Convert.ToUInt32(1033), currentTemplate, True, False) C# SPWeb mySite = SPContext.Current.Web; SPWebCollection subSites = mySite.Webs; string currentTemplate = mySite.WebTemplate;

string siteUrl = TextBox1.Text.ToString(); string siteTitle = TextBox2.Text.ToString(); string siteDescription = TextBox3.Text.ToString();

subSites.Add(siteUrl, siteTitle, siteDescription, 1033, currentTemplate, true, false); The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace. In the example, the WebTemplate property of the SPWeb class returns the name of the current site definition, which is passed as a parameter of the Add method. In addition, three parameters for this method pass the information gathered from the three text boxes. The three other parameters specify 1033 as the locale folder, true to create a site with unique permissions, and false to convert any existing Web site at the same location to a SharePoint site. To delete a site, use the Delete method of the SPWeb class or the Delete method of the SPWebCollection class.

The following example assumes the use of a text box to specify the URL of a site to delete, and uses the Delete method of theSPWebCollection class to delete the site. Visual Basic Dim deleteSite As String = TextBox1.Text.ToString()

Dim mySite As SPSite = SPContext.Current.Site Dim sites As SPWebCollection = mySite.AllWebs

sites.Delete(deleteSite) C# string deleteSite = TextBox1.Text.ToString();

SPSite mySite = SPContext.Current.Site; SPWebCollection sites = mySite.AllWebs;

sites.Delete(deleteSite); The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace. In the example, the AllWebs property of the SPSite class returns the collection of all sites within the current site collection. To create a site collection, use the Sitesproperty of the SPVirtualServer class to return the collection of site collections on the virtual server and use one of the Add methods of the SPSiteCollection class. The following example creates a site collection within the collection of site collections of the current SharePoint Web application. Visual Basic Dim webApplication As SPWebApplication = SPContext.Current.Site.WebApplication Dim siteCollections As SPSiteCollection = webApplication.Sites

siteCollections.Add("http://Server_Name/sites/Site_Collection_Name", "User_Name", "User_Email") C# SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

SPSiteCollection siteCollections = webApplication.Sites;

siteCollections.Add("http://Server_Name/sites/Site_Collection_Name", "User_Name","User_Email "); The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint.Administration namespace. The example instantiates the SPGlobalAdmin class in order to call the OpenVirtualServer method and return the virtual server with the specified URI. To delete a site collection from a virtual server requires security validation that uses the AdminFormDigest property of theSPGlobalAdmin class to insert a message digest on the page in the browser. You can do this by registering the digest as a hidden field through the RegisterHiddenField method of the System.Web.UI.Page class. In addition, use the RequestFromAdminPortfield of the SPGlobalAdmin class to specify that the context of the request is through the administrative port. The following example uses the Page_Load event to include an administrative form digest on the page and to establish the context of the request. Visual Basic Private globalAdmin As New SPGlobalAdmin()

Private Sub Page_Load(sender As Object, e As System.EventArgs)

Context.Items(SPGlobalAdmin.RequestFromAdminPort) = True Page.RegisterHiddenField("__REQUESTDIGEST", globalAdmin.AdminFormDigest)

End Sub 'Page_Load

Private Sub Button1_Click(sender As Object, e As System.EventArgs)

Dim globalAdmin As New SPGlobalAdmin() Dim uri As New System.Uri("http://Server_Name") Dim vServer As SPVirtualServer = globalAdmin.OpenVirtualServer(uri) Dim siteCollections As SPSiteCollection = vServer.Sites

siteCollections.Delete("sites/Site_Collection")

End Sub 'Button1_Click C# private SPGlobalAdmin globalAdmin = new SPGlobalAdmin();

private void Page_Load(object sender, System.EventArgs e) { Context.Items[SPGlobalAdmin.RequestFromAdminPort] = true; Page.RegisterHiddenField("__REQUESTDIGEST", globalAdmin.AdminFormDigest); }

private void Button1_Click(object sender, System.EventArgs e) { SPGlobalAdmin globalAdmin = new SPGlobalAdmin(); System.Uri uri = new System.Uri("http://Server_Name"); SPVirtualServer vServer = globalAdmin.OpenVirtualServer(uri); SPSiteCollection siteCollections = vServer.Sites;

siteCollections.Delete("sites/Site_Collection"); } The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint.Administrationnamespace. How to: Create or Delete Lists To create a new list, use the one of theAdd methods of the SPListCollection class. The following example adds a new Generic, Events, or Announcements list, based on user input. A Switch clause is used to determine the type of list that the user specifies and sets the type of list template accordingly. 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 Dim mySite As SPWeb = SPContext.Current.Web Dim lists As SPListCollection = mySite.Lists

Dim listTitle As String = TextBox1.Text Dim listDescription As String = TextBox2.Text Dim listType As String = ListBox1.SelectedItem.Text

Dim listTemplateType As New SPListTemplateType()

Select Case listType Case "Generic List" listTemplateType = SPListTemplateType.GenericList Exit Case "Events" listTemplateType = SPListTemplateType.Events Exit Case "Announcements" listTemplateType = SPListTemplateType.Announcements Exit End Select lists.Add(listTitle, listDescription, listTemplateType) C# SPWeb mySite = SPContext.Current.Web; SPListCollection lists = mySite.Lists;

string listTitle = TextBox1.Text; string listDescription = TextBox2.Text; string listType = ListBox1.SelectedItem.Text;

SPListTemplateType listTemplateType = new SPListTemplateType();

switch(listType) { case "Generic List": { listTemplateType = SPListTemplateType.GenericList; break; }

case "Events": { listTemplateType = SPListTemplateType.Events; break; }

case "Announcements": { listTemplateType = SPListTemplateType.Announcements; break; } }

lists.Add(listTitle, listDescription, listTemplateType); The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace. The example instantiates an SPListTemplateType object in order to contain the type of list template that is specified by the user. This object must be passed as a parameter in the Add method. The example assumes the existence of two text boxes where the user can type a title and a description, as well as a drop-down list that displays the list types for the user to select from. In addition to using the SPListTemplateType enumeration to create a list, you can also create a list from an SPListTemplateobject. The ListTemplates property of the SPWeb class can be used to return a collection of list template objects and a name indexer can be used to specify the list template to use. This is shown in the following example, which assumes the existence of a Decision Meetings Workspace site. Visual Basic Dim mySite As SPWeb = SPContext.Current.Web

Dim template As SPListTemplate = mySite.ListTemplates("Decisions") mySite.Lists.Add("My Decisions", "This is a list of decisions", template) C# SPWeb mySite = SPContext.Current.Web;

SPListTemplate template = mySite.ListTemplates["Decisions"]; mySite.Lists.Add("My Decisions", "This is a list of decisions", template); The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace. Using the GetCustomListTemplates method of the SPSite class, the next example returns the custom list templates for a specified site and creates a new list that is based on a specified list template. Visual Basic Dim siteCollection As SPSite = SPContext.Current.Site Dim mySite As SPWeb = SPContext.Current.Web

Dim listTemplates As SPListTemplateCollection = siteCollection.GetCustomListTemplates(mySite) Dim listTemplate As SPListTemplate = listTemplates("Custom List Template") mySite.Lists.Add("Custom List", "A list created from a custom list template in the list template catalog", listTemplate) C# SPSite siteCollection = SPContext.Current.Site; SPWeb mySite = SPContext.Current.Web;

SPListTemplateCollection listTemplates = siteCollection.GetCustomListTemplates(mySite); SPListTemplate listTemplate = listTemplates["Custom List Template"];

mySite.Lists.Add("Custom List", "A list created from a custom list template in the list template catalog", listTemplate); The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace. To delete a list, you must specify the GUID of the list as the parameter for the Delete method. Use the ID property of the SPListclass to find the GUID. Visual Basic Dim mySite As SPWeb = SPContext.Current.Web Dim lists As SPListCollection = mySite.Lists

Dim list As SPList = lists(TextBox1.Text) Dim listGuid As System.Guid = list.ID

lists.Delete(listGuid) C# SPWeb mySite = SPContext.Current.Web; SPListCollection lists = mySite.Lists;

SPList list = lists[TextBox1.Text]; System.Guid listGuid = list.ID;

lists.Delete(listGuid); The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace. The example assumes the existence of a text box in which the user specifies the name of the list.

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 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# 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

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# 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 theDelete 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 theSPListItemCollection 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 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# 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 andMicrosoft.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 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#

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 andMicrosoft.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 theSPSiteDataQuery class to define a query, and then uses the GetSiteData method to return items where the Status column equals "Completed". Visual Basic 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# 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 andMicrosoft.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 Updatemethod 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

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# 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 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# 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. How to: Access, Copy, and Move Files You can use the GetFolder method of theSPWeb class to return a specified folder and then access individual files in the folder. After instantiating an SPWeb object (for example, as mySite), use SPFolder myFolder = mySite.GetFolder("Shared Documents") (in Visual Basic 2005, use Dim myFolder As SPFolder = mySite.GetFolder("Shared Documents")) to return the Shared Documents folder for the site. Example The following example returns the collection of files in the folder and displays information about the files. Visual Basic Dim myFiles As SPFileCollection = myFolder.Files Dim file As SPFile

For Each file In myFiles

Response.Write(file.Url.ToString() & "<BR>") Response.Write(file.Length.ToString() & "<BR>")

Next file C# SPFileCollection myFiles = myFolder.Files;

foreach (SPFile file in myFiles) { Response.Write(file.Url.ToString() + "<BR>"); Response.Write(file.Length.ToString() + "<BR>"); } The previous example lists the URL and size of every file within the folder. The example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint namespace. To copy files from one location to another, use one of the CopyTo methods of the SPFile class. In the following example, thePage_Load event handler instantiates

an SPWeb object for the current site context. The Click event handler iterates through all the files in the folder, listing the name and size (in kilobytes) of each file that exceeds a multiple of the value specified by the user in a text box, and copying the file to a folder named Archive. Visual Basic Private mySite As SPWeb

Private Sub Page_Load(sender As Object, e As System.EventArgs)

mySite = SPControl.GetContextWeb(Context)

End Sub 'Page_Load

Private Sub Button1_Click(sender As Object, e As System.EventArgs)

Dim maxSize As Integer = Convert.ToInt32(TextBox1.Text) Dim myFolder As SPFolder = mySite.GetFolder("Shared Documents") Dim myFiles As SPFileCollection = myFolder.Files Dim file As SPFile

For Each file In myFiles

If file.Length > maxSize * 1024 Then

Response.Write(SPEncode.HtmlEncode(file.Name) & " :: " & file.Length / 1024 & "kb<BR>") file.CopyTo("Archive/" & file.Name, True)

End If

Next file

End Sub 'Button1_Click

C# private SPWeb mySite;

private void Page_Load(object sender, System.EventArgs e) { mySite = SPControl.GetContextWeb(Context); }

private void Button1_Click(object sender, System.EventArgs e) { int maxSize = Convert.ToInt32(TextBox1.Text);

SPFolder myFolder = mySite.GetFolder("Shared Documents"); SPFileCollection myFiles = myFolder.Files;

foreach (SPFile file in myFiles) {

if (file.Length>(maxSize*1024)) { Response.Write(SPEncode.HtmlEncode(file.Name) + ": " + file.Length/1024 + "kb<BR>"); file.CopyTo("Archive/" + file.Name, true); } } } In the example, the CopyTo method uses two parameters, one that specifies the destination URL for the copied file, and the other a Boolean value that specifies whether to overwrite any file of the same name that is located at the destination. The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint,Microsoft.SharePoint.Utilities, and Microsoft.SharePoint.WebControls namespaces.

The following example moves all files from the Shared Documents list of the current site to another folder named StorageFolder, overwriting any file of the same name that may be located there. Visual Basic Dim mySite As SPWeb = SPControl.GetContextWeb(Context) Dim myFolder As SPFolder = mySite.GetFolder("Shared Documents") Dim myFiles As SPFileCollection = myFolder.Files Dim i As Integer

For i = myFiles.Count - 1 To 0 Step -1

myFiles(i).MoveTo("StorageFolder/" & myFiles(i).Name, True)

Next i C# SPWeb mySite = SPControl.GetContextWeb(Context); SPFolder myFolder = mySite.GetFolder("Shared Documents"); SPFileCollection myFiles = myFolder.Files;

for (int i = myFiles.Count - 1; i > -1; i--) { myFiles[i].MoveTo("StorageFolder/" + myFiles[i].Name, true); } As the example illustrates, when collections are modified in the course of code execution by deleting or moving items, the counter for iterating through the collection must decrease in value with each iteration. The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint andMicrosoft.SharePoint.WebControls namespaces. How to: Upload a File to a SharePoint Site from a Local Folder This programming task shows how to upload a file from a local folder to a folder on a Windows SharePoint Services site. The task uses the EnsureParentFolder method to ensure that the destination folder exists. Procedures To upload a file to a folder on a SharePoint site from a local folder

1. Create a Web application in Visual Studio 2005 as described in How to: Create a Web
Application in a SharePoint Web Site, adding a FormDigest control and a page directive for the Microsoft.SharePoint.WebControls namespace to the .aspx file, as follows: 2. <%@ Register Tagprefix="SharePoint" 3. 4. 5. Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> Note: You can obtain the PublicKeyToken value for the current Windows SharePoint Services deployment from the default.aspx file in the Local_Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\SiteTemplates\sts folder, or from information provided for the Microsoft.SharePoint assembly atLocal_Drive:\%WINDOWS%\assembly in Windows Explorer.

6. Add an HtmlInputFile control, a text box, and a button to the form on the .aspx
page: 7. <form id="Form1" method="post" runat="server"> 8. 9. 10. 11. 12. <SharePoint:FormDigest runat="server" /> <input id="File1" type="file" runat="server" title="upldFileBox"> <asp:Button id="Button1" runat="server" Text="Upload File"></asp:Button> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> </form>

13. In the .aspx.cs code-behind file, add using directives for


the System.IO and Microsoft.SharePoint namespaces, as follows: Visual Basic Imports System.IO Imports Microsoft.SharePoint C# using System.IO; using Microsoft.SharePoint;

14. Add the following code to the Click event for the button:

Visual Basic If File1.PostedFile Is Nothing Then Return End If

Dim destUrl As String = TextBox1.Text

Dim site As SPWeb = New SPSite(destUrl).OpenWeb()

Dim fStream As Stream = File1.PostedFile.InputStream Dim contents(fStream.Length) As Byte

fStream.Read(contents, 0, CInt(fStream.Length)) fStream.Close()

EnsureParentFolder(site, destUrl)

site.Files.Add(destUrl, contents) C# if (File1.PostedFile == null) return;

string destUrl = TextBox1.Text;

SPWeb site = new SPSite(destUrl).OpenWeb();

Stream fStream = File1.PostedFile.InputStream; byte[] contents = new byte[fStream.Length];

fStream.Read(contents, 0, (int)fStream.Length); fStream.Close();

EnsureParentFolder(site, destUrl);

site.Files.Add(destUrl, contents); The value that you type in the text box for the destination must be an absolute URL, including the file name, which is assigned to the destUrl parameter. In addition to instantiating an SPWeb object for the parent site, the combined use of the SPSite constructor and OpenWebmethod validates the URL and throws an argument exception if the URL is not served by the current Windows SharePoint Services deployment. A System.Web.UI.HtmlControls.HtmlInputFile object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.

15. The EnsureParentFolder method ensures that the parent folder in the destination

URL exists in the specified site, and it returns the site-relative URL of the parent folder. The EnsureParentFolder method accepts two parameters: an SPWebobject that represents the parent site, and a string that contains the absolute URL that is passed from the UploadFilemethod. If the parent folder does not exist, the EnsureParentFolder method creates it. Visual Basic Public Function EnsureParentFolder(parentSite As SPWeb, destinUrl As String) As String

destinUrl = parentSite.GetFile(destinUrl).Url

Dim index As Integer = destinUrl.LastIndexOf("/") Dim parentFolderUrl As String = String.Empty

If index > - 1 Then parentFolderUrl = destinUrl.Substring(0, index) Dim parentFolder As SPFolder = parentSite.GetFolder(parentFolderUrl)

If Not parentFolder.Exists Then Dim currentFolder As SPFolder = parentSite.RootFolder Dim folder As String

For Each folder In parentFolderUrl.Split("/"c)

currentFolder = currentFolder.SubFolders.Add(folder) Next folder End If End If

Return parentFolderUrl End Function 'EnsureParentFolder C# public string EnsureParentFolder(SPWeb parentSite, string destinUrl) { destinUrl = parentSite.GetFile(destinUrl).Url;

int index = destinUrl.LastIndexOf("/"); string parentFolderUrl = string.Empty;

if (index > -1) { parentFolderUrl = destinUrl.Substring(0, index);

SPFolder parentFolder = parentSite.GetFolder(parentFolderUrl);

if (! parentFolder.Exists) { SPFolder currentFolder = parentSite.RootFolder;

foreach(string folder in parentFolderUrl.Split('/')) { currentFolder = currentFolder.SubFolders.Add(folder); } }

} return parentFolderUrl; } of the SPFile class to convert the URL to a site-relative URL, throwing an exception if the specified URL is not found within the scope of the site. The URL of the parent folder is calculated by using the String.LastIndexOf method to determine the last appearance of a forward slash (/) within the destination URL. If there is no slash (in other words, the index equals -1), then the destination is the root folder for the site and the parentFolderUrl parameter returns an empty string. Otherwise, the example uses the GetFolder method of theSPWeb class to return the destination parent folder. If the folder does not exist, the example constructs the folder. To upload a file from a local folder on the same server that is running Windows SharePoint Services, you can use aSystem.IO.FileStream object instead. In this case, add a using directive for the System.IO namespace, in addition to directives for System and Microsoft.SharePoint. The following example uses the Click event handler to call an UploadFile method, which in turn calls the previously described EnsureParentFolder method. Visual Basic Public Sub UploadFile(srcUrl As String, destUrl As String)

16. The GetFile method of the SPWeb class is used in combination with the Url property

If Not File.Exists(srcUrl) Then

Throw New ArgumentException(String.Format("{0} does not exist", srcUrl), "srcUrl")

End If

Dim site As SPWeb = New SPSite(destUrl).OpenWeb()

Dim fStream As FileStream = File.OpenRead(srcUrl) Dim contents(fStream.Length) As Byte fStream.Read(contents, 0, CInt(fStream.Length)) fStream.Close()

EnsureParentFolder(site, destUrl)

site.Files.Add(destUrl, contents)

End Sub 'UploadFile C# public void UploadFile(string srcUrl, string destUrl) { if (! File.Exists(srcUrl)) { throw new ArgumentException(String.Format("{0} does not exist", srcUrl), "srcUrl"); }

SPWeb site = new SPSite(destUrl).OpenWeb();

FileStream fStream = File.OpenRead(srcUrl); byte[] contents = new byte[fStream.Length]; fStream.Read(contents, 0, (int)fStream.Length); fStream.Close();

EnsureParentFolder(site, destUrl); site.Files.Add(destUrl, contents); } The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of the destination. A System.IO.FileStream object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class. How to: Add a Recurring Event to Lists on Multiple Sites This programming task shows how to add a recurring event with a Meeting Workspace site to the Events list of every site in a collection of subsites. To add a recurring event with a Meeting Workspace site to the Events list of every site in a collection of subsites

1. Create a console application in Microsoft Visual Studio 2005, as described in How to:
Create a Console Application.

2. Add a using or Imports directive to the opening of the .cs or .vb file for
the Microsoft.SharePoint andMicrosoft.SharePoint.Meetings namespaces, as follows: Visual Basic Imports Microsoft.SharePoint Imports Microsoft.SharePoint.Meetings C# using Microsoft.SharePoint; using Microsoft.SharePoint.Meetings;

3. Use the SPSite constructor to instantiate a specified site collection. This example

uses an indexer on the AllWebs property of the SPSite class to return a specific site, and the Webs property of the SPWeb class to return the collection of subsites beneath the site. Set up a foreach loop to iterate through all the subsites and obtain the Events list for each site and the collection of list items in each Events list, as follows: Visual Basic Dim evtTitle As String = Console.ReadLine()

Dim siteCollection As New SPSite("Absolute_Url") Dim site As SPWeb = siteCollection.AllWebs("Site_Name") Dim subSites As SPWebCollection = site.Webs Dim subSite As SPWeb

For Each subSite In subSites

Dim list As SPList = subSite.Lists("Events") Dim listItems As SPListItemCollection = list.Items C# string evtTitle = Console.ReadLine();

SPSite siteCollection = new SPSite("Absolute_Url"); SPWeb site = siteCollection.AllWebs["Site_Name"]; SPWebCollection subSites = site.Webs;

foreach (SPWeb subSite in subSites) { SPList list = subSite.Lists["Events"]; SPListItemCollection listItems = list.Items;

4. Create a list item. This example uses the Add method of

the SPListItemCollection class to create an uninitialized list item, uses indexers to set various properties for the new item, and then uses the Update method to finish creating the item. Visual Basic Dim recEvent As SPListItem = listItems.Add()

Dim recdata As String = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek>" _ & "<repeat><daily dayFrequency='1' /></repeat>" _ & "<repeatInstances>5</repeatInstances></rule></recurrence>"

recEvent("Title") = evtTitle recEvent("RecurrenceData") = recdata recEvent("EventType") = 1 recEvent("EventDate") = New DateTime(2003, 8, 15, 8, 0, 0) recEvent("EndDate") = New DateTime(2003, 9, 25, 9, 0, 0) recEvent("UID") = Guid.NewGuid() recEvent("TimeZone") = 13 recEvent("Recurrence") = - 1 recEvent("XMLTZone") = "<timeZoneRule><standardBias>480</standardBias>" _ & "<additionalDaylightBias>-60</additionalDaylightBias>" _ & "<standardDate><transitionRule month='10' day='su' weekdayOfMonth='last' />" _ & "<transitionTime>2:0:0</transitionTime></standardDate>" _ & "<daylightDate><transitionRule month='4' day='su' weekdayOfMonth='first' />" _

& "<transitionTime>2:0:0</transitionTime> </daylightDate></timeZoneRule>"

recEvent.Update() C# SPListItem recEvent = listItems.Add();

string recData = "<recurrence><rule> <firstDayOfWeek>su</firstDayOfWeek>" + "<repeat><daily dayFrequency='1' /></repeat>" + "<repeatInstances>5</repeatInstances></rule></recurrence>";

recEvent["Title"] = evtTitle; recEvent["RecurrenceData"] = recData; recEvent["EventType"] = 1; recEvent["EventDate"] = new DateTime(2003,8,15,8,0,0); recEvent["EndDate"] = new DateTime(2003,9,25,9,0,0); recEvent["UID"] = System.Guid.NewGuid(); recEvent["TimeZone"] = 13; recEvent["Recurrence"] = -1; recEvent["XMLTZone"] = "<timeZoneRule> <standardBias>480</standardBias>" + "<additionalDaylightBias>-60</additionalDaylightBias>" + "<standardDate><transitionRule month='10' day='su' weekdayOfMonth='last' />" + "<transitionTime>2:0:0</transitionTime></standardDate>" + "<daylightDate><transitionRule month='4' day='su' weekdayOfMonth='first' />" + "<transitionTime>2:0:0</transitionTime> </daylightDate></timeZoneRule>";

recEvent.Update();

The recData variable contains an XML fragment that specifies properties for a recurring event taking place daily for five days, and the XMLTZone indexer assigns time zone information for the current site. The XML that defines the recurrence and specifies the time zone information is contained in the ntext3 and ntext4 columns of the UserData table in the content database. The following table shows examples of the different kinds of recurrence that can be used. Description Every other day until a specified end date Example <recurrence><rule> <firstDayOfWeek>su</firstDayOfWeek> <repeat><daily dayFrequency='2' /></repeat> <windowEnd>2003-0920T09:00:00Z</windowEnd> </rule></recurrence> Weekly on Monday <recurrence><rule> <firstDayOfWeek>su</firstDayOfWeek> <repeat><weekly mo='TRUE' weekFrequency='1' /></repeat> <repeatForever>FALSE</repeatForever> </rule></recurrence> Every two months on the third day for five sessions <recurrence><rule> <firstDayOfWeek>su</firstDayOfWeek> <repeat><monthly monthFrequency='2' day='3' /></repeat> <repeatInstances>5</repeatInstances> </rule></recurrence> Monthly on the first Tuesday until a specified end date <recurrence><rule> <firstDayOfWeek>su</firstDayOfWeek> <repeat> <monthlyByDay tu='TRUE'

weekdayOfMonth='first' monthFrequency='1' /> </repeat> <windowEnd>2003-0802T10:00:00Z</windowEnd> </rule></recurrence> Yearly on the twentieth day of the ninth <recurrence><rule> month until a specified end date <firstDayOfWeek>su</firstDayOfWeek> <repeat><yearly yearFrequency='1' month='9' day='20' /></repeat> <windowEnd>2007-0920T07:00:00Z</windowEnd> </rule></recurrence>

5. To add a Meeting Workspace site to the recurring event, use one of

the Add methods of the SPWebCollection class and theLinkWithEvent method of the SPMeeting class. Visual Basic Dim mwsSites As SPWebCollection = subSite.Webs

Dim path As String = recEvent("Title").ToString()

Dim newSite As SPWeb = mwsSites.Add(path, "Workspace_Name", _ "Description", Convert.ToUInt32(1033), "MPS#0", False, False)

Dim mwsSite As SPMeeting = SPMeeting.GetMeetingInformation(newSite)

Dim guid As String = list.ID.ToString() Dim id As Integer = recEvent.ID

Try

mwsSite.LinkWithEvent(subSite, guid, id, "WorkspaceLink", "Workspace")

Catch ex As System.Exception

Console.WriteLine(ex.Message)

End Try

Next subSite C# SPWebCollection mwsSites = subSite.Webs;

string path = recEvent["Title"].ToString();

SPWeb newSite = mwsSites.Add(path, "Workspace_Name", "Description", 1033, "MPS#0", false, false);

SPMeeting mwsSite = SPMeeting.GetMeetingInformation(newSite);

string guid = list.ID.ToString(); int id = recEvent.ID;

try { mwsSite.LinkWithEvent(subSite, guid, id, "WorkspaceLink", "Workspace"); }

catch (System.Exception ex) {

Console.WriteLine(ex.Message); } } After the Meeting Workspace site is created, the GetMeetingInformation method returns an SPMeeting object representing the site. 6. Press F5 to start the Console Application. 7. At the command prompt, type a name for the Meeting Workspace site, and then press ENTER to add a recurring event with a Meeting Workspace site to the Events list in all the subsites beneath a site.

WebTemp.xml
Each front-end Web server in a deployment of Windows SharePoint Services has at least the originally installed WebTemp.xml file located in the Local_Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LCID\XML folder, where LCID is the numeric ID of the language/culture, such as 1033 for English. There may also be one or more custom WebTemp*.xml files. The WebTemp*.xml files contain the site definition configurations that are available on the Template Selection section of the New SharePoint Site page. Caution: You must create a custom site definition by copying an existing site definition and adding a WebTemp*.xml file that defines custom definition configurations for instantiating sites, rather than modifying the original WebTemp.xml file that is installed with Windows SharePoint Services. Changes that you make to originally installed files may be overwritten when you install updates or service packs to Windows SharePoint Services, or when you upgrade an installation to the next product version. For more information about creating a custom site definition, see How to: Create a Custom Site Definition and Configuration.

File Format The Templates element specifies the site definitions being made available in the WebTemp*.xml file. Each site definition is defined with a Template element. Each site definition has one or more site definition configurations that can be used to instantiate sites. Each Template element specifies a unique ID and a name that corresponds to a site definition subfolder within the Local_Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\SiteTemplates folder. A Template element can contain any number of Configuration child elements. Each such child represents a site definition configuration. The ID attribute of each Configuration element corresponds to the ID of another Configuration element that is in an Onet.xml

file. The second Configuration element specifies the lists and modules of the site definition configuration. Each Configuration element in a WebTemp*.xml file also specifies the title, the description, the virtual path to the image that is displayed in the Template Selection section of the New SharePoint Site page, and the tab in the selection box on which the site definition configuration will appear. A configuration can be hidden from the user interface (UI) by setting its Hidden attribute to TRUE. Note: When Windows SharePoint Services 3.0 ships there are two tabs on the selection box in the Template Selection section of the New SharePoint Site page: "Collaboration" and "Meetings". If you create a custom site template by saving an existing site as a template, then a third tab, called "Custom" will appear in the box. If you use any value other than "Collaboration", "Meetings", or "Custom" as the value of the DisplayCategory attribute of a Configuration element in a WebTemp*.xml file, then a new tab with the new value as its name will appear in the box.

The following excerpt shows the format of a WebTemp.xml file. Xml

Copy Code <Templates xmlns:ows="Microsoft SharePoint"> <Template Name="STS" ID="1"> <Configuration ID="0" Title="Team Site" Hidden="FALSE" ImageUrl="/_layouts/images/stsprev.png" Description="A site for teams to quickly organize, author, and share information. It provides a document library, and lists for managing announcements, calendar items, tasks, and discussions." DisplayCategory="Collaboration" /> ... <Configuration ID="2" Title="Document Workspace" Hidden="FALSE" ImageUrl="/_layouts/images/dwsprev.png" Description="A site for colleagues to work together on a document. It provides a document library for storing the primary document and supporting files, a tasks list for assigning to-do items, and a links list for resources related to the document."

DisplayCategory="Collaboration" /> </Template> <Template Name="MPS" ID="2"> <Configuration ID="0" Title="Basic Meeting Workspace" Hidden="FALSE" ImageUrl="/_layouts/images/mwsprev.png" Description="All the basics to plan, organize and track your meeting. This Meeting Workspace contains the following lists: Objectives, Attendees, Agenda, and Document Library." DisplayCategory="Meetings" /> ... </Template> </Templates>

Onet.xml
When you install Windows SharePoint Services 3.0, six Onet.xml files are placed within the setup directory, one in \Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\GLOBAL\XML that applies globally to the deployment, and five in different folders within ...\TEMPLATE\SiteTemplates that apply to each of the five site definitions that ship with Windows SharePoint Services 3.0. They are Blog sites, the central administration site, Wiki sites, Meeting Workspace sites, and team SharePoint sites. Only the last two of these families contain more than one site definition configuration in Windows SharePoint Services 3.0. The global Onet.xml file defines list templates for hidden lists, list base types, a default definition configuration, and modules that apply globally to the deployment. The five Onet.xml files in the \SiteTemplates directory define navigational areas, list templates, document templates, configurations, modules, components, and server e-mail footer sections used in the five site definitions. Functions of Onet.xml Depending on its particular use, an Onet.xml file can serve multiple functions, such as the following: Define the top and side navigation areas that appear on the home page and in list views for a site definition. Specify the list definitions that are used in each site definition and whether they are available for creating lists on the Create page. Specify document templates that are available in the site definition for creating document library lists on the New page, and specify the files used in the document templates.

Define the base list types from which default Windows SharePoint Services lists are derived. (Only the global Onet.xml file serves this function.)

Specify the configurations of lists and modules that are used within each site definition.

Specify Windows SharePoint Services components. Define the footer section used in server e-mail.

Web Site Definition Tasks with Onet.xml The following kinds of tasks can be performed in a custom Onet.xml to create a custom site definition: Specify an alternate cascading style sheet (CSS) file, JavaScript file, or ASPX header file for a site definition. Modify navigation areas for the home page and list pages. Add a list definition as an option to the Create page. Add a document template for creating document libraries. Define one or more configurations for the site definition, specifying the lists, modules, files, and Web Parts that are included when a site definition configuration is instantiated. Caution: Making changes to an originally installed Onet.xml file on a server running Windows SharePoint Services can break existing sites, and the changes may be overwritten when you install updates or service packs for Windows SharePoint Services, or when you upgrade an installation to the next product version. Always create a new Onet.xml; do not modify the original file. For more information, see How to: Create a Custom Site Definition and Configuration.

File Format The following sections define the various elements of the Onet.xml file. Project Element The top-level Project element specifies a default name for sites that are created through any of the site configurations in the site definition and specifies the directory that contains subfolders in which the files for each list definition reside.

Note: Unless indicated otherwise, excerpts used in the following examples are taken from the Onet.xml file for the STS site definition. Xml

Copy Code <Project Title="$Resources:onet_TeamWebSite;" Revision="2" ListDir="$Resources:core,lists_Folder;" xmlns:ows="Microsoft SharePoint"> Note: In all the excerpts in this topic, the strings that begin with "$Resources" are constants that are defined in an .resx file. For example, "$Resources:onet_TeamWebSite" is defined in core.resx as "Team Site". When you create a custom Onet.xml file, you can use literal strings.

This element can also have an AlternateCSS attribute that specifies an alternate CSS file for style definitions, a CustomJSUrl attribute specifies an alternate JavaScript file for custom script, and an AlternateHeader attribute specifies an ASPX file for alternate headers. The Project element does not contain any attribute identifying the site definition that it defines. Each Onet.xml is associated with a site definition by virtue of the directory path in where it resides, which (except for the global Onet.xml) is Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\SiteTemplates\site_type\XML\ , where site_type is the name of the site definition, such as STS or MPS. NavBars Element The NavBars element contains definitions for the top navigation area that is displayed on the home page or in list views, and definitions for the side navigation area that is displayed on the home page. Note: A NavBar is not necessarily a toolbar. It can be, for example, a tree of links. Xml

Copy Code <NavBars> <NavBar Name="$Resources:core,category_Top;" Separator="&amp;nbsp;&amp;nbsp;&amp;nbsp;" Body="&lt;a ID='onettopnavbar#LABEL_ID#' href='#URL#' accesskey='J'&gt;#LABEL#&lt;/a&gt;" ID="1002" /> <NavBar Name="$Resources:core,category_Documents;" Prefix="&lt;table border=0 cellpadding=4 cellspacing=0&gt;" Body="&lt;tr&gt;&lt;td&gt;&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' ID='100' alt='' border=0&gt;&amp;nbsp;&lt;/td&gt;&lt;td valign=top&gt;&lt;a ID=onetleftnavbar#LABEL_ID# href='#URL#'&gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" Suffix="&lt;/table&gt;" ID="1004" /> ... </NavBars> A NavBarLink element defines links for the top or side navigational area, and an entire NavBar section groups new links in the side area. Each NavBar element specifies a display name and a unique ID for the navigation bar, and defines how to display the navigation bar. For information on customizing the navigation areas on Windows SharePoint Services pages, see Customizing Site Navigation. ListTemplates Element The ListTemplates section specifies the list definitions that are part of a site definition. Note: The ListTemplates section is not included in the Onet.xml file of the standard Windows SharePoint Services site definition, which instead uses list definition Features and element .xml files to define its list templates. The following example is taken from the Onet.xml file for the Meetings Workspace site definition. Xml

Copy Code <ListTemplates> <ListTemplate Name="meetings" DisplayName="$Resources:xml_onet_mwsidmeetingDisp;" Type="200"

BaseType="0" Unique="TRUE" Hidden="TRUE" HiddenList="TRUE" DontSaveInTemplate="TRUE" SecurityBits="11" Description="$Resources:xml_onet_mwsidmeetingDesc;" Image="/_layouts/images/itevent.gif"> </ListTemplate> <ListTemplate Name="agenda" DisplayName="$Resources:xml_onet_mwsidagendaDisp;" Type="201" BaseType="0" FolderCreation="FALSE" DisallowContentTypes="TRUE" SecurityBits="11" Description="$Resources:xml_onet_mwsidagendaDesc" Image="/_layouts/images/itagnda.gif"> </ListTemplate> ... </ListTemplates> Each ListTemplate element specifies an internal name that identifies the list definition. The ListTemplate element also specifies a display name for the list definition and whether the option to add a link on the Quick Launch bar appears selected by default on the New page. In addition, this element specifies the description of the list definition and the path to the image representing the list definition, which are both displayed on the Create page. If Hidden="TRUE" is specified, the list definition does not appear as an option on the Create page. The ListTemplate element has two attributes for type, Type and BaseType. The Type attribute specifies a unique identifier for the list definition, while BaseType identifies the base list type for the list definition and corresponds to the Type value specified for one of the base list types defined within the global ONET.XML file (\TEMPLATE\GLOBAL\XML). For a programming task that shows how to add a list template, see How to: Create a Custom List Definition. DocumentTemplates Element The DocumentTemplates section defines the document templates that are listed on the New page. Xml

Copy Code <DocumentTemplates> ...

<DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_Word;" Type="121" Default="TRUE" Description="$Resources:core,doctemp_Word_Desc;"> <DocumentTemplateFiles> <DocumentTemplateFile Name="doctemp\word\wdtmpl.dotx" TargetName="Forms/template.dotx" Default="TRUE" /> </DocumentTemplateFiles> </DocumentTemplate> ... </DocumentTemplates> Each DocumentTemplate element specifies a display name, a unique identifier, and a description for the document template. If Default is set to TRUE, the template is the default template selected for document libraries that are created in sites created with a configuration in the site definition that the Onet.xml is specifying. Despite its singular name, a DocumentTemplate element actually can contain a collection of DocumentTemplateFile elements. The Name attribute of each DocumentTemplateFile element specifies the relative path to a local file that serves as the template. The TargetName attribute specifies the destination URL of the template file when a document library is created. The Default attribute specifies whether the file is the default template file. For a programming task involving document templates, see How to: Add a Document Template, File Type, and Editing Application to a Site Definition. BaseTypes Element The BaseTypes element of the global Onet.xml file is used during site or list creation to define the five list types on which all list definitions in Windows SharePoint Services are based. Each list template that is specified in the list templates section is identified with one of the base types: Generic List, Document Library, Discussion Forum, Vote or Survey, or Issues List. Note: In Windows SharePoint Services 3.0 the BaseTypes section is implemented only in the global Onet.xml file (\TEMPLATE\GLOBAL\XML), from which the following example is taken. Xml

Copy Code <BaseTypes> <BaseType

Title="Generic List" Image="/_layouts/images/itgen.gif" Type="0"> <MetaData> <Fields> <Field ID="{1d22ea11-1e32-424e-89ab-9fedbadb6ce1}" ColName="tp_ID" RowOrdinal="0" ReadOnly="TRUE" Type="Counter" Name="ID" PrimaryKey="TRUE" DisplayName="$Resources:core,ID" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="ID"> </Field> <Field ID="{03e45e84-1992-4d42-9116-26f756012634}" RowOrdinal="0" Type="ContentTypeId" Sealed="TRUE" ReadOnly="TRUE" Hidden="TRUE" DisplayName="$Resources:core,Content_Type_ID;" Name="ContentTypeId" DisplaceOnUpgrade="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="ContentTypeId" ColName="tp_ContentTypeId"> </Field> ... </Fields> </MetaData> </BaseType> ... </BaseTypes> Each BaseType element specifies the fields used in lists that are derived from the base type. The Type attribute of each Field Element (List - Definition) element identifies the field with a field type that is defined in FldTypes.xml. Caution: Do not modify the contents of the global Onet.xml file (file (\TEMPLATE\GLOBAL\XML), because doing so can break the installation. Base list types cannot be added. For information on how to add a list definition, see How to: Create a Custom List Definition. Configurations Element

Each Configuration element in the Configurations section specifies the lists and modules that are created by default when the site definition configuration is instantiated. Xml

Copy Code <Configurations> ... <Configuration ID="0" Name="Default"> <Lists> <List FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101" Type="101" Title="$Resources:core,shareddocuments_Title;" Url="$Resources:core,shareddocuments_Folder;" QuickLaunchUrl="$Resources:core,shareddocuments_Folder;/Forms/AllItems.aspx" /> ... </Lists> <Modules> <Module Name="Default" /> </Modules> <SiteFeatures> <Feature ID="00BFEA71-1C5E-4A24-B310-BA51C3EB7A57" /> <Feature ID="FDE5D850-671E-4143-950A-87B473922DC7" /> </SiteFeatures> <WebFeatures> <Feature ID="00BFEA71-4EA5-48D4-A4AD-7EA5C011ABE5" /> <Feature ID="F41CC668-37E5-4743-B4A8-74D1DB3FD8A4" /> </WebFeatures> </Configuration> ... </Configurations> The ID attribute identifies the configuration (uniquely relative to the other configurations in the site definition) and corresponds to the ID attribute of a Configuration element in WebTemp.xml. Each List element specifies the title of the list definition and the URL for where to create the list. The QuickLaunchUrl attribute can be used to set the URL of the view page to use when adding a link in the Quick Launch to a list created from the list definition. The value of the Type attribute corresponds to the Type attribute of a template in the list templates

section. Each Module element specifies the name of a module defined in the modules section. The SiteFeatures and WebFeatures elements contain references to site collection and site scoped Features to include in the site definition. For post-processing capabilities, use an ExecuteUrl element within a Configuration element to specify the URL that is called following instantiation of the site. For more information on definition configurations, see How to: Use Site Definition Configurations. Modules Element The Modules collection specifies the modules to include by default in creating a site collection. Each Module element in turn specifies one or more files to include, often for Web Parts, which are cached in memory on the front-end Web server along with the schema files. You can use the Url attribute of the Module element to provision a folder as part of the site definition. Xml

Copy Code <Modules> <Modules> <Module Name="Default" Url="" Path=""> <File Url="default.aspx" NavBarHome="True"> <View List="$Resources:core,lists_Folder; /$Resources:core,announce_Folder;" BaseViewID="0" WebPartZoneID="Left" /> <View List="$Resources:core,lists_Folder; /$Resources:core,calendar_Folder;" BaseViewID="0" RecurrenceRowset="TRUE" WebPartZoneID="Left" WebPartOrder="2" /> <AllUsersWebPart WebPartZoneID="Right" WebPartOrder="1"><![CDATA[<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" xmlns:iwp="http://schemas.microsoft.com

/WebPart/v2/Image"> <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly> <TypeName>Microsoft.SharePoint.WebPartPages.ImageWebPart </TypeName> <FrameType>None</FrameType> <Title>$Resources:wp_SiteImage;</Title> <iwp:ImageLink>/_layouts/images/homepage.gif </iwp:ImageLink> <iwp:AlternativeText>$Resources:core,sitelogo_wss; </iwp:AlternativeText> </WebPart>]]> </AllUsersWebPart> <View List="$Resources:core,lists_Folder; /$Resources:core,links_Folder;" BaseViewID="0" WebPartZoneID="Right" WebPartOrder="2" /> <NavBarPage Name="$Resources:core,nav_Home;" ID="1002" Position="Start" /> <NavBarPage Name="$Resources:core,nav_Home;" ID="0" Position="Start" /> </File> </Module> ... </Modules> The Module element specifies a name for the module, which corresponds to a module name that is specified within a configuration in ONET.XML. The Url attribute of each File element in a module specifies the name of a file to create when a site is created. When the module includes a single file, such as default.aspx, NavBarHome="TRUE" specifies that the file will serve as the destination page for the Home link in navigation bars. The File element for default.aspx also specifies the Web Parts to include on the home page and information about the home page for other pages that link to it. For more information about using modules in Windows SharePoint Services 3.0, see How to: Provision a File. Components Element The Components element specifies components to include in sites created through the definition. Xml

Copy Code <Components> <FileDialogPostProcessor ID="BDEADEE4-C265-11d0-BCED-00A0C90AB50F" /> </Components> ServerEmailFooter Element The ServerEmailFooter element specifies the footer section used in email sent from the server. Xml

Copy Code <ServerEmailFooter>$Resources:ServerEmailFooter;</ServerEmailFooter> How to: Create a Custom Site Definition and Configuration You can create a custom site definition by copying an existing site definition and then modifying the copy. In the modification stage you will change some Collaborative Application Markup Language Core Schemas markup in two schema files: one that is a copy of a WebTemp.xml file, and the other a copy of an Onet.xml file. Caution: You must not modify the originally installed WebTemp.xml file.

1. Copy an existing site definition folder located in the Local_Drive:\Program


Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\ directory. Your copy should be a peer of the original and you can give it any name that contains no spaces. For example, to create a custom site definition that derives from the team site definition for Windows SharePoint Services, copy the \sts folder.

2. Make a copy of the WebTemp.xml file that is located in Local_Drive:\Program


Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\1033\XML. Give the file a unique name by appending a string to the name of the original file; for example, WebTempAction.xml. At run time, the compiler merges information

contained in this file with the information contained in the original file to specify which site definition configurations are available for creating new sites. 3. Customize the contents of the new WebTemp file. Each WebTemp.xml file contains a collection of Template elements and Configuration subelements, which identify to the compiler all the site definition configurations that can be instantiated. The Configuration element defines, for example, a title, a description, the URL for the image displayed in the user interface (UI), and a display category that specifies the tab on which to display the template in the Template Selection section of the New SharePoint Site page.

Important: In each Template element defined in the WebTemp file, the Name attribute must contain the same name that is assigned to the new folder. Also, to avoid conflict with IDs already used in Windows SharePoint Services, use unique values greater than 10,000 for the ID attribute.

Example The following example defines a single site definition. The example assumes the existence of an \ActionCommittee folder that has been created as previously described.

Copy Code <?xml version="1.0" encoding="utf-8" ?> <Templates xmlns:ows="Microsoft SharePoint"> <Template Name=" ActionCommittee " ID="10001"> <Configuration ID="0" Title="Action Committee Team Site" Hidden="FALSE" ImageUrl="images/stsprev.jpg" Description="This template provides a forum for the team to create, organize, and share information quickly and easily. It includes a Document Library, and basic lists such as Announcements, Events, Contacts, and Quick Links." DisplayCategory="Collaboration"> </Configuration> </Template> </Templates> You may need to reset Internet Information Services (IIS) to cause the new definition configuration to appear as an option in the UI. To do this, enter iisreset at a command prompt.

Getting Started with Programmatically Customizing a SharePoint Web Site in Visual Studio The Microsoft Visual Studio 2005 integrated development environment (IDE) offers the premier environment for customizing Web sites based on Windows SharePoint Services. You can create, for example, Windows applications, console applications, or class libraries, as well as browser-based Web applications (called an "ASP.NET Web site" or "Web application" in Visual Studio) and Web services that implement the Windows SharePoint Services object model. You run code that uses namespaces of theMicrosoft.SharePoint assembly on the server that runs the deployment, while applications that use SharePoint Web services run remotely from a client computer. To develop Web applications and Web services, you can run Visual Studio either on the same server that runs Windows SharePoint Services or on a remote computer, as described in the following procedures. Note: To customize Windows SharePoint Services 3.0 through its object model or Web services, you must use Visual Studio 2005, not an earlier version. After you determine the type of application to create for your task, you must specify an appropriate location at which to create the project. After the project is created, you must set a reference to Microsoft.SharePoint.dll. To create a project, ASP.NET Web site, or file 1. Open Visual Studio, and on the File menu, point to New. You will see a drop-down list with Project, Web Site, and File as possible selections. 2. Choose the type of application you want to create: To create a Windows application, console application, or class library, click Project. To create an ASP.NET Web application (Web Site) or Web service, click Web Site. To create an individual file, such as a Web Form, User Control, or Master Page, click File.

3. Depending on your selection in Step 2, perform one of the following procedures in the dialog box that opens. To create a Project in the New Project dialog box . . . In the Project types box, select the language and type of project. In the Templates box, select the appropriate Visual Studio template. Specify a name and location for the project, and click OK. To create a Web Site in the New Web Site dialog box . In the Templates box, choose the appropriate template.

. In the Location and Language boxes, select HTTP and the language of your choice.

If you are creating a Web application, type a path in one of the following formats: . http://MyServer/_layouts/MyApplicationName http://MyAdminServer:Port#/MyApplicationName The first format creates the application in \\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS, and the second format creates the application in \\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\ADMIN. Create applications in the administrative directory that use theMicrosoft.SharePoint.Administration namespace to work with global settings. If you are creating a custom Web service on the server that implements the Windows SharePoint Services object model, specify a path in the following form: http://IISWebSiteName:Port#/MyApplicationName For more information about creating a custom Web service that uses the Windows SharePoint Services object model, see Walkthrough: Creating a Custom Web Service.

. Click OK to create the application. If you receive a message indicating that debugging is not enabled, make sure Add a new web.config file with debugging enabled is selected, and then click OK. To create a file in the New File dialog box . . In the Categories box, select the language of your choice. In the Templates box, select the appropriate template and click OK.

. If you are creating a User Control, copy the .ascx file to Local_Drive:\\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES. If you are creating an ASPX page, copy the .aspx file either to \\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS, or to \\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\ADMIN if your code uses the Microsoft.SharePoint.Administration namespace to modify global settings. Creating a Web Site or Project Remotely If you are writing code in a Visual Studio installation on a remote computer, create a Project or Web Site within the file system of the server running Windows SharePoint Services. Open the same dialog boxes as indicated previously, but specify a path in this format: \\Computer_Name\Drive$\.... If you are creating a Web application, for example, specify File System in the Location box and use a path such as the following to create the application within the /_layouts virtual directory: \\Computer_Name\Drive$\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\MyApplication. Setting a Reference to the Microsoft.SharePoint Assembly After creating a project, add a reference to the Microsoft.SharePoint assembly to import its namespaces and implement IntelliSense features in the Object Browser and Code Editor.

To add a reference to the Microsoft.SharePoint assembly 1. In Solution Explorer, right-click the project, and then click Add Reference on the shortcut menu.

2. On the .NET tab of the Add Reference dialog box, select Windows SharePoint
Services in the list of components, and then click OK. To run or debug code that uses the Microsoft.SharePoint assembly, you must run the code on the server running Windows SharePoint Services. If you are using Visual Studio 2005 on a remote computer, you cannot run or debug code that uses the object model. However, you can set a remote reference to the assembly to write code and see the Microsoft.SharePointassembly represented in the Code Editor. To add a remote reference in this way, do the following: Click the Browse tab of the Add Reference dialog box and navigate to Microsoft.SharePoint.dll in the \\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI folder on the server running Windows SharePoint Services. You may instead want to copy Microsoft.SharePoint.dll from this folder to a local drive on the remote computer, and then open this local copy of the DLL. Click Open.

IntelliSense Within the IDE of Visual Studio 2005, IntelliSense features are provided for namespaces in the Microsoft.SharePoint assembly after a reference is set to this assembly. The file that provides the information used by IntelliSense for Windows SharePoint Services is Microsoft.SharePoint.xml, which is installed in the path Local_Drive:\\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI on each front-end Web server in the deployment. For updates to this file, visit the Windows SharePoint Services Developer Center.

Getting References to Sites, Web Applications, and other Key Objects To work with a deployment of Windows SharePoint Services, your code must first get a reference to the objects it will be working with, including Web sites, site collections, and Web applications. There are two methods for doing this: one applies when your code will be used in a console or Windows-based application; the other applies when your code will be used in a browser-hosted application, such as when you choose "Web Site" as the type of Microsoft Visual Studio project. Note: Most sample code in the Windows SharePoint Services SDK uses the second method, so if you are writing for a console or Windows-based application, you must change the code. For guidance in doing so, see the section "Console and Windows Applications: Use Object Constructors" later in this topic.

Browser-Hosted Applications: Establish Site Context To work with a deployment of Windows SharePoint Services by means of a browser-hosted application, your code must first establish the site context or site collection context for requests that are made to the server. You must obtain the HTTP context of the request in the code. Microsoft recommends that you do this by using theMicrosoft.SharePoint.SPContext class and its members. Some examples are as follows. To return the current site collection, you can use SPContext.Current.Site property. Note: All examples in this article require a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace. Visual Basic Dim oSiteCollection As SPSite = SPContext.Current.Site C# SPSite oSiteCollection = SPContext.Current.Site; To return the Web site of the current request, you can use SPContext.Current.Web. Visual Basic Dim oWebSite As SPWeb = SPContext.Current.Web C# SPWeb oWebSite = SPContext.Current.Web; Alternatively, when your code is contained in an .aspx file or the "code behind" in an .aspx.cs file, you can use methods of theSPControl object with the System.Web.UI.Page.Context property as the parameter. For example, use the GetContextWeb method to get a reference to the current Web site. Visual Basic Dim oWebSite As SPWeb = SPControl.GetContextWeb(Context) C# SPWeb oWebSite = SPControl.GetContextWeb(Context); Finally, if your .aspx page inherits from UnsecuredLayoutsPageBase or LayoutsPageBase instead of Page, you can use the Site orWeb properties of the former classes to obtain references to the, respectively, the current site collection or Web site. (Or you can use the System.Web.UI.Page,Context property as the parameter to the GetContextWeb and GetContextSite methods.)LayoutsPageBase gives you some extra SharePoint-oriented functionality, mainly in connection with managing user rights to the page that is not available with Page.

For example, the following code, when used in an .aspx page that inherits from LayoutsPageBase (or the code behind the page) gets a reference to the current Web site. Note: This example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint.WebControls namespace. Visual Basic Dim oWebSite As SPWeb = this.Web C# SPWeb oWebSite = this.Web; Warning: You should not dispose any SPSite or SPWeb object obtained by any of the above methods. The Windows SharePoint Services 3.0 runtime will dispose of them after page completion. Calling the Dispose or Close method of these objects will result in unpredictable behavior. This is in marked contrast to obtaining references to these types of objects using a constructor as described below in "Console and Windows Applications: Use Object Constructors". There are a number of nuances to the best practices with regard to when objects should and should not be disposed. Carefully study Best Practices: Using Disposable Windows SharePoint Services Objects. To return the current top-level server farm object, use SPContext.Current.Site.WebApplication.Farm. Visual Basic Dim oFarm As SPFarm = SPContext.Current.Site.WebApplication.Farm C# SPFarm myFarm = SPContext.Current.Site.WebApplication.Farm; To return the top-level Web site of the current site collection, use the RootWeb property. Visual Basic Dim oTopSite As SPWeb = SPContext.Current.Site.RootWeb C# SPWeb oTopSite = SPContext.Current.Site.RootWeb; The SPContext class does not limit you to getting the current object of any given type. For example, you can use theMicrosoft.SharePoint.SPSite.AllWebs property to obtain a reference to a Web site other than the current one. The following line returns the context of a specified site by using an indexer with the AllWebs property. Visual Basic

Dim oWebSite As SPWeb = SPContext.Current.Site.AllWebs("myOtherSite") C# SPWeb oWebSite = SPContext.Current.Site.AllWebs["myOtherSite"]; Caution: You should explicitly dispose of references to objects obtained through the AllWebs property. There are a number of nuances to the best practices with regard to when objects should and should not be disposed. Carefully study Best Practices: Using Disposable Windows SharePoint Services Objects. Finally, to get a reference to either the server farm or the current physical server, you can use the static propertiesMicrosoft.SharePoint.Administration.SPFarm.Local and Microsoft.SharePoint.Admin istration.SPServer.Local. The following line is an example. Visual Basic Dim oFarm As SPFarm = SPFarm.Local C# SPFarm oFarm = SPFarm.Local; To use either of the Local properties, you must add using directive (Imports in Visual Basic) for theMicrosoft.SharePoint.Administration namespace. You can use any of the preceding techniques not only in Web applications and .aspx pages, but also in custom Web services and Web Parts. Important: If you install "Infrastructure Update for Windows SharePoint Services 3.0 (KB951695)," custom solutions may fail if they call the SharePoint object model while impersonation is suspended. If you use Windows authentication and your code calls the SharePoint object model from an IIS worker process, the request must impersonate the calling users identity. Windows SharePoint Services configures ASP.NET to impersonate the calling user automatically, but your code may work unexpectedly, or fail, if you suspend impersonation--for example, by calling the RevertToSelf function of the Windows API, or by calling the System.Security.Principal.WindowsIdentity.Impersonate method and passing IntPtr.Zero as the value of the user token parameter. Even if your code does not explicitly revert to self, it might be called by ASP.NET after it reverts to self, such as happens when implementing a virtual path provider; if your code does not impersonate the calling user, it might not function properly. Console and Windows Applications: Use Object Constructors The SPContext class has no meaning in a console or Windows-based application. If you are writing code for either of those types of applications and you want to work with a specific

site collection, use the SPSite constructor to instantiate an object that represents the site collection, as in the following example. Note: Your code should dispose any SPSite or SPWeb object obtained by using a constructor. There are a number of nuances to the best practices with regard to when Windows SharePoint Services objects should and should not be disposed. Carefully study Best Practices: Using Disposable Windows SharePoint Services Objects. Visual Basic Dim oSiteCollection As New SPSite("http://localhost") ... oSitecollection.Dispose(); C# SPSite oSiteCollection = new SPSite("http://localhost"); ... oSitecollection.Dispose();

// Even better, take advantage of a "using" block to ensure // that the object is disposed. using (SPSite oSiteCollection = new SPSite("http://localhost")) { ... } Note: The "localhost" is a Windows alias for the computer on which the code is running. For console applications, Microsoft recommends that you always use "localhost" instead of the actual server name. This is because a console application can only operate on the local computer anyway. If you hard code a server name, such as "MyServer", then your console application cannot be ported to another computer and your console applications will break if the server's name is ever changed. After you have a reference to a collection, you can use the AllWebs collection to obtain a reference to a particular web site in the collection. Visual Basic Dim oWebSite As SPWeb oWebSite = mySiteCollection.AllWebs("mySite")

... oWebSite.Dispose(); C# SPWeb oWebSite = mySiteCollection.AllWebs["mySite"]; ... oWebSite.Dispose();

// Even better, take advantage of a "using" block to ensure // that the object is disposed. using (SPWeb oWebSite = mySiteCollection.AllWebs["mySite"]) { ... } Alternatively, you can use the OpenWeb method as shown in the following line. Visual Basic Dim oWebSite As SPWeb oWebSite = mySiteCollection.OpenWeb("mySite") ... oWebSite.Dispose(); C# SPWeb oWebSite = mySiteCollection.OpenWeb("mySite"); ... oWebSite.Dispose();

// Even better, take advantage of a "using" block to ensure // that the object is disposed. using (SPWeb oWebSite = mySiteCollection.OpenWeb("mySite")) { ... }

Working with List Objects and Collections To perform actions on list data in a SharePoint Web site, you must first obtain an SPWeb object to serve as an entry point to the object model, allowing you to access lists, items, documents, users, alerts, etc. For information about how to return SharePoint Web sites, see Getting References to Sites, Web Applications, and other Key Objects. Objects Most classes in the Microsoft.SharePoint and Microsoft.SharePoint.Administration namespaces start with SP. Generally, classes in the Microsoft.SharePoint assembly that don't start with this prefix represent Web form controls. Windows SharePoint Services typically does not save modifications of object properties to the database until you call the Updatemethod on the given object. The following example shows how to change the title and description for the Tasks list. Visual Basic

Dim myList As SPList = myWeb.Lists("Tasks") myList.Title = "New_Title" myList.Description = "List_Description" myList.Update() C# SPList myList = myWeb.Lists["Tasks"]; myList.Title="New_Title"; myList.Description="List_Description"; myList.Update(); Note: Metadata for the document cannot be modified using the Update method of the SPListItem object if the document is checked out from a document library. Collections Just as lists are at the center of a SharePoint site, so are collections at the center of its object models. You can use each collection to add, delete, enumerate, and update a type of object. Collection classes generally share the following traits: Has a name that ends in "Collection." Implements the System.Collections.ICollection interface. Has a Count property of type Int32. Has an Int32 indexer that can be used to get the nth item in the collection.

Has an indexer that takes an item identifier. Has Add and Delete methods.

Calling the Add method for a collection usually updates the database on the back-end server with the appropriate data, except when additional information is required in order to update data. In this case, using the Add method returns an object that you can use to gather the information. For example, to add an item to a list, first use the Add method of theMicrosoft.SharePoint.SPListItemCollection class to return an SPListItem object, assign values to appropriate properties of the object, and then call the Update method to effect changes within the content database. Indexers Indexers provide a useful means to access individual items in collections. To return an item, use square brackets ([]) in C# or parentheses (()) in Visual Basic to contain either an index or a string that identifies the item within the collection. For example, if mySite represents an instance of the SPWeb class, then SPList myList = mySite.Lists["Announcements"] returns the Announcements list in C#, while Dim myList As SPList = mySite.Lists("Announcements") returns the same list in Visual Basic. You can then use the Items property for the list object to return all the list items in the list (in C#, SPListItemCollection myItems = myList.Items, or in Visual Basic, Dim myItems As SPListItemCollection = myList.Items). To return only a subset of items from the list, you can call the list object's GetItems method and pass an SPQuery object to specify the subset: SPListItemCollection myItems = myList.GetItems(myQuery) (in Visual Basic, Dim myItems As SPListItemCollection = myList.GetItems(myQuery)). You can use an indexer to return a specific field from a list (for example, myList.Items["Field_Name"] in C#, or myList.Items("Field_Name") in Visual Basic). You can also specify a field name in an indexer and iterate through the collection of items in a list in order to return values from the field. This example displays the Due Date, Status, and Title values for each item in a list: Visual Basic

Dim myItem As SPListItem

For Each myItem In myItems

Response.Write(SPEncode.HtmlEncode(myItem("Due Date").ToString()) + "<BR>") Response.Write(SPEncode.HtmlEncode(myItem("Status").ToString()) + "<BR>") Response.Write(SPEncode.HtmlEncode(myItem("Title").ToString()) + "<BR>")

Next myItem C#

foreach(SPListItem myItem in myItems) { Response.Write(SPEncode.HtmlEncode(myItem["Due Date"].ToString()) + "<BR>"); Response.Write(SPEncode.HtmlEncode(myItem["Status"].ToString()) + "<BR>"); Response.Write(SPEncode.HtmlEncode(myItem["Title"].ToString()) + "<BR>"); } Note: In addition to requiring a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace, the previous example requires a directive for the Microsoft.SharePoint.Utilities namespace. The next example shows how to return all Title and Status values for the Tasks list on a SharePoint Web site. Visual Basic

Dim myWeb As SPWeb = SPContext.Current.Web Dim myTasks As SPList = myWeb.Lists("Tasks") Dim myItems As SPListItemCollection = myTasks.Items Dim myItem As SPListItem

For Each myItem In myItems

Response.Write(SPEncode.HtmlEncode(myItem("Title").ToString()) + " :: " _ & SPEncode.HtmlEncode(myItem("Status").ToString()) + "<BR>")

Next myItem C# SPWeb mySite = SPContext.Current.Web;

SPList myTasks = mySite.Lists["Tasks"]; SPListItemCollection myItems=myTasks.Items;

foreach(SPListItem myItem in myItems)

{ Response.Write(SPEncode.HtmlEncode(myItem["Title"].ToString()) + " :: " + SPEncode.HtmlEncode(myItem["Status"].ToString()) + "<BR>"); } Note: In addition to requiring a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace, the previous example requires a directive for the Microsoft.SharePoint.Utilities namespace. You can also use indexers to modify values in a list. In the following example, a new list item is added to a collection and the values for a URL column are assigned to the item: Visual Basic

Dim myNewItem As SPListItem = myList.Items.Add()

myNewItem("URL_Field_Name") = "URL, Field_Description"

myNewItem.Update() C# SPListItem myNewItem = myList.Items.Add();

myNewItem["URL_Field_Name"] ="URL, Field_Description";

myNewItem.Update(); Note: The URL field type is unique because it involves two values (separated by a comma and a space), and in the above example these values are both assigned to the new item through a single indexer. The following example sets the Status and Title values for a list item. Visual Basic Dim myItem As SPListItem = myItems(0)

myItem("Status") = "Task_Status"

myItem("Title") = "Task_Title"

myItem.Update() C# SPListItem myItem = myItems[0];

myItem["Status"]="Task_Status"; myItem["Title"]="Task_Title";

myItem.Update(); Note: An indexer throws an ArgumentOutOfRange exception if it does not find the specified item. For information about specific data formats that are used for list items in Windows SharePoint Services, see the SPListItem class Registering and Importing Namespaces Use processing instructions to register namespaces, assemblies, and other properties for the installation of Windows SharePoint Services. For Microsoft ASP.NET pages, use instructions such as the following at the beginning of the code, which register theMicrosoft.SharePoint.WebControls, Microsoft.SharePoint.Utilities, Microsoft.SharePoint, and Microsoft.SharePoint.WebPartPagesnamespaces. <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint" %> <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral,

PublicKeyToken=71e9bce111e9429c" %> You can obtain the PublicKeyToken value for the current Windows SharePoint Services deployment from the default.aspx file that is located in Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates/sts, or from information provided for the Microsoft.SharePoint assembly at Local_Drive:\%Windir %\assembly in Windows Explorer. In code-behind files or console applications, import namespaces in Microsoft Visual C# through the using directive, as follows. C# using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using Microsoft.SharePoint.WebPartPages; In Microsoft Visual Basic, use the Imports statement to import namespaces, as follows. Visual Basic Imports Microsoft.SharePoint Imports Microsoft.SharePoint.WebControls Imports Microsoft.SharePoint.WebPartPages

Você também pode gostar