Expand Minimize

How to Create a Silverlight Web Part in ASP.NET for Use in SharePoint Server 2007

SharePoint 2007

Summary: Discover how to develop a basic Microsoft Silverlight Web Part in ASP.NET that hosts a canvas and that can be used with Microsoft Office SharePoint Server 2007 and Windows SharePoint Services 3.0. (6 printed pages)

Avneesh Kaushik, Microsoft Global Services India (MGSI)

June 2008

Applies to: Microsoft Office SharePoint Server 2007, Microsoft Silverlight 1.0 Runtime, Windows SharePoint Services 3.0

Download the sample that accompanies this article: Basic Silverlight Web Part for Office SharePoint Server 2007

Contents

Introduction to Creating a Silverlight Web Part

This article describes how to create a very simple Microsoft Silverlight Web Part in ASP.NET that hosts a canvas (XAML), which can have events mapped to ECMAScript (JScript, JavaScript). We develop the Silverlight Web Part by using Microsoft Visual Studio 2005. The Silverlight Web Part uses Microsoft Silverlight only on the client side, and is based on the Microsoft Silverlight 1.0 Runtime. You can then use the Silverlight Web Part in Microsoft Office SharePoint Server 2007 and Windows SharePoint Services 3.0 to display a canvas (XAML).

Cc627341.note(en-us,office.12).gifNote:

This article is the first in a series of two. The second article (coming soon) will discuss advanced options such as how to dynamically create a canvas based on an RSS feed from Office SharePoint Server 2007.

Prerequisites

  • To successfully create and use the Silverlight Web Part, you must understand the following: Microsoft Silverlight, XAML, ECMAScript (JScript or JavaScript code), and ASP.NET control development.

  • To be able to test the solution, you must have the latest version of the Silverlight plug-in installed on the client computer.

To view the Page.xaml.js file and Default_html.js file referred to in this article, see Complete Page.xaml.js File and Default_html.js File.

Creating the Silverlight Web Part

The first part of our task is to create a solution in Visual Studio 2005, and then create the Silverlight Web Part.

To create the Silverlight Web Part

  1. In Microsoft Visual Studio 2005, open a Visual C# Class Library project.

  2. Remove Class1.cs.

  3. Add the basic SilverlightWebpart.cs to the project.

  4. In the project references, add a reference to System.Web.

  5. Copy the following code and paste it into the .cs file.

    Code listing 1. Add using section

    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Serialization;
    using System.Text;
    using System.IO;
    using System.Globalization;
    
  6. Add the rest of the class as shown in code listing 2 and code listing 3.

    Code listing 2. Add remainder of class

    namespace SomeNameSilverLightWebPart
    {
        /// <summary>
        /// This is a generic/basic Silverlight Web Part.
        /// </summary>
        [DefaultProperty("Text"),
        ToolboxData("<{0}:BasicSLWebPart runat=server></{0}:BasicSLWebPart>"),
        XmlRoot(Namespace = "http://SomeNameSilverLightWebPart")]
        public class BasicSilverLightWebPart : WebPart
        {
            //Constructor.
            public BasicSilverLightWebPart()
            {
            }
    
    }//class 
          
    }//namesapace
    

    Code listing 3. Add variables to class

    #region Private Variables
            private string _JSPath = "";
            private const string defaultText = "";
            private string text = defaultText;
            private string _SLCtlHeight = "100%";
            private string _SLCtlWidth = "100%";
            private string _MainCtlJS = "Default_html";
            private string _XAMLPageName = "Page";
            #endregion
    
  7. Add private properties, which set the path to .js files and the .xaml file. You can add properties to customize the Silverlight Web Part to suit your specific needs.

    Code listing 4. Add private properties

    #region Properties
    
            [Browsable(true),Personalizable(), WebBrowsable,Category("Custom Settings"), 
            DefaultValue(defaultText),Description("Text Property")]
            public string Text
            {
                get { return text;}
                set { text = value; }
            }
    
    
            [Browsable(true),Personalizable(), WebBrowsable,Category("Custom Settings"),
            DefaultValue("100%"),Description("Silverlight Control Width")]
            public string SLControlWidth
            {
                get { return _SLCtlWidth; }
                set { _SLCtlWidth = value; }
            }
    
            [Browsable(true),Personalizable(), WebBrowsable, Category("Custom Settings"),
            DefaultValue("100%"), Description("Silverlight Control Height")]
            public string SLControlHeight
            {
                get { return _SLCtlHeight; }
                set { _SLCtlHeight = value; }
            }
    
            [Browsable(true),Personalizable(), WebBrowsable,Category("Custom Settings"),
            DefaultValue(""),Description("Javascript file path")]
            public string JSPath
            {
                get { return _JSPath; }
                set {_JSPath = value; }
            }
    
            [Browsable(true),Personalizable(), WebBrowsable,Category("Custom Settings"),
            DefaultValue(""),Description("Main JS file Name")]
            public string MainCtlJS
            {
                get { return _MainCtlJS; }
                set { _MainCtlJS = value; }
            }
    
            [Browsable(true),Personalizable(), WebBrowsable,Category("Custom Settings"),
            DefaultValue("Page"), Description("Xaml FileName")]
            public string XAMLPageName
            {
                get { return _XAMLPageName; }
                set { _XAMLPageName = value; }
            }
            #endregion
    
  8. Register the following three EcmaScript (JScript, JavaScript) files in the Web Part; these files are part of any standard Silverlight project or control:

    • silverlight.js   A standard file that detects whether the Silverlight client plug-in is installed on the client computer. If not, the file shows an icon of a location from where you can install the plug-in.

    • Default_html.js   The same as createsilverlight.js; this file contains the createSilverlight function that we need to modify with the code shown in code listing 7.

    • Page.xaml.js   Contains the event listeners.

    Code listing 5. Add .js script tags to render

    protected override void OnPreRender(EventArgs e)
    {
    
       String JSString;
    
    // Register the Web Part-specfic script (each different type of Web Part needs its own main script). 
    // Multiple instances of the same Web Part on a page can reference the same script.
       JSString = "<script type=\"text/javascript\" src=\"" + _JSPath +  _MainCtlJS +  ".js\"></script>\n";
       if (!Page.ClientScript.IsClientScriptBlockRegistered("SilverlightWebPartScript"))
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SilverlightDefaultScript", JSString);
    
    // Register the general scripts (two Web Parts can use the same script block as the scripts are generic).
        JSString = "<script type=\"text/javascript\" src=\"" + _JSPath + "Silverlight.js\"></script>\n";
    
        JSString += "<script type=\"text/javascript\" src=\"" + _JSPath  + "Page.xaml.js\"></script>\n";
                if (!Page.ClientScript.IsClientScriptBlockRegistered("GeneralSilverlightScripts"))
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "GeneralSilverlightScripts", JSString);
    }
    
  9. Add the code that generates the HTML <div> tag where the Silverlight object will be created in your Web Part (for more information, see Creating Custom Web Parts).

    Code listing 6. Add <div> tag where Silverlight object will be created

    protected override void RenderContents(HtmlTextWriter writer)
    {
         EnsureChildControls();
    
                HtmlTextWriter textWriter = new HtmlTextWriter(new StringWriter(CultureInfo.InvariantCulture));
    
                try
                {
                    string width, height;
    
                    width = "400px"; height = "300px";
                    if (this.SLControlWidth.Length > 0)
                        width = _SLCtlWidth;
    
                    if (this.SLControlHeight.Length > 0)
                        height = _SLCtlHeight;
    
                    textWriter.WriteLine("<div id='SilverlightControlHost" + this.ClientID + "' Class=''>");
                    textWriter.WriteLine("<script type=\"text/javascript\"> ");
                    textWriter.WriteLine("createSilverlight('SilverlightControlHost" + this.ClientID + "', '" + _XAMLPageName + "', 'SilverlightControl" + this.ClientID + "','" + width + "','" + height + "');  ");
    
    
                    textWriter.WriteLine("</script></div>");
    
                }
                catch 
                {
                    textWriter = new HtmlTextWriter(new StringWriter(CultureInfo.InvariantCulture));
                    textWriter.WriteLine("<TABLE class='ms-summarycustombody' cellpadding='0' cellspacing='0' border='0'>");
                    textWriter.WriteLine("<TR><TD>Error</TD></TR>");
                    textWriter.WriteLine("</TABLE>");
                }
    
                writer.Write(textWriter.InnerWriter.ToString());
    
            }
    
  10. Create a Default_html.js file and copy the following code into it to modify the createSilverlight function.

    Code listing 7. Modify createSilverlight function

    function createSilverlight(controlHost, xamlSource, controlName, controlWidth, controlHeight, mainSceneObject)
    {
       var SLPage = new SilverlightTest1.Page();
       Silverlight.createObjectEx({
          source: xamlSource,
          parentElement: document.getElementById(controlHost),
          id: controlName,
          properties: {
             width: controlWidth,
             height: controlHeight,
             version: "1.0"
          },
          events: {
             onLoad: Silverlight.createDelegate(SLPage, SLPage.handleLoad)
          }
       });
    }
    
    
    if (!window.Silverlight) 
       window.Silverlight = {};
    
    Silverlight.createDelegate = function(instance, method) {
       return function() {
          return method.apply(instance, arguments);
       }
    
    

Creating the XAML

You can use Microsoft Expression Blend 2 to create the Silverlight XAML. We can use the following XAML for testing purposes.

Cc627341.note(en-us,office.12).gifNote:

For more information about Silverlight, see Getting Started.

Code listing 8.

<Canvas
   xmlns="http://schemas.microsoft.com/client/2007"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Width="640" Height="480"
   Background="White"
   x:Name="Page">
   <TextBlock Width="247" Height="72" Canvas.Left="197" Canvas.Top="121"
     Text="This is great" TextWrapping="Wrap"/>
</Canvas>

Deploying the Silverlight Web Part on Office SharePoint Server 2007

You can deploy the Silverlight Web Part on your server running Office SharePoint Server 2007 by using the following steps.

To deploy the Silverlight Web Part

  1. Ensure latest version of the Silverlight plug-in is installed on the client computer. In the case that the plug-in is not installed, when the page with the Web Part loads for the first time, it displays a link that will show a location from which to download and install the plug-in. (This will happen automatically and no code is required.)

  2. Copy the SomeName.dll (in our sample it will be SilverlightWebPart.dll) into the _app_bin directory of your SharePoint application; for example, C:\Inetpub\wwwroot\wss\VirtualDirectories\80\_app_bin. The .dll file can be signed and copied to the global assembly cache also.

  3. Copy the files default_html.js, Page.xaml, Page.xaml.js and SilverLight.js into the top-level site (root) of the SharePoint Web application (for example, C:\Inetpub\wwwroot\wss\VirtualDirectories\80\_app_bin). We can copy these files at other locations also. Change the Silverlight Web Part property JSPath to the path where you have copied the .js files.

  4. Add the following entry to the web.config file.

    <SafeControl Assembly="SilverLightWebPart2005" 
           Namespace="SilverLightWebParts" TypeName="*" Safe="True" />
    

    For strong-named assemblies, the version, culture, and publickeytoken attributes will be added to the SafeControl element.

  5. Go to the Web Part gallery from the site collection administration page. Click New, select BasicSilverLightWebPart, and then click populate gallery.

  6. Go to any sample SharePoint site, and add the Silverlight Web Part to a page. Modify custom properties, such as the Silverlight control height and width.

  7. Ensure that you supply the complete path to the Page.xaml file in the Silverlight Web Part’s custom properties (for example, /Page.xaml).

  8. Save or publish the page.

Complete Page.xaml.js File and Default_html.js File

The following is the code for the Page.xaml.js file and Default_html.js file.

Page.xaml.js

if (!window.SilverlightTest1)
   window.SilverlightTest1 = {};

SilverlightTest1.Page = function() 
{
}

SilverlightTest1.Page.prototype =
{
   handleLoad: function(control, userContext, rootElement) 
   {
      this.control = control;
      
      // Sample event hookup:
      rootElement.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseDown));
   },
   
   // Sample event handler:
   handleMouseDown: function(sender, eventArgs) 
   {
      // The following line of code shows how to find an element by name and call a method on it.
      // this.control.content.findName("Timeline1").Begin();
   }
}

Default_html_js

function createSilverlight()
{
   var scene = new SilverlightTest1.Page();
   Silverlight.createObjectEx({
      source: "Page.xaml",
      parentElement: document.getElementById("SilverlightControlHost"),
      id: "SilverlightControl",
      properties: {
         width: "100%",
         height: "100%",
         version: "1.0"
      },
      events: {
         onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
      }
   });
}



function createSilverlight(controlHost, xamlSource, controlName, controlWidth, controlHeight)
{
   var SLObj = new SilverlightTest1.Page();
   Silverlight.createObjectEx({
      source: xamlSource,
      parentElement: document.getElementById(controlHost),
      id: controlName,
      properties: {
         width: controlWidth,
         height: controlHeight,
         version: "1.0"
      },
      events: {
         onLoad: Silverlight.createDelegate(SLObj, SLObj.handleLoad)
      }
   });
}


if (!window.Silverlight) 
   window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
   return function() {
      return method.apply(instance, arguments);
   }
}

Conclusion

This article describes the steps you can take to create a Silverlight Web Part that can host any Silverlight-compatible XAML. By using this Silverlight Web Part, you can create some very sophisticated additional Web Parts, which I will address in a later article.

About the Author

Avneesh Kaushik is a senior consultant working with Microsoft Global Services India (MGSI) in the IW/Collaboration service line. He has helped design and deploy the Hawaiian Airlines Web Content Management (WCM) site.

Additional Resources

Community Additions

ADD
Show:
© 2014 Microsoft