Silverlight in SharePoint: Developing Your Own Silverlight Web Part

This entry is part 4 of 4 in the series Silverlight in SharePoint

In SharePoint 2010, we have an out-of-the-box Silverlight web part that can host almost any Silverlight application. But in this fourth part of the Silverlight series, we’re going to show how to build your own web part that hosts a Silverlight application.

In SharePoint 2010, we can develop two different types of web parts: a visual web part or a classic web part. With a visual web part, we can design the user interface within an .ascx user control. This control is then loaded in the web part infrastructure when the web part is loaded to the SharePoint page. The .ascx user control is typically deployed to the CONTROLTEMPLATES folder of the SharePoint 14 hive.

The classic web part is the web part we still know from the SharePoint 2007 era. In general, you will develop visual web parts because they are easier to create, but in cases where you have to work with sandboxed solutions, no files can be deployed to the file system, so you will have to develop a web part in the classic way.

Creating Your Own Visual Web Part

If you need to pass extra information to the Silverlight application that cannot be handled by the out-of-the-box Silverlight application, you can create your own web part. In this article, we will build our own visual web part hosting the services banner we created in the previous article, “The Silverlight Client Object Model.” In next article, we will extend that visual web part with a custom tool pane where the user can choose the color of the service item controls. The color picker in this custom tool pane will also be a Silverlight application.

You can create a visual web part using the SharePoint 2010 tools for Visual Studio 2010.

Visual WebPart Template

When looking at Solution Explorer, you will see that the Visual Web Part is created with a number of files. The ServicesBannerVisualWebPart.cs class contains the code to load the user control ServicesBannerVisualWebPartUserControl.ascx. It is in this control that the user interface elements will be defined.

Solution Explorer

To be able to render a Silverlight application, a number of HTML elements must be added to the page. The Silverlight control itself is an <object> tag that must be rendered within a <div> element with a well-defined width and height. This width and height can be relative or absolute. Also, the <object> element must specify a width and height; otherwise, the Silverlight application will not be visible. The <object> element contains a number of <param> elements with name and value attributes.

  • source: The value indicates the location of the Silverlight application. The out-of-the-box Silverlight application lets you specify your own location, but this example specifies the Silverlight application from the previous article, which is located in the XAPS library.
  • initParams: The value of this element depends on which information you want to pass to the Silverlight application when it initializes. The services banner requests that the name of the Service Offering list is passed, but this value is constructed dynamically when the web part loads, which is the reason for the value=”<%= InitParameters %>” /> notation.
  • the minRuntimeVersion and autoUpgrade attributes are also required, but their values are predefined and cannot be changed by you.
  • Some Silverlight applications also have an onError parameter, requiring a Javascript function treating errors.
   <asp:Panel ID="SilverlightPanel" runat="server" >
     <div id="silverlightControlHost" style="width:100%;height:150">
       <object id="SLServicesBanner"
               data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
           <param name="source" value="/XAPS/Sample2.ServicesBanner.xap"/>
           <param name="initParams" value="<%= InitParameters %>" />
           <param name="background" value="white" />
           <param name="minRuntimeVersion" value="4.0.50401.0" />
           <param name="autoUpgrade" value="true" />
           <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
              <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
           </a>
       </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
     </div>
   </asp:Panel>

The code behind this user control contains a Page_Load event. It is this event that is responsible for rendering the Silverlight application. It verifies whether the initParameters variable is properly filled out; if so, the Silverlight application is rendered in a panel. If the initParameters value is empty or doesn’t contain the list parameter, a message is displayed instructing the user to open the web part tool pane in order to fill out the required Silverlight properties. You can use an out-of-the-box JavaScript function to open the tool pane.

   protected void Page_Load(object sender, EventArgs e)
   {
      if (string.IsNullOrEmpty(initParameters) || !initParameters.Contains("list="))
      {
         SilverlightPanel.Visible = false;
         openEditorPartControl = new LiteralControl(string.Format(
              "To show a Silverlight control <a href=\"javascript:MSOTlPn_ShowToolPane2('Edit','{0}');\">open the tool pane</a> and set the Silverlight properties.",
              webPartID));
         this.Controls.Add(openEditorPartControl);
      }
      else
      {
         SilverlightPanel.Visible = true;
      }
    }

The InitParameters property is filled from within the ServicesBannerVisualWebPart.cs class. While the ascx user control takes care of the rendering of the visual elements, this ServicesBannerVisualWebPart.cs class  represents the web part itself. You first have to define a property that can be set from within the tool pane of the web part. It will be displayed in its own category, Silverlight Properties:

   [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
   Category("Silverlight Properties"),
   DefaultValue(""),
   System.Web.UI.WebControls.WebParts.Personalizable(
   System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
   Description("Specify the InitParams string to initialize the Silverlight application.")]
   public string InitParameters
   {
       get { return initParameters; }
       set { initParameters = value; }
   }

The web part class also contains the classic CreateChildControls method with some predefined code loading the .ascx user control, which is of base type Control.

   protected override void CreateChildControls()
   {
      Control control = Page.LoadControl(_ascxPath);
      Controls.Add(control);
   }

Because we want to pass information to the InitParameters property in the user control, we have to modify this code slightly in order to load and render the more specific ServiceBannerVisualWebPartUserControl (a name created by the Visual Studio 2010 templates). When the control is loaded, the web part ID and a value for the InitParameters property is passed. The web part ID is needed when the user control needs to display a message that the InitParameters property is not properly filled out.

   protected override void CreateChildControls()
   {
       //Control control = Page.LoadControl(_ascxPath);
       ServicesBannerVisualWebPartUserControl control = this.Page.LoadControl(_ascxPath) as ServicesBannerVisualWebPartUserControl;
       if (control != null)
       {
           control.WebPartID = this.ID;
           control.InitParameters = BuildInitParameters();
           Controls.Add(control);
       }
   }

The value for the InitParameters property is constructed within a private method BuildInitParameters and needs an extra word of explanation. As we saw in the previous article, “The Silverlight Client Object Model,” you can use the ClientContext.Current to get a hold on the SharePoint context. Under the hood, the Silverlight application needs a parameter with name MS.SP.url passed in via the InitParameters. When using the out-of-the-box Silverlight web part, this parameter is passed automatically, but when developing your own custom web parts, you have to pass that parameter yourself. If you don’t pass the parameter MS.SP.url, your ClientContext will be null.

The ServicesBanner Silverlight application also requests the list parameter to be passed, but this one needs to be passed by the user in the tool pane of the custom web part.

   private string BuildInitParameters()
   {
       if (string.IsNullOrEmpty(initParameters))
          initParameters = "MS.SP.url=" + SPContext.Current.Web.Url;
       else if (!initParameters.Contains("MS.SP.url"))
          initParameters = initParameters + ",MS.SP.url=" + SPContext.Current.Web.Url;
       return initParameters;
   }

Deploying Your Visual Web Part

Your web part is now ready to deploy. If you want it to appear in its own category in the Web Part gallery, you will have to modify the .webpart file. You can also do the necessary customizations to the feature file. Once your web part is deployed, you can add it to a web part page. You will have to click the hyperlink within the message displayed under the web part title. This is because the list parameter is missing from the InitParameters string.

Click the hyperlink to set the Silverlight properties

When you’re in the web part tool pane, locate the Silverlight Properties section and add the string list=Services Offering to the content of the text box. Don’t forget to add a comma without a whitespace to separate the two parameters:

Custom tool pane properties

Click the Apply or OK button to render the Silverlight application within the web part.

Your custom Silverlight webpart

Conclusion

In this article, I explained how you can develop your own visual web part to host a Silverlight application. In next article, I will explain how you can create a custom tool pane that hosts a Silverlight color picker.

Series NavigationSilverlight in SharePoint: The Silverlight Client Object Model
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!

Leave a Reply

Before you post, please prove you are sentient.

what is 3 plus 2?