<?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>Visual Stuart</title>
	<atom:link href="http://www.visualstuart.net/blog2/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.visualstuart.net/blog2</link>
	<description>Confessions of a polymath</description>
	<lastBuildDate>Sat, 12 Nov 2011 18:11:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Sharing values across WP7 pages</title>
		<link>http://www.visualstuart.net/blog2/2011/11/sharing-values-across-wp7-pages/</link>
		<comments>http://www.visualstuart.net/blog2/2011/11/sharing-values-across-wp7-pages/#comments</comments>
		<pubDate>Sat, 12 Nov 2011 18:11:39 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/2011/11/sharing-values-across-wp7-pages/</guid>
		<description><![CDATA[When you’re writing a Silverlight application, such as Windows Phone 7 application, it is common to have a value one one page and want to use the value on another page. A good solution for this situation is to use &#8230; <a href="http://www.visualstuart.net/blog2/2011/11/sharing-values-across-wp7-pages/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When you’re writing a Silverlight application, such as Windows Phone 7 application, it is common to have a value one one page and want to use the value on another page. A good solution for this situation is to use application resources, or to be more specific <a href="http://msdn.microsoft.com/en-us/library/cc903952(v=VS.95).aspx">using the ResourceDictionary</a> for the current application. You can access to the application resources using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.application(v=VS.95).aspx">Application</a>.<a href="http://msdn.microsoft.com/en-us/library/system.windows.application.current(v=VS.95).aspx">Current</a>.<a href="http://msdn.microsoft.com/en-us/library/system.windows.application.resources(v=VS.95).aspx">Resources</a> property.</p>
<h2>ApplicationResources class</h2>
<p>If you use application resources frequently, you’ll find that working directly with Application.Current.Resources is a little tedious and can clutter the code with details of working with the <a href="http://msdn.microsoft.com/en-us/library/system.windows.resourcedictionary(v=VS.95).aspx">ResourceDictionary</a> object. I like to wrap these details in a general purpose ApplicationResources class, and then use that class to implement an ApplicationProperties class specific to my application. It provides a nice degree of abstraction, making my application easier to write and later read, and the right amount of reuse across applications.</p>
<p>Let’s start with the ApplicationResources class that I can use without alteration in any WP7 application. This class encapsulates the low-level details of working with application resources. I’ve remove most comments for readability, but you’ll find them in the source code download, see below.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Windows;

<span class="kwrd">namespace</span> VisualStuart.WP7.Applications
{
  <span class="kwrd">public</span> <span class="kwrd">class</span> ApplicationResources
  {

    <span class="kwrd">public</span> <span class="kwrd">static</span> T GetResource&lt;T&gt;( <span class="kwrd">object</span> key )
    {
      <span class="kwrd">object</span> <span class="kwrd">value</span> = AppResources[ key ];
      <span class="kwrd">return</span> ( <span class="kwrd">value</span> == <span class="kwrd">null</span> )  <span class="rem">// if resource doesn't exist or is set to null</span>
        ? <span class="kwrd">default</span>( T )          <span class="rem">// return null for reference type, 0 for numeric value types, etc.</span>
        : (T)<span class="kwrd">value</span>;             <span class="rem">// otherwise return the resource value</span>
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> SetResource( <span class="kwrd">object</span> key, <span class="kwrd">object</span> resource )
    {
      <span class="kwrd">if</span> ( AppResources.Contains( key ) )
        AppResources.Remove( key );

      AppResources.Add( key, resource );
    }

    <span class="rem">// Helper methods</span>

    <span class="kwrd">private</span> <span class="kwrd">static</span> ResourceDictionary AppResources
    { get { <span class="kwrd">return</span> Application.Current.Resources; } }
  }
}
</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>The ResourceDictionary stores resources as System.Object types, so the <strong>GetResource&lt;T&gt;</strong> method adds type safety to the return type. It also deals with two related considerations. First, it is possible for an application to try to get a resource before setting the resource. Rather than flagging that situation as an error, <em>e.g.</em>, by throwing an exception, and making the consuming code deal with that, I’ve opted to return a reasonable default value when getting resource before it is set. Second, the resource type might be a value type (such as bool, int, or a struct) which cannot be null. Now, using a key to index into a ResourceDictionary that does not contain that key will return null. That’s an acceptable value for reference types, but will generate an error for value types. The <a href="http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx">default keyword for generics</a> provides just what is needed for both value and reference types.</p>
<p>The <strong>SetResource</strong> method hides a distracting little detail that application resources are not mutable: once a resource has been added to the ResourceDictionary its value cannot be changed. However, you can create the illusion of changing a resource’s value by first removing the old resource, if it exists, and then adding the new resource.</p>
<p>While the ApplicationResources class successfully encapsulates most of the details of programming with application resources, it does not address the question of managing the keys used within an application. That’s next.</p>
<h2>ApplicationProperties</h2>
<p>I really want to avoid unrestricted use of string literals as application resource keys, sprinkling them throughout my code. The big problem with that is what happens when one of those string values changes, or I just type it wrong in the first place. A string value is a string value, my code will compile without error, and I’ll be faced with debugging a problem that can be extremely subtle to detect. So I like to create an ApplicationProperties class for each application that is the exclusive consumer of the ApplicationResources class in the application.</p>
<pre class="csharpcode"><span class="kwrd">using</span> VisualStuart.WP7.Applications;

<span class="kwrd">namespace</span> WP7ShareValueAcrossPages
{
  <span class="rem">/// &lt;summary&gt;</span>
  <span class="rem">/// Properties backed by application resources.</span>
  <span class="rem">/// &lt;/summary&gt;</span>
  <span class="kwrd">public</span> <span class="kwrd">class</span> ApplicationProperties
  {
    <span class="rem">// Properties</span>

    <span class="rem">// Sample property of a reference type</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> UserText
    {
      get { <span class="kwrd">return</span> ApplicationResources.GetResource&lt;<span class="kwrd">string</span>&gt;( userTextKey ); }
      set { ApplicationResources.SetResource( userTextKey, <span class="kwrd">value</span> ); }
    }

    <span class="rem">// Sample property of a value type</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> UserLikesPears
    {
      get { <span class="kwrd">return</span> ApplicationResources.GetResource&lt;<span class="kwrd">bool</span>&gt;( userLikesPearsKey ); }
      set { ApplicationResources.SetResource( userLikesPearsKey, <span class="kwrd">value</span> ); }
    }

    <span class="rem">// Resource keys</span>

    <span class="rem">// A key can be an object of any type. Strings are used here for readability.</span>
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> <span class="kwrd">string</span> userLikesPearsKey = <span class="str">"userLikesPears"</span>;
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> <span class="kwrd">string</span> userTextKey = <span class="str">"UserText"</span>;
  }
}</pre>
<p>This class encapsulates the keys used for application resources, and makes the resources available as properties. The setter method also strengthens the type-safety, since the property enforces that the getter and setter use identical types.</p>
<p>Since this class is specific to each application that I write, I can customize it as needed. For example, I can create a read-only property by marking the visibility of the set method as private. Or I can insert additional logic in the getter and setter to match the data semantics of my application.</p>
<h2>Using application properties</h2>
<p>Putting it all together, I have created a sample Widows Phone 7 application containing two pages. Values set on PageOne are consumed on PageTwo.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Windows;
<span class="kwrd">using</span> System.Windows.Navigation;
<span class="kwrd">using</span> Microsoft.Phone.Controls;

<span class="kwrd">namespace</span> WP7ShareValueAcrossPages
{
  <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> PageOne : PhoneApplicationPage
  {
    <span class="rem">// other code elided...</span>

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnNavigatedFrom( NavigationEventArgs e )
    {
      ApplicationProperties.UserText = UserTextBox.Text;
    }

    <span class="kwrd">private</span> <span class="kwrd">void</span> LikePearsCheckBox_Checked( <span class="kwrd">object</span> sender, RoutedEventArgs e )
    {
      ApplicationProperties.UserLikesPears = LikePearsCheckBox.IsChecked ?? <span class="kwrd">false</span>;
    }
  }
}</pre>
<p>When navigating away from PageOne, the event handler saves a value from a TextBox control on the page into the UserText application property that I created above. The syntax is clear and simple.</p>
<p>Another event handler is invoked each time a a CheckBox control on the page is checked or unchecked, and the handler sets the UserLikesPears application property accordingly. That leaves open the possibility that the CheckBox may never checked before navigating away from PageOne. That works in a completely natural way in the consuming PageTwo.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Windows.Navigation;
<span class="kwrd">using</span> Microsoft.Phone.Controls;

<span class="kwrd">namespace</span> WP7ShareValueAcrossPages
{
  <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> PageTwo : PhoneApplicationPage
  {
    <span class="rem">// other code elided...</span>

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnNavigatedTo( NavigationEventArgs e )
    {
      <span class="kwrd">string</span> userText = ApplicationProperties.UserText;

      <span class="kwrd">if</span> ( <span class="kwrd">string</span>.IsNullOrEmpty( userText ) )
        userText = <span class="str">"(You didn't enter any text)"</span>;

      userTextBlock.Text = userText;

      pearPreferenceTextBlock.Text = ApplicationProperties.UserLikesPears
        ? <span class="str">"You like pears"</span>
        : <span class="str">"You do not like pears"</span>;
    }
  }
}</pre>
<p>When PageTwo is navigate to, the UserText and UserLikesPears application properties are used in setting the text on different controls. If the bool UserLikesPears property was not set on PageOne, the default value for bool (false) is provided. Since the CheckBox on PageOne is initially unchecked, this default value works correctly.</p>
<h2>Resources</h2>
<p><a href="http://visualstuart.net/code/Sharing_values_across_WP7_pages.zip">Download the completed code</a>.</p>
<p>You will need the <a href="http://create.msdn.com/en-us/home/getting_started">Windows Phone SDK</a> to compile and run the sample code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/11/sharing-values-across-wp7-pages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anatomy of a simple REST client</title>
		<link>http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-client/</link>
		<comments>http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-client/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 07:19:27 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[services]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-client/</guid>
		<description><![CDATA[In Anatomy of a simple REST service we created a service using WFC Web HTTP services. The service has a single resource that supports the GET and POST verbs. Let’s create a client for this REST service. Creating a client &#8230; <a href="http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-client/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/">Anatomy of a simple REST service</a> we created a service using WFC Web HTTP services. The service has a single resource that supports the GET and POST verbs. Let’s create a client for this REST service.</p>
<h2>Creating a client application</h2>
<p>Start with the <a href="http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/">previous solution</a> (see the download at the end) open in Visual Studio, and create a new Console Application: in the Solution Explorer, right-click on the solution node and select <strong>Add | New Project | Visual C# | Windows | Console Application</strong> and name it <strong>AcmePaintClient</strong>.</p>
<h2>Creating a client DTO</h2>
<p>The Colors service from the previous solution has the Color resource’s GET send, and POST receive Color objects. However, they are JSON object on the wire, so on the client side we are free to create any DTO we want so long as it’s compatible.with the JSON object. Compatibility include having properties whose names match the names of the fields in the JSON object. Compatibility does not include having the same class name as was using in the server DTO or preserving the order of the properties..</p>
<p>Add a class named AcmeColor and add properties whose names match the names of the Color DTO defined in the previous solution, like this.</p>
<h2>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> AcmeColor
{
  <span class="kwrd">public</span> <span class="kwrd">byte</span> Green { get; set; }
  <span class="kwrd">public</span> <span class="kwrd">byte</span> Blue { get; set; }
  <span class="kwrd">public</span> <span class="kwrd">byte</span> Red { get; set; }
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>Creating a client</h2>
<p>First, let’s change the service URL to be a fixed value. In <strong>Solution Explorer | AcmePaint</strong> double-click on the <strong>Properties</strong> item. On the AcmePaint Properties window, select the <strong>Web</strong> tab. Under <strong>Servers</strong>, verify that Use <strong>Visual Studio Development Server</strong> is selected, and select <strong>Specific port</strong>. Note the value of the port, we’ll be using that shortly. My value is 42524.</p>
<p>Next, we’ll add a reference to an assembly we’ll be using. In Solution Explorer, right-click on the AcmePaintClient project and select Add Reference. On the .NET tab, select System.Runtime.Serialization. </p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
</p>
<p>In the Program.cs file, add the following using declarations and the GetColor method.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Net;
<span class="kwrd">using</span> System.Runtime.Serialization.Json;

<span class="kwrd">private</span> <span class="kwrd">static</span> AcmeColor GetColor( <span class="kwrd">int</span> id )
{
  <span class="kwrd">using</span> ( var client = <span class="kwrd">new</span> WebClient() )
  {
    var uri = <span class="kwrd">new</span> Uri(
      <span class="kwrd">string</span>.Format( <span class="str">"http://localhost:42524/Colors.svc/Color/{0}"</span>, id ) );

    <span class="kwrd">using</span> ( var stream = client.OpenRead( uri ) )
    {
      var serializer = <span class="kwrd">new</span> DataContractJsonSerializer( <span class="kwrd">typeof</span>( AcmeColor ) );
      <span class="kwrd">return</span> (AcmeColor)serializer.ReadObject( stream );
    }
  }
}
</pre>
<p>Quite simply, this is using the <a href="http://msdn.microsoft.com/en-us/library/781fwaz8.aspx">WebClient.OpenRead</a> method (== open then read) to perform the GET operation, which returns a <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.aspx">Stream</a> that contains the returned JSON. Then the <a href="http://msdn.microsoft.com/en-us/library/bb908232.aspx">DataContractJsonSerialicer.ReadObject</a> method reads the JSON stream into an AcmeColor type.</p>
<p>Also in the Program.cs file, add the following PostColor method.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> PostColor( AcmeColor color )
{
  <span class="kwrd">using</span> ( var client = <span class="kwrd">new</span> WebClient() )
  {
    client.Headers[ HttpRequestHeader.ContentType ] = <span class="str">"application/json"</span>;

    var uri = <span class="kwrd">new</span> Uri( <span class="str">"http://localhost:42524/Colors.svc/Color"</span> );
    <span class="kwrd">using</span> ( var stream = client.OpenWrite( uri, <span class="str">"POST"</span> ) )
    {
      var serializer = <span class="kwrd">new</span> DataContractJsonSerializer( <span class="kwrd">typeof</span>( AcmeColor ) );
      serializer.WriteObject( stream, color );
      stream.Close();
    }
  }
}</pre>
<p>This time we’re using the <a href="http://msdn.microsoft.com/en-us/library/3t27yce3.aspx">WebClient.OpenWrite</a> method (== open then write) to perform the POST operation. This method also returns a Stream, but this time it is a stream for us to write the JSON from an AcmeColor type. That task is performed by <a href="http://msdn.microsoft.com/en-us/library/bb908459.aspx">DataContractJsonSerializer.WriteObject</a>.</p>
<p>Also note that we’ve set the HTTP Content-Type header so that the service knows what it is receiving.</p>
<p>Finally, modify the Main method to call both of our methods.</p>
<pre class="csharpcode"><span class="kwrd">static</span> <span class="kwrd">void</span> Main( <span class="kwrd">string</span>[] args )
{
  var color = GetColor( 3 );

  Console.WriteLine( <span class="str">"Color: Red={0}, Green={1}, Blue={2}"</span>,
    color.Red, color.Green, color.Blue );

  PostColor( <span class="kwrd">new</span> AcmeColor { Red = 0x80, Green = 0xff, Blue = 0x80 } );

  Console.WriteLine( <span class="str">"Press any key to exit..."</span> );
  Console.ReadKey();
}</pre>
<h2>Running the client</h2>
<p>In the Solution Explorer, right-click on the <strong>AcmePaintClient</strong> project and select <strong>Set as StartUp Project</strong>. Then press <strong>F5</strong> to start with debugging. The following output is displayed:</p>
<pre class="csharpcode">Color: Red=255, Green=128, Blue=0
Press any key to exit...</pre>
<h2>Debugging the service</h2>
<p>So far you have no real evidence that the PostColor method actually communicated with the Colors.svc service. I did that expressly so that we can also explore how to debug the service, which a very handy thing to know.</p>
<p>Here’s a simple technique based on the following observation. An instance of Visual Studio can only debug a single program at a time; however it can start as many programs as you like without debugging.</p>
<p>Let’s add a pause at the very top of the Program.Main method so that we can control when it starts making service calls.</p>
<pre class="csharpcode">Console.WriteLine( <span class="str">"Press any key to start..."</span> );
Console.ReadKey();
</pre>
<p>Next, in the AcmePaint project, open Color.svc.cs (double-click on the Color.svc item) and set a breakpoint on the close curly-brace for the PostColor method, <em>e.g.</em>, by clicking in the left column next to that line in the source code, or by setting the cursor on that line and pressing <strong>F9</strong>. </p>
<p>Now, with AcmePaintClient still set as the start-up project, press <strong>Ctrl+F5</strong> to start running the client without debugging. </p>
<p>Return to Visual Studio, and in Solution Explorer, right-click on AcmePaint project and select <strong>Set as StartUp Project</strong>. Then press <strong>F5</strong> to start the service with debugging.</p>
<p>Return to the console window running the AcmePaintClient and press any key so that it starts making calls to the service.</p>
<p>Visual Studio should hit the breakpoint at the end of the PostColor method. View the value of the requestedColor variable in the Locals window (if the Locals window is not displayed select <strong>Debug | Windows | Locals.</strong>) You can verify that it is the requestedColor value is the same value that was sent by the client.</p>
<h2>Cleaning up</h2>
<p>In Visual Studio, press <strong>F5</strong> to let the service invocation run to completion. In the AcmePaintClient console window, press any key to exit. In Visual Studio, press <strong>Shift+F5</strong> to stop debugging the AcmePaint service.</p>
<h2>Review</h2>
<p>We created a minimal REST service client using the WebClient class to perform HTTP requests for both the GET and POST verbs. We also learned a technique for debugging and stepping into the service.</p>
<h2>Resources</h2>
<p><a href="http://visualstuart.net/code/Anatomy_of_a_REST_client.zip">Download the completed code</a></p>
<h3>Additional Posts in this series</h3>
<p><a href="http://visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/">Anatomy of a simple REST service</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-client/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anatomy of a simple REST service</title>
		<link>http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/</link>
		<comments>http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 17:34:10 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[services]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/</guid>
		<description><![CDATA[I want to discuss some interesting topics about services, notably service versioning. Let me start by looking at a very simple REST service using WCF Web HTTP services, creating one to explore how it is put together. Creating a service &#8230; <a href="http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I want to discuss some interesting topics about services, notably service versioning. Let me start by looking at a very simple REST service using <a href="http://msdn.microsoft.com/en-us/library/bb412169.aspx">WCF Web HTTP services</a>, creating one to explore how it is put together.</p>
<h2>Creating a service application</h2>
<p>Start by creating a new WCF Service Application project in Visual Studio with <strong>File | New | Project | Visual C# | WCF | WCF Service Application</strong> and name it <strong>AcmePaint</strong>. In the Solution Explorer, delete the generated Service1.svc and IService1.cs files.</p>
<h2>Creating a DTO</h2>
<p>Add a class named <strong>Color</strong>. This class is a <a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html">Data Transfer Object</a> (DTO) whose singular goal should be to represent the service’s message as it is transferred from one process to another. This class is responsible for the shape of “the message on the wire.”</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Color
{
  <span class="kwrd">public</span> <span class="kwrd">byte</span> Red { get; set; }
  <span class="kwrd">public</span> <span class="kwrd">byte</span> Green { get; set; }
  <span class="kwrd">public</span> <span class="kwrd">byte</span> Blue { get; set; }
}
</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<h2>Adding a WCF service</h2>
<p>Right-click on the project in the Solution Explorer and select <strong>Add | New Item | Visual C# | Web | WCF Service</strong> and name it <strong>Colors.svc</strong>. </p>
<h2>Writing the service contract</h2>
<p>The service contract is expressed as an the interface IColors with the [ServiceContract] attribute; that part hasn’t changed since WCF was introduced. Edit the IColors interface to define two operations like this.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.ServiceModel;
<span class="kwrd">using</span> System.ServiceModel.Web;

<span class="kwrd">namespace</span> AcmePaint
{
  [ServiceContract]
  <span class="kwrd">public</span> <span class="kwrd">interface</span> IColors
  {
    [WebGet( UriTemplate = <span class="str">"Color/{id}"</span> )]
    Color GetColor( <span class="kwrd">string</span> id );

    [WebInvoke( Method = <span class="str">"POST"</span>, UriTemplate = <span class="str">"Color"</span> )]
    <span class="kwrd">void</span> PostColor( Color color );
  }
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>The GetColor method is our archetypal method for performing an HTTP request with the GET verb. The [WebGet] attribute tells the WCF infrastructure that this method is invoked using GET, and the UriTemplate named parameter declares the structure of the URL. The id parameter is written in curly braces which declares that its value in the URL will be passed to the method each time the method is invoked.</p>
<p>The PostColor method is our archetypal method invoked using an HTTP request with the POST verb as declared with the [WebInvoke( Method = “POST” )] attribute. Here UriTemplate declares that it uses the same resource name, Color, as the GetColor method, just without any following URL parts.</p>
<p>Note that both methods use the Color class for the resource sent (POST) and received (GET) by the service’s client.</p>
<h2>Writing the service implementation</h2>
<p>Edit the Colors class in Colors.svc.cs which implements the IColors interface. You can get to this file by double-clicking on the Colors.svc entry in the Solution Explorer. I am going to be focusing on getting data in and out of a service, so the implementations here are intentionally bare bones.</p>
<pre class="csharpcode"><span class="kwrd">namespace</span> AcmePaint
{
  <span class="kwrd">public</span> <span class="kwrd">class</span> Colors : IColors
  {
    <span class="kwrd">public</span> Color GetColor( <span class="kwrd">string</span> id )
    {
      <span class="rem">// retrieve the color from its id here...</span>

      <span class="kwrd">return</span> <span class="kwrd">new</span> Color { Red = 0xff, Green = 0x80, Blue = 0x00 };
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> PostColor( Color color )
    {
      Color requestedColor = color; <span class="rem">// illustrate the type of color parameter</span>

      <span class="rem">// do something with color here...</span>
    }
  }
}
</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<h2>Inspecting the .svc file</h2>
<p>In the Solution Explorer, right-click on Colors.svc and select View Markup. You should see that it s a one-liner containing the following.</p>
<pre class="csharpcode">&lt;%@ ServiceHost Language=<span class="str">"C#"</span> Debug=<span class="str">"true"</span> Service=<span class="str">"AcmePaint.Colors"</span> CodeBehind=<span class="str">"Colors.svc.cs"</span> %&gt;</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>Aside from declaring the implementation language and enabling debugging, this file associates a service name, <strong>AcmePaint.Colors</strong>, with a source code file containing the class that implements the service. We’ll see that service name again in our next step.</p>
<h2>Configuring the service</h2>
<p>Open the Web.config file and replace its contents with the following.</p>
<pre class="csharpcode"><span class="kwrd">&lt;?</span><span class="html">xml</span> <span class="attr">version</span><span class="kwrd">="1.0"</span>?<span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">configuration</span><span class="kwrd">&gt;</span>

  <span class="kwrd">&lt;</span><span class="html">system.web</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">compilation</span> <span class="attr">debug</span><span class="kwrd">="true"</span> <span class="attr">targetFramework</span><span class="kwrd">="4.0"</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">system.web</span><span class="kwrd">&gt;</span>

  <span class="kwrd">&lt;</span><span class="html">system.serviceModel</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">services</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">service</span> <span class="attr">name</span><span class="kwrd">="AcmePaint.Colors"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">endpoint</span> <span class="attr">address</span><span class="kwrd">=""</span>
                  <span class="attr">contract</span><span class="kwrd">="AcmePaint.IColors"</span>
                  <span class="attr">kind</span><span class="kwrd">="webHttpEndpoint"</span><span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">service</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">services</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">standardEndpoints</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">webHttpEndpoint</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">standardEndpoint</span> <span class="attr">name</span><span class="kwrd">=""</span>
                          <span class="attr">helpEnabled</span><span class="kwrd">="true"</span>
                          <span class="attr">defaultOutgoingResponseFormat</span><span class="kwrd">="Json"</span><span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">webHttpEndpoint</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">standardEndpoints</span><span class="kwrd">&gt;</span>

  <span class="kwrd">&lt;/</span><span class="html">system.serviceModel</span><span class="kwrd">&gt;</span>

<span class="kwrd">&lt;/</span><span class="html">configuration</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>The <strong>&lt;service&gt;</strong> element declares the service name using the same value we saw in the Colors.svc file.</p>
<p>Inside of that element we declare a service endpoint. The <strong>address</strong> attribute is empty which means that the endpoint address will just be the address of the Colors.svc service. The <strong>contract</strong> attribute names the interface that is our service contract. And the <strong>kind</strong> attribute declares this endpoint to be a <a href="http://msdn.microsoft.com/en-us/library/ee816921.aspx">standard web HTTP endpoint</a>, which uses a fixed webHttpBinding. That is a binding configures endpoints to respond to HTTP requests instead of SOAP messages.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.configuration.standardendpointelement.aspx">standardEndpoint</a> element has an empty name, making this the default for all webHttpEndpoints. We’ve used this default to enable help and to set the default format for outgoing response messages to be JSON..</p>
<h2>Selecting hosting options</h2>
<p>In the AcmePaint project in the Solution Explorer, double-click on the <strong>Properties</strong> item to display the AcmePaint properties window. Select the <strong>Web</strong> tab. In the <strong>Servers</strong> section, verify that <strong>Use Visual Studio Development Server</strong> is selected.</p>
<p>(If you have IIS installed on your local workstation, you could use the option to <strong>Use Local IIS Web Server</strong> instead.)</p>
<h2>Running the service</h2>
<p>In the Solution Explorer, select the AcmePaint project, then press F5 to run the project in debug mode.</p>
<p><em>Selecting a node in the Solution Explorer first is important! Otherwise, e.g., if you have the Colors.svc.cs file open and selected (active), then pressing F5 to run will launch the WCF Test Client which will display an error because this service is not exposing metadata.</em></p>
<p>Be patient for a moment while the ASP.NET Development Server starts up, and then your browser will launch a page with the URL http://localhost:xxxx/ where xxxx is the auto-assigned port number that was listed on the AcmeProject Properties page where you selected to use the Visual Studio Development Server.</p>
<p><a href="http://www.visualstuart.net/blog2/wp-content/uploads/2011/11/restservicedirectorylisting.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="restservicedirectorylisting" border="0" alt="restservicedirectorylisting" src="http://www.visualstuart.net/blog2/wp-content/uploads/2011/11/restservicedirectorylisting_thumb.png" width="244" height="159"></a></p>
<p>In the browser address bar, edit the URL to read http://localhost:xxxx/Colors.svc/help, using the same port number for xxxx as before. This is the help page that we enabled in configuration.</p>
<p><a href="http://www.visualstuart.net/blog2/wp-content/uploads/2011/11/restservicehelppage.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="restservicehelppage" border="0" alt="restservicehelppage" src="http://www.visualstuart.net/blog2/wp-content/uploads/2011/11/restservicehelppage_thumb.png" width="244" height="81"></a></p>
<p>One last time edit the URL in the browser address bar, this time to read http://localhost:xxxx/Colors.svc/Color/42, with xxxx as before. This time the browser prompts whether you was to Open, Save or Cancel the response. Select <strong>Open</strong>. In the Open With dialog, select <strong>Notepad | OK</strong>. In the Open File dialog select <strong>Open</strong>. The following JSON is displayed in Notepad</p>
<pre class="csharpcode">{<span class="str">"Blue"</span>:0,<span class="str">"Green"</span>:128,<span class="str">"Red"</span>:255}</pre>
<h2>Cleaning up</h2>
<p>Close the browser to stop debugging the service.</p>
<h2>Review</h2>
<p>We created a minimal REST service and used a browser as an impromptu client to GET a resource, with the response data being delivered as JSON.</p>
<h2>Resources</h2>
<p><a href="http://visualstuart.net/code/Anatomy_of_a_REST_service.zip">Download the completed code</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/11/anatomy-of-a-simple-rest-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serializing a DataContract class to an XML string</title>
		<link>http://www.visualstuart.net/blog2/2011/10/serializing-a-datacontract-class-to-an-xml-string/</link>
		<comments>http://www.visualstuart.net/blog2/2011/10/serializing-a-datacontract-class-to-an-xml-string/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 15:18:42 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[services]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/2011/10/serializing-a-datacontract-class-to-an-xml-string/</guid>
		<description><![CDATA[Sometimes during development I want to have a light-weight approach to logging request and response messages without setting up WCF tracing.​ Regardless of how I am logging (Trace, EntLib, whatever), I need to get a printable version of the data &#8230; <a href="http://www.visualstuart.net/blog2/2011/10/serializing-a-datacontract-class-to-an-xml-string/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Sometimes during development I want to have a light-weight approach to logging request and response messages without setting up WCF tracing.​ Regardless of how I am logging (Trace, EntLib, whatever), I need to get a printable version of the data message.</p>
<p>I always recommend treating DataContract classes strictly as data transfer objects (DTO), that is they exist purely for describing the shape of the message on the wire. That means I don&#8217;t add any fancy constructors or business logic of any kind to the DTOs. This maintains a separation of concerns. However, all CLR types do have a ToString method, so I an fine with putting it to better use than telling me the name of the type.
<p>In the sample code, CreateSecretRequest overrides ToString using a static helper method, Helper.ToXmlString. That helper method wraps an XmlSerializer and a StringWriter together to serialize the DTO to a string of XML that I can log. All DataContract classes can use the same ToXmlString method to implement their override of ToString in a simple one-liner.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.IO;
<span class="kwrd">using</span> System.Xml.Serialization; 

<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> Helper
{
  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> ToXmlString( <span class="kwrd">object</span> <span class="kwrd">value</span>, <span class="kwrd">string</span> defaultNamespace )
  {
    var writer = <span class="kwrd">new</span> StringWriter();
    (<span class="kwrd">new</span> XmlSerializer( <span class="kwrd">value</span>.GetType(), defaultNamespace )).Serialize( writer, <span class="kwrd">value</span> );
    <span class="kwrd">return</span> writer.ToString();
  }
} 

<span class="rem">// a sample data transfer object</span>

<span class="kwrd">using</span> System.Runtime.Serialization; 

[DataContract( Namespace = XmlNamespaces.Secret.CreateSecretRequest )]
<span class="kwrd">public</span> <span class="kwrd">class</span> CreateSecretRequest
{
  [DataMember]
  <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; } 

  [DataMember]
  <span class="kwrd">public</span> <span class="kwrd">string</span> Description { get; set; } 

  <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">string</span> ToString()
  { <span class="kwrd">return</span> Helper.ToXmlString( <span class="kwrd">this</span>, XmlNamespaces.Secret.CreateSecretRequest ); }
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>Be careful! This is not the same XML that the service sent or received on the wire. Use WCF Tracing to see what is really happening with your services. This is nearly a 100% genuine approximation of the message, suitable for some quick-and-dirty logging or debugging diagnostics.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/10/serializing-a-datacontract-class-to-an-xml-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get your current WindowsIdentity name and groups</title>
		<link>http://www.visualstuart.net/blog2/2011/10/get-your-current-windowsidentity-name-and-groups/</link>
		<comments>http://www.visualstuart.net/blog2/2011/10/get-your-current-windowsidentity-name-and-groups/#comments</comments>
		<pubDate>Thu, 27 Oct 2011 16:52:02 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[identity]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/2011/10/get-your-current-windowsidentity-name-and-groups/</guid>
		<description><![CDATA[Are you having a little identity crisis? Not sure who you really are in a given environment? Or what groups you belong to? Find out for real, for sure. Get the name of the current WindowsIdentity (Windows user) and the &#8230; <a href="http://www.visualstuart.net/blog2/2011/10/get-your-current-windowsidentity-name-and-groups/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Are you having a little identity crisis? Not sure who you really are in a given environment? Or what groups you belong to? Find out for real, for sure. Get the name of the current WindowsIdentity (Windows user) and the groups to which the user belongs.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Text;
<span class="kwrd">using</span> ssp = System.Security.Principal;

<span class="kwrd">var</span> user = ssp.WindowsIdentity.GetCurrent();
<span class="kwrd">var</span> name = user.Name;

<span class="kwrd">var</span> groups = <span class="kwrd">new</span> StringBuilder();
<span class="kwrd">foreach</span> ( <span class="kwrd">var</span> group <span class="kwrd">in</span> user.Groups )
  groups.AppendLine( group.Translate( <span class="kwrd">typeof</span>( ssp.NTAccount ) ).ToString() );

<span class="kwrd">var</span> message = <span class="kwrd">string</span>.Format( <span class="str">"Name: {0}\nGroups: {1}"</span>, name, groups.ToString() );
</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>This nugget of code has saved me at least three times when I was convinced that I was someone else or in some other role/group than I really was.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/10/get-your-current-windowsidentity-name-and-groups/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Upsert performs update or insert</title>
		<link>http://www.visualstuart.net/blog2/2011/10/upsert-performs-update-or-insert/</link>
		<comments>http://www.visualstuart.net/blog2/2011/10/upsert-performs-update-or-insert/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 17:18:51 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[data]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/2011/10/upsert-performs-update-or-insert/</guid>
		<description><![CDATA[The SQL MERGE statement, introduced in SQL-92, is the best way to update columns in a table if the the row exists, or insert a new row if the row does not exist. This is performed in a single T-SQL &#8230; <a href="http://www.visualstuart.net/blog2/2011/10/upsert-performs-update-or-insert/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/bb522522.aspx">SQL MERGE statement</a>, introduced in SQL-92, is the best way to update columns in a table if the the row exists, or insert a new row if the row does not exist. This is performed in a single T-SQL statement.
<p>The source code below updates or inserts values into a Prices table that has a Name and Price column.</p>
<pre class="csharpcode"><span class="kwrd">CREATE</span> <span class="kwrd">PROCEDURE</span> [dbo].[UpsertPrice]
(
  @name nvarchar(<span class="kwrd">MAX</span>),
  @price <span class="kwrd">decimal</span>(18, 2)
)
<span class="kwrd">AS</span>
<span class="kwrd">BEGIN</span>
  <span class="kwrd">SET</span> NOCOUNT <span class="kwrd">ON</span>; 

  <span class="kwrd">MERGE</span> Prices <span class="kwrd">AS</span> target
  <span class="kwrd">USING</span> (<span class="kwrd">SELECT</span> @name, @price) <span class="kwrd">AS</span> source (Name, Price)
  <span class="kwrd">ON</span> (target.Name = source.Name)
  <span class="kwrd">WHEN</span> MATCHED <span class="kwrd">THEN</span>
    <span class="kwrd">UPDATE</span> <span class="kwrd">SET</span> target.Price = source.Price
  <span class="kwrd">WHEN</span> <span class="kwrd">NOT</span> MATCHED <span class="kwrd">THEN</span>
    <span class="kwrd">INSERT</span> (Name, Price)
    <span class="kwrd">VALUES</span> (source.Name, source.Price);
<span class="kwrd">END</span>;
</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>This combination of update-or-insert values is known by the portmanteau ‘upsert’. I read it on the Internet so it must be true.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/10/upsert-performs-update-or-insert/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to demo and test sending email</title>
		<link>http://www.visualstuart.net/blog2/2011/10/how-to-demo-and-test-sending-email/</link>
		<comments>http://www.visualstuart.net/blog2/2011/10/how-to-demo-and-test-sending-email/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 15:13:45 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/2011/10/how-to-demo-and-test-sending-email/</guid>
		<description><![CDATA[Making your application send email is a pretty common requirement. But without setting up your very own development SMTP server to actually send that email, how can you demonstrate that capability to the stakeholder or test that it works? The &#8230; <a href="http://www.visualstuart.net/blog2/2011/10/how-to-demo-and-test-sending-email/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Making your application send email is a pretty common requirement. But without setting up your very own development SMTP server to actually send that email, how can you demonstrate that capability to the stakeholder or test that it works?</p>
<p>The sample below shows how to send email locally on your workstation. The email will appear as a .eml file in a specified folder. Double-click on the .eml file and it will open in Outlook.
<pre class="csharpcode"><span class="kwrd">using</span> System.Net.Mail;

<span class="kwrd">namespace</span> SmtpDemo
{
  <span class="kwrd">class</span> Program
  {
    <span class="kwrd">static</span> <span class="kwrd">void</span> Main( <span class="kwrd">string</span>[] args )
    {
      <span class="rem">// Note: In .NET 4.0, System.Net.Mail.SmtpClient implements IDisposable;</span>
      <span class="rem">// .NET 3.5 and earlier it does not.</span>
      <span class="kwrd">using</span> ( var smtpClient =
                  <span class="kwrd">new</span> SmtpClient( <span class="str">"localhost"</span> )
                  {
                    DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                    PickupDirectoryLocation = <span class="str">@"C:\Users\visualstuart\Desktop"</span>
                  } )
      {
        <span class="kwrd">string</span> from = <span class="str">"&lt;a href="</span>mailto:support@visualstuart.net<span class="str">"&gt;support@visualstuart.net&lt;/a&gt;"</span>;
        <span class="kwrd">string</span> to   = <span class="str">"&lt;a href="</span>mailto:pipi@visualstuart.net<span class="str">"&gt;pipi@visualstuart.net&lt;/a&gt;"</span>;
        <span class="kwrd">string</span> subject = Your request has been received<span class="str">";
        string body = "</span>We got your request. Hang <span class="kwrd">in</span> there, help <span class="kwrd">is</span> on the way.";

        smtpClient.Send( from, to, subject, body );
      }
    }
  }
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>The interesting bits are in the instantiation of the SmtpClient object. Also note the comment on SmptClient implementing IDisposable in .NET 4.0, but not in earlier versions of the framework. Since I am targeted the .NET 4.0 framework, I’ve treated that instantiation as resource acquisition and enclosed it in a using statement.&nbsp;
<p>This sample uses no configuration. Alternatively, you can <a href="http://msdn.microsoft.com/en-us/library/ms164240.aspx">configure these values</a> in the &lt;smtp&gt; element of app.config.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/10/how-to-demo-and-test-sending-email/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reversing something that doesn&#8217;t belong to you</title>
		<link>http://www.visualstuart.net/blog2/2011/10/reversing-something-that-doesnt-belong-to-you/</link>
		<comments>http://www.visualstuart.net/blog2/2011/10/reversing-something-that-doesnt-belong-to-you/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 17:48:04 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[services]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/?p=20</guid>
		<description><![CDATA[I was working on an implementation of a REST service recently, making it respond to the HTTP Accept headers on the incoming request. As you can see from the HTTP/1.1 specification, Accept request-headers should be honored in the order that &#8230; <a href="http://www.visualstuart.net/blog2/2011/10/reversing-something-that-doesnt-belong-to-you/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was working on an implementation of a REST service recently, making it respond to the HTTP Accept headers on the incoming request. As you can see from the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">HTTP/1.1 specification</a>, Accept request-headers should be honored in the order that they’re listed. So it was absolutely awesome to learn that</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.ServiceModel.Web;

var acceptHeaders = WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements();
<span class="kwrd">foreach</span> ( var acceptHeader <span class="kwrd">in</span> acceptHeaders )
{
  <span class="rem">// process acceptHeader...</span>
}</pre>
<p><style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>processes the headers in the opposite order in which they are specified in the request. And that’s not awesome in a good sense.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.incomingwebrequestcontext.getacceptheaderelements(VS.100).aspx">IncomingWebRequestContext.GetAcceptHeaderElements</a> method returns a <a href="http://msdn.microsoft.com/en-us/library/ms132397.aspx">System.Collections.ObjectModel.Collection&lt;T&gt;</a> and that is not a class I own or can change. But still I’d like an iterator for Collection&lt;T&gt; that yields up its elements in reverse order so that I can still use the foreach syntax. Since Collection&lt;T&gt; is not a class I can modify, <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension methods</a> come to mind. Here’s an extension method for an <a href="http://msdn.microsoft.com/en-us/library/dscyy5s0.aspx">iterator</a> on Collection&lt;T&gt; that does the trick.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Collections.ObjectModel;

<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> Extensions
{
  <span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;T&gt; Reverse&lt;T&gt;( <span class="kwrd">this</span> Collection&lt;T&gt; collection )
  {
    <span class="kwrd">for</span> ( <span class="kwrd">int</span> i = collection.Count - 1; i &gt;= 0; --i )
      <span class="kwrd">yield</span> <span class="kwrd">return</span> collection[ i ];
  }
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>Now I can write the foreach loop to use the extension method.</p>
<pre class="csharpcode"><span class="kwrd">foreach</span> ( var acceptHeader <span class="kwrd">in</span> acceptHeaders.Reverse() )
{
  <span class="rem">// process acceptHeader in the correct order...</span>
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>I am still dumbfounded that GetAcceptHeaderElements reverses the order of the elements (why would that ever be good?) but a few lines sends me on my way without cluttering up the code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/10/reversing-something-that-doesnt-belong-to-you/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Or you could look it up</title>
		<link>http://www.visualstuart.net/blog2/2011/10/or-you-could-look-it-up/</link>
		<comments>http://www.visualstuart.net/blog2/2011/10/or-you-could-look-it-up/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 07:58:43 +0000</pubDate>
		<dc:creator>Visual Stuart</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.visualstuart.net/blog2/?p=8</guid>
		<description><![CDATA[I look at a lot of code. Code that was written a long time ago and those coders have long since left the building. Code that someone once cut their C# teeth on. Code that only its mother could love. &#8230; <a href="http://www.visualstuart.net/blog2/2011/10/or-you-could-look-it-up/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I look at a lot of code. Code that was written a long time ago and those coders have long since left the building. Code that someone once cut their C# teeth on. Code that only its mother could love.</p>
<p>A common shortcoming is writing out what should be a table look up with flow control logic. Here’s an example of what I mean.</p>
<pre class="csharpcode"><span class="kwrd">enum</span> AccountType { Retail, Wholesale, Nonprofit }

<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">decimal</span> GetDiscountUsingIf( AccountType type )
{
  <span class="kwrd">if</span> ( type == AccountType.Wholesale )
    <span class="kwrd">return</span> 0.2M;
  <span class="kwrd">else</span> <span class="kwrd">if</span> ( type == AccountType.Nonprofit )
    <span class="kwrd">return</span> 0.1M;
  <span class="kwrd">else</span> <span class="kwrd">if</span> ( type == AccountType.Retail )
    <span class="kwrd">return</span> 0.0M;

  <span class="kwrd">return</span> 0.0M;
}</pre>
<p>There’s no joy in this code. If the enumeration is prone to change over time, support and maintenance of this style of code quickly becomes error prone. And why is there a default return value at the end of the GetDiscountUsingIf method? Is it a hedge against additional values being added to the enumerations?</p>
<p>Only slightly better would be to convert if/else-if structure to a switch statement.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">decimal</span> GetDiscountUsingSwitch( AccountType type )
{
  <span class="kwrd">switch</span> ( type )
  {
    <span class="kwrd">case</span> AccountType.Wholesale:
      <span class="kwrd">return</span> 0.2M;
    <span class="kwrd">case</span> AccountType.Nonprofit:
      <span class="kwrd">return</span> 0.1M;
    <span class="kwrd">case</span> AccountType.Retail:
      <span class="kwrd">return</span> 0.0M;
    <span class="kwrd">default</span>:
      <span class="kwrd">return</span> 0.0M;
  }
}</pre>
<p>This time the reason for having a default clause is that without it the compiler will warn that not all code paths return a value. Switch statements are cumbersome (e.g., with the potential for fall-throughs, etc.), the performance isn’t great (average number of comparisons is N/2, and worst case in N comparisons), and I think switch statements in general tend to be overused. So every time you see a switch statement I encourage you to think hard if it can be replaced. In this case, it is easily replaced with a Dictionary from the System.Collections.Generic namespace.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Collections.Generic;

<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Dictionary&lt;AccountType, <span class="kwrd">decimal</span>&gt; discounts =
  <span class="kwrd">new</span> Dictionary&lt;AccountType, <span class="kwrd">decimal</span>&gt;
  {
    { AccountType.Wholesale, 0.2M },
    { AccountType.Nonprofit, 0.1M },
    { AccountType.Retail, 0.0M }
  };

<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">decimal</span> GetDiscountUsingDictionary( AccountType type )
{
  <span class="kwrd">if</span> ( discounts.ContainsKey( type ) )
    <span class="kwrd">return</span> discounts[ type ];
  <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentOutOfRangeException( <span class="str">"type"</span> );
}</pre>
<p>The discounts dictionary structure separates the relationship of the keys and values from the lookup logic. The indexer property, discounts[ type ], does most of the lookup logic, and at O(1) it is more efficient than the O(N) linear search approach of the previous two solutions. With the key-value association and lookup work taken care of with pretty terse syntax, the code is simple enough that I can contemplate what should be done with an AccountType key that’s not in the table, in this case throwing an exception that the argument is out of range.</p>
<p>So the next time you’re got a job that is essentially a dictionary look up, use a Dictionary to look it up.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.visualstuart.net/blog2/2011/10/or-you-could-look-it-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
