Sunteți pe pagina 1din 31

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart White Paper

Published: 9/2/2004

Contents
Introduction...........................................................................................................1 Getting Started ......................................................................................................1 Binary Streaming Chart ...........................................................................................2 Implementing the chart .......................................................................................2 Create the basic web form project.......................................................................2 Add the chart to the project ...............................................................................2 Connecting the chart to an XML file .....................................................................3 Enabling Binary Streaming .................................................................................5 Connecting the image web part ..........................................................................8 Passing Parameters via Web Part Connections........................................................... 10 Setup ........................................................................................................... 10 Create the web part assembly .......................................................................... 10 Create an installation project for the web parts ................................................... 10 Strong name the web part assembly ................................................................. 12 Edit the DWP files to reference the public key ..................................................... 12 Install the test web parts ................................................................................. 13 Add the web parts to a SPS page ...................................................................... 14 Passing parameters to the Dundas Chart............................................................ 15 Rendering a chart based on Web Part parameters................................................ 19 Rendering a chart in the Consumer web part ...................................................... 23 Enabling the chart to handle parameters ............................................................ 25 Summary and Close ........................................................................................ 27 Installing the Sample Code .................................................................................... 27 Configure the project as an application in IIS...................................................... 27 Troubleshooting.................................................................................................... 29 Additional Resources ............................................................................................. 29 About the Author .................................................................................................. 29

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart


White Paper
Published: 9/2/2004
For the latest information, please see http://www.dundas.com

Introduction
Effective corporate portals convey a wealth of information in a concise presentation that employees from C-Level executives down to front line knowledge workers can view and act on. Like the dashboard of an airplane, these digital dashboards present critical corporate information that can be acted on to drive the business of the enterprise. A key component of the dashboard is the charting of critical information and creation graphical indicators that convey the overall health of the corporation. Dundas charts enable the creation of the charts necessary for viewing enterprise information. Microsoft SharePoint Portal Server (SPS) enables the creation of corporate portal sites for collaboration. Personal sites enable users to create a custom dashboard view that combines both tactical and strategic information into a view that drive business decisions.

Getting Started
All the examples in this white paper are based on Microsoft Visual Studio 2003. You may download and install the evaluation version of Dundas Web Chart from www.dundas.com. The examples in this white paper have been tested with Dundas Chart Version 3.6.0.1634 (DundasWebChart.dll)

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Binary Streaming Chart


The first example will produce an ASP.Net page that will render a chart as a binary stream. The page can then be referenced by an image web part that renders the chart in a SharePoint web part page.

Implementing the chart


To create a chart as a binary stream you will first create a chart as you normally do with either the Dundas Chart Wizard, or through code. Our example will consume an XML file as the data source. Create the basic web form project

1. In Visual Studio choose File | New | Project 2. In the New Project dialog choose Visual C# Projects from the Project Types list. 3. From the Templates list choose ASP .NET Web Application. 4. In the Location edit box enter the desired location and name for your project (e.g. http://localhost/TestChart). 5. Click OK to create the project.
Add the chart to the project Visual Studio will create the project and open the default page WebForm1.aspx in HTML mode. We will add the Dundas Chart to the design page and then edit the appropriate properties to enable binary streaming.

1. Switch the form into design view by choosing View | Design. 2. From the toolbox, drag and drop a Dundas Chart control onto the page. 3. The Dundas Chart & Data Wizard will open. Click Finish. 4. Save the project and run it to test the basic functionality.
Note: If you receive the following error. Access to the path "c:\inetpub\wwwroot\TestChart\ChartPic_000001.jpeg" is denied You need to enable access to the local directory so that the application can write out the temporary image file. This is only for testing, since we will switch to binary streaming mode eliminating the need to create a temporary image. Details for providing access to your project are in the Dundas Web Control ReadMe.html file.

You should see something like the screen shot below.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Not terribly interesting, but an important first step for this demonstration. Close the browser and return to Visual Studio. Connecting the chart to an XML file

1. If you havent already done so, copy the files topten.xml and topten.xsd into your project folder. 2. In Visual Studio choose View | Code. 3. Locate the section:
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here }

4. Replace this section with the following:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

private void Page_Load(object sender, System.EventArgs e) { // Resolve the address to the XML document string fileNameString = this.MapPath("."); string fileNameSchema = this.MapPath("."); fileNameString += "\\topten.xml"; fileNameSchema += "\\topten.xsd"; // Initializes a new instance of the DataSet class DataSet custDS = new DataSet(); // Read XML schema into the DataSet. custDS.ReadXmlSchema( fileNameSchema ); // Read XML schema and data into the DataSet. custDS.ReadXml( fileNameString ); // Initializes a new instance of the DataView class DataView firstView = new DataView(custDS.Tables[0]); //Remove the default Series Chart1.Series.Clear(); //Create the DataSeries Chart1.Series.Add("Last Year"); Chart1.Series.Add("This Year"); // since the DataView implements and IEnumerable, pass the // reader directly into the DataBind method with the name // of the Columns selected in the query Chart1.Series["Last Year"].Points.DataBindXY(firstView, "name",firstView, "lyamount"); Chart1.Series["This Year"].Points.DataBindXY(firstView, "name",firstView, "tyamount"); } Note: The character represents a line wrap that occurred due to the formatting of the article. These characters should be removed and the code should be on one line.

5. Run the application and you should see a chart similar to the following:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

6. Close the browser window and return to Visual Studio.


Enabling Binary Streaming So far we have simply created a chart and connected it to an XML file. In the next steps we will enable binary streaming and create a simple HTML file that will call our project page as if it were an image.

1. Choose the WebForm1.aspx file in Visual Studio, if you are not in design mode choose View | Design. 2. Select the chart object and in the property editor locate the Image section and the RenderType property. 3. Change the property from ImageTag to BinaryStreaming. The result of this change is that the chart will be streamed to the browser as binary data. The browser does not know how to handle the data without HTML tags to format the data. If you run the project now you will see something like the following:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Dont despair! This is exactly what you want to see. What we need to do now is simply create a page that will test our binary streaming page. Close the browser window and return to Visual Studio.

4. In the Solution Explorer right click on the project folder and choose Add | Add HTML Page 5. In the Add New Item dialog rename the new page to TestChart.htm. 6. Click OK to create the page. 7. Just below the <body> tag add the following code:
<img src=WebForm1.aspx />

8. In the Solution Explorer right click on the new TestChart.htm file and choose Set As Start Page. 9. Click on the tab for WebForm1.aspx and if you are not in HTML mode choose View | HTML Source. 10. Your HTML page should look like the following if you have not modified the code:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

<%@ Register TagPrefix="dcwc" Namespace="Dundas.Charting.WebControl" Assembly="DundasWebChart" %> <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="TestChart.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="http://schemas.microsoft.com /intellisense/ie5" name="vs_targetSchema"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <DCWC:CHART id="Chart1" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 24px" runat="server" Palette="Pastel" RenderType="BinaryStreaming"> <Legends> <dcwc:Legend Name="Default"></dcwc:Legend> </Legends> <Series> <dcwc:Series Name="Series1" BorderColor="64, 64, 64" ShadowOffset="1"></dcwc:Series> <dcwc:Series Name="Series2" BorderColor="64, 64, 64" ShadowOffset="1"></dcwc:Series> </Series> <ChartAreas> <dcwc:ChartArea Name="Default"></dcwc:ChartArea> </ChartAreas> </DCWC:CHART></form> </body> </HTML>

11. Since we only want the chart object returned we need to remove all references to HTML. Leave the register tags at the top of the page and then remove all code that is not contained between the <DCWC:CHART > and </DCWC:CHART> tags. When you are done the code for the page will look like the following:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

<%@ Register TagPrefix="dcwc" Namespace="Dundas.Charting.WebControl" Assembly="DundasWebChart" %> <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="TestChart.WebForm1" %> <DCWC:CHART id="Chart1" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 24px" runat="server" Palette="Pastel" RenderType="BinaryStreaming"> <Legends> <dcwc:Legend Name="Default"></dcwc:Legend> </Legends> <Series> <dcwc:Series Name="Series1" BorderColor="64, 64, 64" ShadowOffset="1"></dcwc:Series> <dcwc:Series Name="Series2" BorderColor="64, 64, 64" ShadowOffset="1"></dcwc:Series> </Series> <ChartAreas> <dcwc:ChartArea Name="Default"></dcwc:ChartArea> </ChartAreas> </DCWC:CHART></form>

12. Save the file and run the project and you should see the following:

Notice that the URL is a reference to an HTML page. The HTML page is calling our ASPX page as if it were an image. The ASPX page is collecting the data and rendering the chart. Connecting the image web part The hard part is over. You now have a chart that displays the data that you are interested in as a graphic. To view this chart in a web part follow the following steps.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

1. Open a browser window to the SharePoint Portal page that you want to contain your chart. 2. Choose Modify Shared Page | Add Web Parts | Browse. 3. Locate the Image Web Part in the Web Part List. Drag and drop am image web part into a web part zone. 4. Click open the tool pane in the text of the web part to open the Image Web Part property editor. 5. Edit the Image Link property to create the link to the binary streaming aspx file (e.g. http://localhost/TestChart/WebForm1.aspx).
Note: Clicking the Test Link will open a browser that displays the binary stream as indicated above.

6. Click OK to close the property editor and your browser should refresh and display the chart.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Passing Parameters via Web Part Connections


Setup If you do not have the web part project templates installed in Visual Studio 2003 you can download and install the web part templates for Visual Studio 2003 from Microsoft (http://www.microsoft.com/downloads/details.aspx?familyid=cac3e0d2bec1-494c-a74e-75936b88e3b5&displaylang=en) Create the web part assembly

1. In Visual Studio choose File | New | Project 2. In the New Project dialog select the Visual C# Projects folder, in the templates section choose Web Part Library. 3. Provide a name for your assembly like ChartWebParts, and choose a Location for the project files. 4. Click OK to create the project. 5. In the new project right click the WebPart1.cs file and choose Delete. 6. Right Click WebPart1.dwp and choose Delete. 7. Right click the project file and choose Add | Add New Item 8. In the Add New Item dialog choose Consumer Web Part. Rename the file to myConsumerWebPart.cs. 9. Right click the project file and choose Add | Add New Item 10. In the Add New Item dialog choose Provider Web Part. Rename the file to myProviderWebPart.cs. 11. Right click the project file and choose Add | Add New Item 12. In the Add New Item dialog choose Web Part DWP. Rename the file to myConsumerWebPart.dwp. 13. Right click the project file and choose Add | Add New Item 14. In the Add New Item dialog choose Web Part DWP. Rename the file to myProviderWebPart.dwp. 15. Right click the project and choose Build. The project should build without error.
Create an installation project for the web parts

1. Right click the solution and choose Add | New Project 2. In the Add New Project dialog choose the Setup and Deployment Projects folder, from the templates choose Cab Project. 3. In the name field provide a meaningful name like ChartWebParts.Setup. 4. Specify the Location for your project. 5. Right click the setup project and choose Add | Project Output.
Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

6. In the Add Project Output Group dialog the Project list should display the web part project. From the output types choose Content Files. 7. Click OK. 8. Right click the setup project and choose Add | Project Output. 9. In the Add Project Output Group dialog the Project list should display the web part project. From the output types choose Primary Output. 10. Click OK. 11. Select the Manifest.xml file, in the property editor change the Build Action property to content. Repeat this step on each of the dwp files: myConsumerWebPart.dwp and myProviderWebPart.dwp. 12. Open the manifest.xml file in Visual Studio. This file is used by the installer to point to our web part dwp files. The <DwpFiles> section will look like this:
<DwpFiles> <DwpFile FileName="WebPart1.dwp"/> </DwpFiles>

Edit the section to look like this:


<DwpFiles> <DwpFile FileName="myConsumerWebPart.dwp"/> <DwpFile FileName="myProviderWebPart.dwp"/> </DwpFiles>

13. If there is a <ClassResources> section:


<ClassResources> <ClassResource FileName=""/> </ClassResources>

14. Remove the section. 15. Save and close the manifest file.
To facilitate installation of the web parts we will add our assembly to the Global Assembly Cache (GAC). In order to comply with the security standards enforced by SharePoint and Windows Server 2003 you must strong name your assembly before you add it to the GAC. The process involves creating a strong name key (SNK) file and then compiling the key into the assembly by referencing the file from the projects AssemblyInfo.cs file.

1. Open a window to the Visual Studio command line by choosing Start | All Programs | Microsoft Visual Studio .Net 2003 | Visual Studio Tools | Visual Studio .Net 2003 Command Prompt. 2. In the command window type c: [enter] then cd\ [enter]. The prompt should now read C:\>. 3. On the command line type:
sn -k ChartWebParts.snk

4. The Response should be:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Microsoft (R) .NET Framework Strong Name Utility Version 1.1.4322.573 Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. Key pair written to ChartWebParts.snk

5. The public key token is needed to complete the installation of the web part. To extract the public key token from the snk file and store it in a text file for later reference type the folloing on the command line:
sn t ChartWebParts.snk > myKeyFile.txt

6. Open the text file and you should see an entry similar to the following, though the token will be different.
Microsoft (R) .NET Framework Strong Name Utility Version 1.1.4322.573 Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. Public key token is 1cbdc6f47a0071a8

Strong name the web part assembly Now that we have all of the necessary components created we have to assemble all of the pieces and test out installation.

1. To create a reference to the key file; open the file AssemblyInfo.cs in Visual Studio. 2. Locate the line:
[assembly: AssemblyKeyFile("")]

3. Change the line to reference the snk file in the project directory.
[assembly: AssemblyKeyFile("C:\\ChartWebParts.snk")]

4. Build the project to ensure that the file references are valid. Correct any errors that are raised.
Edit the DWP files to reference the public key

1. In Visual Studio open the two DWP files (myConsumerWebPart.dwp and myProviderWebPart.dwp) for editing. 2. Each DWP file will initially look like this:
<?xml version="1.0" encoding="utf-8"?> <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" > <Title></Title> <Description></Description> <Assembly>ChartWebParts</Assembly> <TypeName></TypeName> </WebPart>

3. Edit the Title, Description, Assembly, and TypeName elements to reflect the values necessary for our project. The most important section is the <Assembly> element. This section is case sensitive. It takes the following form:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

<Assembly>{Assembly Name}, Version={Version from AssemblyInfo file}, Culture={Neutral unless you changed it}, PublicKeyToken={Token from myKeyFile.txt created earlier} </Assembly>

4. So when you are done editing the myProviderWebPart.dwp file should look like this:
<?xml version="1.0" encoding="utf-8"?> <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" > <Title>Test Provider Web Part</Title> <Description>Provider web part test</Description> <Assembly>ChartWebParts, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=1cbdc6f47a0071a8</Assembly> <TypeName>ChartWebParts.myProviderWebPart</TypeName> </WebPart>

5. The myConsumerWebPart.dwp file should look like this:


<?xml version="1.0" encoding="utf-8"?> <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" > <Title>Test Consumer Web Part</Title> <Description>Consumer web part test</Description> <Assembly>ChartWebParts, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=1cbdc6f47a0071a8</Assembly> <TypeName>ChartWebParts.myConsumerWebPart</TypeName> </WebPart> Note: If you are cutting and pasting the code from this article you still MUST change the PublicKeyToken property to match the token generated by your computer or the installation will fail.

6. Build the solution to create the web part library and the installation CAB file. Resolve any errors that arise before proceeding.
Install the test web parts The web parts can be installed to the SharePoint Portal Server or Windows SharePoint Services virtual server of your choice. The tool to perform the installation is buried in the common files directory for Windows SharePoint Services usually located on system drive of the web server hosting SharePoint.

1. Open a command window to:


C:\Program Files\Common Files\Microsoft Shared\web server extensions\60\BIN

2. This directory should contain a application file named STSADM.EXE. 3. STSADM facilitates the addition of web parts through the addwppack command line switch. You must provide the path to the CAB file as part of the command line parameters through the filename switch. 4. To install the web parts and add the assembly to the GAC at the same time, execute the following command from the command line:
stsadm -o addwppack -filename C:\Projects\ChartWebParts\ ChartWebParts.Setup\Debug\ChartWebParts.Setup.CAB -globalinstall -force

5. The result should be:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

chartwebparts.setup.cab: Deploying to http://gator:100/. Operation completed successfully.

6. If not address the errors and retry the installation.


Add the web parts to a SPS page

1. Open a browser window and browse to the SharePoint server where installed the web parts. 2. Choose Modify Shared Page | Add Web Parts | Browse. 3. Click the Virtual Server Gallery link to view the web parts for this virtual server. 4. Locate the Test Provider Web Part and Test Consumer Web Part in the Web Part List (you may have to click next to locate the web parts). 5. Drag and drop the Test Consumer Web Part into a web part zone. 6. Drag and drop the Test Provider Web Part into a web part zone.
Note: If you receive the following error: A Web Part or Web Form Control on this Web Part Page cannot be displayed or imported because it is not registered on this site as safe. Recheck the previous instructions and confirm that you followed the directions for naming and installing the web parts exactly.

7. If you add the parts one on top of the other you should see something like the following:

8. Click the button on the Consumer web part and choose Connections | Cell Consumer | Test Provider Web Part. 9. Click the Part. button on the Provider Web Part and choose Modify Shared Web

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

10. In the property pane open the Miscellaneous section and edit the Text property by entering Hello from the provider web part. 11. Click OK to close the property editor. 12. The connections property allows one web part to pass data to another web part. The Consumer Web Part is listening for a string. The provider Web Part provides the string in the form of the Text property. The web site should refresh and display the following:

If you have gotten this far I am sure you are wondering what all this has to do with creating a connected web part for imaging. Well, we have been laying the foundation so that you can develop two web parts that talk to one another. In the next section well add code to our web parts to pass parameters from one part to the other and render the chart based on the parameters passed by the web part. Passing parameters to the Dundas Chart In the example above we connected two web parts and passed a simple parameter. In the next exercise well pass an integer parameter from the provider to the consumer. In the consumer part well pass the parameter to the chart producing aspx page and render a different chart based on the parameter from the web part. Add an integer property to the web part

1. In Visual Studio open myProviderWebPart.cs and locate the following code. This is the property definition for the Text property that we passed earlier.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

const string _defaulttext = ""; private string text=_defaulttext; [Browsable(true), Category("Miscellaneous"), DefaultValue(_defaulttext), Description(""), FriendlyName("Text"), WebPartStorageAttribute(Storage.Personal)] public string Text { get { return text; } set { } }

text = value;

2. On the line below the Text property insert the following code:
const int _customerID = -1; private int customerID=_customerID; [Browsable(true), Category("Miscellaneous"), DefaultValue(_customerID), Description(""), FriendlyName("Customer ID"), WebPartStorageAttribute(Storage.Personal)] public int CustomerID { get { return customerID; } set { } }

customerID = value;

3. This code will create a CustomerID property in the Provider web part. Copy the code and paste it into the same section of the Consumer web part. 4. In the Consumer web part locate the RenderWebPart method. The method should look like the following:
protected override void RenderWebPart(HtmlTextWriter output) { output.Write(SPEncode.HtmlEncode(Text)); }

5. Add a line to render the CustomerID to ensure that the web parts are talking to one another.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

protected override void RenderWebPart(HtmlTextWriter output) { output.Write(SPEncode.HtmlEncode("CustomerID = " + CustomerID.ToString())); }

6. Now we have to configure the communications between the web parts to pass the CustomerID property rather than the Text property. In the Consumer web part locate the CellReady method.
public void CellReady(object sender, CellReadyEventArgs cellReadyArgs) { //Set the label text to the value of the "Cell" //that was passed by the Provider if(cellReadyArgs.Cell != null) { Text = cellReadyArgs.Cell.ToString(); } }

7. Change the assignment from the Text property to the CustomerID property.
public void CellReady(object sender, CellReadyEventArgs cellReadyArgs) { //Set the label text to the value of the "Cell" //that was passed by the Provider if(cellReadyArgs.Cell != null) { CustomerID = Convert.ToInt32(cellReadyArgs.Cell.ToString()); } }

8. We should rename the data to provide a better user experience. Locate the cellName declaration.
private string _cellName = "Cell Data";

9. Change this to reference Customer ID.


private string _cellName="Customer ID";

10. In the Provider web part we need to send the CustomerID property rather than the Text property. Locate the PartCommunicationMain method. It should look like the following:
public override void PartCommunicationMain() { //If there is a listener, send CellReady event if (CellReady != null) { //Need to create the args for the CellProviderInit event CellReadyEventArgs cellReadyArgs = new CellReadyEventArgs(); //Set the Cell to the value of the TextBox text //This is the value that will be sent to the Consumer cellReadyArgs.Cell = Text; //Fire the CellReady event. //The Consumer will then receive the Cell value CellReady(this, cellReadyArgs);

11. Change the assignment of the Text property to the CustomerID property.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

public override void PartCommunicationMain() { //If there is a listener, send CellReady event if (CellReady != null) { //Need to create the args for the CellProviderInit event CellReadyEventArgs cellReadyArgs = new CellReadyEventArgs(); //Set the Cell to the value of the TextBox text //This is the value that will be sent to the Consumer cellReadyArgs.Cell = CustomerID; //Fire the CellReady event. //The Consumer will then receive the Cell value CellReady(this, cellReadyArgs);

12. Lastly, lets provide a better name for the data that were passing. Locate the declaration for the Cell Name:
private string _cellName="Cell Data";

13. Change the name to Customer ID.


private string _cellName="Customer ID";

14. Build the project and address any build errors. 15. Reinstall the web part by using the command line tool STSADM as indicated earlier. 16. After you have successfully installed the new web parts, open a browser to the page where you installed them and you should see that the consumer web part is displaying the default CustomerID of -1.

13. Click the Part.

button on the Provider Web Part and choose Modify Shared Web

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

14. In the property pane open the Miscellaneous section and edit the CustomerID property by entering 1. 15. Click OK to close the property editor. The browser should refresh and display CustomerID = 1.
Rendering a chart based on Web Part parameters

1. In Visual Studio open myProviderWebPart.cs. Locate the class definition line:


public class myProviderWebPart : Microsoft.SharePoint.WebPartPages.WebPart, ICellProvider {

2. Add the following variable references:


public class myProviderWebPart : Microsoft.SharePoint.WebPartPages.WebPart, ICellProvider { LinkButton lbCustomer = null; Literal litBR = null;

3. Locate the RenderWebPart method and change it as follows:


protected override void RenderWebPart(HtmlTextWriter output) { //Write a header output.Write(SPEncode.HtmlEncode("Top 5 Customers")); output.RenderBeginTag(HtmlTextWriterTag.Hr); output.RenderEndTag(); //Render the web child controls RenderChildren(output); //Write the text property output.Write(SPEncode.HtmlEncode(Text)); }

4. Below the RenderWebPart method add the CreateChildControls method.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

protected override void CreateChildControls () { //Carter Industries //Create the Customer Link Button lbCustomer = new LinkButton(); //Create the text string for display lbCustomer.Text = SPEncode.HtmlEncode("Carter Industries"); //Create the CustomerID Parameter lbCustomer.CommandArgument = SPEncode.HtmlEncode("1"); lbCustomer.CommandName = "CustomerID"; lbCustomer.Command += new CommandEventHandler(lbCustomer_Command); //Add the Link Button to the controls array Controls.Add(lbCustomer); litBR = new Literal(); litBR.Text = "<BR>"; Controls.Add(litBR); //Create the Customer Link Button lbCustomer = new LinkButton(); //Create the text string for display lbCustomer.Text = SPEncode.HtmlEncode("Napa Auto Parts"); //Create the CustomerID Parameter lbCustomer.CommandArgument = SPEncode.HtmlEncode("2"); lbCustomer.CommandName = "CustomerID"; lbCustomer.Command += new CommandEventHandler(lbCustomer_Command); //Add the Link Button to the controls array Controls.Add(lbCustomer); litBR = new Literal(); litBR.Text = "<BR>"; Controls.Add(litBR); //Create the Customer Link Button lbCustomer = new LinkButton(); //Create the text string for display lbCustomer.Text = SPEncode.HtmlEncode("Claymoore Mines"); //Create the CustomerID Parameter lbCustomer.CommandArgument = SPEncode.HtmlEncode("3"); lbCustomer.CommandName = "CustomerID"; lbCustomer.Command += new CommandEventHandler(lbCustomer_Command); //Add the Link Button to the controls array Controls.Add(lbCustomer); litBR = new Literal(); litBR.Text = "<BR>"; Controls.Add(litBR); //Create the Customer Link Button lbCustomer = new LinkButton(); //Create the text string for display lbCustomer.Text = SPEncode.HtmlEncode("Springsteen Packaging"); //Create the CustomerID Parameter lbCustomer.CommandArgument = SPEncode.HtmlEncode("4"); lbCustomer.CommandName = "CustomerID"; lbCustomer.Command += new CommandEventHandler(lbCustomer_Command); //Add the Link Button to the controls array Controls.Add(lbCustomer); litBR = new Literal(); litBR.Text = "<BR>"; Controls.Add(litBR); //Create the Customer Link Button lbCustomer = new LinkButton(); //Create the text string for display
Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

lbCustomer.Text = SPEncode.HtmlEncode("Gentry Collections"); //Create the CustomerID Parameter lbCustomer.CommandArgument = SPEncode.HtmlEncode("5"); lbCustomer.CommandName = "CustomerID"; lbCustomer.Command += new CommandEventHandler(lbCustomer_Command); //Add the Link Button to the controls array Controls.Add(lbCustomer); litBR = new Literal(); litBR.Text = "<BR>"; Controls.Add(litBR); //Create the Customer Link Button lbCustomer = new LinkButton(); //Create the text string for display lbCustomer.Text = SPEncode.HtmlEncode("Show Top Ten"); //Create the CustomerID Parameter lbCustomer.CommandArgument = SPEncode.HtmlEncode("0"); lbCustomer.CommandName = "CustomerID"; lbCustomer.Command += new CommandEventHandler(lbCustomer_Command); //Add the Link Button to the controls array Controls.Add(lbCustomer); litBR = new Literal(); litBR.Text = "<BR>"; Controls.Add(litBR); }

5. Add a common event handler for our LinkButtons. On the line below the CreateChildControls method add the following event handler.
private void lbCustomer_Command(object sender, CommandEventArgs e) { switch(e.CommandName) { case "CustomerID": // Test whether the command argument is an int. try { CustomerID = Convert.ToInt32(e.CommandArgument.ToString()); } catch (Exception ex) { Text = ex.Message; } break; default: // The command name is not recognized. break;

6. Build the project and address any errors that may arise. Install the web parts as before and open the page in a browser. You should see a result like the following:

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

7. Notice the CustomerID in the consumer web part, it is currently set to the default value we entered in Visual Studio. Clicking the link for Claymoore Mines activates the event handler setting the CustomerID property to 3.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Rendering a chart in the Consumer web part

1. In Visual Studio open myConsumerWebPart.cs and locate the Text property. Insert the following property declaration to create a property to hold the URL to the chart page.
const string _chartPageURL = ""; private string chartPageURL=_chartPageURL; [Browsable(true), Category("Miscellaneous"), DefaultValue(_chartPageURL), Description(""), FriendlyName("Chart Page URL"), WebPartStorageAttribute(Storage.Personal)] public string ChartPageURL { get { return chartPageURL; } set { chartPageURL = value; } }

2. Locate the RenderWebPart method and modify it to render an image tag. 3.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

protected override void RenderWebPart(HtmlTextWriter output) { output.Write(SPEncode.HtmlEncode("CustomerID = " + CustomerID.ToString())); }

4. Change the method to render an image tag before the CustomerID property and pass the CustomerID as a parameter to the chart page.
protected override void RenderWebPart(HtmlTextWriter output) { output.Write(SPEncode.HtmlEncode("CustomerID = " + CustomerID.ToString())); output.Write("<br>"); output.Write("<img alt=\"Customer ID: " + CustomerID.ToString() + "\" src=\"" + ChartPageURL + "?CustomerID=" + CustomerID.ToString() + "\">"); }

5. Build the project and install the web part. Browse to your test page and you should see something like the following:

6. The image link is broken because we have not provided the ChartPage URL property value. Click the button on the Consumer web part and choose Modify Shared Web Part. 7. Open the Miscellaneous property section and edit the Chart Page URL property to point to the chart page that we created earlier. For example: http://localhost/TestChart/WebForm1.aspx 8. Click OK to close the property editor and you should see the chart.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

9. Hover over the chart image and you should see the alt text Customer ID: and the currently selected CustomerID from the Provider web part. Try clicking another customer from the Provider web part and after the browser refreshes, you should see the alt text change to reflect the CustomerID of the customer you selected.
Enabling the chart to handle parameters The last step is to edit the chart page so it will react to changes in the parameter string passed to it from the web part.

10. In Visual Studio close the web part solution and reopen the TestChart solution. 11. Open WebForm1.cs and locate the Page_Load method. Immediately after the line that reads:
DataView firstView = new DataView(custDS.Tables[0]);

12. Insert the following code to filter the XML based on the QueryString:
Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

//Is there a CustomerID? string strCustomerID = ""; strCustomerID = Request.QueryString["CustomerID"]; if ((strCustomerID != null) && (strCustomerID != "") && (Convert.ToInt32(strCustomerID) > 0)) { firstView.RowFilter = "id='" + strCustomerID + "'"; }

13. Build the project and address any compile errors that arise. 14. Return to the browser window that is viewing your web parts. Click on one of the companies listed in the provider part and you should see the following:

If you see that you have successfully connected the web parts and parameters are being passed correctly you deserve a break. Pat your self on the back or go demo it to a friend!

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Summary and Close Creating graphically rich user interfaces used to be the domain of a select few that understood the limited tools that were available. With the advent of powerful and easy to use component libraries like Dundas Charts the creation of data driven charts, graphs, dials and gauges is now very simple for web pages and web applications. With this introduction to web part development we hope to demonstrate that a framework can be developed that can be leveredged by Windows SharePoint Services and SharePoint Portal Server for the creation of information portals that display data driven charts.

Installing the Sample Code


TestChart.zip contains the necessary files to create the example for the basic demo. To install these files on your web server perform the following steps. Unzip the project files to a directory on your web server. For example c:\inetpub\wwwroot\TestChart. Open the Visual Studio and choose File | Open | Project From Web. In the Open Project From Web dialog enter the URL to the location where you unzipped the files. Click OK. In the Open Project dialog select the TestChart.csproj file. Right click the Solution in the Solution Explorer and choose Save. In the Save File As dialog browse to the project file location (c:\inetpub\wwwroot\TestChart) and choose Save. Right click the TestChart.htm file in the solution Explorer and select Set As Start Page. Right click the project and choose Build. The project should build without errors. Configure the project as an application in IIS. If you Run the project and you may see the following:

This simply means that the application is not configured properly in IIS. Open Internet Information Services Manager by clicking Start | Administrative Tools | Internet Information Services Manager. In IIS Manager browse to the Web Site that contains your application folder. Right click the application folder and choose Properties.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

On the Directory tab in the Application settings section click the Create button. This will configure IIS to run your application under the default application pool. Click OK to save your changes. Close Internet Information Services Manager. In Visual Studio run the application and you should see the following.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

Troubleshooting
We intend to expand this section Web part installation check the GAC. If following an installation of a web part, the browser shows the old version perform an iisreset.

Additional Resources
Dundas Web Chart Evaluation - http://www.dundas.com

About the Author


Matthew McDermott is a Managing Consultant and the Collaboration Team Lead with Catapult Systems, Inc. based in Austin, TX. Catapult Systems is a Microsoft Gold Partner and technology implementer that utilizes Dundas chart for creating graphically rich portals and dashboards for private enterprise and government clients. An accomplished cook and bartender, in his spare time Matt spends as much time with his wife as his dog will allow.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Creating a Microsoft Windows SharePoint Web Part with Dundas Chart

S-ar putea să vă placă și