Types of Web Parts in Windows SharePoint Services 3.0

bubblemessengerΑσφάλεια

5 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

310 εμφανίσεις

Web Parts Overview

Web Parts are server
-
side controls that run inside the context of special pages (that is, Web
Part Pages) within an ASP.NET application or a Windows SharePoint Services site. They are
the "building blocks" of pages in Windows SharePoint
Services. Windows SharePoint
Services includes built
-
in Web Parts that you can use as soon as you have installed the
product. In addition, you can build your own Web Parts and deploy them to the server.

Because of the popularity of Web Parts in Windows Sha
rePoint Services 2.0, support for a
new Web Part infrastructure for ASP.NET 2.0 was added to Windows SharePoint Services
3.0. The new Web Part infrastructure is similar yet distinct from the Web Part infrastructure
in Windows SharePoint Services 2.0.

Types

of Web Parts in Windows SharePoint Services 3.0

There are now two different Web Part styles in Windows SharePoint Services 3.0. Both are
supported, but the ASP.NET 2.0 Web Part is the recommended style for your new projects.



SharePoint
-
based Web Parts



T
he older style Web Parts have a dependency on
Microsoft.SharePoint.dll and must inherit from the

WebPart

base class in
the

Microsoft.SharePoint.WebPartPages

namespace. These Web Parts can only be
used in SharePoint Web sites. Yet in Windows SharePoint Services 3.0, the
Microsoft.SharePoint.dll was changed so that Web

Parts written in the older style
would be compatible with the Windows SharePoint Services 3.0 runtime.


Note:

For more information about when to derive from the Windows SharePoint Services
WebPart Class, see the section "When to Derive from the Windows
SharePoint
Services WebPart Class" in the

Web Part Infrastructure in Windows SharePoint
Services

topic.



ASP.NET 2.0 Web Parts



These Web Parts are built on top of the ASP.NET Web
Part in
frastructure. The newer ASP.NET
-
style Web Parts have a dependency
on

System.Web.dll

and must inherit from a different base class named

WebPart

in
the

System.Web.UI.WebControls.WebParts

namespace. These Web Parts can be
used in Windows SharePoint Services applications whether Windows SharePoint
Services is involved
or not, making them highly reusable.


Note:

If you are creating your Web Part specifically for a SharePoint site, and it will
consume the Windows SharePoint Services object model, you can derive from the
ASP.NET

System.Web.UI.WebControls.WebParts.WebPart

base class and add
a reference to the SharePoint object model in your project.

More about ASP.NET 2.0 Web Parts

The Windows SharePoint Services 3.0 Web Part infrastructure is built on top of a control
named

SPWebPartManager

that is derived from the ASP.N
ET
2.0
WebPartManager

control. The

SPWebPartManager

control overrides the standard
behavior of the

WebPartManager

control to persist Web Part data inside the Windows
SharePoint Services

content database instead of in the ASP.NET services database. In most
c
ases, you do not have to worry about dealing directly with
the

SPWebPartManager

control because the one and only required instance is already
defined in

default.master
. When you create a content page that links to
default.master
,
the

SPWebPartManager

contro
l is already there.


Note:

Web Part zones for a Web Part Page in Windows SharePoint Services 3.0 should be created
by using the

WebPartZone

control defined inside
the
Microsoft.SharePoint.WebPartPages

namespace, not by using the
standard

WebPartZone

contr
ol from ASP.NET 2.0.

When you create a Web Part Page for a standard ASP.NET 2.0 application, you need to add
logic that interacts with the

WebPartManager

control to manage the Web Part display
mode, and generally you also need to explicitly add editor par
ts and catalog parts to the
page along with the HTML layout to accommodate them. Fortunately, you do not have to
perform these changes when creating content pages for a Windows SharePoint Services 3.0
site. Instead, you inherit from the
WebPartPage

class that is defined inside
the

Microsoft.SharePoint.WebPartPages

namespace and it does all the work behind the
scenes for you.

For more information about cre
ating ASP.NET Web Parts, see

ASP.NET AJAX in Windows
SharePoint Services

and

Web Parts Control Set Overview

in the ASP.N
ET documentation.

Custom Web Parts

Custom Web Parts provide developers with a method to create user interface elements that
support both customization and personalization. A site owner or a site member with the
appropriate permissions can customize Web Par
t Pages by using a browser or by using
Microsoft Office SharePoint Designer 2007 to add, reconfigure, or remove a Web Part.

In Windows SharePoint Services 2.0, developers could extend SharePoint sites by creating
custom Web Parts, to add the extra dimensio
ns of user customization and personalization.
The term

customization

implies that changes are seen by all site members. Individual users
can further personalize Web Part Pages by adding, reconfiguring, and removing Web Parts.
The term

personalization

impli
es that these changes will be seen only by the user that made
them. Developing custom Web Parts provides an easy and powerful way to extend Windows
SharePoint Services sites.

Because the Windows SharePoint Services Web Part infrastructure is now built on t
op of the
ASP.NET 2.0 Web Parts control set, you can reuse your knowledge of ASP.NET programming
to create quick and robust custom Web Parts.

Following are some ways in which you can benefit from and use custom Web Parts:



Creating custom properties you can

display and modify in the user interface.



Improving performance and scalability. A compiled custom Web Part runs faster than
a script.



Implementing proprietary code without disclosing the source code.



Securing and controlling access to content within the
Web Part. Built
-
in Web Parts
allow any users with appropriate permissions to change content and alter Web Part
functionality. With a custom Web Part, you can determine the content or properties
to display to users, regardless of their permissions.



Making y
our Web Part connectable, allowing Web Parts to provide or access data
from other connectable Web Parts.



Interacting with the object models that are exposed in Windows SharePoint Services.
For example, you can create a custom Web Part to save documents to
a Windows
SharePoint Services document library.



Controlling the cache for the Web Part by using built
-
in cache tools. For example,
you can use these tools to specify when to read, write, or invalidate the Web Part
cache.



Benefiting from a rich development
environment with debugging features that are
provided by tools such as Microsoft Visual Studio 2005.



Creating a base class for other Web Parts to extend. For example, to create a
collection of Web Parts with similar features and functionality, create a cus
tom base
class from which multiple Web Parts can inherit. This reduces the overall cost of
developing and testing subsequent Web Parts.



Controlling the implementation of the Web Part. For example, you can write a
custom server
-
side Web Part that connects t
o a back
-
end database, or you can
create a Web Part that is compatible with a broader range of Web browsers.

Web Part Infrastructure in Windows SharePoint Services

Web Parts in Windows SharePoint Services 3.0 are based on the Microsoft ASP.NET 2.0 Web
Part

infrastructure. To create Web Parts for applications targeting Windows SharePoint
Services, you should build custom Web Parts on top of the ASP.NET Web Part infrastructure.
However, in a very few cases, you may have to create Web Parts that support Window
s
SharePoint Services features that are not available in the ASP.NET Web Part infrastructure.
For more information, see "When to Derive from the Windows SharePoint Services Class" in
this topic.

Web Part Inheritance Model in Windows SharePoint Services

The

Windows SharePoint Services 3.0

WebPart

class has been rebased to inherit from the
Microsoft ASP.NET 2.0

WebPart

class, providing a compatibility layer to ensure that Web
Parts written for Windows SharePoint Services 2.0 work in Windows SharePoint Services 3.0
without modification. It exists primari
ly for the purpose of backward compatibility, and
secondarily, to provide a small set of features that are not available in the
ASP.NET

WebPart

class.


Note:

The Windows SharePoint Services

WebPa
rt

class is part of the Web Part infrastructure
that was designed specifically for Windows SharePoint Services 2.0 sites.

The following diagram demonstrates the inheritance hierarchy for the Windows SharePoint
Services

WebPart

class.


Core Controls for W
eb Part Pages

The following section describes core controls for Web Part Pages for both SharePoint
-
based
Web Parts and ASP.NET 2.0 Web Parts.

SharePoint
-
based Web Parts

The Windows SharePoint Services 3.0 Web Part infrastructure uses many of the controls i
n
the ASP.NET 2.0 Web Part control set, as well as introduces several of its own controls that
inherit from base classes supplied by the ASP.NET 2.0 Web Parts control set.

For example, Web Part Pages for a Windows SharePoint Services site do not use the
st
andard ASP.NET

WebPartManager
. Instead, they use the Windows SharePoint Services
-
specific

SPWebPartManager

that inherits from the ASP.NET

WebPartM
anager
. The
following figure shows the

WebPartManager

class inheritance.


Similarly, Web Part Pages for a Windows SharePoint Services site also use Windows
SharePoint Services
-
specific

WebPartZone

that inherits from the ASP.NET
WebPartZone
.

ASP.NET Web Parts

The ASP.NET Web Part infrastructure is based on a

WebPartManager

class that manages
the lifetime of Web Part instances at run time.

Each ASP.NET pag
e that uses Web Part controls must contain:



Exactly one

WebPartManager

object that tracks which Web Parts have been added
to each particular zone, and stores and retrieves data about how each Web Part has
been customized and personalized.



One or more

WebPa
rtZone

objects, into which Web Parts are placed.

To run Web Parts in an ASP.NET 2.0 application, you must create an .aspx page that
contains exactly one instance of the

WebPartManager

control and one or
more

WebPartZone

controls. The

WebPartManager

is resp
onsible for serializing Web
Part
-
related data as well as storing and retrieving it from the services database.

The .aspx page serving as a Web Part Page can contain editor parts that allow users to
customize and personalize persistent Web Part properties.
Web Part Pages can also contain
catalog parts that let users add new Web Parts into zones. Windows SharePoint Services 3.0
does the work to add the catalog and editor parts for you, so that you do not need to
explicitly do this in a Web page designer. The
following figure shows
the

WebPartZone

class inheritance.


The

SPWebPartManager

and

WebPartZone

controls manage the serialization of data
associated with Web Parts into the appropriate Windows SharePoint Services content
database. To be able to persist da
ta, your ASP.NET Web Parts must be placed on a page
with these two controls.

Because these Windows SharePoint Services
-
specific controls are required on pages that
contain Web Parts, you cannot simply copy your ASP.NET page into a Windows SharePoint
Servic
es site. To move ASP .NET Web Parts from an ASP.NET application to a Windows
SharePoint Services application, you should export them from ASP .NET and import them
into a Windows SharePoint Services site.


Note:

The default master page that is provided wi
th the Windows SharePoint Services technology
includes an instance of

SPWebPartManager
, so this control is automatically included with
all of your Windows SharePoint Services content pages.

Differences in Web Part Behavior between Windows SharePoint Servi
ces 2.0 and
Windows SharePoint Services 3.0

The Windows SharePoint Services team has gone to great lengths to ensure that your
Windows SharePoint Services 2.0 Web Parts work seamlessly in Windows SharePoint
Services 3.0. There are a small number of cases,
however, in which your Windows
SharePoint Services 2.0 Web Parts may behave differently. These include:



In Windows SharePoint Services 2.0, Web Parts were managed by zones; however,
in Windows SharePoint Services 3.0, Web Parts are managed by
the
SPWebPartM
anager
. If you use a Web Part's

Parent

property, you get a
reference to

SPWebPartManager

rather than a reference to the
containing
WebPartZone
.



In Windows SharePoint Services 2.0, both provider and consumer Web Parts can
have multiple connections. In Window
s SharePoint Services 3.0, the provider part
can have multiple connections but the consumer part can have only one connection
(same as that of ASP.NET 2.0 Web Part controls). You can replicate Windows
SharePoint Services 2.0 behavior, however, by specifyin
g

UnlimitedConnections

on
the consumer Web Part.

When to Derive from the Windows SharePoint Services WebPart Class

In a very few cases
, you may have to create Web Parts that support Windows SharePoint
Services features that are not available in the ASP.NET Web Part infrastructure. In these
cases, you can create a class that inherits from the Windows SharePoint
Services

WebPart

base class
. Web Parts such as these are known as

SharePoint
-
based Web
Parts

and can only be used in SharePoint sites.

Following is the list of features provided exclusively by the Windows SharePoint
Services

WebPart

class:



Cross page connections



Connections between
Web Parts that are outside of a Web Part zone



Client
-
side connections (Web Part Page Services Component)



A data caching infrastructure that allows caching to the content database

Another reason you may consider deriving from the

WebPart

class is related to

creating
new versions of your Web Parts. If your original Web Part derived from the
WebPart

class,
and you want to upgrade instances of that Web Part to a new version, then the new version
of the Web Part should also derive from the SharePoint
WebPart

class
.


Developing Web Parts in Windows SharePoint Services

This section of the Windows SharePoint Services Software Development Kit (SDK) provides configuration
information, security guidance, and programming examples that introduce you to programming Web Part
s
for Windows SharePoint Services 3.0.

In This Section

Securing Web Parts in Windows SharePoint Services

Deploying Web Pa
rts in Windows SharePoint Services

Walkthrough: Creating a Basic Web Part

Walkthrough: Creating a Basic SharePoint Web P
art

Walkthrough: Creating Connectable Web Parts in Windows SharePoint Services


Securing Web Parts in Windows SharePoint Services

Web Parts in Windows SharePoint Services provide a powerf
ul way for users to interact with other systems.
Windows SharePoint Services has built
-
in security settings to restrict the access that a Web Part has to
underlying systems. A developer can create custom security policy files to give a Web Part greater acc
ess to
the underlying system. This topic introduces the built
-
in settings, an overview of a Code Access Security
(CAS) policy, and how to include a custom Code Access Security policy in a Windows SharePoint Services
solution.

Code Access Security

Code Acce
ss Security is a resource
-
constraints model that limits the access that an assembly has to
protected system resources and operations. Windows SharePoint Services has built
-
in security policies built
on top of the built
-
in security policies of ASP.NET. By d
efault, Windows SharePoint Services uses a minimal
set of permissions in order to protect the server and underlying infrastructure from malicious code.

If your Web Part needs greater access than what is provided in the minimal settings, there are a number
of
ways to increase the permissions of your Web Part, but only one is recommended. The recommended
practice is to create a custom Code Access Security policy for your Web Part. The second method is to
increase the overall trust level of the server farm in
the

web.config

file. This is a security risk and is not
recommended. For more information about deployment, see

Deploying Web Parts in Windows SharePoint
Services
.

Built
-
In Security Settin
gs

Windows SharePoint Services is a partial trust application by default. Windows SharePoint Services can use
the ASP.NET built
-
in trust levels but defines two trust levels of its own:



WSS_Minimal



WSS_Medium

The trust levels extend the

Minimal

and

Medium

t
rust levels of ASP.NET for use withWindows SharePoint
Services. Trust levels are defined in policy files found on the file system of each web server.

Important

By default, the built
-
in Windows SharePoint Services policy files,
named

wss_minimaltrust.conf
ig

and

wss_mediumtrust.config
, are found
in

%SYSTEMDRIVE%
\
Program Files
\
Common Files
\
Microsoft Shared
\
web server
extensions
\
12
\
config
.

By default, Windows SharePoint Services applies the

WSS_Minimal

trust level for the virtual server. This
trust level gran
ts all of the permissions in the ASP.NET
Minimal

trust as well as Web Part connections.
The

WSS_Minimal

policy restricts the Web Part from accessing many resources for advanced operations,
including the object model and file operations.

The

WSS_Medium

trust

level grants greater access to the environment. Also,

WSS_Medium

allows access
to the Windows SharePoint Services object model and file operations including read, write, append, and path
discovery. This trust level also allows access to environment variab
les.

The following table outlines the specific permissions granted with
the

WSS_Minimal

and

WSS_Medium

policy files in the ASP.NET 2.0 environment.

Permission

WSS_Medium Trust Level

WSS_Minimal
Trust Level

AspNetHostingPermission

Medium

Minimal

DirectoryServicesPermission

None

None

DnsPermission

Unrestricted

None

EnvironmentPermission

Read: TEMP, TMP, OS, USERNAME,
COMPUTERNAME

None

EventLogPermission

None

None

FileIOPermission

Read, Write, Append, PathDiscovery:Application
Directory

None

IsolatedStoragePermission

AssemblyIsolationByUser, Unrestricted
None

UserQuota

MessageQueuePermission

None

None

OleDBPermission

None

None

Performance Counters

None

None

PrintingPermission

Default printing

None

ReflectionPermission

None

None

RegistryPermi
ssion

None

None

SecurityPermission

Execution, Assertion, ControlPrincipal,
ControlThread, RemotingConfiguration

Execution

ServiceControllerPermission

None

None

SharePoint
Permission

(Microsoft.SharePoint.Security)

ObjectModel = true

None

SocketPermission

None

None

SqlClientPermission

AllowBlankPassword=false

None

WebPermission

Connect to origin host (if configured)

None


Note:

For

more information about Code Access Security, see

Using Code Access Security with
ASP.NET

and also

Security Guidelines f
or .NET Framework 2.0
.

Creating a Code Access Security Policy

Windows SharePoint Services 3.0 added the ability to deploy a CAS policy file with a solution. This feature
makes it easier for you to create custom permissions for your Web Parts and allows W
indows SharePoint
Services to handle the deployment.

The following code example shows the basic structure of a CAS policy file in a Windows SharePoint Services
solution package.

Xml

<
CodeAccessSecurity
>


<
PolicyItem
>


<
PermissionSet

class="NamedPermi
ssionSet" version="1"


Description="Permission set for custom test WebParts"
>


<
IPermission

class="AspNetHostingPermission" version="1"


Level="Minimal"
/>


<
IPermission

class="SecurityPermission" version="1"


Flags="Exec
ution"
/>


<
IPermission



class="Microsoft.SharePoint.Security.SharePointPermission,


Microsoft.SharePoint.Security, version=11.0.0.0,


Culture=neutral, PublicKeyToken=71e9bce111e9429c" version="1"


ObjectModel="True"
/>


<
IPermission

class="System.Net.WebPermission, System,


version=1.0.5000.0, Culture=neutral,


PublicKeyToken=b77a5c561934e089" version="1"
>


<
ConnectAccess
>


<
URI

uri="https?://.*"
/>


</
ConnectAccess
>


</
IPermission
>


<
IPermission



class="System.Security.Permissions.SecurityPermission,


mscorlib, version=1.0.5000.0, Culture=neutral,


PublicKeyToken=b77a5c561934e089" version="1"


Flags="ControlThread, Unmana
gedCode"
/>


<
IPermission



class="System.Security.Permissions.EnvironmentPermission,


mscorlib, version=1.0.5000.0, Culture=neutral,


PublicKeyToken=b77a5c561934e089" version="1" Read="UserName"
/>


</
PermissionSet
>


<
Assemblies
>


<
Assembly

PublicKeyBlob=PublicKeyBlob
/>


</
Assemblies
>


</
PolicyItem
>

</
CodeAccessSecurity
>

The list below includes some general guidelines that apply when you use a <CodeAccessSecurity> section in
your solution manifest.



There c
an only be one <CodeAccessSecurity> per solution manifest.



There can be multiple <PolicyItem> nodes.



Every <PolicyItem> node can only contain one <PermissionSet> node.



Every <PolicyItem> node can only contain one <Assemblies> node.



Each <PermissionSet> nod
e can contain multiple <IPermission> nodes.



There can be multiple <Assembly> nodes under the <Assemblies> node.

For more information about the schema of the <CodeAccessSecurity> area, see

CodeAccessSecurity
Element
.

When you deploy your assembly using a custom CAS policy, you must use the

-
allowCasPolicies

option
with the stsadm.exe utility. The command is as follows:
stsadm
-
o deploySolution
-
name <insert
name>
-
allowCasPolicies

Deploying
Web Parts in Windows SharePoint Services

Windows SharePoint Services requires that a Web Part be deployed in the Web Part gallery before it can be
added to the page. This section describes differences between the bin folder and the Global Assembly Cache
(G
AC), security permissions considerations, how to strong name an assembly for deployment, how to create
a SafeControl entry, and finally, how to create a Web Part definition file to deploy the Web Part.

Deployment Considerations

There are two primary locati
ons within a SharePoint site where you can deploy a Web Part assembly.



bin directory



The bin directory is a folder stored in your Web application root directory. The
location of this folder is determined when the Web site is created in Internet Informati
on Services
(IIS). In Windows SharePoint Services, this can happen either through the SharePoint 3.0 Central
Administration site, or by manually creating a new Web site in IIS manager.


Important:

If a bin directory does not exist you must add one manual
ly. Do not store Web Parts in the
local

_app_bin

directory, which is reserved for use by Microsoft.

For more information, see

How to: Find the Web Application Root
.



global assembly cache



A global location where signed assemblies can be deployed. The global
assembly cache enables you to share assemblies across numerous applications. The global assembly
cache is automatically installed with the .NET runtime. Components are typically stored

in

C:
\
WINNT
\
Assembly
.

Each location has advantages and disadvantages, as described in the following table.

Deployment
Location

Advantages

Disadvantages

bin directory

Assemblies run with partial trust, by default.
Code that runs from this directory has a
low level
of code access security (CAS) permissions.
Because administrators must explicitly raise
permissions that have been granted to a Web
Part so it can function properly, they often prefer
that assemblies run in the bin directory with a
known set of r
equired CAS permissions.

A bin directory is specific to a Web application.
This makes it possible to isolate code to a
particular Web application.

In order for the Web Part to run in
multiple Web applications, you must
deploy it to the global assembly cach
e.

global
assembly
cache

Assemblies run with full trust by default. They
are globally installed, so they will work in any
Web application. The global assembly cache can
contain multiple versions of the same assembly.

Generally no CAS restrictions on code
installed to the global assembly cache;
therefore, you lose the defense
-
in
-
depth security benefit.

Also, an assembly deployed to the GAC
is cached, so if the assembly is rebuilt,
it is not automatically updated on the
SharePoint site. You must force
Window
s SharePoint Services to reload
the assembly by resetting Internet
Information Services (IIS).

Security Permissions Considerations

By default, code access security permissions for the bin directory are low; only pure execution is allowed. In
most cases yo
u need to elevate these permissions to make your assembly run correctly, for example, if your
Web Part requires access to the SharePoint object model.

There are two ways to elevate permissions:



Recommended method



Create a new trust policy file and point
your

web.config

file at the
new file. This option is more complicated but it gives you a precise attribution of permissions for
your Web Parts.

For more information about trust policy files, see

Securing Web Parts in Windows SharePoint
Services
.



Optional method



Raise the net trust level of the bin directory. In the

web.config

file in the
Web application root, there is a tag called

<trust>

with a default attribute
of

level="WSS_Minimal"
. Y
ou can change this level to

WSS_Medium
. While this option is
simpler, it grants arbitrary new permissions that you might not need and is less secure than
creating a new trust policy file.

Strong Naming a Web Part Assembly

Strong naming uses a private key t
o digitally sign an assembly. Strong naming also stamps the assembly
with a public key to validate the signature. This technique guards against unauthorized versions of a Web
Part. If the public key fails to validate the digital signature, Windows SharePoi
nt Services will refuse to run
the module.

When deploying a Web Part to the bin, the recommend practice is to strong name the assembly. When
deploying a Web Part to the Global Assembly Cache, the assembly

must

have a strong name. An assembly
without a stro
ng name is not recommended in Windows SharePoint Services.

To sign an assembly, you use the sn.exe tool that is included with the .NET Framework Software
Development Kit (SDK). For more information about the .NET Framework SDK, see

SDKs, Redistributables &
Service Packs
. The sn.exe tool is also used to extract the public key that is needed to register your control
as safe in the SafeControls list. For more information about using the
sn.exe tool, see

Strong Name Tool
(Sn.exe)
.

Creating a SafeControl Entry

A fundamental assumption of the Windows SharePoint Services technology is that untrusted users can
upload and crea
te ASPX pages within the system that is running Windows SharePoint Services. To prevent
untrusted users from arbitrarily adding server
-
side code within ASPX pages, Windows SharePoint Services
provides a SafeControls list.

The SafeControls list is a list of

approved controls and Web Parts specific to your SharePoint site that you
have designated as safe for invocation on any ASPX page within your site. This list is contained in
the

web.config

file in your Web application root.

A SafeControl entry is an XML
-
b
ased declaration of a Web Part that has the following form.

Xml

<SafeControl Assembly="
AssemblyNameWithoutDLLExtension
,
Version=
AssemblyVersionNumber
, Culture=neutral,
PublicKeyToken=
PublicKeyToken
" Namespace="
NamespaceOfYourProject
"
TypeName="*" Safe="Tru
e" />

The SafeControl entry uses the assembly name, namespace, versioning information, and, if it is signed, it
also requires a public key token to verify that the control is safe. If a Web Part assembly is signed, you can
use the Strong Name Tool to retri
eve the public key token for use in the SafeControl entry. The following
command will retrieve the public key token for an assembly.


Creating a .Webpart File

A Web Part definition (
.webpart
) file is a simple XML file that contains property settings for a
single Web
Part. To import your Web Part into a Web Part Page, simply upload the

.webpart

file or add the Web Part
to the Web Part gallery. After uploading the Web Part, you can display the Web Part by dragging it into one
of the zones of the Web Part Page
. To display a default name and description for the Web Part after it is
imported, you should include the

Title

and

Description

properties. If you want to set other Web Part
properties during import, you can also define them in a

.webpart

file. A

.webpart

file takes the following
form.

Xml

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


<webParts>


<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">


<metaData>


<type name="
TypeName
, Version=
VersionNumber
, Culture=neutral,


Publi
cKeyToken=
PublicKeyToken
" />


<importErrorMessage>Cannot import this Web


Part.</importErrorMessage>


</metaData>


<data>


<properties>


<property name="Title" type="string">


WebPartTitle
</prop
erty>


<property name="Description" type="string">


WebPartDescription


</property>


</properties>


</data>


</webPart>


</webParts>


Walkthrough: Creating a Basic Web Part

This walkthrough provides the
steps for creating a basic custom Web Part that can be added to your Web
Part Pages. It is a simple Web Part that allows the user to define a custom message to be displayed inside
the Web Part. This Web Part will derive from the ASP.NET 2.0 Web Part class,

which is the recommended
practice for Windows SharePoint Services. Note that this walkthrough describes how to create a Web Part
without the Visual Studio Extensions for Windows SharePoint Services.

For more information about ASP.NET Web Parts, see the fo
llowing ASP.NET documentation:

ASP.NET
QuickStart Tutorials

and

ASP.NET Web Parts Controls
.


Note:

You can also develop your Web Parts by using the Visual Studio Extensions for Windows SharePoint
Services. By using these extensions, you can greatly reduce the work involved in creating and deploying
your Web Parts. The extensions require development in

a server environment, and offer the following
benefits:



Automatic generation of your solution package



Automatic generation of the WebPart XML file



Ability to deploy Web Parts directly from inside Visual Studio to your Web site

For guidance on using the ex
tensions or to download extensions for Visual Studio 2005 or Visual Studio
2008, see



Windows SharePoint Services 3.0 Tools: Visual Stu
dio 2005 Extensions User Guide, Version 1.1



Windows SharePoint Services 3.0 Tools: Visual Studio Extensions, Version 1.1



Windows SharePoint Services 3.0 Tools: Visual Studio Extensions, Version 1.2



Prerequisites

Windows SharePoint Services 3.0

Visual Studio 200
5



Step 1: Create an ASP.NET Web Part assembly

To create a Web Part, you start by creating a class library project that derives from the

WebPart

base cl
ass.

To create an ASP.NET Web Part Assembly

1.

Start Visual Studio 2005

2.

On the

File

menu, point to

New
, and then click

Project
.

3.

In

Project Types
, under

Visual Basic

or

C#
, select

Windows
.

4.

In the

Templates

pane, select

Class Library
.

5.

Type

Sample.DisplayMessage

as the project name.



Step 2: Rename the base class and add required namespaces

After you create the project, a blank class file is displayed. You can change the default class name
of

Class1

to easily identify your new Web Part. In a class library, only

a few namespaces are included. You
must add two required namespaces and references to their assemblies. You must also derive the base class
from

WebPart
.

To add namespace references and rebase your Web Part

1.

Rename the default class by selecting

Class1

in
Solution Explorer, right
-
click, click

Rename
, and
type

DisplayMessageWebPart

as the file name.

2.

On the

Project

menu, click

Add Reference
.

3.

In the

Add Reference

dialog on the .NET tab, select

System.Web

and click

OK
.

4.

In the references area of the class file,
add a reference
to

System.Web.UI.WebControls.WebParts

and rebase your class to inherit from

WebPart
, as shown
in the following code sample.

C#

using

System;

using

System.Collections.Generic;

using

System.Text;

using

System.Web;

using

System.Web.UI.WebControls.WebParts;


namespace

Sample.DisplayMessage

{


public

class

DisplayMessageWebPart : WebPart


{


}

}

Visual Basic

Imports

System

Imports

System.Collect
ions.Generic

Imports

System.Text

Imports

System.Web

Imports

System.Web.UI.WebControls.WebParts


Public

Class

DisplayMessage


Inherits

WebPart


End

Class

5.

You have now created a basic structure for the Web Part.



Step 3: Add a user
-
customizable Web Part

property

After configuring the new class to act as a Web Part, add a customizable property for the Web Part.

The Web Part property determines the text that is rendered inside the Web Part. This is customized on the
basis of the individual user.


Note:

F
or more information about customization and personalization, see

Web Parts Personalization
.

For Web Parts based on the

ASP.NET Web Parts Pages

base class, the tags that are used for the
customizable properties are named differently than Web Parts that are based on the

WebPart

base class.
The following list describes each of those properties:



The

WebBrowsableAttribute

class attribute ensures

that your custom property renders in the editing
tool pane in Windows SharePoint Services.



The

WebDescriptionAttribute

class attri
bute displays a tooltip to help guide users when editing your
custom property.



The

WebDisplayNameAttribute

class attribute shows a
display name for your custom property.



The

PersonalizableAttribute

class attribute determines if changes to your custom property af
fects all
users or on a per
-
user basis.

To create the Web Part property

1.

In the

DisplayMessageWebPart

file, copy and paste the following code to create a basic
customizable property.

C#

private

string

customMessage = “Hello, world!”;


public

string

DisplayM
essage

{


get

{
return

customMessage; }


set

{ customMessage = value; }

}

Visual Basic

Private

customMessage
As

String

= “Hello, world!”


Public

Property

DisplayMessage()
as

String


Get


Return

customMessage


End

Get


Set
(
ByVal

value
as

String
)


customMessage = value


End

Set

End

Property

2.

Then, add the following tags above the public declaration to allow changes on a per
-
user basis:

C#

[WebBrowsable(
true
),

WebDescription(
"Displays a custom message"
),

WebDisplayName(
"Display M
essage"
),

Personalizable(PersonalizationScope.User)]

Visual Basic

<WebBrowsable(
True
), _

WebDescription(
"Displays a custom message"
), _

WebDisplayName(
"Display Message"
), _

Personalizable(PersonalizationScope.User)> _

3.

Now you have created a customizable We
b Part property.



Step 4: Override the Render method and build your Web Part

Now you must add functionality to your Web Part. By overriding the

Control.Render M
ethod
, you can tell the
Web Part what operations to perform when the page is visited. In this example, the Web Part will render the
user
-
defined text.

To override the Render method and compile the assembly

1.

In the

DisplayMessageWebPart

file, copy and paste

the following code to override
the

Render

method.

C#

protected

override
void

Render(System.Web.UI.HtmlTextWriter writer)

{


writer.Write(DisplayMessage);

}

Visual Basic

Protected

Overrides

Sub

Render(
ByVal

writer
As

System.Web.UI.HtmlTextWriter)


wr
iter.Write(DisplayMessage)

End

Sub

2.

Compile the solution. Now you have an assembly that contains
your

DisplayMessageWebPart

Web Part.



Step 5: Place your assembly in the bin directory or global assembly cache

Within a SharePoint site, you can deploy a Web

Part assembly to one of two locations listed below. Note that
the recommended practice is to deploy assemblies to the bin directory.



bin directory



The bin directory is a folder stored in your Web application root directory. For
most installations, this
is located in
the
%SYSTEMDRIVE%
\
inetpub
\
wwwroot
\
wss
\
VirtualDirectories
\
<port
number>
\
bin

directory, but if you need more information, see

How to: Find the Web Application
Root
.



Global Assem
bly Cache (GAC)



The GAC enables you to share assemblies across numerous
applications. The GAC is automatically installed with the .NET framework runtime. Components are
typically installed in the

%SYSTEMDRIVE%
\
WINDOWS
\
Assembly

directory.

For more informa
tion about choosing the correct deployment location, see

Deploying Web Parts in Windows
SharePoint Services
.

For the following example, place the assembly in the bin directory.





Step 6: A
dd your Web Part to the SafeControls list


Windows SharePoint Services provides a SafeControls list to prevent users from arbitrarily adding
server
-
side code within ASPX pages. The SafeControls list is a list of approved controls and Web
Parts that are spec
ific to the SharePoint site that you have designated as safe for invocation on any
ASPX page within your site. This list is contained in the

web.config

file in your Web application
root. The local path contains the physical location of the

web.config

file.


Note:

The

web.config

file is located in the folder where the virtual directory for the Web site is located. This is
normally

c:
\
inetpub
\
wwwroot
\
wss
\
VirtualDirectories
\
<port number>
\
,

but your
administrator may have set up your directory differently and

this may not be the location of the file.

You can find the location of your

web.config

file with the Internet Information Services (IIS) snap
-
in.
The IIS snap
-
in is an administration tool for IIS that has been integrated with other administrative
function
s. To launch the IIS snap
-
in and locate the

web.config

file:

1.

Click

Start
, point to

Programs
, point to

Administrative Tools
, and click Internet Information
Services (IIS) Manager.

2.

Expand the node that is the name of your computer, and expand the

Web Sites

i
tem in the tree

3.

Locate the Web site that is running your Windows SharePoint Services installation (often it
is

Default Web Site
).

4.

Right
-
click and select

Properties
.

5.

Select the

Home Directory

tab.

To add your Web Part to the SafeControls list

1.

Open the

web.
config

file in the application root.

2.

In the

SafeControls

section of your

web.config

file, add a

SafeControls

entry for your custom
assembly in the

web.config

file as follows.

Xml

<
SafeControl

Assembly="Sample.DisplayMessage, Version=1.0.0.0,
Culture=neutra
l, PublicKeyToken=null" Namespace="Sample.DisplayMessage"
TypeName="DisplayMessageWebPart" Safe="True"
/>



Step 7: Add your Web Part to the Web Part gallery

In order to add your Web Part to a Web Part page, you must add it to the gallery.

To add your Web

Part to the Web Part Gallery

1.

Navigate to the page on your SharePoint site where you want the Web Part to be accessible.

2.

In the Web Part page, click

Site Actions
, and select

Site Settings
.

3.

On the

Site Settings

page, click

Web Parts

under the

Galleries

head
ing.

4.

On the toolbar in the Web Part gallery, click

New
.

5.

In the

New Web Parts

list, check the box next
to

Sample.DisplayMessage.DisplayMessageWebPart

and click

Populate Gallery
.

6.

Your Web Part can now be added to any Web Part page.



Step 8: Add your Web Pa
rt to a Web Part Page

In this step, you import the Web Part to a page in any SharePoint site and test the custom property you
added to the Web Part. The following procedure explains the steps for adding the Web Part to a page and
changing the Display Messa
ge custom property.

To add and test your Web Part

1.

Navigate to the Web Part page on your SharePoint site where you want to add the Web Part.

2.

In the Web Part page, click

Site Actions
, and select

Edit Page
.

3.

In the Web Part zone where you want to add the

Displ
ayMessageWebPart
, click

Add a Web
Part
.

4.

On the

Add Web Parts

dialog, find the

Miscellaneous

category under

All Web Parts

and check
the box next to

DisplayMessageWebPart
. Click

Add
.

5.

To modify the text displayed on the Web Part, choose

Modify Shared Web Part

from the chrome
drop
-
down list.

6.

In the

DisplayMessageWebPart

properties pane, expand the

Miscellaneous

category and
change the

Display Message

value. Click

Apply
.

7.

Now the Web Part is displaying the user
-
defined value inside the Web Part.



Walkthrough: Cr
eating a Basic SharePoint Web Part

This programming task includes the steps for creating a basic custom Windows SharePoint Services Web
Part. It is a simple Web Part that allows you to change the Web Part’s

Title

property, which is a Windows
SharePoint Services

WebPart

base class property that sets the
text in the title bar of the Web Part.


Important:

Beginning with Windows SharePoint Services 3.0, the Windows SharePoint Services Web Part infrastructure
is built on top of the Microsoft ASP.NET 2.0 Web Part infrastructure and Web Parts that derive from

the
ASP.NET

WebPart

class are completely supported in Windows SharePoint Services. You should create
ASP.NET Web Parts whenever possible.

For more information about choosing the best Web Part base

class from which to derive, see

Developing
Web Parts in Windows SharePoint Services

in the Windows SharePoint Services Software Development Kit
(SDK). For more information about ASP.NET W
eb Parts, see the

Web Parts Control Set Overview

in the
ASP.NET documentation.



Prerequisites

Microsoft Visual Studio 2005

Windows SharePoint Services 3.0



Step 1: Create a Web Control Library

project

Web Parts are based on ASP.NET Web Form Controls. You create Web Parts in Microsoft Visual C# or
Microsoft Visual Basic by using the ASP.NET Web Control Library template.

To create a new Web Control Library project

1.

Start Visual Studio 2005.

2.

On the

File

menu, point to

New
, and then click

Project
.

3.

In the

New Project

dialog box, click

Visual C# Projects

or

Visual Basic Projects
, and then
select the

Web Control Library

template.

4.

Type

SimpleWebPart

as the name and specify the location for the project fi
les, and then click

OK
.



Step 2: Add a Reference to Microsoft.SharePoint.dll

To create a Web Part, you need to add a reference to the

Microsoft.SharePoint

assembly
(Microsoft.SharePoint.dll) in your Web Control Library project.

To add a reference to Micr
osoft.SharePoint.dll

1.

On the

Project

menu, click

Add Reference
.

2.

On the

.NET

tab, double
-
click

Windows SharePoint Services
.

3.

Click

OK
.



Step 3: Set the Version Number and set up partially trusted callers

By default, the

AssemblyVersion

property of your proj
ect is set to increment each time you recompile your
Web Part. A Web Part page identifies a Web Part with the version number that is specified in
the

web.config

file. With the

AssemblyVersion

property set to increment, if you recompile your Web
Part after
importing it into a Web Part page, the Web Part framework will look for the version number you
specified in the

web.config

file. If the version number does not match, an error will occur. To prevent the
version number of your Web Part from incrementing eac
h time you recompile, you need to set the version
number in the

AssemblyInfo

file.

Since you are creating signed code, you must also tell your assembly to allow partially trusted code calls. By
default, any strong
-
named assembly that does not explicitly op
t in to its use by partially trusted code will be
callable only by other assemblies that are granted full trust by security policy.

To set the version number and allow partially trusted callers

1.

In

Solution Explorer
, double
-
click the

AssemblyInfo

file

2.

Edit
the line:

C#

[assembly: AssemblyVersion(“1.0.*”)]

Visual Basic

<Assembly: AssemblyVersion(“1.0.*”)>

so that it reads:

C#

[assembly: AssemblyVersion(“1.0.0.0”)]

Visual Basic

<Assembly: AssemblyVersion(“1.0.0.0”>

3.

Add the following line to the top of the file
:

C#

using

System.Security;

Visual Basic

Imports

System.Security;

4.

Add the following line to the bottom of the file:

C#

[assembly: AllowPartiallyTrustedCallers]

Visual Basic

<Assembly: AllowPartiallyTrustedCallers()>



Step 4: Rename the Class and Namespac
e

If you are creating multiple Web Parts, you should generally use the same namespace across all of your Web
Parts. By default, the Web Control Library assigns the namespace the same name as your project. For this
example, we are using the arbitrary namesp
ace of

MyWebParts

for the

WebPart

class. After you create
the project, a blank class file is displayed. You can change the default class name of

WebCustomControl

to
easily identify your new Web Part.

To rename the class and namespace

1.

Rename the default cla
ss by selecting

WebCustomControl1

in

Solution Explorer
, right
-
click,
click

Rename
, and type

SimpleWebPart

as the file name.

2.

For C#, change the Web Part namespace by editing the line:

C#

namespace

SimpleWebPart

so that it reads:

C#

namespace

MyWebParts

3.

For
Visual Basic, right
-
click on the the

SimpleWebPart

project in the

Solution Explorer

and
click

Properties
. Replace the text in the

Assembly name
and

Root namespace

text boxes
to

MyWebParts.SimpleWebPart



Step 5: Add a Namespace Directive

To make it easier
to write a basic

WebPart

class, you should use the

using

directive in C# or
the

Imports

directive in Visual Basic to reference the following namespace in your code:



The

Microsoft.SharePoint.WebPartPages

namespace provides the types for Web Part pages, such as
the
Microsoft.SharePoint.WebPartPages.WebPart

class.

To add a namespace directive



Add the following

using

or

Imports

directive near the top of your code:

C#

usi
ng

Microsoft.SharePoint.WebPartPages;

Visual Basic

Imports

Microsoft.SharePoint.WebPartPages



Step 6: Inherit from the Web Part Class

By default, the Web Control Library template creates a custom control that inherits from
the

System.Web.UI.Control

class

(a parent class of both the ASP.NET and SharePoint

WebPart

classes).
To create a SharePoint Web Part, you should inherit from
the

Microsoft.SharePoint.WebPartPages.WebPart

base class.

To inherit from the Web Part base class.



Replace this line of code:

C#

public

class

SimpleWebPart : WebControl

Visual Basic

Public

Class

SimpleWebPart


Inherits

WebControl

with this line:

C#

public

class

SimpleWebPart : WebPart

Visual Basic

Public

Class

SimpleWebPart


Inherits

WebPart



Step 7: Use the RenderWebPart Meth
od

The

WebPart

base class seals the

Render

method of

System.Web.UI.Control

because the Web Part
infrastructure needs to control rendering the contents of a Web Part. For this reason, custom Web Parts
must override the

RenderWebPart

method of the

WebPart

ba
se class.

To use the RenderWebPart method.



Replace this line of code:

C#

protected

override
void

Render(HtmlTextWriter output)

Visual Basic

Protected

Overrides

Sub

RenderContents(
ByVal

output
as

HtmlTextWriter)

with this line:

C#

protected

override
void

Re
nderWebPart(HtmlTextWriter output)

Visual Basic

Protected

Overrides

Sub

RenderWebPart(
ByVal

output
as

HtmlTextWriter)



Step 8: Define the Logic and Rendering of your Web Part

After you complete the previous steps, you can define the logic and rendering f
or your Web Part. For this
part, we will write some basic ASP.NET code to create two controls: a text box and a button that will set
the

Title

property of the Web Part.

To define the logic and rendering of your Web Part

1.

Create two user interface objects by

adding the following code near the top of
the

SimpleWebPart

file.

C#

Button saveTitle;

TextBox newTitle;

Visual Basic

Public

saveTitle
as

Button

Public

newTitle
as

TextBox

2.

Create the button handling event by adding the following code inside the class.

C#

public

void

saveTitle_click(object sender, EventArgs e)

{


this
.Title = newTitle.Text;


try


{


this
.SaveProperties =
true
;


}


catch

(Exception ex)


{


this
.Title =
"Error: "

+ ex.Message;


}

}

Visual Basic

Pu
blic

Sub

saveTitle_Click(
ByVal

sender
As

Object
,
ByVal

e
As

EventArgs)


Me
.Title = newTitle.Text


Try


Me
.SaveProperties =
True


Catch

ex
As

Exception


Me
.Title =
"Error: "

& ex.Message


End

Try

End

Sub

3.

Override the

CreateChildCon
trols()

method by adding the following code inside the class.

C#

protected

override
void

CreateChildControls()

{


//Create text box


newTitle =
new

TextBox();


newTitle.Text =
""
;


Controls.Add(newTitle);



//Create button


saveTitl
e =
new

Button();


saveTitle.Text =
"Set Web Part Title"
;


saveTitle.Click +=
new

EventHandler(saveTitle_click);


Controls.Add(saveTitle);

}

Visual Basic

Protected

Overrides

Sub

CreateChildControls()


'Create text box


newTitle =
New

Text
Box()


newTitle.Text =
""


Controls.Add(newTitle)



'Create button


saveTitle =
New

Button()


saveTitle.Text =
"Set Web Part Title"


AddHandler

saveTitle.Click,
AddressOf

saveTitle_Click


Controls.Add(saveTitle)

End

Sub

4.

Replace the

Ren
derWebPart()

method with the following line of code.

5.

protected override void RenderWebPart(HtmlTextWriter output)

6.

{

7.


RenderChildren(output);

}

Visual Basic

Protected

Overrides

Sub

RenderWebPart(
ByVal

output
as

HtmlTextWriter)


RenderChildren(output
)

End

Sub



Step 9: Create a Valid Strong Name for the Assembly

Web Parts are designed to be distributed over the Internet or an intranet. For security reasons, when you
create a custom Web Part, you should give it a strong name to ensure that the Web Par
t can be trusted by
your users. For more information about strong naming, see

Deploying Web Parts in Windows SharePoint
Services

and also

Assembly Signing Frequently Asked Questions
.

To assign a strong name to an assembly

1.

In

Solution Explorer
, right
-
click on the

SimpleWebPart

project and click

Properties
.

2.

In the

SimpleWebPart

properties, click the

Signing

tab on the
left side.

3.

On the

Signing

tab, check the

Sign the assembly

checkbox.

4.

Select

New

in the

Choose a strong name key file

drop
-
down menu.

5.

In the

Create Strong Name Key

dialog, type

SimpleWebPartKey

and uncheck

Protect my key
file with a password
.

6.

Now, the assem
bly will be signed when it is built.



Step 10: Build Your Web Part

After you add all of the preceding code, you can build your sample Web Part.

To build your Web Part



On the

Build

menu, click

Build Solution
.



Step 11: Copy Your DLL to the Bin Directory

After the Web Part is built, you must copy the resulting DLL to the bin directory.

To copy your DLL to the bin directory

1.

On the file system, locate the

SimpleWebPart.dll

file. The default location for Visual Studio
2005 is

C:
\
Documents and Settings
\
UserNa
me
\
My Documents
\
Visual Studio
2005
\
Projects
\
SimpleWebPart
\
SimpleWebPart
\
bin
\
Debug
.

2.

Copy the

SimpleWebPart.dll

file from the output directory to the Web application root bin
directory. The default location of the Web application root for
is
C:
\
Inetpub
\
wwwroo
t
\
wss
\
VirtualDirectories
\
PortNumber
\
bin
.

For more information, see

How to: Find the Web Application Root
.



Step 12: Increase the Default Trust Level and Add a SafeControl Entry for your
Web Part

provides a SafeControls list to prevent users from arbitrarily adding server
-
side code within ASPX pages. The
SafeControls list is a list of approved controls and Web Parts specific to your SharePoint site that you have
designated as safe for invo
cation on any ASPX page within your site. This list is contained in
the

web.config
file in your Web application root. The local path contains the physical location of
the

web.config

file.

By default, the trust level for this server is

WSS_Minimal
, which doe
s not allow access to the Windows
SharePoint Services object model. For this Web Part to set the

SaveProperties

property, you must perform
o
ne of the following three actions:



Create a custom policy file for your assembly, or



Install your assembly in the global assembly cache, or



Increase the trust level for the entire virtual server.

In this example, you will increase the default trust from

WS
S_Minimal

to

WSS_Medium

in
the

web.config

file.


Note:

The

web.config

file is located in the folder where the virtual directory for the Web site runs. It is usually
located in the following directory:
c:
\
inetpub
\
wwwroot
\
wss
\
VirtualDirectories
\
PortNumber
,
but your administrator may have set up your directory differently and this may not be the location of the
file.

You can find the location of your

web.config

file by using the Internet Information Services (IIS) snap
-
in. The IIS snap
-
in is an administration

tool for IIS that has been integrated with other administrative
functions. To launch the IIS snap
-
in and locate the

web.config

file:

1.

Click

Start
, point to

Programs
, point to

Administrative Tools
, and click

Internet Information
Services (IIS) Manager
.

2.

Expa
nd the node that is the name of your computer, and expand the

Web Sites

item in the tree.

3.

Locate the web site that is running your Windows SharePoint Services installation (often it
is

Default Web Site
).

4.

Right
-
click and select

Properties
.

5.

Select the

Home D
irectory

tab.

To increase the default trust level and add a SafeControl entry for your Web Part

1.

Open the

web.config

file in the Web application root.

2.

In the

level

attribute of the

trust

section, change

WSS_Minimal

to

WSS_Medium
.

3.

In the

SafeControls

sectio
n of your

web.config

file, add a

SafeControl

entry for your custom
assembly as follows.

Xml

<SafeControl Assembly="SimpleWebPart, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=
PublicKeyToken
" Namespace="MyWebParts"
TypeName="SimpleWebPart" Safe="True"/>

4.

Replace the

PublicKeyToken

with the actual value for your Web Part's assembly. To determine the
correct

PublicKeyToken

for your Web Part, use the sn.exe command
-
line utility.

sn.exe
-
T
C:
\
inetpub
\
wwwroot
\
wss
\
VirtualDirectories
\
PortNumber
\
bin
\
SimpleWebPart
.
dll



Step 13: Create a DWP File to Deploy your Web Part

A Web Part definition file (.dwp) is a simple XML file that contains property settings for a single Web Part. To
import your Web Part into a Web Part page, simply upload the .dwp file. After upload
ing the Web Part, you
can display the Web Part by dragging it into one of the zones of the Web Part page.

Two properties are required in the .dwp file:

Assembly

and

TypeName
. However, to display a default
name and description for the Web Part after it is i
mported, you should also include
the

Title

and

Description

properties. If you want to set other Web Part properties during import, you can
also define them in a .dwp file. A .dwp file takes the following form.

Xml

<?xml version="1.0"?>

<WebPart xmlns="http
://schemas.microsoft.com/WebPart/v2">


<Assembly>
AssemblyName(with no .dll extension)
,


Version=
VersionNumber
, Culture=
Culture
,


PublicKeyToken=
PublicKeyToken
</Assembly>


<TypeName>
WebPartNameSpace.WebPartClassName
</TypeName>


<Title>
DefaultW
ebPartTitle
</Title>


<Description>
WebPartDescription
</Description>

</WebPart>

To create a DWP file

1.

Copy and paste the following XML into a new text file.

Xml

<?xml version="1.0"?>

<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">


<Assembly>Sim
pleWebPart, Version=1.0.0.0, Culture=Neutral,
PublicKeyToken=
PublicKeyToken
</Assembly>


<TypeName>MyWebParts.SimpleWebPart</TypeName>


<Title>My Simple Web Part</Title>


<Description>A simple Web Part</Description>

</WebPart>


Important:

You must r
eplace

PublicKeyToken

in the XML above with the public key token of your assembly.

2.

Save this file as

SimpleWebPart.dwp

in the bin directory of the Web application root.



Step 14: Import your Web Part into a Web Part Page

To use and test your Web Part, i
mport it into a Web Part page on a server that is running Windows
SharePoint Services or Microsoft Office SharePoint Server 2007.

To import your Web Part

1.

Navigate to the page on your SharePoint site where you want the Web Part to be accessible.

2.

In the Web
Part page, click

Site Actions
, and select

Site Settings
.

3.

On the

Site Settings

page, click

Web Parts

under the

Galleries

heading.

4.

On the toolbar in the Web Part gallery, click

Upload
.

5.

On the

Upload Web Part

page, click

Browse

and select the

.dwp

file that y
ou created.


Note:

This should be in

C:
\
inetpub
\
wwwroot
\
wss
\
VirtualDirectories
\
PortNumber
\
bin
\
.

6.

Click

OK
.

7.

Navigate back to the Web Part page. In the Web Part page, click

Site Actions
, and select

Edit
Page
.

8.

In your preferred zone, click

Add a Web Part

an
d check the box next to

My Simple Web Part

in
the dialog box. Click

Add
.

9.

After the Web Part is added to the zone, type some text in the text box and click

Set Web Part
Title

to test the Web Par



Walkthrough: Creating Connectable Web Parts in Windows
Share
Point Services

This programming task describes how to create two connectable SharePoint Web Parts: a Web Part that can
consume a single cell value and another Web Part that can provide a single cell value.


Important:

Beginning with Windows SharePoint Se
rvices 3.0, the SharePoint Web Part infrastructure is built on top of
the Microsoft ASP.NET 2.0 Web Part infrastructure and Web Parts that derive from the
ASP.NET

WebPart

class are completely suppo
rted in SharePoint, including the ASP.NET connection model.
Whenever possible, you should create ASP.NET Web Parts, and use the ASP.NET connection model to
connect your Web Parts.

For more information about choosing the best

WebPart

base class from which t
o derive, see

Developing
Web Parts in Windows SharePoint Services
. For more information about ASP.NET Web Parts and its
connection model, see

Web Parts Connections Overview

in the ASP.NET documentation.



About Connectable Web Parts

The SharePoint Web Part infrastructure provides a standardized set of interfaces called connection interfaces
that allow Web Parts to exchange informa
tion with each other at run time. For example, the List Web Part
that is built into Microsoft Windows SharePoint Services can provide (send) a row of data to any other Web
Part that can consume (receive) that row, such as a Web Part that implements a form
to display the row.

Because the Web Part infrastructure provides a standard set of connection interfaces, connectable Web Parts
can be developed by entirely different developers or companies to communicate with one another. A Web
Part that supports connect
ion interfaces can be connected by an end user with either Microsoft Office
SharePoint Designer 2007 or a Web browser. This allows end users to build sophisticated combinations of
Web Parts through a simple menu
-
driven user interface.

The Windows SharePoin
t Services connection classes and interfaces are implemented in
the

Microsoft.SharePoint.WebPartPages.Communication

namespace.

Connection Interfaces

Connection interfaces are paired events relevant to a specific item, such as a row in a list. The paired
interfaces form a communication bus between Web Parts that implement them. A connectable Web Part
raises an interface event to one or more connected pa
rts to make them perform an action. Interfaces are
paired as a provider to a consumer. Events from the provider get handled in the consumer and vice versa.
The following table briefly describes each pair of connection interfaces.

Connection interface pair

Description

ICellProvider
,
ICellConsumer

Connection interfaces for providing or consuming a
single value item, such as a cell or field.

IRowProvider
,
IRowConsumer

Connection interfaces for providing or consuming a
single row (or multiple rows) of values.

IListProvider
,
IListConsumer

Connection inter
faces for providing or consuming an
entire list.

IFilterProvider
,
IFilterConsumer

Connection interfaces for providing or consuming a
filter value. For example, the SharePoint List Web Part
supports
IListProvider
,

IRowProvider
,
and

IFilterConsumer
. Because

IRowProvide
r

can
connect to

IFilterConsumer
, two different SharePoint
Lists can be connected to one another. This allows one
list to filter the other connected list.

IParametersInProvider
,
IParametersInConsumer

The

IParameterIn

interfaces allow passing and
receivin
g of any set of arbitrary parameters between
Web Parts. These interfaces cover a situation where
the consumer Web Part owns the parameter list and
needs to communicate this to other Web Parts.

IParametersOutProvider
,
IParametersOutConsumer

The

IParamet
erOut

interfaces allow passing and
receiving of any set of arbitrary parameters between
Web Parts. These interfaces cover a situation where
the provider Web Part owns the parameter list and
needs to communicate this to other Web Parts.

Compatibility Rules

Web Parts can only be connected if they are compatible. Following are several compatibility rules which are
assessed by the Web Part infrastructure when determining whether two Web Parts can be connected. If the
Web Parts are found to be incompatible, the

Connection

menu item in the browser is dimmed and a tooltip
explains the reason for incompatibility.

Opposite Pairs

A connection interface can only connect with other compatible interfaces. The most basic compatibility rule
is that interfaces must be conn
ected as opposite pairs or connected through a transformer. Connecting as
opposite pairs means that a Web Part that implements the

IRowProvider

interface can connect with
another part that implements the

IRowConsumer

interface.

Transformers

In the case whe
re one Web Part needs to connect to another part that doesn’t have the exact same
interface, the Web Part infrastructure provides interface transformers, which help users connect two distinct
interfaces in a natural and transparent manner.

For example, a u
ser may want to connect a contact list to a picture viewer. However, the contact list only
has the

IRowProvider

interface and the picture viewer only has the

ICellConsumer

interface. To solve
this problem, an interface transformer is provided that allows t
hese two interfaces to connect to each other.

The following table shows the interface pairs that can be connected to one another through a transformer
and whether the connections require Microsoft SharePoint Designer 2007.

Transformer

Connect in
browser

Co
nnect in SharePoint
Designer

IRowProvider

to

ICellConsumer

Yes

Yes

IRowProvider

to

IFilterConsumer

Yes

Yes

IParametersOutProvider

to

IParametersInConsumer

No

Yes

IRowProvider

to

IParametersInConsumer

No

Yes

Cross
-
Page Connections

Some interfaces are a
llowed to connect to Web Parts on a different page. The behavior is similar to a
hyperlink.

You should understand the following about cross
-
page connections:



A Web page editor that is compatible with Microsoft Windows SharePoint Services, such as
SharePoin
t Designer required to author cross
-
page connections. However, once a cross
-
page
connection has been formed, it can be used by any supported Web browser at run time.



Only connectable Web Parts that have implementations designed to run on the server
(the

CanRunAt

method has a

Conn
ectionRunAt

value of

Server

or
ServerAndClient
) can establish
cross
-
page connections. Connections that are formed on the client side are not allowed to cross
Web Pages.

The following table shows the interfaces that can be connected across pages.

Source pag
e interface

Target page interface

IRowProvider

IFilterConsumer

IRowProvider

IParametersInConsumer

IFilterProvider

IFilterConsumer

IParametersOutProvider

IParametersInConsumer

IParametersInProvider

IParametersInConsumer

When working with cross
-
page We
b Part connections, you must do the following:



Pass

ConnectionRunAt
.Server or

ConnectionRunAt
.ServerAndClient to
the

runAtOptions

parameter of the

RegisterInterface

method.



Pass

true

to th
e

allowCrossPageConnection

parameter of the

RegisterInterface

method.



Implement the

GetInitEventArgs

method to provide specific informatio
n about data that is passed
through the connection interface.

Client and Server Connections

At any given time, Web Parts are allowed to run on the client or the server. Some Web Parts, if designed
accordingly, can detect the conditions under which they are

running and dynamically switch to run on the
client or the server. Web Parts can only be connected to other Web Parts running in the same location. For
example, server
-
side parts can only be connected to other server
-
side parts. Server
-
side parts cannot b
e
connected to client
-
side parts. The connection chain must be homogenous. If a part can dynamically switch
between client or server connections, the Web Part infrastructure will automatically pin the Web Part to be a
client
-
side or server
-
side part depend
ing upon the Web Part chain to which it is being connected.

Maximum Number of Connections

When registering an interface, the maximum number of connections to other Web Parts can be specified in
the

maxConnections

parameter of the
RegisterInterface

method. I
f the connection limit is exceeded on a
Web Part, it cannot be connected to other parts.

The options are 1 or unlimited.



Microsoft.Shar
ePoint.WebPartPages.WebPart.UnlimitedConnections

specifies that a connectable Web
Part can accept an unlimited number of connections to another Web Part.



Microsoft.SharePoint.WebPartPages.WebPart.LimitOneConnection

specifies that a connectable Web
Part can accept only one connection.

No Circular Connections

A Web Part cannot be connected to itself, either directly or through a chain of co
nnections.

Shared and Private Web Part Connections

A shared Web Part can be connected to a private Web Part, if the private Web Part is a consumer and the
shared Web Part supports an unlimited number of connections.

Program Flow

Connected Web Parts pass in
formation to each other by firing specific interface events. When a Web Part
implements an interface such as

ICellProvider
, it must override a number of methods. The firing of the
interface events is performed by the Web Part infrastructure calling into th
e overridden methods at
designated times. The following steps for creating connectable Web Parts define which methods need to be
overridden and the typical code that a Web Part author should use to do so.



Creating a Web Part that Implements the ICellPro
vider Interface

This programming task defines the process of creating a class that implements all of the necessary methods
and events for a connection interface using the
ICellProvider

interface. For a complete code example, refer
to the

ICellProvider

and

I
CellConsumer

source code samples at the end of these steps.

To start this programming task, perform the steps described in

Walkthrough: Creating a Basic SharePoint
Web Part

up to the steps

for "Defining the Rendering and Logic of Your Web Part."

Following are 11 high
-
level steps that you must complete to implement a connection interface for your Web
Part:

1.

Create the interface class.

2.

Declare events.

3.

Override the

EnsureInterfaces

method, and then call the

RegisterInterface
method.

4.

Override the

CanRunAt

method.

5.

Override the

PartCommunicationConnect
method.

6.

Override the

PartCommunicationIn
it
method.

7.

Override the

PartCommunicationMain
method.

8.

Override the

GetInitEventArgs

method.

9.

Implement the interface event handlers.

10.

Ov
erride the

RenderWebPart
method.

11.

Implement supporting methods.



Step 1: Create the interface class

Create a class that implements one of the

predefined connection interfaces. In this example, we'll implement