Getting field values of an SPListItem returned from an SPQuery – watch out!

16 02 2010

I have seen and read about this gotcha before but even so I still fell for it today and it took for a couple of hours to figure out so I’ve decided to blog about it.

If you are working with SharePoint items in code which you have returned using a CAML query then you should always populate the SPQuery instance’s ViewFields property. You must include in here all the fields for which you might need to get the value of later. Failure to do this will mean the returned SPListItem instances might not contain the data for certain fields and will throw an exception (usually ‘Value was not within the expected range’).

The ViewFields property is set like this:


    <fieldref name="Title" /><fieldref name="Created" /><fieldref name="ID" />

    

You can then access a fields value on an SPListItem instance using the normal code:


    SPListItem item = list.GetItemById(1);

    string Title = item["Title"].ToString();

    

Hope this helps!!

Advertisements




SharePoint, AJAX UpdatePanel and SPWebPartManager woes

26 01 2010

If you are having trouble getting your AJAX UpdatePanel to update properly in a SharePoint page or Web Part then you have come to the right place. You may already be aware that to get an UpdatePanel working in SharePoint you need to add a an additional function to your code that alters the _spFormOnSubmitWrapper and the _spSuppressFormOnSubmitWrapper. See here for an example –

http://petesullivan.wordpress.com/2008/06/13/ajax-update-panels-and-sharepoint/

However!! If you are using a custom Master Page then watch out because there is another gotcha!

It seems that if the SPWebPartManager tag appears before the Form tag in your master page then your updatepanel will not update properly and most likely won’t display any content. This should be changed so the SPWebPartManager tag appears underneath the form tag, see below for an example –

Incorrect

<WebPartPages:SPWebPartManager ID="SPWebPartManager1" runat="server"/>   
<form id="Form1" runat="server" onsubmit="return _spFormOnSubmitWrapper();">

Correct

<form id="Form1" runat="server" onsubmit="return _spFormOnSubmitWrapper();">
<WebPartPages:SPWebPartManager ID="SPWebPartManager1" runat="server"/>

Hope this helps! 🙂





Creating Custom SharePoint Web Part Connections

25 01 2010

I created my first web part connection the other day and was surprised at how easy and effective it was. I thought I would walk through the process that is required to connect two custom web parts together.

In this brief tutorial I am not going to cover how to create a web part or how to deploy one. I will assume that you (the reader) already knows how to do this. All code in this tutorial will be written in C#.

1. To begin create yourself two web parts – one of these will be the ‘Provider’ and the other the ‘Consumer’. You can create these however you like either using the VseWSS extensions or perhaps in an empty class library project.

2. Create an interface similar to the one below –

 public interface IExampleProvider
 {
        String TestParam { get; }
  
 }

Inside this interface you should define any parameters that you wish to send to your ‘Consumer’ web part.

3. In your Provider web part ensure that it implements the interface you have just created –

 public class ProviderWebPart: WebPart, IGovernanceProvider
 {
 }

4. Next create a property that returns the interface and decorate it with the  ConnectionProvider attribute. The parameters of  are the display name and the real name (ID) of the connection.

 [ConnectionProvider(&quot;Test Parameter&quot;,&quot;ExampleID&quot;, AllowsMultipleConnections=true)]
 public IExampleProvider GetExampleProvider()
 {
    return this;
 }

5. Finally for the Provider web part you need to ensure that the parameter property from your interface is implemented –

protected string _TestParam = &quot;&quot;; 
public string TestParam 
{
 get { return _TestParam; } 
}

6. Now its time to setup the Consumer web part, in your consumer web part class define a method that will accept the interface as a parameter and decorate it with the ConnectionConsumer attribute.

private IExampleProvider exampleProvider;
[ConnectionConsumer(&quot;Site URL&quot;)]
public void RegisterProvider(IExampleProvider provider)
{
   this.exampleProvider = provider;
}

7. You can now retrieve the value/values that have been sent to the consumer web part by calling the properties of the exampleProvider. Note you should check if a connection has been made first by seeing if the exampleProvider is null.

string myParam = this.exampleProvider.TestParam;

8. Deploy your two web parts by whatever method you wish, when you add the web parts to the page and click the ‘edit’ dropdown you should see a new menu option called ‘Connections’. The menu will appear on both the provider and consumer web parts but you only need to configure one.

Consumer Web Part:

image

Provider Web Part:

image

9. You are finished!

I hope you enjoyed this brief tutorial into web part connections, if you have any questions then feel free to leave a comment!

Hope this helps 🙂





Enabling .NET 3.5 support in your SharePoint environment – ‘The easy way’

19 01 2010

I used enable this support manually i.e. opening up the web.config file and making the necessary changes. I felt that this was a safer way to ensure that nothing went wrong. Recently though I have found a much better way to do this – Jan Tielens has a blog post on how to enable .NET 3.5 in SharePoint by using Visual Studio to modify the web.config for you, it works very well and is really quick to do.

You can find his blog post here –

http://weblogs.asp.net/jan/archive/2008/10/10/enabling-net-3-5-in-sharepoint-2007-sites-the-lazy-way.aspx

Thanks Jan!  (@jantielens on Twitter)





Silverlight & Cross-Domain Policy

3 12 2009

If you are creating a Silverlight application that makes calls to a web service – either WCF or standard ASP.NET based then you will more than likely need an xml ‘policy’ file that allows cross domain access.

In my case I was calling one of the SharePoint inbuilt web services – lists.asmx from my silverlight application. When I tried to debug the application I received the following error –

An error occurred while trying to make a request to URI ‘http://localhost/sites/mysite/_vti_bin/lists.asmx’. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place.

To fix this problem you need to create an xml file called ‘clientaccesspolicy.xml’ with the following content –

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="*">
                <domain uri="*" />
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</access-policy>

This xml file should be placed in the IIS virtual directory where your web service is located. In my case the SharePoint site collection that contained the web service was inside the IIS default website so I put the xml file in ‘C:\Inetpub\wwwroot’.

Once you have created this xml file make sure you do an IISRESET. Your silverlight application should now be calling the web service correctly and not throwing the above exception.

Hope this helps 🙂





Getting started with the Bing Maps Silverlight SDK

16 11 2009

I got the chance this morning to have a look at the newly released Bing Maps Silverlight SDK. The bing maps SDK allows you to add a map to your silverlight application and enhance it by adding pushpins, images, videos, shapes and scalable elements etc.

I’m impressed at how easy it is to get a bing map displaying in your silverlight application and start customising it.

I decided to create this getting started guide to help you create a simple silverlight application displaying a bing map.

When you have completed the guide below you should have a map similar to the one below.

image

1. Download and install the Bing Maps Silverlight Control SDK from here –

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=beb29d27-6f0c-494f-b028-1e0e3187e830

2. Create a new ‘Silverlight Application’ project in Visual Studio 2008/2010 whichever you prefer. When the box pops up to asking whether or not you want VS to host the silverlight app in a new web site – make sure its ticked.

3. Add a reference to the dll’s

Microsoft.Maps.MapControl.dll

Microsoft.Maps.MapControl.Common.dll

you can find these dll’s in a subfolder of the installation directory called ‘Libraries’.

4. Create an account at the ‘Bing Maps Account Center’ and create a new application key (you will need this key to be able to use the bing map control) –

https://www.bingmapsportal.com/

4. Open the MainPage.xaml file of your project (not the web project) and a new xml namespace:

xmlns:m=”clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl”

5. Next add the following code inside the Grid control (make sure you paste your bing maps application key into the CredentialsProvider property –

<m:Map
Height=”300″
Width=”350″
x:Name=”testMap”
CredentialsProvider=”Your application key goes here
Background=”White”
Mode=”Road”
Center=”19.642588,50.273438″
ZoomLevel=”0″>
<m:Pushpin Location=”52.97421339369046,-1.246250867843628″/>
<m:Pushpin Location=”-27.469442,153.030136″/>
</m:Map>

6. Refresh the designer in visual studio by clicking the link and then build your project.

7. Hey Presto! – you should now be seeing a bing map just like the one above showing the locations of the ID offices.





Getting started with Silverlight 3 and SharePoint

12 11 2009

Silverlight Logo Recently I have been focusing on creating some Silverlight charts using the ‘Silverlight Toolkit’ from Codeplex (see the link in the instructions below).

Once I had created my first chart I wondered how to get it to display in SharePoint. It seems there are a number of options for displaying a Silverlight application (xap) in a SharePoint web part.

I found lots of blog posts that described separate bits of configuring I needed to do to get Silverlight working happily in SharePoint. I’ve decided to create a getting started list of what you need to do to get Silverlight installed and how to display your xap file with the built in ‘Content Editor Web Part’. I have linked to other blog posts where necessary.

Configuration

1. Download and install the Silverlight 3 runtime from silverlight.net –

http://silverlight.net/getstarted/silverlight3/

2. Download and install the Silverlight 3 SDK and tools for Visual Studio from the silverlight site – 

http://silverlight.net/getstarted/

3. <Optional> Download and install the Silverlight Toolkit (If you want to use some of these cool and free Silverlight controls) –

http://silverlight.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30514

4. If you are running Windows Server 2008 you can skip this step as the MIME types should have been automatically added to IIS7 for you. For server 2003 users you will need to add the Silverlight MIME types to IIS6, follow the instructions here –

http://blogs.technet.com/jorke/archive/2007/09/11/silverlight-mime-types-in-iis6.aspx

5. This step involves configuring the web.config files for the SharePoint sites that you wish to run your Silverlight applications in. Follow the instructions on this blog post –

http://blogs.msdn.com/steve_fox/archive/2009/03/11/amending-the-web-config-file-to-support-silverlight-development-on-sharepoint.aspx

6. Ensure that the assembly System.Web.Silverlight is in the global assembly cache. If not then you can find it at the following location –

C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Server

7. Configuration complete! – now read on to the deployment section

Deployment

To get your silverlight xap displaying on a SharePoint page follow the steps below. In terms of where to store your .xap file there are a number of places for you to choose. Some people recommend storing it in a folder called ‘ClientBin’ in the IIS virtual directory of the SharePoint web application but I was not able to get this working. I opted for the simplest method which was to store the file in a document library.

1. Upload your Silverlight xap file to a document library

2. Switch to edit mode for your SharePoint page and add a Content Editor Web Part

3. Insert the following HTML code – 

<!–<div width=”600px” height=”100px” id=”silverlightControlHost”>
<object data=”data:application/x-silverlight”, type=”application/x-silverlight-2″ width=”450″ height=”450″>
<param name=”source” value=”
http://yoursite/sites/charting/XAPs/SimpleSilverlightChart.xap”/>
<param name=”onerror” value=”onSilverlightError” />
<param name=”background” value=”white” />
<a href=”
http://go.microsoft.com/fwlink/?LinkID=108182″ style=”text-decoration: none;”>
<img src=”
http://go.microsoft.com/fwlink?LinkID=108101″ alt=”Get Microsoft Silverlight” style=”border-style: none”/>
</a>
</object>
<iframe style=’visibility:hidden;height:0;width:0;border:0px’></iframe>
</div> –>

Remember to remove the comments from the above code and replace the param value=”” with the url to your document library and xap file.

4. Click apply and save the changes to your content editor web part

5. If all went well you should be seeing your Silverlight application displaying correctly!

Note: You may need to play around with the width and height of both the <div> and <object> tags to size them correctly for your Silverlight application.

Good Luck! 🙂