Docstoc

Building Silverlight Custom Field Controls

Document Sample
Building Silverlight Custom Field Controls Powered By Docstoc
					Hands-On Lab
Building Silverlight Custom Field Controls
Lab version:    1.0.0
Last updated:   12/2/2011
CONTENTS




OVERVIEW ................................................................................................................................................... 3

EXERCISE 1: BUILDING THE CUSTOM FIELD CONTROL ..................................................................... 4
       Task 1 – Preparing ................................................................................................................................. 4
       Task 2 – Telling SharePoint About our Custom Field ............................................................................ 5
       Task 3 – The User Display Control......................................................................................................... 6
       Task 4 – The Field Definition ................................................................................................................. 6
       Exercise 1 Verification ......................................................................................................................... 10

EXERCISE 2: ADDING THE SILVERLIGHT CONTROL .......................................................................... 10
       Task 1 – Examining the Silverlight Markup ......................................................................................... 10
       Task 2 – Adding the Silverlight Control ............................................................................................... 11
       Exercise 2 Verification ......................................................................................................................... 13

EXERCISE 3: INTERACTING WITH SHAREPOINT ................................................................................. 13
       Task 1 – Retrieving Silverlight Parameters.......................................................................................... 13
       Task 2 – Creating the Silverlight Application ...................................................................................... 14
       Exercise 3 Verification ......................................................................................................................... 18

SUMMARY .................................................................................................................................................. 18
Overview
SharePoint ships with thirteen supported field types out of the box, but one of its key strengths is the
ability to add custom field types if the out of the box ones don’t meet your need. If one of the needs
that are not met is a custom display of the data, then a Silverlight custom field control might be the
solution. Adding Silverlight’s rich UI capabilities, along with the managed code and off-server client
object model code, can produce a compelling user experience.


Objectives
This lab will demonstrate how to build a custom SharePoint field control that uses a Silverlight
application to provide the end user display. Specifically, you will

       Build a custom SharePoint field control
       Add a Silverlight user interface
       Add the code to interact with the SharePoint list



System Requirements
You must have the following items to complete this lab:
       2010 Information Worker Demonstration and Evaluation Virtual Machine

       Microsoft Visual Studio 2010
       Silverlight 4
       Silverlight web part extension for Visual Studio
       Silverlight 4 Toolkit



Setup
You must perform the following steps to prepare your computer for this lab...
        1. Download the 2010 Information Worker Demonstration and Evaluation Virtual Machine and
           create the Hyper-V image.
        2. Install the Visual Studio 2010 Silverlight Web Part. The Silverlight Web Part is an add-on to
           Visual Studio 2010.
        3. Ensure that the latest version of Silverlight 4 is installed.
        4. Install the Silverlight 4 Toolkit.
        5. Run the SetupLab.cmd file from the
           <install>\Labs\BuildingSilverlightCustomFieldControls\Source\Begin folder to establish the
           SharePoint environment necessary for this lab



Exercises
This Hands-On Lab comprises the following exercises:
    1. Building the Custom field control
    2. Adding the Silverlight control
    3. Interacting with SharePoint

Estimated time to complete this lab: 45 minutes.


Starting Materials
This Hands-On Lab includes the following starting materials.
       Visual Studio solutions. The lab provides the following Visual Studio solutions that you can use
        as starting point for the exercises.

                ◦    <install>\Labs\BuildingSilverlightCustomFieldControls\Source\Begin\SLNavigation
                     \SLFieldControl.sln: This solution contains the beginnings of a SharePoint custom
                     field control. You will finish off the field control and add the Silverlight application.

          Note: Inside each exercise folder, you will find an end folder containing a solution with the
          completed lab exercise.




Exercise 1: Building the Custom field
control
In this exercise you will build upon the starter project to finish off a custom SP field control. The starter
solution is set up only to contain the core files required plus a little supporting code. You will explore
the starter project and add the rest of the code.

Task 1 – Preparing
In this task, you will open the starter solution in VS 2010 and explore the environment to understand
what has been done to get things set up for the rest of the exercise.

       1. Using Visual Studio 2010, open the starter solution named SLNavigation from the
          <Install>\labs\BuildingSilverlightCustomFieldControls\source\begin\SLNavigation folder.
          Solution Explorer should look like this:




        Figure 1
        Solution Explorer


        Notice that there are two projects in this solution:
                a. SLSliderField – this is the actual project that will be deployed to SharePoint. It is an
                   Empty SharePoint Project with the items added to it necessary for a custom
                   SharePoint field control. We’ll examine these elements throughout this lab.
                b. Silverlight.XAML.SliderControl.Slider – this is the Silverlight project in which we will
                   build our Silverlight application. The output of this project is packaged with the
                   output of the SLSliderField project and deployed to SharePoint.
    2. Double-click on the Properties node in Solution Explorer underneath the SLSliderField project
       and then open the SharePoint tab. Notice that the checkbox next to Enable Silverlight
       debugging is selected. This is necessary if we need to step through our code later on. Close the
       properties pane.
    3. [Optional] If desired, explore the different files in both projects. There are several files
       included in this starter project

Task 2 – Telling SharePoint About our Custom Field
In this task, you will explore the FldTypes file. This file is responsible for letting SharePoint know about
our new field control. Each FldTypes file must be an XML file that adheres to a defined schema. It must
be placed into the <SharePointRoot>\TEMPLATE\XML folder and must be named fldtypes*.xml, where *
represents a unique identifier. For this lab, the FLDTYPES file is named fldtypes_SliderField.xml.
     1. Open the fldtypes_SliderField.xml file. It is located inside the XML mapped folder of the
        SLSliderField project. Placing it inside this mapped folder will ensure that it ends up in the right
        place when our solution is deployed.
     2. Examine the contents of this file. Notice that the top of the file consists of several field
        definitions – TypeName, TypeDisplayName, TypeShortDescription, etc. Notice, too that
        the FieldTypeClass field defines the assembly that will be loaded when this field control is
        used in a list. It points to the custom class we will build later in this exercise. The bottom part
        of this file includes several custom property definitions – Minimum, Maximum, Step and
        XAPPath. These are used to customize a particular instance of this custom field control when
        it is added to a SharePoint list. We’ll see these custom properties when we are working with
        our custom field control.
     3. Close the fldtypes_SliderField.xml file.

Task 3 – The User Display Control
In this task, you will explore the user control (.ASCX) that is used to render the custom field control on a
form (Display, New or Edit) in SharePoint. In the case of our Silverlight field control, things are a little
different because we are adding all of the controls dynamically, but it is still important to understand the
function that this file serves.
     1. Open the file SliderField_UserDisplay.ascx from the CONTROLTEMPLATES mapped folder.
        Placing the file in this mapped folder will ensure that it ends up in the right place when our
        solution is deployed.
     2. Examine the SharePoint:RenderingControl element. Notice that the ID of the
        RenderingControl matches the TypeName value from the fldtypes_SliderField.xml file –
        SliderField. It is this element of the custom field control that tells SharePoint how to find our
        user control file. SharePoint looks for a RenderingControl with an ID value that matches what it
        finds in the FldTypes file.
     3. As mentioned above, for this particular custom field, the Silverlight control will be added
        programmatically at runtime so our RenderingTemplate is blank. Normally, any controls that
        you include here would be shown on the SharePoint form.

Task 4 – The Field Definition
In this task, you will explore the file that is used to define our custom field control. This is a class file
that inherits from one of the out of the box field types; in this case SPFieldNumber because our slider
control field is used to enter numbers into a SharePoint list.
     1. Open the file SliderField_Definition.cs from the root of the SLSliderField project.
2. Position your cursor on line 30, inside the FieldRenderingControl property getter, and add
   the following code:
   C#
   return new SliderFieldControl(){FieldName = InternalName};



   This code returns an instance of our user control with the FieldName property set appropriately.
   In a more complex custom field control, this class would do more, such as, calculating values,
   returning the control used to render on a mobile device, controlling whether the field is able to
   be sorted and filtered and other things as well. To examine some of the possibilities, position
   your cursor on line 35 and type public override. Intellisense will pop up and show you the
   members that could be used to add additional functionality.
3. Save the SliderField_Definition.cs file.
4. Right-click on the SLSliderField project in Solution Explorer and select Deploy from the context
   menu.




   Figure 2
   Deploy SLSliderField project


  5. Once Visual Studio has deployed the solution, navigate to
     http://intranet.contoso.com/sites/advanced/Lists/Announcements/AllItems.aspx.
  6. Click on the List tab in the Ribbon
  7. Click the Create Column button
Figure 3
Create a Column


8. Enter a name for the new column and select Silverlight Slider Control as the column type.
   This custom column type shows up because of the fldtypes_SliderField.xml file that was
   deployed with our solution




Figure 4
Create a Silverlight Slider Control column


9. After clicking on the Silverlight Slider Control field type, the page will refresh to show the
   custom properties we defined as part of our custom field:
Figure 5
Additional Column Settings


10. Change the minimum, maximum, and step values from their defaults if you wish, but leave
    the XAP Path value set to its default.
11. Click OK to create the new field on the Announcements list. You will be returned to the
    default view of the list with the new column added to the default view:




Figure 6
Slide1 column


12. Click the Add new announcement link to test out the new field. Your screen should look like
    this:
        Figure 7
        Slide1 Field


        The field shows up on the list, but there is nothing rendered to allow us to edit the field. We’ll
        add that in Exercise 2.
        That concludes this exercise. The framework for our custom field control is now complete. In
        later exercises, we will complete this field control to add the rest of the functionality.

Exercise 1 Verification
In order to verify that you have correctly performed all steps of Exercise 1, proceed as follows:

Verification 1
In this verification, you can compare the anticipated output shown in steps 8, 9, 11 and 12 with the
actual output shown on your screen. If your screen shows a similar view, you have completed the
exercise successfully.


Exercise 2: Adding the Silverlight control
This exercise adds the Silverlight control to our custom field control so that something is rendered on
the SP form to allow us to change the value stored in the field.

Task 1 – Examining the Silverlight Markup
In this task, you will review the XAML that is already included in the starter project to render our slider
field. The XAML is fairly long so rather than having you type it all out, you will just examine it.
    1. If the browser window is still open from Exercise 1, close it.
    2. Back in Visual Studio, open the file MainPage.xaml in the SL.XAML.SliderControl.Slider project.
    3. The top part of the file display will show a visual display of the control and the bottom the
       textual markup, the XAML.
    4. Take a few minutes to examine the XAML to see how the UI is built. You can click inside the
       visual display at the top of the page and the corresponding XAML will be highlighted in the
       bottom part of the display.

Task 2 – Adding the Silverlight Control
In this task, you will write the managed code to cause the Silverlight control to be loaded when the user
control for our custom field is loaded by SharePoint.
    1. Open the file SliderField_UserDisplay.aspx.cs (located under the CONTROLTEMPLATES mapped
       folder).
    2. The starter project includes some code already in this file, take a minute to examine what is
       already there. Notice that the class inherits from a class called NumberField. Our class must
       ultimately derive from BaseFieldControl, which NumberField does. Also, it includes some
       functionality to allow the field to store numeric values.
    3. Position your cursor on line 49 and hit <Enter>. Add the following code:
        C#
        valueField = new HtmlInputHidden();
        valueField.ID = ValueFieldNameID;
        valueField.Name = ValueFieldNameID;
        base.Controls.Add(valueField);



        This code adds a hidden HTML field to the HTML DOM. This field will be used to store the value
        selected in the Silverlight application and provide it to SharePoint. Review the existing code
        already in the file for the Value property and the UpdateFieldValueInItem method.
        These two pieces of code work with the hidden HTML field to retrieve the value from the field
        and store the value in the field respectively.
    4. Position your cursor on line 54 and hit <Enter>. Add the following code:
        C#
        double   minimum = (double)Field.GetCustomProperty("Minimum");
        double   maximum = (double)Field.GetCustomProperty("Maximum");
        double   step = (double)Field.GetCustomProperty("Step");
        string   SLSource = (string)Field.GetCustomProperty("XAPPath");
    This code sets up a few variables and populates them with the values retrieved from the four
    custom properties set up inside our fldtypes_SliderField.xml file and seen step 9 of Exercise 1.
5. Position your cursor on line 84 and hit <Enter>. Add the following code:
   C#
   LiteralControl silverlightHost = new LiteralControl(string.Format(@"
        <div id='{0}' style=\"width:100%; height:100%\">{1}</div>",
        SLId, slstring));
   this.Controls.Add(silverlightHost);



    This code actually adds the Silverlight control to our user control (remember that this is the
    code behind for our user control and all of the code we’ve added is inside the
    CreateChildControls method). This code uses the slstring variable we built up in the
    code from lines 60 through 80 that were already in this file. We also make use of a JavaScript
    function that is defined in the JavaScript library \Layouts\SLSliderField\SLUtils.js.
    Open up the JavaScript library in the file \Layouts\SLSliderField\SLUtils.js and examine the
    CreateSL function defined on line 32. This function makes use of the createObjectEx
    method, which is defined in the file Silverlight.js that is deployed with SharePoint. Some of the
    code that was added to the starter project made sure that the two JavaScript libraries
    (Silverlight.js and SLUtils.js) are included on the page – beginning on line 33 in the OnInit
    method.
6. That concludes the coding for this exercise. Right-click on the SLSliderField project in Solution
   Explorer and select Deploy from the context menu.




   Figure 8
   Deploy SLSliderField


7. Once Visual Studio has deployed the solution, navigate to
   http://intranet.contoso.com/sites/advanced/Lists/Announcements/AllItems.aspx.
8. Click the Add new announcement link to test out the new field. Your screen should look like
   this:
        Figure 9
        Slide1 Field


        The field shows up on the list as before, but now includes the Silverlight control. The Silverlight
        control doesn’t include any functionality yet, we’ll add that in Exercise 3.

Exercise 2 Verification
In order to verify that you have correctly performed all steps of Exercise 2, proceed as follows:

Verification 1
In this verification, you can compare the anticipated output shown in step 8 with the actual output
shown on your screen. If your screen shows a similar view, you have completed the exercise
successfully.


Exercise 3: Interacting with SharePoint
This exercise adds the code to the Silverlight project to have it interact with SharePoint.

Task 1 – Retrieving Silverlight Parameters
In this task, you will see how to retrieve parameters passed to Silverlight and add the code to use them
to customize the Silverlight UI.
     1. If the browser is still open from Exercise 2, close it
     2. In Visual Studio 2010, open the file App.xaml.cs from Solution Explorer
     3. Look at the code already in the starter project in the Application_Startup method. Notice the
        use of e.InitParams to retrieve the initiation parameters.
     4. Position you cursor on line 65 and add the following code:
         C#
         this.RootVisual = new MainPage(valueControlId, siteUrl, listId, minimum,
                                        maximum, step, itemId, fieldName, value);



         This code uses the parameters passed into Silverlight from the hosting user control to create a
         new instance of the MainPage object

Task 2 – Creating the Silverlight Application
In this task, you will
        1. Open the file MainPage.xaml.cs from Solution Explorer
        2. Position your cursor on line 46 and enter the following code:
         C#
         ClientContext ctx = new ClientContext(siteUrl);
         list = ctx.Web.Lists.GetById(new Guid(listId));
         ctx.Load(list);
         item = list.GetItemById(itemId);
         ctx.Load(item);
         ctx.ExecuteQueryAsync(OnReadSuccess, OnFailure);



         This code uses the values passed in as parameters and some Silverlight client object model code
         to retrieve the SPListItem being displayed in the current form.
        3. Position your cursor on line 58 and enter the following code:
         C#
         Dispatcher.BeginInvoke(() =>
         {
             object newValueObj = null;
             double newValue;
             newValueObj = item[this.fieldName];
             if (null == newValueObj)
             {
                 SetToMinValue();
             }
             else
             {
                 double.TryParse(newValueObj.ToString(), out newValue);
                 if (newValue < this.MinValue || newValue > this.MaxValue)
                 {
               newValue = this.MinValue;
           }
           SelectedValue = Convert.ToInt32(newValue);
           SetNewValue();
           this.SliderBlock.Visibility = System.Windows.Visibility.Visible;
      }
});



This code runs on the background thread, so we need to make use of an anonymous delegate
and Dispatcher.BeginInvoke since it needs to interact with the UI. It attempts to retrieve the
value of the corresponding field in the current list item. If the value can’t be retrieved for some
reason, the control will be configured to display the minimum value allowed (set from the
custom property in Exercise 1, step 9). Otherwise, it makes sure the current value is legal,
setting it to the minimum value if not, and sets the control to display the current value and
shows the slider block.
4.    Position your cursor on line 86 and enter the following code:
C#
SetToMinValue();



This code will be called if the ExecuteQueryAsync call from either step 2 or step 3 returns a
failure – due to there not being a current item (step 2) or the item not having a value in the
slider field (step 3). In either event, the control will be configured to display the minimum value.
5. Position your cursor on line 89 and enter the following code:
C#
private void SetValueInHiddenControl()
{
    string valuestring =
                  this.SelectedValue.ToString(CultureInfo.InvariantCulture);
    HtmlElement element = HtmlPage.Document.GetElementById(valueControlId);
    if (element != null)
    {
        element.SetAttribute("value", valuestring);
    }
}



This code is called whenever the value displayed in the Silverlight control is changed. It finds the
hidden HTML field that was added to the user control in Exercise 2 step 3, and uses the HTML
Bridge to set its value to the same value as the Silverlight control. This makes sure that the
value will be stored back in SharePoint properly when the form is saved.
6. Take a few minutes to examine the code in the starter project in the code regions – Slider
   properties and Slider methods. For the most part, these members are involved with
   calculating and positioning the slider block appropriately, but there is some interesting code
   that is worth investigating.
That concludes the coding for this exercise. Right-click on the
Silverlight.XAML.SliderControl.Slider project in Solution Explorer and select Rebuild from the
context menu:




Figure 10
Rebuild project


This will refresh the XAP file with our code changes and copy the XAP file to the LAYOUTS/
SLSliderField folder in the SLSliderField project.
7. Right-click on the SLSliderField project in Solution Explorer and select Deploy from the
   context menu.




Figure 11
Deploy SLSliderField


This will rebuild the deployment package to make sure it includes the updated XAP file and then
deploy the solution to SharePoint.
8. Once Visual Studio has deployed the solution, navigate to
   http://intranet.contoso.com/sites/advanced/Lists/Announcements/AllItems.aspx.
9. Depending on how your browser is configured, it may be necessary to clear the browser
   cache so that the new XAP file is downloaded and used. Go ahead and clear the cache now.
10. Click the Add new announcement link to test out the new field. Your screen should look like
    this:




Figure 12
Slider1 Field


The Silverlight control shows up on the list as before, but now includes the slider block to
indicate the value in the field. Notice that it is set to the configured minimum. Change the
slider to a new value and enter that same value in the Title field. Click Save.
11. You will be returned to the default view of the Announcements list with the new item added:




Figure 13
New item added to Announcements List


12. Select Edit Item from the ECB menu of the new item to load the edit form:
        Figure 14
        Slider1 Field


        13. Notice that the slider shows the value you set previously.

Exercise 3 Verification
In order to verify that you have correctly performed all steps of Exercise 3, proceed as follows:

Verification 1
In this verification, you can compare the anticipated output shown in steps 10, 11 and 12 with the actual
output shown on your screen. If your screen shows a similar view, you have completed the exercise
successfully.


Summary
In this lab you have seen how to:

       Build a custom SharePoint field control
       Add a Silverlight user interface

       Add the code to interact with the SharePoint list
The functionality demonstrated in this lab can be used to increase the usefulness a SharePoint site or
application by delivering an improved experience for end users.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:8
posted:12/2/2011
language:English
pages:18