Karine Bosch’s Blog

On SharePoint

Silverlight in SharePoint

End 2010 the online SharePoint Magazine asked to write a series of articles on Silverlight integration in SharePoint. The first part is recently published. It is an overview on my history with Silverlight integration in SharePoint. You find the overview article here.

In further articles of this series I will explain how you can integrate Silverlight in somewhat every SharePoint artifact.

I hope you like it.

Advertisements

March 5, 2011 Posted by | SharePoint 2010, Silverlight | Leave a comment

Silverlight meets SharePoint

Last week I did a presentation on Silverlight integration in SharePoint for a company called Vortalities/SharePoint Designers.  The developers were really responsive and I liked it very much.

So if your company is located in Belgium and is investigating on integrating Silverlight with SharePoint 2010 (or 2007), please feel free to contact me. I’ll be glad to do the presentation for your developers.

February 4, 2011 Posted by | SharePoint 2007, SharePoint 2010, Silverlight | 1 Comment

Silverlight control not stretching to its full width when hosted in a SharePoint Web Part (continued)

When creating the sample I first tried

         <TextBlock x:Name="MarqueeTextBox" Foreground="White" FontFamily="Comic Sans MS"
                   FontSize="16" FontStyle="Italic" Width="Auto" Height="Auto" Padding="5"            
                   HorizontalAlignment="Stretch" VerticalAlignment="Stretch" TextWrapping="Wrap"                   
                   Text="This is a very long text that will be stretched automatically when the width of the containing web part changes."/>

but this didn’t make the text wrap through the canvas. This is because you need to specify a fixed width to make wrapping happen. If you want your text wrap through the canvas while stretching when the web part width changes, you have to add a little more code. First I changed the Width property to a fixed width:

         <TextBlock x:Name="MarqueeTextBox" Foreground="White" FontFamily="Comic Sans MS"
                   FontSize="16" FontStyle="Italic" Width="200" Height="Auto" Padding="5"            
                   HorizontalAlignment="Stretch" VerticalAlignment="Stretch" TextWrapping="Wrap"                   
                   Text="This is a very long text that will be stretched automatically when the width of the containing web part changes."/>

In code behind I defined a ResizeTextBlock method. This method resizes the width of the TextBlock and is executed when the Silverlight application loads. You also need to add an event handler for the SizeChanged event of the Silverlight control to ensure that the TextBlock is resized each time the web part width changes.

    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            ResizeTextBlock();
            this.SizeChanged += new SizeChangedEventHandler(MainPage_SizeChanged);
        }
        void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ResizeTextBlock();
        }
    }

First i t ried to set the width of the TextBlock to the width of the root canvas:

As you can see, the LayoutRoot has no actual width because no Width property has been defined on the canvas. The same problem occurs when you want to set the width of the TextBlock to the width of the Silverlight control itself, using this.Width. You have to rely on the width that has been set on the web part. You can grab the actual width of the plug-in display area represented by App.Current.Host.Content. Be aware that the ActualWidth property and the ActualHeight property do not contain meaningful values until after the Content.Resized event occurs for the first time.

        private void ResizeTextBox()
        {
            if (App.Current.Host.Content.ActualWidth > 0)
            {
                MarqueeTextBox.Width = App.Current.Host.Content.ActualWidth;
            }
        }

The text now wraps over the width of the canvas:

 

July 25, 2010 Posted by | SharePoint 2007, SharePoint 2010, Silverlight | 9 Comments

Silverlight control not stretching to its full width when hosted in a SharePoint Web Part

In the past few months I had a number of comments on my Silverlight posts where people ask how to make a Silverlight application stretch to the full width and/or height of the SharePoint web part that hosts the Silverlight application. I found a solution to this problem when working on Silverlight integration in SharePoint 2010, but I’m pretty certain this also works for SharePoint 2007.

Creating the Silverlight application

When you create the Silverlight application, you have to remove a Width and/or Height setting of the <UserControl>. Also don’t specify any width and/or hight on the container Grid or Canvas.

<UserControl x:Class="SLMarquee.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
    <Canvas x:Name="LayoutRoot" >
        <Canvas.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >
                <GradientStop Color="Orange"/>
                <GradientStop Color="DarkRed" Offset="1"/>
            </LinearGradientBrush>
        </Canvas.Background>
        <TextBlock x:Name="MarqueeTextBox" Foreground="White" FontFamily="Comic Sans MS" FontSize="16" FontStyle="Italic"                   
                   Width="Auto" Height="Auto"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Padding="5"
                   Text="This is a very long text that will be stretched automatically when the width of the containing web part changes."/>
    </Canvas>
</UserControl>

I added LinearGradientBrush to the background of the Canvas to make it easier to demonstrate that the canvas stretches to the size of the web part.

Creating the SharePoint web part

The Silverlight application will be hosted in a <div> element. This <div> element is typically created in the CreateChildControls method of the web part. I created a classic web part in Visual Studio 2010 to let people working on SharePoint 2007 also benifit from the post.

    public class SilverlightWrapperWebPart : WebPart
    {
        protected override void CreateChildControls()
        {
            HtmlGenericControl div = new HtmlGenericControl("div");
            div.ID = "SilverlightHost";
            // generate the Silverlight control
            StringBuilder sb = new StringBuilder("<object id=\"SilverlightHost\"");
            sb.Append(" width=\"100%\"");
            sb.Append(" height=\"100%\"");
            sb.Append(" data=\"data:application/x-silverlight-2,\"");
            sb.Append(" type=\"application/x-silverlight-2\" >");
            sb.Append(" <param name=\"source\" value=\"/XAPS/SLMarquee.xap\"/>");
            sb.Append(" <a href=\"http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0\" ");
            sb.Append(" style=\"text-decoration: none;\">");
            sb.Append(" <img src=\"http://go.microsoft.com/fwlink/?LinkId=108181\" ");
            sb.Append(" alt=\"Get Microsoft Silverlight\" ");
            sb.Append(" style=\"border-style: none\"/>");
            sb.Append(" </a>");
            sb.Append("</object>");
            div.InnerHtml = sb.ToString();
            this.Controls.Add(div);
        }
    }

If you want your Silverlight application stretch to the width and height of your web part, you have to set the width and height properties of the <object> tag to 100%. You can also choose that only the width needs to resize whenever the web part is resized. In that case you can specify an absolute value for the height and a relative value (in percentage) for the width. Notice also that no <param name=”width” value =”xxx” /> and no <param name=”height” value = “xxx” /> is specified within the <object></object> tags. This is also not necessary if you want your Silverlight application to stretch.

If I now add my web part to a web part page and set the width of the web part to 250 pixels and the height to 100 pixels (by using the standard tool pane of the web part), my Silverlight applications shows as follows:

If I modify the width of the web part to 750 pixels, I see the following:

Notice that not only the full text is now shown, but also that the background gradient is more stretched, proving that the canvas really resizes when the size of the web part is changed.

It is a different story if you want to wrap the text through the canvas because then the TextBox control need to have a fixed width, but that’s for tomorrow 🙂

July 24, 2010 Posted by | SharePoint 2007, SharePoint 2010, Silverlight | 5 Comments

Silverlight meets SharePoint

The first versions of Silverlight have seen the light in 2007 and 2008, and in July 2009 Silverlight 3 has been released. It is an exciting and promising new technology. Silverlight is a browser plug-in that runs on the client and that can render animations, audio and video. To shorten the learn curve for the developer it exposes a subset of the .NET framework, but it is also able to execute javascript and to interact with other elements on the HTML page.

I have been involved in the integration of Silverlight in SharePoint 2007 from the first version of Silverlight and I had the luck to work on the Silverlight BluePrint for SharePoint together with Patrick Tisseghem. I’m a big fan ever since. I’m very glad to see that Microsoft follows this path and that Silverlight integration is built in out of the box in SharePoint 2010. I followed blogs and presentations on this subject for years now, and to my humble opinion these publications never go far enough.  I’m convinced there is a future for this match. Silverlight can be used to enrich your SharePoint sites but it can also play an important functional role.

In the following series I’m going to use the best of both worlds and detail a number of samples in almost every scenario in SharePoint 2007 that I can think of. You will also be able to download most of the samples.

I hope this set of samples will get you started and I hope it inspires you to come up with other scenarios.

February 8, 2010 Posted by | SharePoint 2007, Silverlight | Leave a comment

Silverlight 3 Media Viewer Web Part for SharePoint

Some time ago, I created a Silverlight 2 variant on one of the Silverlight BluePrint for SharePoint samples. Since a few weeks people start to request a Silverlight 3 version. You can download the Silverlight 3 version of the web part here. The zip contains the source code for the web part and the Silverlight application. It also contains a .wsp that you can upload and deploy to your SharePoint sites.

If you want to know how to install Silvelright 3 and what you need to know before using Silverlight 3 with SharePoint, read this post.

If you want to read more details about this web part, read this post.

January 8, 2010 Posted by | SharePoint 2007, Silverlight | 8 Comments

Visual Studio 2010 and Silverlight 3

After having installed Visual Studio 2010 I wanted to start developing a Silverlight 3 application. The Silverlight project templates seem available but when trying to create a Silverlight application, I got an error message mentioning that the Silverlight developer runtime wasn’t installed.
To be able to create a Silverlight 3 project I had to download and install the following things:

Visual Studio 2010 comes with some enhancements when it comes to Silverlight 3 application development. You can develop Silverlight applications for different versions of the runtime, meaning that you can choose if you want to develop for Silverlight 2 or Silverlight 3. You can also drag and drop controls from the toolbox onto the Silverlight interface, like for any other type of application.  But there are also some limitations: .NET RIA Services development is not yet available for Visual Studio 2010. You can read more about this in Tim Heuers post.

September 27, 2009 Posted by | Silverlight | Leave a comment

Create a SharePoint Application Page hosting a Silverlight 3 application

In my previous post on Silverlight 3 integration in SharePoint I explained that there is no System.Web.Silverlight.dll in the SDK anymore. Of course you can install the Silverlight 3 SDK side by side with the Silverlight 2 SDK to be able to continue using the <asp:Silverlight> control but  if you want to keep up with the newest technologies, you adapt to the rules.

In that case you can use the <object> tag to create the Silverlight application. The code snippet below contains the entire application page.

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <script type="text/javascript">
        function onSilverlightError(sender, args) {
            var appSource = "";
            if (sender != null && sender != 0) {
                appSource = sender.getHost().Source;
            }
            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;
            if (errorType == "ImageError" || errorType == "MediaError") {
                return;
            }
            var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";
            errMsg += "Code: " + iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";
            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " + args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }
            throw new Error(errMsg);
        }
    </script>
    <div id="silverlightControlHost" style="width:300;height:100">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
            width="100%" height="100%">
            <param name="source" value="HelloSilverlight3.xap" />
            <param name="width" value="300" />
            <param name="height" value="100" />
            <param name="onError" value="onSilverlightError" />
            <param name="background" value="white" />
            <param name="minRuntimeVersion" value="3.0.40624.0" />
            <param name="autoUpgrade" value="true" />
            <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration: none">
                <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight"
                    style="border-style: none" />
            </a>
        </object>
    </div>
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    Silverlight 3 Demo Application Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" runat="server" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea">
    Silverlight 3 Demo Application Page
</asp:Content>

InitParameters can be passed by using another <param> element. The value string is comma separated as it has always been:

<param name="initParams" value="key1=value,key2=value2" />

The only disadvantage is that you have to click the Silverlight application before you can start interacting with it.

Silverlight 3 app page

You can download the demo project here. Have fun with it!

July 24, 2009 Posted by | SharePoint 2007, Silverlight | 17 Comments

Integrating Silverlight 3 in SharePoint 2007

Silverlight 3 has been released last week and it comes with really really great features. To learn more about them, I refer to posts like those of Tim HeuerScott Guthrie and Shawn Wildermuth. And a blog I personally like very much is the blog of Mike Snow.  Besides those listed here, there are a lot of other interesting resources you can find on the net.

All these new features sounds very exciting. Today I have been trying to integrate Silverlight 3 into SharePoint and it has not been easy at all.

Installation of Silverlight 3

 – Download Silverlight 3 runtime and install

– Download the Silverlight 3 SDK and install 

– If you are a developer, download Silverlight 3 Tools for Visual Studio and install. If you run  your environment in a Virtual PC (like most of the SharePoint developers do) you will encounter problems when you have no internet connection from within your Virtual PC. Until the beta version of Silverlight 3 you could use the trick to copy the content of the temporary folder while the exe was aching to install, and then install everything separately, but this time you will not find the Silverlight.3.x_Developer.exe file to enable Silverlight debugging in Visual Studio so you DO need an internet connection this time. (To enable internet access from within your VPC, I can recommend this post).

– If you need to develop more advanced user interfaces (and you will), you can download and install the Blend 3 trial.

If you installed all these bits, you are ready to go. Open Visual Studio 2008 and you can start developing your first Silverlight 3 applications. Exciting isn’t it? But if you are a SharePoint developer like me, there is the next hurdle to take: how can I display my first Silverlight 3 application in SharePoint? The SharePoint path has always been steep and has never been easy to take.

Configuration of the SharePoint server

Here comes the good news: in despite of previous versions, with Silverlight 3 you have to change NOTHING to the web.config of your SharePoint web application(s) on the server. You only have to configure the web.config for Framework 3.5 but this can easily lazily be done by Visual Studio 2008.

The last week I received a lot of questions on my blog: “Where is the System.Web.Silverlight.dll? I can’t find it.”. Well, I’m sorry, but it doesn’t exist anymore. You have to create the silverlight applications from within javascript, at least if you want to stay compatible.

Consequences for the SharePoint developer

You have two options:

– You are conservative and you install the Silverlight 3 SDK side by side with the Silverlight 2 SDK. In that case you can continue using the SilverlightControl, even with Silverlight 3 applications. 

– You are progressive and you remove the Silverlight 2 SDK and install the Silverlight 3 SDK. In that case you have to change your code.

The conservative way

Install the Silverlight 3 SDK side by side with the Silverlight  2 SDK. In that case the System.Web.Silverlight.dll is still available and can be deployed in the Global Assembly Cache, and you can continue using the Silverlight control, residing in that System.Web.Silverlight.dll. The control works with Silverlight 2 and Silverlight 3 applications.

PS. I haven’t checked HttpWebRequest to call SharePoint web services, so I don’t know if that’s boobytrapped too. 

The progressive way

Update 25/07/2009: because of encountering problems with execution of the script inside the web part code, I altered this post slightly.

This post explains how you can create a SharePoint web part that hosts a Silverlight 3 application. In a following post you will read how to host a Silverlight 3 application from within an application page. Both techniques are the basics that can be used in every SharePoint development scenario.

Create a javascript file with f.e. the name SpSilverlight.js. Include the following script to create a Silverlight application based on the silverlight.CreateObjectEx method:

function onSilverlightError(sender, args) {
         var appSource = "";
         if (sender != null && sender != 0) {
            appSource = sender.getHost().Source;
         }

         var errorType = args.ErrorType;
         var iErrorCode = args.ErrorCode;
         if (errorType == "ImageError" || errorType == "MediaError") {
             return;
         }
         var errMsg = "Unhandled Error in Silverlight Application " +  appSource + "\n" ;
         errMsg += "Code: "+ iErrorCode + "    \n";
         errMsg += "Category: " + errorType + "       \n";
         errMsg += "Message: " + args.ErrorMessage + "     \n";
         if (errorType == "ParserError") {
             errMsg += "File: " + args.xamlFile + "     \n";
             errMsg += "Line: " + args.lineNumber + "     \n";
             errMsg += "Position: " + args.charPosition + "     \n";
         }
         else if (errorType == "RuntimeError") {          
             if (args.lineNumber != 0) {
                 errMsg += "Line: " + args.lineNumber + "     \n";
                 errMsg += "Position: " +  args.charPosition + "     \n";
             }
             errMsg += "MethodName: " + args.methodName + "     \n";
         }
         throw new Error(errMsg);
}
function createSL(divid, swidth, sheight, source, initparameters)
{
    var pluginid = divid + "Plugin";
    var divElement = document.getElementById(divid);
    var altHTML = divElement.innerHTML;
    if (swidth == null)
       swidth='100%';
    if (sheight == null)
       sheight='750px';     
    Silverlight.createObjectEx(
    {
        source: source,
        parentElement: divElement,
        id: pluginid,
        properties:
        {
          // Plug-in properties
          width:swidth, 
          height:sheight,
          minRuntimeVersion:'2.0.31005.0'
        },
        events:
        {
           OnError: onSilverlightError // OnError property value -- event-handler function name.
           // OnLoad property value -- event-handler function name.
        },
        initParams: initparameters
    });
}

You can also create a Silverlight object using the silverlight.CreateObject method and include that in the SpSilverlight.js file.

In your web parts in the OnPreRender event you will have to register following javascript files:

  •  the Silverlight.js file (which comes with Silverlight and can be found in the C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Tools directory)
  • the SpSilverlight.js file you just created.
protected override void OnPreRender(EventArgs e)
{
     base.OnPreRender(e);
     ClientScriptManager cs = Page.ClientScript;// Include the required javascript file.
     if (!cs.IsClientScriptIncludeRegistered("sl_javascript"))
         cs.RegisterClientScriptInclude(this.GetType(), "sl_javascript", "/_LAYOUTS/SL3/Silverlight.js");
     if (!cs.IsClientScriptIncludeRegistered("spsl_javascript"))
         cs.RegisterClientScriptInclude(this.GetType(), "spsl_javascript", "/_LAYOUTS/SL3/SpSilverlight.js");
}

Notice the path to the javascript files. I both deployed them to a sub folder of the 12\TEMPLATE\LAYOUTS folder. To avoid having to deploy these files for each web part and application page, you can best deploy them once to a single sub folder of the 12\TEMPLATE\LAYOUTS folder. You can also deploy them to the ClientBin folder under your SharePoint web application (in IIS).

Call the above javascript from within the CreateChildControls method:

protected override void CreateChildControls()
{
    string slstring = "<script type=\"text/javascript\">"
       + "createSL('silverlightHost', '300', '100', '/_LAYOUTS/SL3/HelloSilverlight3.xap', null);"
       + "</script>";
    silverlightHost = new LiteralControl(string.Format("<div id=\"silverlightHost\" style=\"width:100%; height:100%\"></div>{0}", slstring));           
    this.Controls.Add(silverlightHost);
}

If you need to pass data to the Silverlight control you need to set the initParams argument. This is a comma delimited string which has the following syntax:

key1=value1,key2=value2,...

Note that there are no spaces.

The CreateChildControls method would look as follows:

protected override void CreateChildControls()
{
    string xaplocation = "/_LAYOUTS/SL3/HelloSilverlight3.xap";
    string initparams = string.Format("url={0},list=Shared Documents", SPContext.Current.Web.Url);
    string slstring = string.Format("<script type=\"text/javascript\">"
       + "createSL('silverlightHost', '300', '100', '{0}', '{1}');"
       + "</script>", xaplocation, initparams);
    silverlightHost = new LiteralControl(string.Format("<div id=\"silverlightHost\" style=\"width:100%; height:100%\"></div>{0}", slstring));           
    this.Controls.Add(silverlightHost);
}

Voila! If you get this easy one to work, you are ready to go for all the great new stuff Silverlight 3 brings you!

Have fun!

July 17, 2009 Posted by | SharePoint 2007, Silverlight | 90 Comments

I will be present(ing) at the Belgian Silverlight User Group on 14th of May

On May 14th I will give a presentation on how Silverlight can play a useful role in SharePoint. As I’m also writing a MSDN white paper on this subject, I’m all over into it.

As the attendees will merely be Silverlight developers (I also hope to welcome some SharePoint developers), I will not much talk about how to integrate Silverlight into SharePoint but more on what can be the added value of using Silverlight in SharePoint.

I will try to show some great demos like a list based on a custom list template that opens a Silverilght-enabled form when the New or Edit button is clicked, and an application page that retrieves and updates SharePoint data. If time permits I will also show a Vista gadget rendering SharePoint information.

Got intrigued? You can register here!

April 22, 2009 Posted by | SharePoint 2007, Silverlight | 5 Comments