<?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>The Gray Zone</title>
	<atom:link href="http://thegrayzone.co.uk/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://thegrayzone.co.uk/blog</link>
	<description>A journey through geekdom...</description>
	<lastBuildDate>Thu, 17 Nov 2011 13:47:00 +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>Implementing DPAPI in Compact Framework</title>
		<link>http://thegrayzone.co.uk/blog/2011/05/implementing-dpapi-in-compact-framework/</link>
		<comments>http://thegrayzone.co.uk/blog/2011/05/implementing-dpapi-in-compact-framework/#comments</comments>
		<pubDate>Fri, 13 May 2011 15:20:51 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[COM interop]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=456</guid>
		<description><![CDATA[I have used the Windows Data Protection API in a number of Windows applications for machine encrypting values. I was trying to implement CryptProtectData and CryptUnprotectData for use on a Windows Mobile device. I tried using the wrapper class that I use for standard Windows development with the following DllImports: [DllImport("crypt32.dll", EntryPoint = "CryptProtectData", CharSet [...]]]></description>
			<content:encoded><![CDATA[<p>I have used the <a href="http://msdn.microsoft.com/en-us/library/ms995355.aspx" target="_blank">Windows Data Protection API</a> in a number of Windows applications for machine encrypting values.  I was trying to implement <a href="http://msdn.microsoft.com/en-us/library/ms884464.aspx" target="_blank">CryptProtectData</a> and <a href="http://msdn.microsoft.com/en-us/library/ms884634.aspx" target="_blank">CryptUnprotectData</a> for use on a Windows Mobile device.</p>
<p>I tried using the wrapper class that I use for standard Windows development with the following DllImports:</p>
<pre class="brush:c-sharp">
[DllImport("crypt32.dll", EntryPoint = "CryptProtectData", CharSet = CharSet.Auto)]
public static extern bool Encrypt ( .... )

[DllImport("crypt32.dll", EntryPoint = "CryptUnprotectData", CharSet = CharSet.Auto)]
public static extern bool Decrypt( .... )
</pre>
<p>However, when I tried to use this I received the error:</p>
<blockquote><p>Can&#8217;t find an Entry Point &#8216;CryptProtectData&#8217; in a PInvoke DLL &#8216;crypt32.dll&#8217;.</p></blockquote>
<p>It took me a while to figure out what was happening.  The issue was that in Compact Framework the methods are from coredll.dll, not Crypt32.dll as it is in Desktop Windows.  So the signature (including parameters) now becomes:</p>
<pre class="brush:c-sharp">
[DllImport("coredll.dll", EntryPoint = "CryptProtectData", CharSet = CharSet.Auto)]
public static extern bool Encrypt(
  ref DataBlob dataIn,
  String description,
  ref DataBlob optionalEntropy,
  IntPtr reserved,
  ref CryptProtectPromptStruct promptStruct,
  int flags,
  out DataBlob dataOut);

[DllImport("coredll.dll", EntryPoint = "CryptUnprotectData", CharSet = CharSet.Auto)]
public static extern bool Decrypt(
  ref DataBlob dataIn,
  String description,
  ref DataBlob optionalEntropy,
  IntPtr reserved,
  ref CryptProtectPromptStruct promptStruct,
  int flags,
  out DataBlob dataOut);
</pre>
<p>This is obvious when you fully read the MSDN articles I&#8217;ve linked too but I was in a hurry and presumed that it would be the same dll!</p>
<p>I also use the following two structures for passing to the above methods:</p>
<pre class="brush:c-sharp">
[StructLayout(LayoutKind.Sequential)]
internal struct CryptProtectPromptStruct
{
	internal Int32 Size;
	internal Int32 Flags;
	internal IntPtr Window;

	[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
	internal String Message;
}

internal struct DataBlob
{
	internal Int32 Size;
	internal IntPtr Data;
}
</pre>
<p>Without the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx" target="_blank">StructLayoutAttribute</a> and <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx" target="_blank">MarshalAsAttribute</a> on the CryptProtectPromptStruct you will receive the following error:</p>
<blockquote><p>&#8220;NotSupportedException&#8221; at System.Runtime.InteropServices.Marshal.SizeOfInternal()</p></blockquote>
<p>This is because (thanks to <a href="http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/8a652df9-b0e8-4702-8c06-504600ff7d4f/" target="_blank">this article</a> for the info) the struct must be a <a href="http://en.wikipedia.org/wiki/Blittable_types" target="_blank">Blittable type</a>, meaning that the struct must be represented identically in both managed and unmanaged memory.</p>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2011/05/implementing-dpapi-in-compact-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Changing app.config for Build Configurations</title>
		<link>http://thegrayzone.co.uk/blog/2011/05/changing-app-config-for-build-configurations/</link>
		<comments>http://thegrayzone.co.uk/blog/2011/05/changing-app-config-for-build-configurations/#comments</comments>
		<pubDate>Thu, 05 May 2011 12:52:31 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[MSBuild]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=450</guid>
		<description><![CDATA[I&#8217;m currently working on an application where config data (connection strings etc) is stored machine encrypted, using the Windows Data Protection API, in app.config. The Problem In the standard app.config file all strings are encrypted for my development machine. I also wanted to store them encrypted for the deployment machine and automatically publish these values [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on an application where config data (connection strings etc) is stored machine encrypted, using the <a href="http://msdn.microsoft.com/en-us/library/ms995355.aspx" target="_blank">Windows Data Protection API</a>, in app.config.</p>
<h6>The Problem</h6>
<p>In the standard app.config file all strings are encrypted for my development machine.  I also wanted to store them encrypted for the deployment machine and automatically publish these values when building a release version of the application.</p>
<h6>The Solution</h6>
<p>The solution was to alter the csproj/vbproj file, adding an <a href="http://msdn.microsoft.com/en-us/library/646dk05y.aspx" target="_blank">ItemGroup</a> with a condition to deploy a different app.config depending on the build configuration.</p>
<p>First I added another app.config file within a &#8216;Release&#8217; folder.  I then edited the csproj file.<br />
To do this you can either:</p>
<ol>
<li>Use a text editor (Notepad, Notepad++, Wordpad etc).</li>
<li>In Visual Studio, right click -> Unload Project. Right click -> Edit.</li>
</ol>
<p>Within the csproj file you will find the following XML within the main Project node:</p>
<pre class="brush:xml">
&lt;ItemGroup&gt;
  &lt;None Include="App.config" /&gt;
&lt;/ItemGroup&gt;
</pre>
<p>Remove this tag and replace it with the following:</p>
<pre class="brush:xml">
&lt;ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "&gt;
  &lt;None Include="App.config" /&gt;
&lt;/ItemGroup&gt;
&lt;ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "&gt;
  &lt;None Include="Release\App.config" /&gt;
&lt;/ItemGroup&gt;
</pre>
<p>This tells MSBuild to use App.config when using Debug configuration, or Release\App.config when using Release configuration.</p>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2011/05/changing-app-config-for-build-configurations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Asynchronous Operations</title>
		<link>http://thegrayzone.co.uk/blog/2011/04/unit-testing-asynchronous-operations/</link>
		<comments>http://thegrayzone.co.uk/blog/2011/04/unit-testing-asynchronous-operations/#comments</comments>
		<pubDate>Mon, 11 Apr 2011 19:11:18 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=436</guid>
		<description><![CDATA[The Problem I&#8217;m currently working on an application that uses the MapPoint 2010 API to generate routing data. Some of the operations can be quite long-running (often < 20s but some can run up to a couple of mins). Due to this I use a BackgroundWorker in my main class to process each route&#8217;s data. [...]]]></description>
			<content:encoded><![CDATA[<h6>The Problem</h6>
<p>I&#8217;m currently working on an application that uses the MapPoint 2010 API to generate routing data.  Some of the operations can be quite long-running (often < 20s but some can run up to a couple of mins).  Due to this I use a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" target="_blank">BackgroundWorker</a> in my main class to process each route&#8217;s data.<br />
I ran into some problems unit testing this since it is an asynchronous process but I found a solution, not necessarily the cleanest but it works.</p>
<h6>The Solution</h6>
<p>In the end the solution was quite simple.  I had to figure a way of making the thread wait until the &#8220;CalculationComplete&#8221; event is raised.  To do this I used the <a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx" target="_blank">ManualResetEvent</a> class.  I can then use the <a href="http://msdn.microsoft.com/en-us/library/58195swd.aspx" target="_blank">ManualResetEvent.WaitOne()</a> method to tell the current thread to wait until it receives notification.  Notification is then sent using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.set.aspx" target="_blank">ManualResetEvent.Set()</a> event, called from the completed event of the asynchronous method being tested.</p>
<p>For this example I will use a class called &#8220;CalculateData&#8221; which has a &#8220;CalculationComplete&#8221; event and a method called &#8220;StartCalculationAsync&#8221;.</p>
<pre class="brush:c-sharp">
[TestMethod]
public void Test_Calculation()
{
  // Instantiate class to test
  CalculateData calcData = new CalculateData();

  // Instantiate ManualResetEvent, setting to unsignalled
  ManualResetEvent eventCompletion = new ManualResetEvent(false);

  // Variable to store return args
  CustomEventArgs eventArgs = null;

  // Use an anonymous function to set value of eventArgs and signal to ManualResetEvent to continue
  calcData.CalculationComplete += (sender, e) =>
  {
    eventArgs = e;

    // Call set method to signal thread to continue
    eventCompletion.Set();
  };

  // Call async method to be tested
  calcData.StartCalculationAsync(arg1, arg2);

  // Signal thread to wait here until signal received
  eventCompletion.WaitOne();

  // Assert statement will be reached once completion event raised.
  Assert.IsFalse(eventArgs.boolProperty);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2011/04/unit-testing-asynchronous-operations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up MantisBT on IIS 7 w/ SQL Server</title>
		<link>http://thegrayzone.co.uk/blog/2011/03/setting-up-mantisbt-on-iis-7-w-sql-server/</link>
		<comments>http://thegrayzone.co.uk/blog/2011/03/setting-up-mantisbt-on-iis-7-w-sql-server/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 12:12:57 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=427</guid>
		<description><![CDATA[I recently decided to give a new Bug Tracking system a try and after some reading decided to go with Mantis as it is web based, Open Source, lightweight and easy to use. I decided to host it locally with IIS 7 on my Windows 7 development machine, using Microsoft SQL Server 2008 R2 Express [...]]]></description>
			<content:encoded><![CDATA[<p>I recently decided to give a new Bug Tracking system a try and after some reading decided to go with <a href="http://www.mantisbt.org/" target="_blank">Mantis</a> as it is web based, Open Source, lightweight and easy to use.</p>
<p>I decided to host it locally with IIS 7 on my Windows 7 development machine, using <a href="http://www.microsoft.com/express/Database/" target="_blank">Microsoft SQL Server 2008 R2 Express</a> as the database.  I chose MSSQL as the database as I already had it installed on my machine.</p>
<p>The steps that are required to get Mantis running on Windows are fairly straightforward and consist of:</p>
<ol>
<li>Install PHP on IIS.</li>
<li>Setup Mantis.</li>
<li>Track bugs!</li>
</ol>
<p>However I found a lot of articles on the internet with people having issues setting up Mantis on Windows so I thought I would put down how I did it to try and help anyone else with similar issues.</p>
<h6>Install PHP on IIS</h6>
<p>This was a lot easier than I thought it would be, go through the following steps and you&#8217;ll be good to go:</p>
<ol>
<li>
The initial steps are to enable FastCGI in IIS and configure IIS to process PHP requests.  These are pretty simple and detailed in this <a href="http://us2.php.net/manual/en/install.windows.iis7.php" target="_blank">article on php.net</a>.
</li>
<li>
Next you need to download PHP for Windows.  I downloaded the zip file of PHP 5.3.6 &#8220;VC9 x86 Non Thread Safe&#8221; version from <a href="http://windows.php.net/download/" target="_blank">http://windows.php.net/download/</a>.
</li>
<li>
After downloading the zip file, unzip it to a location on your local computer, I used C:\PHP.
</li>
<li>
Most documentation I found stated that I would need php_mssql.dll in order for PHP to use MSSQL.  It turns out that PHP 5.3 doesn&#8217;t support this anymore.  Fortunately there is a Microsoft PHP driver for MSSQL, available for download <a href="http://www.microsoft.com/sqlserver/2005/en/us/php-driver.aspx" target="_blank">here</a>.
</li>
<li>
Extract the dlls from the above executable, I unzipped them to an MSSQL folder within my PHP install folder (C:\PHP\MSSQL).  Copy php_sqlsrv_53_nts_vc9.dll from the extracted files and paste it into the php &#8220;ext&#8221; folder (C:\PHP\EXT).
</li>
<li>
The final step is now to enable the above dll for PHP to be able to use it.  You can do this by either adding into the following your php.ini file or using the &#8220;Enable or disable an extension&#8221; option in <a href="http://www.iis.net/community/default.aspx?tabid=34&#038;g=6&#038;i=2007" target="_blank">PHP Manager for IIS 7</a>:</p>
<pre class="brush:php">
[PHP_SQLSRV_53_NTS_VC9]
extension=php_sqlsrv_53_nts_vc9.dll
</pre>
</li>
</ol>
<p>Now that PHP is installed, setup in IIS and the relevant drivers installed the next step is to setup Mantis.</p>
<h6>Setup Mantis</h6>
<p>Setting up Mantis was also pretty straightforward, the only possibly tricky part is setting the Database connection options.</p>
<ol>
<li>
First download the zip file of the latest release of Mantis Bug Tracker from <a href="http://www.mantisbt.org/download.php" target="_blank">http://www.mantisbt.org/download.php</a>, currently 1.2.4.
</li>
<li>
Unzip this to any location.  Copy the contents of the mantisbt-1.2.4 folder to C:\Inetpub\wwwroot\mantis\ (or change if the location of your root directory is different).
</li>
<li>
Before setting up the configuration file for Mantis you need to create a DB and a User.  My database was called &#8220;mantisBT&#8221; and I created a user called &#8220;mantisdbuser&#8221;.
</li>
<li>
Next you need to setup the configuration file for Mantis.  To do this rename the file &#8220;config_inc.php.sample&#8221; to &#8220;config_inc.php&#8221;, then change the &#8220;Database Configuration&#8221; section. For the following my computername is &#8220;COMPUTERNAME&#8221; and MSSQL instance name is &#8220;EXPRESS&#8221;.</p>
<pre class="brush:php">
# --- Database Configuration ---
$g_hostname      = 'Driver={SQL Server};SERVER=COMPUTERNAME\EXPRESS;DATABASE=mantisBT;UID=mantisdbuser;PWD=mantisPassword;';
$g_db_username   = 'mantisdbuser';
$g_db_password   = 'mantisPassword';
$g_database_name = 'mantisBT';
$g_db_type       = 'odbc_mssql';
</pre>
</li>
<li>
The final step is to run the installation scripts to create all of the required Database tables.  This will be at: http://localhost/mantis/admin/install.php.  You will see a &#8220;pre-installation check&#8221; screen which will warn you of any problems that need looked at before you install the Database.
</li>
</ol>
<p>You should now be good to go, navigate to http://localhost/mantis/ and login using the default username and password (administrator, root).</p>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2011/03/setting-up-mantisbt-on-iis-7-w-sql-server/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Debugging a Memory Leak in Silverlight 4</title>
		<link>http://thegrayzone.co.uk/blog/2010/11/debugging-a-memory-leak-in-silverlight-4/</link>
		<comments>http://thegrayzone.co.uk/blog/2010/11/debugging-a-memory-leak-in-silverlight-4/#comments</comments>
		<pubDate>Wed, 10 Nov 2010 13:46:46 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=402</guid>
		<description><![CDATA[The Problem I was having a bit of trouble with a memory leak somewhere in my Silverlight 4 application. There was nothing obvious in my code that was causing it, I was cleaning up and disposing of objects as I went. I then discovered the very handy WinDbg tool that comes as part of the [...]]]></description>
			<content:encoded><![CDATA[<h6>The Problem</h6>
<p>I was having a bit of trouble with a memory leak somewhere in my Silverlight 4 application.  There was nothing obvious in my code that was causing it, I was cleaning up and disposing of objects as I went.  I then discovered the very handy WinDbg tool that comes as part of the <a href="http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx" target="_blank">Debugging tools for Windows</a> download.  Using this it becomes a lot easier to find, and fix, your memory leak.</p>
<h6>The Solution</h6>
<p>First you need to download and install the Debugging tools for Windows, after this is done go through the following procedure to find and fix the memory leak.</p>
<ol>
<li>
Run your application in IE and get it to a stage where you think the memory leak is occuring.  If you are running the application from Visual Studio you need to start without debugging (Ctrl+F5), or WinDbg won&#8217;t be able to attach because the VS debugger is already attached.
</li>
<li>
Next you need to find the Process ID (PID) of the IE process running the Silverlight application.  Since multiple IE instances will be running I&#8217;ve found the easiest way to do this is to use the <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" target="_blank">Process Explorer</a> tool.  The PID you want is the child process, not the parent.  See screenshot below with PID 4128 highlighted:<br />
<div id="attachment_403" class="wp-caption alignnone" style="width: 310px"><a href="http://thegrayzone.co.uk/blog/wp-content/uploads/2010/11/Process-Explorer-closeup.jpg"><img src="http://thegrayzone.co.uk/blog/wp-content/uploads/2010/11/Process-Explorer-closeup-300x116.jpg" alt="Screenshot of Process Explorer" title="Process Explorer" width="300" height="116" class="size-medium wp-image-403" /></a><p class="wp-caption-text">Screenshot of Process Explorer</p></div>
</li>
<li>
Now that you have the appropriate PID, open up WinDbg and select File -> Attach to a Process (or press F6).  This will show you a list of all processes, select the appropriate process and hit the OK button.
</li>
<li>
Before you can see any stats for the Silverlight app you need to load the <a href="http://msdn.microsoft.com/en-us/library/bb190764.aspx" target="_blank">sos.dll</a> for Silverlight, to do this use the command <i>&#8220;.load C:\\Program Files\\Microsoft Silverlight\\4.0.50917\\sos.dll&#8221;</i> (changing file path as appropriate).  This now enables you to view all debug information for the application.
</li>
<li>
There are a few different commands that you can use from here to assist you in hunting down the memory leak:</p>
<ol>
<li>
<i>&#8220;!dumpheap -stat&#8221;</i> shows a listing of all objects that are in memory, how many instances there are of each and the total space that they take up.  From here you can easily see if there is a particular object that is not being cleared.<br />
<div id="attachment_415" class="wp-caption alignnone" style="width: 410px"><a href="http://thegrayzone.co.uk/blog/wp-content/uploads/2010/11/Dump-Stats.jpg"><img src="http://thegrayzone.co.uk/blog/wp-content/uploads/2010/11/Dump-Stats.jpg" alt="WinDbg Dump Stats" title="Dump Stats" width="400" height="363" class="size-full wp-image-415" /></a><p class="wp-caption-text">Screenshots Dump Stats</p></div>
</li>
<li>
<i>&#8220;!dumpheap –stat –type TYPENAME&#8221;</i> will show the same above status but for the specified type.
</li>
<li>
<i>&#8220;!dumpheap –type TYPENAME&#8221;</i> will show a listing of all memory addresses for the specified type.  You can then use the memory address with the <i>&#8220;!gcroot ADDRESS&#8221;</i> command.  This shows what is holding the reference to the object, helping you hunt down what is holding a reference and preventing the object being cleared.
</li>
</ol>
</li>
</ol>
<p>In my case the memory leak issue was actually caused by an <a href="http://silverlight.codeplex.com/workitem/7089" target="_blank">issue</a> with the ContextMenu from the Silverlight Toolkit not unsubscribing from the MouseMove event and so not being garbage collected.</p>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2010/11/debugging-a-memory-leak-in-silverlight-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Update Silverlight TextBox Binding Source on change</title>
		<link>http://thegrayzone.co.uk/blog/2010/10/update-silverlight-textbox-binding-source-on-change/</link>
		<comments>http://thegrayzone.co.uk/blog/2010/10/update-silverlight-textbox-binding-source-on-change/#comments</comments>
		<pubDate>Fri, 29 Oct 2010 10:26:11 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Data Binding]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=387</guid>
		<description><![CDATA[Problem By default any binding for a TextBox is not updated until the field loses focus. This didn&#8217;t suit my needs for an application I&#8217;m currently working on because I wanted the Binding source to be updated whenever something is entered into the TextBox. With WPF this is done easily by setting the UpdateSourceTrigger property [...]]]></description>
			<content:encoded><![CDATA[<h6>Problem</h6>
<p>By default any binding for a TextBox is not updated until the field loses focus.  This didn&#8217;t suit my needs for an application I&#8217;m currently working on because I wanted the Binding source to be updated whenever something is entered into the TextBox.  With WPF this is done easily by setting the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx" target="_blank">UpdateSourceTrigger</a> property to <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger.propertychanged.aspx" target="_blank">PropertyChanged</a> in the Binding definition, unfortunately this is not available for Silverlight.</p>
<h6>The Solution</h6>
<p>A workaround that I found for this was to add a KeyUp event to the required TextBox and update the binding in code behind.</p>
<h6>The Code</h6>
<p>For example if you had the following TextBox declared in your XAML file:</p>
<pre class='brush:html'>
&lt;TextBox Text="{Binding Path=ClientName, Mode=TwoWay}" Name="tbName"/&gt;
</pre>
<p>You could add the following to your code behind file:</p>
<pre class='brush:c-sharp'>
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

public MyUserControl()
{
  InitializeComponent();

  tbName.KeyDown += new KeyEventHandler(tbName_KeyUp);
}

private void tbName_KeyUp(object sender, KeyEventArgs e)
{
  BindingExpression binding = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
  binding.UpdateSource();
}
</pre>
<p>Since the above is not dependent on any particular TextBox or ViewModel it could be changed to a custom TextBox control that auto-updates on KeyUp, for example:</p>
<pre class='brush:c-sharp'>
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

public class AutoUpdateTextBox : TextBox
{
  protected override void OnKeyUp(KeyEventArgs e)
  {
    BindingExpression binding = this.GetBindingExpression(TextBox.TextProperty);
    binding.UpdateSource();
    base.OnKeyUp(e);
  }
}
</pre>
<p>This would then be used in XAML like a standard TextBox:</p>
<pre class='brush:html'>
&lt;my:AutoUpdateTextBox Text="{Binding Path=ClientName, Mode=TwoWay}"/&gt;
</pre>
<h6>Key Points</h6>
<ol>
<li>Firstly we use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.getbindingexpression.aspx" target="_blank">FrameworkElement.GetBindingExpression()</a>, passing in the TextBox.TextProperty DependencyProperty to get the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.aspx" target="_blank">BindingExpression</a> object, which contains information about the textboxes Binding.</li>
<li>We then call the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.updatesource.aspx" target="_blank">UpdateSource()</a> method to update the Binding&#8217;s source property.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2010/10/update-silverlight-textbox-binding-source-on-change/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Binding to WebContext.Current in XAML</title>
		<link>http://thegrayzone.co.uk/blog/2010/10/binding-to-webcontext-current-in-xaml/</link>
		<comments>http://thegrayzone.co.uk/blog/2010/10/binding-to-webcontext-current-in-xaml/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 09:40:15 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[xaml]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=370</guid>
		<description><![CDATA[When using the RIA Services Business Application template in VS 2010 I noticed that the WebContext.Current object is added to the applications ResourceDictionary: private void Application_Startup(object sender, StartupEventArgs e) { this.Resources.Add("WebContext", WebContext.Current); ... } As this is now stored as a resource you can easily bind to it, using the StaticResource extension. I&#8217;ve used it [...]]]></description>
			<content:encoded><![CDATA[<p>When using the RIA Services Business Application template in VS 2010 I noticed that the WebContext.Current object is added to the applications ResourceDictionary:</p>
<pre class="brush:c-sharp">
private void Application_Startup(object sender, StartupEventArgs e)
{
  this.Resources.Add("WebContext", WebContext.Current);
  ...
}
</pre>
<p>As this is now stored as a resource you can easily bind to it, using the <a href="http://msdn.microsoft.com/en-us/library/ms750950.aspx" target="_blank">StaticResource</a> extension.  I&#8217;ve used it with a simple Value Converter to show/hide options depending on whether the user is Authorised, e.g.:</p>
<pre class="brush:html">
&lt;UserControl
  ...
  xmlns:converters="clr-namespace:theGrayZone.Converters;assembly=theGrayZone.Common">

&lt;UserControl.Resources&gt;
  &lt;converters:BoolToVisibilityConverter x:Key="BoolVisibilityConverter"/&gt;
&lt;/UserControl.Resources&gt;

  &lt;HyperlinkButton NavigateUri="/Search" TargetName="ContentFrame" Content="Search" Visibility="{Binding Path=User.IsAuthenticated, Source={StaticResource WebContext}, Converter={StaticResource BoolVisibilityConverter}}"/&gt;
</pre>
<p>using the following as my converter:</p>
<pre class="brush:c-sharp">
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace theGrayZone.Converters
{
  public class BoolToVisibilityConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      return (bool)value ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2010/10/binding-to-webcontext-current-in-xaml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stored Procedures with Entity Framework 4 and RIA Services</title>
		<link>http://thegrayzone.co.uk/blog/2010/10/stored-procedures-with-entity-framework-4-and-ria-services/</link>
		<comments>http://thegrayzone.co.uk/blog/2010/10/stored-procedures-with-entity-framework-4-and-ria-services/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 09:14:14 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[WCF RIA Services]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=354</guid>
		<description><![CDATA[I&#8217;ve been using WCF RIA-Services to pass data retrieved via Stored Procedure/EF 4 to a Silverlight 4 application. The system is based on an existing system and a lot of the legwork is already done in Stored Procedures so I was required to re-use them. To start with, I imported my stored procedures to my [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using WCF RIA-Services to pass data retrieved via Stored Procedure/EF 4 to a Silverlight 4 application. The system is based on an existing system and a lot of the legwork is already done in Stored Procedures so I was required to re-use them.</p>
<p>To start with, I imported my stored procedures to my Entity Framework model, added a Function Import and created a Complex Type for each stored procedure, as per this <a href="http://msdn.microsoft.com/en-us/library/bb896231.aspx" target="_blank">MSDN Article</a>.</p>
<p>I had 4 issues that I had to solve when using this approach.</p>
<ol>
<li>Get Output parameter from Stored Procedure</li>
<li>Add properties to Complex Types.</li>
<li>Add methods to Complex Types to be available on client side.</li>
<li>Store nested Complex Types within other Complex Types.</li>
</ol>
<h6>Defining Key for Entity</h6>
<p>Before returning any complex types from RIA-Services you must define a Key for each.  This is normally taken from the database but when using Stored Procedures you have to manually add them.  If you don&#8217;t you&#8217;ll get the following error:</p>
<blockquote><p>The entity &#8216;Employee&#8217; in DomainService &#8216;MyDomainService&#8217; does not have a key defined. Entities exposed by DomainService operations must have at least one public property marked with the KeyAttribute</p></blockquote>
<p>Fortunately they are easy to add using <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx" target="_blank">DataAnnotations</a>.  Create a new partial class for the element that you want to add the key to and insert something similar to:</p>
<pre class="brush:c-sharp">
using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(EmployeeMetadata))]
public partial class Employee
{
  internal sealed class EmployeeMetadata
  {
    public EmployeeMetadata() { }

    [Key]
    public int EmployeeClassID { get; set; }
  }
}
</pre>
<h6>Get Output parameter from Stored Procedure</h6>
<p>The first problem that I had to figure out was how to retrieve an output parameter from a stored procedure.  Take the following stored procedure:</p>
<pre class="brush:sql">
CREATE PROCEDURE SelectWeeklyHours
  @EmployeeID INT
, @TotalHours INT OUTPUT
AS

SELECT
  @TotalHours = SUM(Hours)
FROM
  Hours
WHERE
  EmployeeID = @EmployeeID
</pre>
<p>To get the value of @TotalHours in my DomainService I use the following code:</p>
<pre class="brush:c-sharp">
using System.Data.Objects;

private int GetTotalHours(int employeeID)
{
  // Declare ObjectParameter object to store output param
  ObjectParameter total = new ObjectParameter("TotalHours", typeof(int));

  // Call stored procedure, passing in ObjectParameter
  this.ObjectContext.SelectWeeklyHours(employeeID, total);

  // ObjectParameter will have output param value
  return Convert.ToInt32(total.Value);
}
</pre>
<h6>Add property to Complex Types.</h6>
<p>The second issue that I had to solve was that I wanted to add a new property to a complex type.  At first I tried adding this to the Complex Type using the Model Browser, with the thought that I would add the appropriate value after the Stored Procedure has been called.  However this throws the following exception at run time:</p>
<blockquote><p>The data reader is incompatible with the specified &#8216;MyModel.Employee&#8217;. A member of the type, &#8216;Manager&#8217;, does not have a corresponding column in the data reader with the same name.</p></blockquote>
<p>The easiest way to do this is create a new partial class and add the required property and decorate it with the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx" target="_blank">DataMemberAttribute</a> to specify that the property is part of the data contract and is to be serialized.  For example, using the above Employee example you wanted to add an extra property, Manager, to the class you would do:</p>
<pre class="brush:c-sharp">
using System.Runtime.Serialization;

public partial class Employee
{
  [DataMember]
  public string Manager { get; set; }
}
</pre>
<h6>Add methods to Complex Types to be available on client side</h6>
<p>I also had a requirement where I wanted to add a couple of methods to the server side generated class for the complex type and have that available on client side.  This is done by naming your class using the shared notation.  E.g. if you had a complex type named Employee you would add a new class file and name it Employee.shared.cs, this file will now be copied to the client side and you will be able to access any methods there.</p>
<pre class="brush:c-sharp">
public partial class Employee
{
  public override ToString()
  {
    return EmployeeID.ToString();
  }

  public string FullName
  {
    return string.Format("{0} {1}", Forename, Surname);
  }
}
</pre>
<p>You will now be able to access Employee.FullName or Employee.ToString() from the client application.</p>
<h6>Store nested Complex Types within other Complex Types</h6>
<p>The last requirement that I had to fill was the ability to store a complex type returned from one stored procedure within the complex type of another stored procedure.  At first I tried to add this into the complex type definition in the Model Browser, however this throws an error the same was as trying to add a scalar value did.</p>
<p>The solution to this again involves using a partial class to include the property, but rather than use the DataMemberAttribute, like above, you need to use the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.domainservices.server.includeattribute%28VS.91%29.aspx" target="_blank">IncludeAttribute</a> and <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.associationattribute.aspx" target="_blank">AssociationAttribute</a>.  The AssociationAttribute represents the relationship between the two complex types and the IncludeAttribute specifies that the relationship should be included when the code is generated on the client.  This can be used to add single complex types or collections of complex types:</p>
<pre class="brush:c-sharp">
using System.ServiceModel.DomainServices.Server;
using System.ComponentModel.DataAnnotations;

public partial class Employee
{
  [Include]
  [Association("Employee_Address", "EmployeeID", "EmployeeID")]
  public IEnumerable&lt;Address&gt; Addresses { get; set; }

  [Include]
  [Association("Employee_Position", "PositionID", "PositionID")]
  public Position Position { get; set; }
}
</pre>
<p>The AssociationAttribute takes the name of the relationship and the two key fields, if either of these key are wrong you will get an error similar to:</p>
<blockquote><p>Association named &#8216;Employee_Address&#8217; defined on entity type &#8216;myProject.Model.Employee&#8217; is invalid: ThisKey property named &#8216;EmployeesID&#8217; cannot be found.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2010/10/stored-procedures-with-entity-framework-4-and-ria-services/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Change Opacity of Border on MouseOver</title>
		<link>http://thegrayzone.co.uk/blog/2010/09/change-opacity-of-border-on-mouseover/</link>
		<comments>http://thegrayzone.co.uk/blog/2010/09/change-opacity-of-border-on-mouseover/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 11:19:29 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[xaml]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=346</guid>
		<description><![CDATA[The Problem Recently I was looking for a way of changing the opacity of a Border control when the user mouse&#8217;s over it, and re-setting the opacity when the mouse leaves. I originally wanted to do it using VisualStateManagers but since there is no ControlTemplate this won&#8217;t work. The Solution The solution that I came [...]]]></description>
			<content:encoded><![CDATA[<h6>The Problem</h6>
<p>Recently I was looking for a way of changing the opacity of a Border control when the user mouse&#8217;s over it, and re-setting the opacity when the mouse leaves.  I originally wanted to do it using VisualStateManagers but since there is no ControlTemplate this won&#8217;t work.</p>
<h6>The Solution</h6>
<p>The solution that I came up with (not necessarily the best but it works!) was to create a new class that inherits from the <a href="http://msdn.microsoft.com/en-us/library/ff726531%28v=Expression.40%29.aspx" target="_blank">Behavior&lt;T&gt;</a> class.  I then define the opacity changes in this and it work&#8217;s a treat!</p>
<h6>The Code</h6>
<p>First I created a new class that inherits from Behavior&lt;UIElement&gt;.  All I did was add a MouseEnter and MouseLeave event and change the opacity accordingly:</p>
<pre class="brush:c-sharp">
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace TheGrayZone.Behaviours
{
  public class OpacityHoverBehaviour : Behavior&lt;UIElement&gt;
  {
    protected override void OnAttached()
    {
      base.OnAttached();

      this.AssociatedObject.MouseEnter += new MouseEventHandler(AssociatedObject_MouseEnter);
      this.AssociatedObject.MouseLeave += new MouseEventHandler(AssociatedObject_MouseLeave);
    }

    protected override void OnDetaching()
    {
      base.OnDetaching();

      this.AssociatedObject.MouseEnter -= new MouseEventHandler(AssociatedObject_MouseEnter);
      this.AssociatedObject.MouseLeave -= new MouseEventHandler(AssociatedObject_MouseLeave);
    }

    private void AssociatedObject_MouseLeave(object sender, MouseEventArgs e)
    {
      this.AssociatedObject.Opacity = 0.6;
    }

    private void AssociatedObject_MouseEnter(object sender, MouseEventArgs e)
    {
      this.AssociatedObject.Opacity = 0.8;
    }
  }
}
</pre>
<p>Then in the UserControl containing the Border element use the following XAML. You need to include the System.Windows.Interactivity namespace and the namespace where your behaviour was declared.</p>
<pre class="brush:html">
&lt;UserControl
...
  xmlns:behaviour="clr-namespace:TheGrayZone.Behaviours"
  xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"&gt;

&lt;Border Style="{StaticResource BorderStyle}"&gt;
  &lt;TextBlock Foreground="White" Text="Some Text"/&gt;

  &lt;i:Interaction.Behaviors&gt;
    &lt;behaviour:OpacityHoverBehaviour/&gt;
  &lt;/i:Interaction.Behaviors&gt;
&lt;/Border&gt;
</pre>
<p>Finally I&#8217;ve defined the following style referenced in the above xaml.</p>
<pre class="brush:html">
<Style x:Key="BorderStyle" TargetType="Border">
  <Setter Property="CornerRadius" Value="5,5,5,5"/>
  <Setter Property="Background" Value="Black"/>
  <Setter Property="Width" Value="100"/>
  <Setter Property="Height" Value="50"/>
  <Setter Property="Opacity" Value="0.6"/>
</Style>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2010/09/change-opacity-of-border-on-mouseover/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom URL Protocol in Windows CE</title>
		<link>http://thegrayzone.co.uk/blog/2010/08/custom-url-protocol-in-windows-ce/</link>
		<comments>http://thegrayzone.co.uk/blog/2010/08/custom-url-protocol-in-windows-ce/#comments</comments>
		<pubDate>Fri, 13 Aug 2010 15:50:02 +0000</pubDate>
		<dc:creator>thegrayzone</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Windows Mobile]]></category>

		<guid isPermaLink="false">http://thegrayzone.co.uk/blog/?p=335</guid>
		<description><![CDATA[The Problem One requirement for my current application is that when the user clicks on a specific link on a web application from their Windows Mobile device, a pre-installed application will be launched on the device and a parameter from the web application will be passed to the application. The Solution I decided to use [...]]]></description>
			<content:encoded><![CDATA[<h6>The Problem</h6>
<p>One requirement for my current application is that when the user clicks on a specific link on a web application from their Windows Mobile device, a pre-installed application will be launched on the device and a parameter from the web application will be passed to the application.</p>
<h6>The Solution</h6>
<p>I decided to use a custom URL Protocol (like http, mailto, ftp etc) to launch the application and pass parameters that way.  This would work in the same way as  &#8216;mailto:test@test.com&#8217;.  This launches the default e-mail program and passes in the e-mail address as an argument.  For this article I&#8217;ll create the protocol &#8216;launch&#8217;, e.g. &#8216;launch:my_param&#8217;.</p>
<h6>Registry Settings</h6>
<p>It turns out to be fairly straight forward to get this up and running.  First off I found this MSDN article on <a href="http://msdn.microsoft.com/en-us/library/aa767914%28VS.85%29.aspx" target="_blank">registering a URL protocol</a>. I found this very helpful but there is an extra registry entry required for Windows CE, below are all of the registry entries that need to be made.</p>
<ol>
<li>
<pre class="brush:html">
[HKEY_CLASSES_ROOT\launch]
"URL Protocol"=""
"(Default)"="URL:Launch Protocol"
</pre>
<p>The important part here is the &#8220;URL Protocol&#8221; as this specifies that the entry is a URL Protocol.
</li>
<li>
<pre class="brush:html">
[HKEY_CLASSES_ROOT\launch\Shell]

[HKEY_CLASSES_ROOT\launch\Shell\Open]

[HKEY_CLASSES_ROOT\launch\Shell\Open\Command]
@="\"\\Program Files\\MyApp\\MyApp.exe\" \"%1\""
</pre>
<p>&#8220;\Program Files\MyApp\MyApp.exe&#8221; &#8220;%1&#8243; specifies the application that is to be launched and the &#8220;%1&#8243; part ensures that any arguments will be passed to this application.
</li>
<li>
<pre class="brush:html">
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shell\URLProtocols\launch]
</pre>
<p>This is the last registry entry that you need and is omitted from the above MSDN article.
</li>
</ol>
<h6>Application</h6>
<p>To test the URL Protocol I made a standard Device Application.  Within the program.cs that is created I changed the Main method to take in a string array of arguments.  I then added a string parameter to the constructor of Form1</p>
<pre class="brush:c-sharp">
public static void Main(string[] args)
{
  string param = string.Empty;
  if (args != null &#038;&#038; args.Length > 0)
  {
    param = args[0];
  }

  Application.Run(new Form1(param));
}

public Form1(string parameter)
{
  InitializeComponent();
  label1.Text = string.Format("Passed in value is: {0}", parameter);
}
</pre>
<p>Now when you click on a the following link: &#8220;launch:test_param&#8221; the application will launch and display the parameter.  Without any filtering the whole link will be passed in (i.e. with the &#8220;launch:&#8221; prefix).</p>
]]></content:encoded>
			<wfw:commentRss>http://thegrayzone.co.uk/blog/2010/08/custom-url-protocol-in-windows-ce/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

