Recently I was asked how to display Rich media (mainly video) in Sharepoint 2007 by our communications department. This shouldn’t be too hard to do so time to whip up a quick demo/proof of concept to make sure that it in fact can be done, and what better way than to create a custom web part that embeds Microsoft’s Silverlight.
Adding Silverlight to your web application is easy enough so it shouldn’t be too difficult to do in Sharepoint 2007 either. There are a few different files that you will need in order to do this however, a couple of Javascript files, a XAML and of course your custom web part.
So kick off Visual Studio and lets get cracking. First off we’ll create the Javascript file that you will need (the other one you don’t create, just copy from the SDK but more on that later).
I’m assuming that you have Sharepoint extensions for Visual Studio installed (currently available only for 2005 although a version for Visual Studio 2008 is apparently due out shortly).
Go to File/New and select New Project from the list of available options. Next within the C# Project Type folder, go to the Sharepoint folder and select Web Part. Call it SilverLightPart, give it a location and hit OK. This will create the outline of the custom web part we’ll create later.
Next right click on SilverLightPart project and select Add/New Item. In the dialog that pops up, click on the Visual C# Project Items under categories and select JScript for the Javascript file we’ll create and call it CreateSilverLight.js.
The Javascript function that we’ll create is a small function that simply kicks off the main Silverlight Javascript routine. Copy the following code into your blank Javascript file :-
function createSilverlight()
{
Silverlight.createObject(
“/_layouts/videoplayer.xaml”, // Source property value.
parentElement, // DOM reference to hosting DIV tag.
“myPlugin”, // Unique plug-in ID value.
{ // Plug-in properties.
width:’320′, // Width of rectangular region of plug-in in pixels.
height:’200′, // Height of rectangular region of plug-in in pixels.
inplaceInstallPrompt:true, // Determines whether to display in-place install prompt if invalid version is detected.
background:’white’, // Background color of plug-in.
isWindowless:’true’, // Determines whether to display plug-in in windowless mode.
framerate:’24’, // MaxFrameRate property value.
version:’1.0′ // Silverlight version.
},
{
onError:null, // OnError property value — event-handler function name.
onLoad:null // OnLoad property value — event-handler function name.
},
null, // initParams — user-settable string for information passing.
null); // Context value — passed to Silverlight.js onLoad event handlers.
}
The code is commented so it’s fairly self explanatory. Here we are instantiating the actual Silverlight object. This takes a number of parameters. The first parameter is where the Silverlight object can find the associated XAML file that it requires, next is a reference to a DIV tag that Silverlight will be embedded in, the third parameter is a Unique ID for the plugin followed by a number of parameters giving the width, height, framerate of the video etc. etc.
In the above code, the only parameter that I am effectively passing in is the parentElement parameter, however in your own code you may want to pass in parameters for the XAML file, the width and height properties and a Unique ID. And that’s all there is to this file.
Next we want to create the XAML file that this script references, so add an XML file to your project and call it VideoPlayer.XAML. Delete the default <xml> tag that has been created and insert the following :-
<Canvas
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
x:Name=”root”
>
<Canvas x:Name=”VideoLayer”>
<MediaElement x:Name=”media” Source=”http://download.microsoft.com/download/d/e/2/de2bec9c-4ba1-406e-8029-5c4767dca3eb/WPFE_Getting_Started_2MB_Ch9.wmv”
Width=”300″ Height=”200″ />
</Canvas>
</Canvas>
Here we are defining the root element to be a canvas (just like the canvas painters use to paint on, a blank area with potential) and pointing to the relevant xml namespaces required for XAML files. Next we create our actual Canvas in which we will display our video file. The video file is marked up in XAML using the <MediaElement> tag and here we simply point it to a video that we wish to display and give it a width and height (width and height are optional but if you do input these they are in pixels. You cannot use percentages e.g. 100%). Since this is just a proof of concept we’ll end things here. You can of course add whatever you like to the XAML file, video controls for play, pause etc. and hook into Javascript events that will deal with them, skin it to give it your own personal touch, overlay controls or text etc. For more information on how to do these things you may want to take a look at the excellent Quick Start videos that are freely available on MSDN at the moment.
The last Javascript file that you will need is the actual Silverlight javascript file itself. In order to get this file you will need to download a copy of the SDK found here.
OK so that is the ancillary files out of the way, next we start on the web part itself. I’m not going to do anything fancy here, simply display the Silverlight control which has the video file hard coded within it, however you may want to create your own web part editor and add inputs so that an end user could select the video source, change the width and height etc.
Back to our web part. Open the SilverLightPart.cs file. As you will see, the Microsoft Sharepoint template that you loaded from has already given you an outline to what you will need, so all we need to do is flesh it out a bit. Here is the finished code :-
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Security;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
[assembly: AllowPartiallyTrustedCallers]
namespace SilverLightPart
{
[Guid(“07cd69ef-44e8-403a-93d8-9aa2bdb4f37a”)]
public class SilverLightPart : System.Web.UI.WebControls.WebParts.WebPart
{
public SilverLightPart()
{
this.ExportMode = WebPartExportMode.All;
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write(“<div id=’slControlHost’>n”);
writer.Write(“<script type=’text/javascript’>n”);
writer.Write(“var parentElement = document.getElementById(‘slControlHost’);n”);
writer.Write(“createSilverlight();n”);
writer.Write(“</script>n”);
writer.Write(“</div>”);
}
protected override void OnPreRender(EventArgs e)
{
string script = “<script type=’text/javascript’ src=’/_layouts/CreateSilverlight.js’></script>n”;
string script2 = “<script type=’text/javascript’ src=’/_layouts/Silverlight.js’></script>n”;
if (!Page.ClientScript.IsClientScriptBlockRegistered(“Silverlight”))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “Silverlight”, script2);
}
if (!Page.ClientScript.IsClientScriptBlockRegistered(“CreateSilverlight”))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “CreateSilverlight”, script);
}
base.OnPreRender(e);
}
}
}
First we’ve added a couple of extra namespaces and the Assembly reference to allow for partially trusted callers. This is a security setting used within Sharepoint. Each web part has to have it’s own GUID but this is already supplied for you by the template (as well as the .snk file for signing your DLL when you build it amongst other things).
Next we have the constructor. As this is essentially an ASP.Net 2.0 web part and not specifically a Sharepoint web part, this setting allows you to export this web part so that you can use it in other sites. This isn’t actually required for a Sharepoint web part and you can feel free to delete ExportMode line, however you do require a constructor, even if it’s blank.
Next we have the Render method. The contents in here is actually what will be written to the page. As this was just a proof of concept, I hard coded these lines, however if you were actually building this web part for deployment you might want to use RenderBeginTag, RenderEndTag and AddAttribute methods instead.
Here all that we’re doing is defining is DIV which will hold the silverlight control, then adding some javascript to create the variable parentElement and call the createSilverLight Javascript function we defined earlier. As you may remember, the parentElement variable is actually used within createSilverLight function to tell the Silverlight control where to display.
Finally we override the OnPreRender event. We have to add our two Javascript files to the page. Here we’re simply saying that if these Javascript files aren’t contained within the page, then add the references to them.
And that’s it. Build your project and next we’ll deploy it.
First things first, we want a place that we can add the Javascript and XAML files to so that they can be references no matter where you deploy the web part within the site. As you may have picked up from the source above, I’ve chosen the _Layout directory as this is globally accessible.
Within Windows Explorer, navigate to C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TemplateLayout and copy both the Javascript files (Silverlight.js and CreateSilverLight.js) and the XAML file (VideoPlayer.XAML) into this directory.
Next navigate back to where you created your project and copy the dll from the bin directory to the clipboard (CTRL + C or right click the file and select copy). Now navigate to your Sharepoint site. This will normally be found under the c:inetpubwwwroot directory then navigate to your sharepoint sites’ bin directory (your sharepoint site may be under the wssVirtualDirectories folder within the wwwroot folder) and paste the dll into the bin directory.
Nearly done, next we have to ammend the web.config file to tell Sharepoint that our web control is safe to use. So open the web.config file for your site in either Visual Studio or notepad and add this to the end of the list of SafeControls already defined there :-
<SafeControl Assembly=”SilverLightPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5″ Namespace=”SilverLightPart” TypeName=”*” Safe=”True” />
As we’ve changed the web.config file it’s always best to do an IISReset so that Sharepoint will immediately pick up the new config file.
Now open your Sharepoint site, and under the Site Actions menu select Site Settings and Modify All Site Settings. From the page that appears, click on the “Web Parts” link under the Galleries heading then click on New. Find the Silverlight webpart and select the checkbox next to it then click on the Populate Gallery button at the top.
All that is left is to add your new Silverlight video streaming web part to your page. Navigate to the Sharepoint page where you wish to add this web part, select Edit Page from under the Site Actions menu, click on one of the Add Web Part links that are on the page and add the SilverlightPart web part to your page (found under Miscellaneous).
And there you have it, how to add Silverlight to your Sharepoint 2007 site.