Monday, April 27, 2009

Silverlight: The easiest method to get SharePoint list data

In this post, I will share the simplest, most direct method I’ve found to access SharePoint list data from a Silverlight control hosted within a SharePoint web part. Contrary to most examples I’ve seen, this methodology will not require any custom web services. I’m am however going to assume that you have a working knowledge of how to build a simple SharePoint Web Part and a simple Silverlight control.

In learning new programming techniques, I’d rather read code examples than listen to some one bloviate, so for your reference this article uses four code listings which can be found in this online repository. These listings are:

Step 1: Getting the list data

In this step, we’ll use our old friend owssvr.dll to fetch an XML representation of our list data. For any given list in SharePoint, its XML data can get accessed using this URL:


In the above URL, Guid is the Id for your SharePoint list. To find out the Guid for your list, visit the list’s settings page and snag the Guid from the Url.

Step 2: Create the web part host

In Listing 1, we create a web part to host our Silverlight control. This web part will “lazy load” the Silverlight control’s compiled .xap file at runtime. I recommend uploading the .xap file to a SharePoint document library. This web part has 2 properties; the relative path to our .xap file and the Guid of our SharePoint list. Note that this technique still allows for complete step debugging.

Step 3: Silverlight Application file

In Listing 2, the Silverlight application file handles receiving parameters from our web part and passing the list Guid on to the Silverlight control itself.

Step 4: Silverlight Page code behind

The code in Listing 3 does most of the heavy lifting. This is where we fetch and parse the list data’s XML.

Step 5: Silverlight Page Xaml

Listing 4 is a simple Silverlight Xaml page with a DataGrid added.

And there you have it. I believe this technique to be the simplest, most direct method of fetching SharePoint list data for use in Silverlight. Questions or comments?

Thursday, April 16, 2009

SharePoint Data Zoom: Handling Complex List Field Types

The free SharePoint Data Zoom Web Part gives you the power and flexibility of creating SharePoint apps from .NET code, but with a much quicker result and without the hassles of coding, compiling and deploying your solution.
As a case and point, let’s take a look at the $SPFields context item. We’ve added $SPFields to provide better support for “hard to access” SharePoint list fields like Look-up, User, URL, Multi-Column, Multi-Choice and Rating Scale fields. To illustrate, let’s look at an example:
 1## Get the list
 2#set( $myLinksList = $web.lists.get_item("DOT Links") )
 4#foreach($myLink in $myLinksList.Items)
 6 ## Get hard to read SharePoint fields
 7 #set( $urlValue = $SPFields.GetUrlValue($myLink.get_item("URL")) )
 8 #set( $stateValue = $SPFields.GetLookupValue($myLink.get_item("State")) )
 9 #set( $ownerValue = $SPFields.GetUserValue($web, $myLink.get_item("Owner")) )
11 #beforeall
12   <table class="ms-listviewtable" cellpadding="3" cellspacing="0" border="0" width="100%">
13     <tr class="ms-viewheadertr">
14       <th class="ms-vh2-nofilter">Title</th>
15       <th class="ms-vh2-nofilter">State</th>
16       <th class="ms-vh2-nofilter">Owner</th>
17     </tr>
18 #odd
19     <tr class="">
20 #even
21     <tr class="ms-alternating">
22 #each
23       <td class="ms-vb2"><a href="$urlValue.URL">$urlValue.Description</a></td>
24       <td class="ms-vb2">$stateValue.LookupValue</td>
25       <td class="ms-vb2">$ownerValue.LookupValue</td>
26 #after
27     </tr>
28 #afterall
29   </table>
30 #nodata
31   No links found

In line 2 two of the example above, we load a variable $myLinksList with the “Dot Links” list. In line 4, we begin a for..each loop to iterate over each item in the list. On line 7 though 9, you’ll notice that we’re using the $SPFields context object to set the variables for three complex fields. $SPFields.GetUrlValue will handle parsing the URL type fields, while $SPfields.GetLookupValue can hand fetching the value of a lookup field from another list! Finally, $SPFields.GetUserValue handles parsing a User type field for you.
If you drop your attention down to lines 23 through 25, you’ll see where the convenience of the $SPFields context item really shines. For the URL field, we simply need to call $urlValue.URL and $urlValue.Description to get at our data. With the lookup and user field types, calling $stateValue.LookupValue and $ownerValue.LookupValue does the trick.
Here’s a screen shot of the simple output:

Convenient and flexible yet powerful! Don’t you agree?

Wednesday, April 15, 2009

Released: SharePoint Data Zoom Web Part 1.0.9104.2

We've released an updated version of the SharePoint Data Zoom Web Part with some improvements.

In this release:

  • The $SPFields context item was added to provide better support for hard to access fields like Look-up, User, URL, Multi-Column, Multi-Choice and Rating Scale fields.
  • Additional methods added to the $SPUtility context item to provide a simple, robust way to retrieve the root web, a web by ID and a web by name/path. These methods ensure the SPWeb objects are disposed properly when the context exists.
  • Two Split methods added to the $Expressions context item which allow you to split a string using a regular expression.

Thursday, April 09, 2009

How to Emulate User Roles in InfoPath Forms Services to Automatically Switch Views

Many of my SharePoint consulting clients and students express the need to have different users see different views of an InfoPath form. In the InfoPath client, this is easy to handle using the User Roles
functionality which has been well-documented elsewhere. Unfortunately, User Roles are not supported by InfoPath Forms Services for your browser-enabled forms. Here is a work-around that I have been using for quite some time that has worked well for me and my clients and students.

In this post we'll create a simple InfoPath form with two views: one view for most users and another view for administrators only. When the form loads, it will check to see if the current logged in user is an Administrator for that form and if he is it will display the Admin View to the user. If the user is not an administrator for the form, it will display the User View.

Create a Custom List to Store Users and Permission Levels

Although SharePoint exposes a number of web services that reveal security information and information about SharePoint Groups, I've never been able to get them to work reliably with InfoPath, especially without writing code. Since I can't use SharePoint Groups, I create a custom list to store the names of my users who will be administrators.

  1. Create a custom list called My Form Admins.
  2. Change the name of the Title column to Permission Level.
  3. Create a new column named User, of type Person or Group. Set the Showfield to User Name.
  4. Add a couple users.
  5. Your list should look similar to this:

Create a New InfoPath Form with Two Views

Obviously, you'll need an InfoPath form to use this, so launch InfoPath and create a new blank form.

Within this form, create two views. Rename the default view to User View, name the other one Admin View. You don't have to add any fields on these views, but you can if you want. You will want to make them distinct so you know which view you are looking at, but it could be as simple as just putting the text "User View" and "Admin View" on the top of each view; that's what I did for this post.

Add Some Nodes to Store the Decisioning Information

In my form, I created a new group named AdminCheckingNodes, with two nodes both of type Text named Current UserUserName, and CurrentUserPermissionLevel. These will be used to store the User name of the current logged in user and his permission level, if one is set, in the My Form Admins list in SharePoint.

Add a Data Connection to the SharePoint List Containing the Admin Names

The form needs to be able to look at the My Form Admins list in SharePoint to determine the Permission Level of the current user. Create a data connection to this list.

  1. Click on Tools, Data Connections.
  2. Click Add.
  3. Create a new connection to Receive Data
    from a SharePoint Library or List.
  4. Paste in the path to the My Form Admins list.
  5. Select the My Form Admins list.
  6. Select both the Permission Level and User fields.
  7. Accept all the other defaults in the wizard and close the Data Connection window.

Write Rules to Get the Current User's Permission Level

You need to write four rules to fire when the form first loads.

The first rule will store the name of the current user in the CurrentUserUserName

  1. Click on Tools, Form Options.
  2. Select the Open and Save category.
  3. In the Open Behavior section , click on the Rules button.
  4. Click the Add button.
  5. For the Rule Name, enter "Store Name of Current User".
  6. Click the Add Action button.
  7. Select the
    Set a field's value
  8. For the Field, select the CurrentUserUserName node.
  9. For the Value, click the Data Binding button. Click the Insert Function button, select userName. Click OK, and OK. Your form should look like this:

  10. Click OK. The completed rule will look like this:

  11. Click OK to close the Rules dialog.

Whew! That may have seemed like a lot, but it's only part of what we need to do. You still need to write three more rules. Your Rules for OpeningForms dialog should look like this.

  1. Click the Add button.
  2. For the Rule Name enter, "Clear out the current permission level". You need to do this just to make sure this field is empty in case the current user isn't listed in you're My Form Admins list.
  3. Click the Add Action button.
  4. Select the
    Set a field's value
  5. For the Field, select the CurrentUserPermisisonLevel node.
  6. For the Value, just leave the field blank. Click OK, and OK. Your form should look like this:

  7. Click OK. The completed rule will look like this:

  8. Click OK to close the Rules dialog.
  9. You should have two rules now. You're half done!

The next rule will look at the SharePoint list and store the permission level of the user, if the user's name is in the list.

  1. Click the Add button.
  2. For the Rule Name enter, "Look up and store the current user's permission level".
  3. Click the Add Action button.
  4. Select the
    Set a field's value
  5. For the Field, select the CurrentUserPermisisonLevel node.
  6. For the Value, click on the data binding button.
  7. In the Insert Formula dialog, click on the Insert Field or Group button.
  8. Change the Data Source to My Form Admins (Secondary).
  9. Expand out all the nodes and select Permission Level.

  10. Click on the Filter Data… button.
  11. Click the Add button.
  12. In the first drop-down, select Select a field or group….Then select User, then click OK.
  13. Leave the second drop-down with is equal to.
  14. In the third drop-down, select Select a field or group….Then change the Data Source to Main, select the CurrentUserUserName node. Your condition should look lieke this:

  15. Click OK on the next four dialogs. Your form should look like this:

  16. Click OK three more times. Your rules should look like this:

You're almost done!. Just one more rule to write, then you can publish and test your form. The last rule will look at the value stored by the previous rule and will switch views if it contains the word "Admin."

  1. Click the Add button.
  2. For the Rule Name enter, "Switch to admin view if user is an admin".
  3. This rule will have a condition to check the permission level you stored with the previous rule. Click the Set Condition button.
  4. In the first drop-down, select Select a field or group….Then select CurrentUserPermissionLevel, then click OK.
  5. Leave the second drop-down with is equal to.
  6. In the third drop-down, select Type Text….Type the word "Admin" without the quotes; InfoPath will automatically add quotes for you. Your condition should look like this:

  7. Click OK.
  8. Click the Add Action button.
  9. Select the
    Switch Views
  10. For the view, select the Admin View, and click OK.
  11. Your completed rule will look like this:
  12. Click OK. All four rules should look like this:
  13. Click OK twice to return to your form.

Publish and Test the Form

Now you're ready to test the form! Woohoo! The easiest way to do this is to switch to the User View, then click the Preview button. If you are not listed as an Admin in the My Form Admins table, you shouls see the User View.

Close the form, add yourself as an Admin in the SharePoint list and then preview the form again. You should see the Admin view.


You can do a lot more with this besides just switch views. For example, depending on the permission level you set for the current user, the form may call different web services to populate certain fields of information. You could choose to show or hide different sections using Conditional Formatting. When users with certain permission levels submit the form, you may have a SharePoint Designer workflow check to see if it was submitted by an Administrator, and if it was, do something different than if it was submitted by a regular user. The uses of this are limitless. Let me know in the comments how you plan to make use of this.

SharePoint Data Zoom: What the heck is NVelocity and why should you care?

A few weeks back I announced that we'll be releasing a free web part called the SharePoint Data Zoom Web Part. I'm happy to say that the web part was made publicly available yesterday. In my original post, I made mention of the NVelocity template engine, explaining that NVelocity provided the basis for creating scripts in Data Zoom. In this post, I'd like to give a little more background on NVelocity and begin to show you how the SharePoint Data Zoom Web Part is going to help you get your job done.
You may be asking yourself , "why would I want to use NVelocity for creating SharePoint web applications?". Well, NVelocity is a port to the .NET framework of the Java Apache Software Foundation Velocity project . If you are migrating an existing Java-based application to .NET, and the existing application was written with the Velocity template engine, then using NVelocity could make the migration process much smoother.
Not coming from Java? No problem. Like me, you may just prefer the template syntax of NVelocity over the syntax used in a normal ASP.NET Web Forms page. The Velocity Template Language was designed specifically for building HTML pages. Velocity provides you with a very clean syntax for performing common operations such as iterating over a set of database records and displaying each record in an HTML page. One could say that Velocity and NVelocity are Domain Specific Languages for HTML.
A while back, the folks at the Castle Project took NVelocity and branched it for the purpose of fixing bugs and making a few improvements. The Castle Project maintains the MonoRail code base, a popular Model-View-Control framework (MVC). As you may have already guessed, the "view" in MonoRail's MVC is provided by none other than NVelocity.
OK, let's move on to helping you get your job done with Data Zoom. What does an NVelocity script look like? Is NVelocity really that easy to use? Well, I'll let you be the judge. In the context of our SharePoint Data Zoom Web Part, here's a simple NVelocity example:
1 <div style="padding:10px">
3 #if( $user )
4   Hello $user.Name, welcome back to the '$web.Title' site.
5 #else
6   Welcome to the '$web.Title' site.
7 #end
9 </div>

The above example looks amazingly just like HTML, no? Of course, with the exception of some dollar signs ($) and an 'if..else..end' block. The dollar signs indicate variables, which are really .NET objects in disguise. In the SharePoint Data Zoom Web Part, we provide you with some SharePoint "context" objects to make your life easier. In this case, $user is the current web user, and $web is the current SharePoint web object (see line 4 and line 6). Thus, $user.Name is the name property for the current user, and $web.Title is the title property for the current web site. Piece of cake! It gets even better though. We’ve included a source editor with the Data Zoom web part that will let you create scripts from right there in your SharePoint pages. And just so you don’t have to remember all the names, properties and complicated syntax for intimidating SharePoint objects like “$web.Title” and “$user.Name”, we’ve created a menu system in the source editor which inserts snippets for you in just one click.
Here's a slightly more advanced example. In this case, we'll get the "Tasks" list from the current web site and display its Title, Created and Modified fields for each item in the list:
 1 ## Get the tasks list
 2 #set( $tasksList = $web.lists.get_item("Tasks") )
 4 ## Get edit url information
 5 #set( $sourceUrlEncoded = $HttpUtility.UrlEncode($request.RawUrl) )
 6 #set( $editForm = $tasksList.Forms.get_item($PAGETYPE_PAGE_EDITFORM) )
 8 #foreach($item in $tasksList.Items)
 9  #beforeall
10    <table class="ms-listviewtable" cellpadding="3" cellspacing="0" border="0" width="100%">
11      <tr class="ms-viewheadertr">
12        <th class="ms-vh2-nofilter">Title</th>
13        <th class="ms-vh2-nofilter">Created</th>
14        <th class="ms-vh2-nofilter">Modified</th>
15      </tr>
16  #odd
17      <tr class="">
18  #even
19      <tr class="ms-alternating">
20  #each
21        <td class="ms-vb2"><a href="$web.Url/$editForm.Url?ID=$item.ID&Source=$sourceUrlEncoded">$item.Title</a></td>
22        <td class="ms-vb2">$item.get_item("Created").ToString("d")</td>
23        <td class="ms-vb2">$item.get_item("Modified").ToString("d")</td>
24  #after
25      </tr>
26  #afterall
27    </table>
28  #nodata
29    No tasks found
31 #end

Lines such as 2 and 4 which begin with "##" double pounds signs are just comments. Read them or ignore them. On lines 2,5 and 6 we're calling the "#set" directive to assign values in our own user variables. Specifically, line 2 is where we get the Tasks list. On line 8, we begin a "for..each..end" loop that does the work of running through the Tasks list and printing each item's Title, Created and Modified field values. Slightly more involved than the first example, but still pretty darn simple! By the time you were able to get logged into SharePoint Designer and started doing the work, you could have already had this script done with the Data Zoom web part. ;)
Well, I've tried to provide you with a bit of history on NVelocity, and I've shown you a few simple examples of how our SharePoint Data Zoom Web Part can make it really easy for you to create applications in SharePoint. These examples have been extremely simple. There are more in depth examples available on the community site (link below). I'll wrap up with a few more notes and links you may find useful as next steps.
  • SharePoint Data Zoom Web Part home page

    - Get more info and download the bits.
  • Help documentation

    - Online documentation.
  • Community site

    - Shared scripts library.
  • Support forums

    - Ask questions, get answers.
Even further reading...

Wednesday, April 08, 2009

SharePoint Data Zoom Web Part Released

The SharePoint Data Zoom Web Part is a free tool which allows SharePoint users to easily build dynamic, data-driven content on any page. Data from SharePoint Sites, SharePoint Lists and virtually any other source can be aggregated and formatted with ease.
Using the Data Zoom Web Part, your SharePoint pages can perform powerful, flexible queries on a variety of data sources using simple, familiar syntax that's easy to write and understand. You'll be able to create robust, value-added SharePoint applications in a fraction of the time, without the need for .NET or XSLT programming.
In our experience, several SharePoint-based applications that would have normally taken a .NET development team a few weeks or more to create by contrast took only a few days with the SharePoint Data Zoom Web Part.

We are starting to Tweet!

We now have an account for our company, SharePoint Solutions, on Twitter. You can catch up with us on Twitter at @SharePointSol