Advanced Web Part Development - Pdf 63

Advanced Web Part
Development
A
lthough basic Web Parts are useful for customizing the display of information and some
light system integration, they have some limitations. I noted, for example, that properties were
limited to simple values of types like String, Integer, and enumerations. Also, the Web Parts
you created in Chapters 5 and 6 were isolated from one another and could not take advantage
of Web Part connections. Additionally, all of my examples only operated as server-side code. In
this chapter, you’ll examine advanced Web Part concepts that allow you to overcome the limita-
tions found in the basic Web Part.
Client-Side Web Parts
When I began our discussion of Web Parts, I made it clear that they were essentially ASP.NET
controls running in a special infrastructure. This definition is significant because all of the
Web Parts you have written so far have been designed to operate on the server. They have relied
upon post-back processing to access data and integrate other systems. This fundamental pro-
cessing model is unchangeable in SharePoint Services; however, you can utilize some new
techniques to introduce client-side processing to your Web Parts.
Using ActiveX Controls
The most common reason to use client-side processing is to incorporate an ActiveX control
into your Web Part. In some cases, by using an ActiveX control, you can provide functionality
that is not easily created through server-side processing. A good example of such functionality
is found in the Office Web Components (OWC).
OWC is a set of ActiveX controls that implement spreadsheet and charting functionality
that is compatible with Office products like Excel. The controls have a rich interface that allows
end users to interact with data sources, pivot spreadsheets, and change chart characteristics.
This functionality is not present in ASP.NET and would be difficult to implement through
server-side processing.
You can include ActiveX controls in a Web Part by writing an appropriate <OBJECT> tag in
the RenderWebPart method. As far as the Web Part is concerned, <OBJECT> tags are no different
than any other HTML element. When the Web Part appears to the client, however, the refer-
enced ActiveX control will load into the portal. The following code shows an example of

End With
Using Script Files
In Listing 7-1, I showed you how to generate your own script code directly in the RenderWebPart
method. However, you can also create separate script files that can be accessed at runtime by
your Web Parts. There are two techniques for accessing such scripts: linking and embedding.
Linking a script file allows you to create your script in a separate file and put it on the web
server. When a Web Part references the script, it is loaded into the browser cache. All future
references to the script then utilize the cached code. Linking a script requires you to first cre-
ate the script in a separate text file. Once this file is created, it is placed under a special folder
and referenced in your Web Part.
To make a script available to Web Parts for linking, follow these steps:
1. Open the Windows Explorer, navigate to \inetpub\wwwroot, and create a new subfolder
named \wpresources.
2. In this folder, create a new folder with the name of the Web Part assembly (e.g.,
SPSPageView.Container).
3. Under the new folder, create another folder consisting of the Assembly, Version,
Culture, and PublicKeyToken (e.g., 1.0.0.0_en-us_eb3e58846fb2ac2b).
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT188
5750_c07_final.qxd 11/3/05 9:40 PM Page 188

Note
Although the correct format for the new folder is
version_culture_token
, you may leave out
the culture information when the culture is neutral; however, you must add a double underscore (e.g.,
1.0.0.0__eb3e58846fb2ac2b
).
4. Create a script file in a text editor.

Behind the scenes, SPS uses the Web Part infrastructure to determine which Web Parts on
a page are suitable for connection. Connectable Web Parts are then given a special Connections
item on their drop-down menu that lists all of the other Web Parts to which it can connect.
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT 189
5750_c07_final.qxd 11/3/05 9:40 PM Page 189
If you want to create connectable Web Parts that can be used in SPS, you must understand
how to integrate your Web Parts with the connection infrastructure.
Connection Interfaces
The primary mechanism for integrating Web Parts with the connection infrastructure is
through a set of interfaces. These interfaces expose methods and events that allow the con-
nection infrastructure to query your Web Parts for appropriate connection information and
provide notification when another Web Part wants to connect. The available interfaces sup-
port passing a single piece of data, a row of data, an entire list of data, or custom data sets
between Web Parts. Table 7-1 lists the available interfaces and their purposes.
Table 7-1. Connection Interfaces
Interface Purpose
ICellProvider Provides a single value to other Web Parts
ICellConsumer Consumes a single value from other Web Parts
IRowProvider Provides an entire row of data to other Web Parts
IRowConsumer Consumes an entire row of data from other Web Parts
IListProvider Provides an entire list to other Web Parts
IListConsumer Consumes an entire list from other Web Parts
IFilterProvider Provides a value for filtering to other Web Parts
IFilterConsumer Uses a provided value from other Web Parts for filtering a view
IParametersInProvider Provides arbitrary input values to other Web Parts
IParametersInConsumer Consumes arbitrary input values from other Web Parts
IParametersOutProvider Provides arbitrary output values to other Web Parts
IParametersOutConsumer Consumes arbitrary output values from other Web Parts

IParametersIn-Consumer FP/CPC FP/CPC FP/CPC
1
SPS: Connection creation allowed directly in SPS
2
FP: Connection creation allowed in Microsoft FrontPage
3
CPC: Cross-page connections allowed in Microsoft FrontPage
During the design of your Web Part, you determine the interfaces to implement based
on its intended use. Keep in mind that your Web Part must be easily understood by portal end
users. Your goal is to avoid the need for detailed training or help files associated with your Web
Part. To the greatest extent possible, the purpose of your Web Part should be understood through
its display and the options provided on the connection menu.
Once you have determined which interfaces will be implemented by your Web Part, you
are ready to begin development. You can start your Web Part using the same Web Part templates
that you used in earlier chapters. Although the Web Part templates have some specific templates
available just for connectable Web Parts, they are generally geared toward simple single-value
connections. You will find them lacking if you want to create more sophisticated Web Parts.
Regardless of how you start the project, you must specify the interfaces to implement in your
Web Part. All of the interfaces for connecting Web Parts are located in the Microsoft.SharePoint.

WebPartPages.Communication namespace. Declaring that a class implements an interface from
this namespace requires that every method and event in the interface be declared. Each of the
interfaces available for connecting Web Parts has a somewhat differing set of events and meth-
ods; therefore, you should be careful with the declarations. Listing 7-2 shows an example of
declaring the IRowProvider interface in VB .NET.
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT 191
5750_c07_final.qxd 11/3/05 9:40 PM Page 191
Listing 7-2. Declaring Interfaces

the Web Part infrastructure responds by querying both the provider and consumer Web Parts
to get a reference to interfaces they implement. This information allows the Web Part infra-
structure to begin using the interfaces to create the connection.
Once the Web Part infrastructure has access to the interfaces, the next thing it does is ask the
Web Parts whether they support connecting on the client, the server, or both. This information is
provided to the connecting Web Parts so that they can correctly prepare for the connection.
Once the Web Part architecture determines where the Web Parts run, it connects the Web
Parts. Each Web Part is notified that the connection has taken place and is passed relevant
information regarding the pending data transfer. This way each of the Web Parts can react to
the connection and prepare for the transaction.
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT192
5750_c07_final.qxd 11/3/05 9:40 PM Page 192
Once the Web Parts are connected, the infrastructure instructs the Web Parts to fire any
preparatory events. Typically, these events involve broadcasting schema information regard-
ing the transfer to the other Web Part. The provider part Web Part might broadcast a list of field
names that represent the columns in a row, or it may simply send a single field name associ-
ated with a cell depending upon the implemented interface. For its turn, the consumer part
will broadcast similar schema information to specify what data it is expecting to receive.
At this point in the process, the provider Web Part is waiting for some user interaction that
will signal the start of a transfer. Generally, this involves the selection of an item or row. Such a
selection causes the Web Part infrastructure to notify the provider part that the data transfer
has begun. The provider part then fires an event within the consumer part that sends the selected
data. When the consumer part receives the data, it responds by modifying its view in accordance
with its designed functionality. Once the transfer of data is complete, the Web Part infrastruc-
ture redraws both Web Parts. Figure 7-2 shows a diagram of the connection life cycle.
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT 193

The parameter that specifies whether data is transferred on
the client (ConnectionRunAt.Client), the server
(ConnectionRunAt.Server), or both
(ConnectionRunAt.ServerAndClient).
InterfaceObject Object A reference to the object that implements this interface
(typically Me or this).
ClientReference String A unique identifier used only for client connections. This
name should contain the token _WPQ_, which is replaced
at connection time with a guaranteed unique identifier.
MenuItem String The text that will appear in the connection menu.
Description String A description of the interface.
The ability to register an interface for the purpose of connecting Web Parts is subject to
code access security requirements. By default, Web Part connections are supported in both
the WSS_Minimal and WSS_Medium policies. If you use a custom policy, however, you will have to
add the permission as we discussed in Chapter 5. Because of the potential for an error, you should
call the RegisterInterface method inside of a try/catch block and trap for the SecurityException
class. Listing 7-3 shows an example of calling the RegisterInterface method using C#.
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT194
5750_c07_final.qxd 11/3/05 9:40 PM Page 194
Listing 7-3. Registering an Interface
public override void EnsureInterfaces()
{
try
{
RegisterInterface("MyInterface",
"ICellConsumer",
WebPart.UnlimitedConnections,
ConnectionRunAt.Server,

method passes along relevant information that each Web Part may care to track including a
reference to the other Web Part, the interface that is connected, and where the data transfer
will occur. Table 7-4 lists the arguments of the PartCommunicationConnect method.
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT 195
5750_c07_final.qxd 11/3/05 9:40 PM Page 195
Table 7-4. PartCommunicationConnect Arguments
Argument Type Description
InterfaceName String A friendly name for the interface. This should be the same
as the value you provided in the RegisterInterfaces
method.
ConnectedPart WebPart A reference to the other Web Part in the connection.
ConnectedInterfaceName String The friendly name of the interface on the other Web Part
in the connection.
RunAt Enumeration Specifies where the data transfer will take place.
When the PartCommunicationConnect method is called, your Web Part should validate all
of the information that it receives. This includes checking to see if the friendly interface name
sent in is the same as the one that was sent out when RegisterInterfaces was called. Addi-
tionally, you should call EnsureChildControl to force the CreateChildControls method to run.
This ensures that your user interface is ready to respond to the data transaction. Listing 7-4
shows an example of coding the PartCommunicationConnect method in VB .NET.
Listing 7-4. Receiving Connection Notification
Public Overrides Sub PartCommunicationConnect( _
ByVal InterfaceName As String, ByVal connectedPart As _
Microsoft.SharePoint.WebPartPages.WebPart, _
ByVal connectedInterfaceName As String, ByVal runAt As _
Microsoft.SharePoint.WebPartPages.Communication.ConnectionRunAt)
'Purpose: To inform this Web Part that the infrastructure has connected it to
'another part

convention that dictates events ending with the Init suffix are candidates for firing in the
PartCommunicationInit method. This convention makes it easier to decide how to code the
method. Listing 7-5 shows an example of a Web Part that implements ICellConsumer that
broadcasts schema information via the CellConsumerInit event.
Listing 7-5. Broadcasting Schema Information
public override void PartCommunicationInit()
{
if(m_connectionCount > 0)
{
CellConsumerInitEventArgs initArgs = new CellConsumerInitEventArgs();
initArgs.FieldName = myCellName;
initArgs.FieldDisplayName = myCellTitle;
CellConsumerInit(this, initArgs);
}
}
In many simple Web Parts, the broadcasting of schema information adds little value. If,
for example, a Web Part can only accept a Company Name field, it will be powerless to do any-
thing if it is connected to a Customer Name field instead. Because these situations are possible,
it is important to validate the schema information, but also to provide sufficient error handling
to deal with meaningless values when they are received. Often this is simply a matter of show-
ing no results in the consumer Web Part until a valid value is sent by the provider Web Part.
Exchanging Data
Once the Web Parts have broadcast their schema information, they are ready for the actual
data exchange. The Web Part infrastructure initiates this exchange by calling the
PartCommunicationMain method. This method allows Web Parts to fire any other events that
are necessary to complete the transaction.
Although it is possible for both a provider and consumer Web Part to fire events from the
PartCommunicationMain method, most often you will use it in a provider part to send the actual
CHAPTER 7


//Run the query
try
{
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter adapter = new SqlDataAdapter(strSQL,conn);
adapter.Fill(dataSet,"orders");
}
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT198
5750_c07_final.qxd 11/3/05 9:40 PM Page 198
catch(Exception x)
{
lblMessage.Text += x.Message + "<br>";
}
//Bind to grid
try
{
grdOrders.DataSource=dataSet;
grdOrders.DataMember="orders";
grdOrders.DataBind();
}
catch(Exception ex)
{
lblMessage.Text += ex.Message + "<br>";
}
}
After the data is transferred, both Web Parts will draw their outputs through the
RenderWebPart method. Whether or not the Web Part is involved in a connection does not
make a difference as to how the output is rendered. In fact, you should remember that all of

'This will be the field that consumes the filter.
'Make sure we are being called on the IFilter interface
If strInterfaceName = "FilterConsumer" Then
'Create an object to hold the field list
Dim objFilterConsumerInitEventArgs As New FilterConsumerInitEventArgs
'The field list is created as an array of Strings
Dim strFieldNames(2) As String
Dim strFieldTitles(2) As String
strFieldNames(0) = "comp"
strFieldNames(1) = "cust"
strFieldNames(2) = "ord"
strFieldTitles(0) = "Company"
strFieldTitles(1) = "Customer"
strFieldTitles(2) = "Order"
'Put the data in the event argument
objFilterConsumerInitEventArgs.FieldList = strFieldNames
objFilterConsumerInitEventArgs.FieldDisplayList = strFieldTitles
'Pass the object back
Return objFilterConsumerInitEventArgs
Else
Return Nothing
End If
End Function
Custom Tool Parts
Throughout your investigation of Web Parts, you have used properties to configure the parts
within SPS. The Web Parts you have created have supported fundamental types such as String
and Boolean. The tool pane in SPS automatically creates the appropriate user interface element—
called a tool part—for these basic properties in the tool pane. For example, the tool pane uses
a text box tool part for String properties and a check box tool part for Boolean properties.
There may be times, however, when you may want to create more complex properties.

toolParts(0) = objWebToolPart
toolParts(1) = objCustomProperty
Return toolParts
End Function
In order to create a custom tool part, you must override the default implementation of
GetToolParts and add your own part to the set of tool parts passed to the Web Part infrastruc-
ture. When you create your own tool part, you create a new class that inherits from the ToolPart
class. Inheriting from the ToolPart class allows you to add the new tool part to the set.
Listing 7-10 shows how the GetToolParts method would appear if you added a new tool part
based on a custom class named Tool.
Listing 7-10. Overriding the GetToolParts Method
Public Overrides Function GetToolParts() As ToolPart()
Dim toolParts(2) As ToolPart
Dim objWebToolPart As WebPartToolPart = New WebPartToolPart
Dim objCustomProperty As CustomPropertyToolPart = New CustomPropertyToolPart
toolParts(0) = objWebToolPart
toolParts(1) = objCustomProperty
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT 201
5750_c07_final.qxd 11/3/05 9:40 PM Page 201
'This is where we add our tool part
toolParts(2) = New Tool
Return toolParts
End Function
Creating a Tool Part
As I said earlier, to create a custom tool part, you need to build a new class that inherits from
the ToolPart class. Because a tool part is essentially a specialized Web Part that runs in the tool
pane of SPS, you will find that you use many of the same skills to build a tool part that you
used previously to build Web Parts. You can begin your tool part with a simple class definition

the user cancels an action or if there is a validation error you need to report to the user. The
following code shows a simple example.
CHAPTER 7

ADVANCED WEB PART DEVELOPMENT202
5750_c07_final.qxd 11/3/05 9:40 PM Page 202


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status