<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DevExpertise &#187; Silverlight</title>
	<atom:link href="http://www.devexpertise.com/tag/silverlight/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.devexpertise.com</link>
	<description>Practical tips and tricks for all things .NET, SharePoint, Silverlight, InfoPath, and general application development.</description>
	<lastBuildDate>Wed, 12 May 2010 14:32:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Retrieving SharePoint List Data from Silverlight Without a Custom WCF or ASP.NET Web Service</title>
		<link>http://www.devexpertise.com/2009/02/07/retrieving-sharepoint-list-data-from-silverlight-without-a-custom-wcf-or-aspnet-web-service/</link>
		<comments>http://www.devexpertise.com/2009/02/07/retrieving-sharepoint-list-data-from-silverlight-without-a-custom-wcf-or-aspnet-web-service/#comments</comments>
		<pubDate>Sun, 08 Feb 2009 02:35:52 +0000</pubDate>
		<dc:creator>DevExpert</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[XAML]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.devexpertise.com/2009/02/07/retrieving-sharepoint-list-data-from-silverlight-without-a-custom-wcf-or-aspnet-web-service/</guid>
		<description><![CDATA[I’ve done a little work in the recent months with Silverlight, specifically with leveraging Silverlight inside of SharePoint.&#160; My first project involved a pulling in data from SharePoint via a WCF service, and while it worked, it took a long time to configure correctly and to add the necessary components to SharePoint in order for [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve done a little work in the recent months with Silverlight, specifically with leveraging Silverlight inside of SharePoint.&#160; My first project involved a pulling in data from SharePoint via a WCF service, and while it worked, it took a long time to configure correctly and to add the necessary components to SharePoint in order for it to work.&#160; <a href="http://www.winsmarts.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.winsmarts.com');" target="_blank">Sahil Malik</a> describes a method beginning <a href="http://blah.winsmarts.com/2008-5-SharePoint_2007_as_a_WCF_host_-_Step_-1,_make_a_WCF_Home.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blah.winsmarts.com');" target="_blank">here</a>, and as you can see it’s definitely doable but not the simplest approach.</p>
<p>While creating a WCF will offer you the most power and flexibility when it comes to the data it can expose, as you can manipulate SharePoint data (or any data for that matter) any way you like.&#160; In this post, I’m going to show you how to retrieve SharePoint list data in Silverlight the “old-fashioned” way – by using the out-of-the-box SharePoint web services, and executing an <a href="msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx" target="_blank">HttpWebRequest</a> to get our data.</p>
<p>Because there are a ton of different concepts I could elaborate on related to Silverlight and SharePoint, such as creating a web part host, configuring SharePoint for Silverlight, etc., for the sake of this post I’m going to keep it focused on the data retrieval only.&#160; In future posts, I’ll dive into my approach for hosting a Silverlight app in SharePoint.&#160; Also, take a look at <a href="http://karinebosch.wordpress.com/2009/01/22/22/" onclick="javascript:pageTracker._trackPageview('/outbound/article/karinebosch.wordpress.com');" target="_blank">this post</a> from <a href="http://karinebosch.wordpress.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/karinebosch.wordpress.com');" target="_blank">Karine Bosch</a> – she has a very similar approach and hers is a lot prettier than mine!</p>
<p>First, I defined the “Widgets” list I want to retrieve data from. In addition to the Title field, it contains a Description field and an Image field:<a href="http://www.devexpertise.com/wp-content/uploads/2009/02/image27.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="438" alt="image" src="http://www.devexpertise.com/wp-content/uploads/2009/02/image-thumb25.png" width="610" border="0" /></a></p>
<p>Next, I created a new Silverlight application in Visual Studio, and defined a Widget class, which will serve as the representation of a Widget list item:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas,&#39;Courier New&#39;,courier,monospace; background-color: #f4f4f4">
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Widget </span>{
    <span style="color: blue">public string </span>Title { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Description { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>ImageUrl { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
}</pre>
</div>
<p>I also added a few class-level variables in my Page.xaml.cs file, which I’ll use in my data methods:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas,&#39;Courier New&#39;,courier,monospace; background-color: #f4f4f4">
<pre class="code"><span style="color: blue">private </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Widget</span>&gt; _widgets = <span style="color: blue">null</span>;
<span style="color: blue">private </span><span style="color: #2b91af">Stream </span>_body = <span style="color: blue">null</span>;
<span style="color: blue">private string </span>_responseString;</pre>
</div>
<p>For the data retrieval, I’m going to be leveraging the out-of-the-box Lists.asmx web service to retrieve the list items, and build an HttpWebRequest object.&#160; The <a href="msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx" target="_blank">BeginGetRequestStream</a> method executes the request, and will asynchronously call the RequestCallback method when it finishes:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 1200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas,&#39;Courier New&#39;,courier,monospace; background-color: #f4f4f4">
<pre class="code"><span style="color: blue">private void </span>GetData() {
    <span style="color: blue">try </span>{
        <span style="color: #2b91af">Uri </span>listUri = <span style="color: blue">new </span><span style="color: #2b91af">Uri</span>(<span style="color: #a31515">&quot;http://server/_vti_bin/Lists.asmx&quot;</span>, <span style="color: #2b91af">UriKind</span>.Absolute);
        <span style="color: #2b91af">HttpWebRequest </span>request = (<span style="color: #2b91af">HttpWebRequest</span>)<span style="color: #2b91af">WebRequest</span>.Create(listUri);

        request.Method = <span style="color: #a31515">&quot;POST&quot;</span>;
        request.ContentType = <span style="color: #a31515">&quot;application/soap+xml; charset=utf-8&quot;</span>;
        request.Headers[<span style="color: #a31515">&quot;ClientType&quot;</span>] = <span style="color: #a31515">&quot;Silverlight&quot;</span>;
        request.BeginGetRequestStream(<span style="color: blue">new </span><span style="color: #2b91af">AsyncCallback</span>(RequestCallback), request);
    }
    <span style="color: blue">catch </span>(<span style="color: #2b91af">Exception </span>ex) {
        HandleException(ex);
    }
}</pre>
</div>
<p>Here’s where the real work needs to be done.&#160; In our callback method, we need to build a SOAP envelope that will be passed to the web service in order to get a valid response.&#160; If you’re uncertain where to find that envelope or are unsure if how it should be formatted, simply browse to the web service itself and click the method that you will be executing:</p>
<p><a href="http://www.devexpertise.com/wp-content/uploads/2009/02/image28.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="447" alt="image" src="http://www.devexpertise.com/wp-content/uploads/2009/02/image-thumb26.png" width="713" border="0" /></a></p>
<p>Once the SOAP envelope format is determined, simply add in the listName, viewName (if necessary), query, viewFields, and queryOptions, and you have your envelope.&#160; The next step is to get the response by asynchronously executing the <a href="msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx" target="_blank">BeginGetResponse</a> method and passing in the ResponseCallback callback method:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 1200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas,&#39;Courier New&#39;,courier,monospace; background-color: #f4f4f4">
<pre class="code"><span style="color: blue">private void </span>RequestCallback(<span style="color: #2b91af">IAsyncResult </span>asyncResult) {
    <span style="color: blue">try </span>{
        <span style="color: blue">string </span>envelope =
            <span style="color: #a31515">@&quot;&lt;?xml version=&quot;&quot;1.0&quot;&quot; encoding=&quot;&quot;utf-8&quot;&quot;?&gt;
                &lt;soap12:Envelope
                 xmlns:xsi=&quot;&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&quot;
                 xmlns:xsd=&quot;&quot;http://www.w3.org/2001/XMLSchema&quot;&quot;
                 xmlns:soap12=&quot;&quot;http://www.w3.org/2003/05/soap-envelope&quot;&quot;&gt;
                    &lt;soap12:Body&gt;
                        &lt;GetListItems xmlns=&quot;&quot;http://schemas.microsoft.com/sharepoint/soap/&quot;&quot;&gt;
                            &lt;listName&gt;Widgets&lt;/listName&gt;
                            &lt;query&gt;
                                &lt;Query xmlns=&quot;&quot;&quot;&quot;&gt;
                                    &lt;OrderBy&gt;
                                        &lt;FieldRef Name=&quot;&quot;Title&quot;&quot; /&gt;
                                    &lt;/OrderBy&gt;
                                &lt;/Query&gt;
                            &lt;/query&gt;
                            &lt;viewFields&gt;
                                &lt;ViewFields xmlns=&quot;&quot;&quot;&quot;&gt;
                                    &lt;FieldRef Name=&quot;&quot;Title&quot;&quot; /&gt;
                                    &lt;FieldRef Name=&quot;&quot;Description&quot;&quot; /&gt;
                                    &lt;FieldRef Name=&quot;&quot;Image&quot;&quot; /&gt;
                                &lt;/ViewFields&gt;
                            &lt;/viewFields&gt;
                            &lt;queryOptions&gt;
                                &lt;QueryOptions xmlns=&quot;&quot;&quot;&quot;&gt;
                                    &lt;IncludeMandatoryColumns&gt;False&lt;/IncludeMandatoryColumns&gt;
                                &lt;/QueryOptions&gt;
                            &lt;/queryOptions&gt;
                        &lt;/GetListItems&gt;
                    &lt;/soap12:Body&gt;
                &lt;/soap12:Envelope&gt;&quot;</span>;

        <span style="color: #2b91af">UTF8Encoding </span>encoding = <span style="color: blue">new </span><span style="color: #2b91af">UTF8Encoding</span>();
        <span style="color: #2b91af">HttpWebRequest </span>request = (<span style="color: #2b91af">HttpWebRequest</span>)asyncResult.AsyncState;
        _body = request.EndGetRequestStream(asyncResult);
        envelope = <span style="color: blue">string</span>.Format(envelope, _listName);
        <span style="color: blue">byte</span>[] formBytes = encoding.GetBytes(envelope);

        _body.Write(formBytes, 0, formBytes.Length);
        _body.Close();

        request.BeginGetResponse(<span style="color: blue">new </span><span style="color: #2b91af">AsyncCallback</span>(ResponseCallback), request);
    }
    <span style="color: blue">catch </span>(<span style="color: #2b91af">WebException </span>ex) {
        HandleException(ex);
    }
}</pre>
</div>
<p>The ResponseCallback method is responsible for determining that the response is valid, and to get the data out of the response.&#160; Once the data is retrieved from the response stream, the only step left is to process that data, and for that we call ProcessResponse.&#160; We must use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.begininvoke(VS.95).aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');" target="_blank">BeginInvoke</a>() method of the page’s <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher(VS.95).aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');" target="_blank">Dispatcher</a> object, because all of the data retrieval is done asynchronously on a different thread.&#160; Since you can’t modify controls on a different thread than the one it was created on, we have to invoke it this way and let Silverlight handle the thread marshalling:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 1200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas,&#39;Courier New&#39;,courier,monospace; background-color: #f4f4f4">
<pre class="code"><span style="color: blue">private void </span>ResponseCallback(<span style="color: #2b91af">IAsyncResult </span>asyncResult) {
    <span style="color: #2b91af">HttpWebRequest </span>request = (<span style="color: #2b91af">HttpWebRequest</span>)asyncResult.AsyncState;
    <span style="color: #2b91af">HttpWebResponse </span>response = (<span style="color: #2b91af">HttpWebResponse</span>)request.EndGetResponse(asyncResult);
    <span style="color: #2b91af">Stream </span>content = response.GetResponseStream();

    <span style="color: blue">if </span>(request != <span style="color: blue">null </span>&amp;&amp; response != <span style="color: blue">null</span>) {
        <span style="color: blue">if </span>(response.StatusCode == <span style="color: #2b91af">HttpStatusCode</span>.OK) {
            _widgets = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Widget</span>&gt;();

            <span style="color: blue">using </span>(<span style="color: #2b91af">StreamReader </span>reader = <span style="color: blue">new </span><span style="color: #2b91af">StreamReader</span>(content)) {
                _responseString = reader.ReadToEnd();
                reader.Close();
            }

            <span style="color: blue">try </span>{

                <span style="color: blue">this</span>.Dispatcher.BeginInvoke(ProcessResponse);

            }
            <span style="color: blue">catch </span>(<span style="color: #2b91af">WebException </span>ex) {
                HandleException(ex);
            }
        }
    }
}</pre>
</div>
<p>And finally, the ProcessResponse method that parses the response data and creates are Widgets collection, which is then set as the page’s DataContext:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 1200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas,&#39;Courier New&#39;,courier,monospace; background-color: #f4f4f4">
<pre class="code"><span style="color: blue">private void </span>ProcessResponse() {
    XDocument results = XDocument.Parse(_responseString);

    _widgets = (<span style="color: blue">from </span>item <span style="color: blue">in </span>results.Descendants(XName.Get(<span style="color: #a31515">&quot;row&quot;</span>, <span style="color: #a31515">&quot;#RowsetSchema&quot;</span>))
                <span style="color: blue">select new </span><span style="color: #2b91af">Widget</span>() {
                    Title = item.Attribute(<span style="color: #a31515">&quot;ows_Title&quot;</span>).Value,
                    Description = item.Attribute(<span style="color: #a31515">&quot;ows_Description&quot;</span>).Value
                    ImageUrl = FormatImageUrl(item.Attribute(<span style="color: #a31515">&quot;ows_Image&quot;</span>).Value),
                }).ToList();

    <span style="color: blue">this</span>.DataContext = _widgets;
}

<span style="color: blue">private string </span>FormatImageUrl(<span style="color: blue">string </span>value) {
    <span style="color: blue">return </span>value.Substring(0, value.IndexOf(<span style="color: #a31515">','</span>));
}</pre>
</div>
<p>Now that we have our data, creating a snazzy Silverlight web part is only limited by your creativity and XAML-slinging skills.&#160; Here’s a quick and dirty snippet to verify we’re actually getting data:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 1200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas,&#39;Courier New&#39;,courier,monospace; background-color: #f4f4f4">
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">UserControl </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Class</span><span style="color: blue">=&quot;DevExpertise.Silverlight.App.Page&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">x</span><span style="color: blue">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; &gt;
    &lt;</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">Grid </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;LayoutRoot&quot; </span><span style="color: red">Background</span><span style="color: blue">=&quot;White&quot;&gt;
            &lt;</span><span style="color: #a31515">ListBox </span><span style="color: red">ItemsSource</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding</span><span style="color: blue">}&quot; </span><span style="color: red">VerticalAlignment</span><span style="color: blue">=&quot;Stretch&quot;&gt;
                &lt;</span><span style="color: #a31515">ListBox.ItemTemplate</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">DataTemplate</span><span style="color: blue">&gt;
                        &lt;</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
                            &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                                &lt;</span><span style="color: #a31515">Image </span><span style="color: red">Source</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ImageUrl</span><span style="color: blue">}&quot; </span><span style="color: red">Height</span><span style="color: blue">=&quot;40&quot; /&gt;
                                &lt;</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                                    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Title</span><span style="color: blue">}&quot; </span><span style="color: red">FontWeight</span><span style="color: blue">=&quot;Bold&quot; /&gt;
                                    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Description</span><span style="color: blue">}&quot; /&gt;
                                &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                            &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                        &lt;/</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
                    &lt;/</span><span style="color: #a31515">DataTemplate</span><span style="color: blue">&gt;
                &lt;/</span><span style="color: #a31515">ListBox.ItemTemplate</span><span style="color: blue">&gt;
            &lt;/</span><span style="color: #a31515">ListBox</span><span style="color: blue">&gt;
        &lt;/</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
&lt;/</span><span style="color: #a31515">UserControl</span><span style="color: blue">&gt;</span></pre>
</div>
<p>…and voila!&#160; Silverlight in SharePoint consuming list data:</p>
<p><a href="http://www.devexpertise.com/wp-content/uploads/2009/02/image29.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="426" alt="image" src="http://www.devexpertise.com/wp-content/uploads/2009/02/image-thumb27.png" width="722" border="0" /></a></p>
<p>That’s all it takes to get data from SharePoint without using a custom web service or having to go through the hassle of building and deploying a WCF service.&#160; In a future post, I’ll describe how to build a generic and reusable web part to host Silverlight applications.&#160; Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devexpertise.com/2009/02/07/retrieving-sharepoint-list-data-from-silverlight-without-a-custom-wcf-or-aspnet-web-service/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

