Karine Bosch’s Blog

On SharePoint

Adding an Event Receiver to a Content Type using the Visual Studio 2010 tools for SharePoint 2010

One of my blog readers commented that she tried to add an event receiver to a content type, based on the explanation in one of my older walkthroughs, but wasn’t able to deploy successfully. These walkthroughs are written for SharePoint 2007. If you want to develop for SharePoint 2010 using the Visual Studio 2010 tools, it is a completely different story.

I though, this is an easy one, but as I started to rebuild my sample for SharePoint 2010, I came to the conclusion that Visual Studio 2010 offers you the possibility to add event receivers to different types of list instances and to sites, but not to content types. Some bloggers propose to add the content type to the list instance and then test upon the ContentType field value, but that’s not the way to go in my opinion. I wrote a small walkthrough on how to develop an event receiver for a content type.

 

October 12, 2011 Posted by | SharePoint 2007, SharePoint 2010 | 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

A Microsoft SharePoint custom field type for Microsoft CRM Dynamics 4.0

More than two years ago, I wrote an article on how to integrate CRM Dynamics within SharePoint artifacts like a SharePoint custom field. The article was written for SharePoint 2007 but the same technique is still valid for SharePoint 2010. I saw the post on the U2U site had a number of positive comments lately but that the code is not available anymore.

You can read the article in SharePoint Magazine here and download the source code here.

December 15, 2010 Posted by | SharePoint 2007 | 2 Comments

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

Creating SharePoint-like Custom Dialogs

When working with SharePoint you certainly configured a Content Query Web Part. Never wished that you could reuse this dialog from within your code?

When copying a document from a document library to another destination in the SharePoint site, never wished you could browse to the destination instead of typing in the complete URL?
 

When taking a closer look at the source code of the Content Query Web Part, you will see that the HTML button calls a JavaScript function named mso_LaunchListSmtPicker().
 
The JavaScript function is defined in the same source file. It gets a reference to a TextBox, defines a callback function to which the results of the dialog should return, and finally calls the LaunchPickerTreeDialog() function. You can pass along arguments like the URL to the dialog, the dialog title, description, icon and the previously defined callback function.


 
The LaunchPickerTreeDialog() function is defined in the PickerTreeDialog.js file that is located in the 12\TEMPLATE\LAYOUTS\1033 directory. This function on its turn calls the commonShowModalDialog function, passing through the arguments like URL to the dialog, the size of the dialog and the callback function. The dialogUrl argument is a concatination of the URL of the dialog, completed with query string parameters for the dialog title, the description, the icon,…

commonShowModalDialog(dialogUrl, PickerTreeDlgDimension, callback, null);

You can reuse the complete functionality of the CQWP dialog using the LaunchPickerTreeDialog() function but there will be cases that this dialog is too restrictive. In that case you can build your own custom SharePoint-like dialogs.
The sample code contains a demo application page that calls a custom dialog when browse button is clicked.

 
You can download the sample code here. It comes with an install.bat that you can use to deploy the solution.

Project structure

This is the project structure:

Developing the dialog

The dialog itself is an .aspx page that inherits from UnsecuredLayoutsPageBase. It applies the dialog.master.  It is in fact a special type of SharePoint application page. The demo itself the dialog page has a code behind class. This code behind will populate the TreeView with lists and document libraries, and their folders.

<%@ Page Language="C#" Inherits="BPoint.SharePoint.ApplicationPages.DemoDialog" MasterPageFile="~/_layouts/dialog.master"     %>

This type of application pages that build upon the dialog.master have some special content place holders. The content place holder for the PlaceHolderAdditionalPageHead contains two ScriptLink controls: one that references the core.js JavaScript file and one that references the PickerTreeDialog.js file.
It also contains a piece of JavaScript that validates the user selection and returns the results to the callback function defined in the calling application page.

<asp:Content ID="Content2" contentplaceholderid="PlaceHolderAdditionalPageHead" runat="server">
 <SharePoint:ScriptLink ID="ScriptLink1" language="javascript" name="core.js" runat="server" />
 <SharePoint:ScriptLink ID="ScriptLink2" language="javascript" name="PickerTreeDialog.js" runat="server" />

  <script type="text/javascript" Language="javascript">
      function ValidateAndReturn() {
          var strDlgReturnValue = new Array(1);
          strDlgReturnValue[0] = "<%= SelectedUrl.Value %>";
          var strDlgReturnErr = "<%= smtPickerError.Value %>";
          if (strDlgReturnValue[0] == null || strDlgReturnValue[0].length <= 0) {
              alert("Please, select a list or folder from the treeview before clicking the OK button");
          }
          else {
              return HandleOkReturnValues(strDlgReturnValue, strDlgReturnErr);
          }
      }
 </script>
 <SharePoint:FormDigest ID="FormDigest1" runat=server/>
</asp:Content>

Another content control is the one that references the PlaceHolderDialogBodyMainSection place holder. It contains two hidden fields: one will contain the URL to the selected list, document library or folder, and one for an eventual error message. It also contains the ASP.NET TreeView control that will be populated when the dialog loads.

<asp:Content ID="Content6" contentplaceholderid="PlaceHolderDialogBodyMainSection" runat="server">
  <DIV ID="HiddenFields" >
    <asp:HiddenField ID="SelectedUrl" Value="" runat="server" />
    <asp:HiddenField ID="smtPickerError" Value="" runat="server"/>
  </DIV>
  <DIV>
      <asp:TreeView ID="WebTreeview" runat="server" OnSelectedNodeChanged="WebTreeview_SelectedNodeChanged" ExpandDepth="1" ShowExpandCollapse="true" ShowLines="true">
          <NodeStyle HorizontalPadding="5" ForeColor="#666666" font-name="Tahoma" font-size="8pt"/>
          <SelectedNodeStyle BackColor="0x000080" ForeColor="0xFFFFFF" />
      </asp:TreeView>
   </DIV>
</asp:Content>

 

Calling the dialog from within an application page

The demo page is a normal SharePoint application pages inheriting from the LayoutsPageBase class. This page has no code behind. It contains an InputFormSection control that displays a TextBox control and a Browse button.  It also contains some JavaScript that is called when a user clicks the Browse button.
This function does the following:
– gets a reference to the TextBox control,
– defines a callback that will display the selected destination in the TextBox
– defines the URL to the dialog page
– defines the location of the image that need to be displayed in the dialog header
– builds the URL for the dialog page, adding query string parameters
– and finally calls the commonShowModalDialog function in the  PickerTreeDialog.js file.

<script type="text/javascript">
    function launchPicker() {
    var textboxId = "<%SPHttpUtility.NoEncode(URLTextBox.ClientID,Response.Output);%>";
    var textbox = document.getElementById(textboxId);
    var webUrl = <%SPHttpUtility.AddQuote(SPHttpUtility.EcmaScriptStringLiteralEncode(SPContext.Current.Web.Url),Response.Output); %>;
        var callback = function(results) {
            if (results == null || results == undefined)
                return;

                var textbox = document.getElementById(textboxId);
                textbox.value = webUrl + results[0];
        }
        var listId = "";
        var PickerTreeDlgUrl= "/_layouts/BPoint Application Page with Dialog/DemoDialog.aspx";
        var iconUrl="/_layouts/images/BPoint/BPoint.PNG";
        var dialogUrl= TrimLastSlash(webUrl) + PickerTreeDlgUrl+"?title=Copy To&page=<%SPHttpUtility.NoEncode(ListID,Response.Output);%>&iconUrl=" + iconUrl;
        var PickerTreeDlgDimension= "resizable:yes;status:no;location:no;menubar:no;help:no";
        commonShowModalDialog(dialogUrl, PickerTreeDlgDimension, callback, null);
}
function TrimLastSlash(siteUrl)
{
 return (siteUrl.charAt(siteUrl.length - 1)=="/")? siteUrl.substring(0,(siteUrl.length - 1)) : siteUrl;
}

 The possibility of developing your own custom dialogs and making them look as out of the box Sharepoint dialogs, opens a wide range of possibilities. You could even host a Silverlight application within such a dialog.

March 21, 2010 Posted by | SharePoint 2007 | 17 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

Professional SharePoint 2007 Reporting with SQL Server 2008 Reporting Services

When I came home from work tonight, I found a package that I was waiting for a looong time: the recently published book on SharePoint 2007 and SQL Server 2008 Reporting Services. Some months ago I worked on a project where we needed to generate reports based on SharePoint 2007 data using Reporting Services. It was not that easy to put all parts together and to generate descent and useful reports.

It’s finally on the book shelf in your book store. It is published by Wrox but a big thank you goes to the authors Reza Alirezaei, Coskun Cavusoglu and Jacob J. Sanford. Go and get it to have this little jewel on your bookshelf or under your christmas tree.

November 3, 2009 Posted by | SharePoint 2007 | 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