<?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>Software for fun and profit &#187; Uncategorized</title>
	<atom:link href="http://www.jonathanwax.com/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jonathanwax.com</link>
	<description>Jonathan Wax</description>
	<lastBuildDate>Wed, 04 Jan 2012 20:18:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Silverlight 5 pInvoke USB/Removable Drive detector</title>
		<link>http://www.jonathanwax.com/2012/01/silverlight-5-pinvoke-usbremovable-drive-detector-2/</link>
		<comments>http://www.jonathanwax.com/2012/01/silverlight-5-pinvoke-usbremovable-drive-detector-2/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 20:18:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.jonathanwax.com/?p=130</guid>
		<description><![CDATA[Hi, A friend of mine asked me if an elevated trust Silverlight 5 application could monitor windows events, specifically when a USB drive is inserted or removed. I naturally said YES, knowing that pInvoke is supported, but decided to take a few moments to write some code. After searching the web I found a great [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>A friend of mine asked me if an elevated trust <a title="Silverlight official site link" href="http://www.silverlight.net" target="_blank">Silverlight</a> 5 application could monitor windows events, specifically when a USB drive is inserted or removed. I naturally said YES, knowing that pInvoke is supported, but decided to take a few moments to write some code.</p>
<p>After searching the web I found a great sample (written by <a href="http://social.msdn.microsoft.com/profile/alexandra%20rusina/" target="_blank">Alexandra Rusina</a>)     <br />here: <a href="http://blogs.msdn.com/b/silverlight_sdk/archive/2011/09/27/pinvoke-in-silverlight5-and-net-framework.aspx" target="_blank">http://blogs.msdn.com/b/silverlight_sdk/archive/2011/09/27/pinvoke-in-silverlight5-and-net-framework.aspx</a></p>
<p>I proceeded to create simple class <strong>RemovableDriveMonitor</strong> which monitors windows messages by creating an actual window class (<strong>WNDCLASS</strong>) and hooking into its WndProc message stream as Alexandra demonstrated and added a <strong>RemovableDriveStatusChanged</strong> event to notify the host app of any changes to USB drives.</p>
<p><strong>RemovableDriveMonitor</strong> is initialized by the host application which also subscribes to the <strong>RemovableDriveStatusChanged</strong> event. This even is fired with a different message for “USB Inserted” or “USB Removed”.</p>
<p>Enjoy,</p>
<p>JW.</p>
<h4>How to use?</h4>
<p>Add a class called <strong>RemovableDriveMonitor</strong> like so:</p>
<pre class="csharpcode"><font size="1"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Diagnostics;
<span class="kwrd">using</span> System.Runtime.InteropServices;

<span class="kwrd">namespace</span> SL5Oob
{
    <span class="kwrd">public</span> <span class="kwrd">class</span> RemovableDriveMonitor
    {

        <span class="rem">//Delegate</span>
        <span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">void</span> RemovableDriveMonitorHandler(<span class="kwrd">object</span> sender, RemovableDriveDetectionArgs e);

        <span class="rem">//Event</span>
        <span class="kwrd">public</span> <span class="kwrd">event</span> RemovableDriveMonitorHandler RemovableDriveStatusChanged;

        <span class="kwrd">private</span> <span class="kwrd">void</span> OnRemovableDriveStatusChanged(<span class="kwrd">string</span> msg)
        {
            <span class="kwrd">if</span> (<span class="kwrd">null</span> != RemovableDriveStatusChanged)
            {
                RemovableDriveStatusChanged(<span class="kwrd">this</span>, <span class="kwrd">new</span> RemovableDriveDetectionArgs(msg));
            }
        }

        <span class="rem">// Importing a set of necessary native methods from Win32 API.</span>
        [DllImport(<span class="str">&quot;User32&quot;</span>, EntryPoint = <span class="str">&quot;CreateWindowEx&quot;</span>,
            CharSet = CharSet.Auto, SetLastError = <span class="kwrd">true</span>)]
        <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr CreateWindowEx(<span class="kwrd">int</span> dwExStyle,
            <span class="kwrd">string</span> lpszClassName, <span class="kwrd">string</span> lpszWindowName, <span class="kwrd">int</span> style,
            <span class="kwrd">int</span> x, <span class="kwrd">int</span> y, <span class="kwrd">int</span> width, <span class="kwrd">int</span> height,
            IntPtr hWndParent, IntPtr hMenu, IntPtr hInst,
            [MarshalAs(UnmanagedType.AsAny)] <span class="kwrd">object</span> pvParam);

        [DllImport(<span class="str">&quot;user32.dll&quot;</span>)]
        <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr DefWindowProc(IntPtr hWnd, <span class="kwrd">int</span> uMsg,
            IntPtr wParam, IntPtr lParam);

        [DllImport(<span class="str">&quot;user32&quot;</span>, CharSet = CharSet.Auto, SetLastError = <span class="kwrd">true</span>)]
        <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> <span class="kwrd">short</span> RegisterClass(WNDCLASS wc);

        <span class="rem">// Marshaling the Window structure.</span>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        <span class="kwrd">public</span> <span class="kwrd">class</span> WNDCLASS
        {
            <span class="kwrd">public</span> <span class="kwrd">int</span> style;
            <span class="kwrd">public</span> WndProc lpfnWndProc;
            <span class="kwrd">public</span> <span class="kwrd">int</span> cbClsExtra;
            <span class="kwrd">public</span> <span class="kwrd">int</span> cbWndExtra;
            <span class="kwrd">public</span> IntPtr hInstance;
            <span class="kwrd">public</span> IntPtr hIcon;
            <span class="kwrd">public</span> IntPtr hCursor;
            <span class="kwrd">public</span> IntPtr hbrBackground;
            <span class="kwrd">public</span> <span class="kwrd">string</span> lpszMenuName;
            <span class="kwrd">public</span> <span class="kwrd">string</span> lpszClassName;
        }

        <span class="rem">//system detects USB insertion/removal</span>
        <span class="kwrd">const</span> <span class="kwrd">int</span> WM_DEVICECHANGE = 0x0219;
        <span class="rem">// system detects a new device</span>
        <span class="kwrd">const</span> <span class="kwrd">int</span> DBT_DEVICEARRIVAL = 0x8000;
        <span class="rem">// device removed</span>
        <span class="kwrd">const</span> <span class="kwrd">int</span> DBT_DEVICEREMOVECOMPLETE = 0x8004;

        <span class="rem">// Callbacks must have AllowReversePInvokeCalls attribute.</span>
        [AllowReversePInvokeCalls]
        <span class="kwrd">private</span> IntPtr Callback(
            IntPtr hWnd, <span class="kwrd">int</span> msg, IntPtr wparam, IntPtr lparam)
        {
            <span class="kwrd">if</span> (msg == WM_DEVICECHANGE)
            {
                <span class="kwrd">if</span> (wparam.ToInt32() == DBT_DEVICEARRIVAL)
                {
                    Debug.WriteLine(<span class="str">&quot;USB inserted&quot;</span>);                   <span class="rem">//&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</span>
                    OnRemovableDriveStatusChanged(<span class="str">&quot;USB Inserted&quot;</span>);
                }
                <span class="kwrd">if</span> (wparam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
                {
                    Debug.WriteLine(<span class="str">&quot;USB removed&quot;</span>);                    <span class="rem">//&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</span>
                    OnRemovableDriveStatusChanged(<span class="str">&quot;USB Removed&quot;</span>);
                }
            }
            <span class="kwrd">return</span> DefWindowProc(hWnd, msg, wparam, lparam);
        }

        <span class="kwrd">public</span> <span class="kwrd">delegate</span> IntPtr WndProc(
            IntPtr hWnd, <span class="kwrd">int</span> msg, IntPtr wParam, IntPtr lParam);

        <span class="rem">// Preventing garbage collection of the delegate</span>
        <span class="kwrd">private</span> <span class="kwrd">static</span> WndProc dontGCthis;

        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Default Constructor</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> RemovableDriveMonitor()
        {
            WNDCLASS wc = <span class="kwrd">new</span> WNDCLASS();

            <span class="rem">// Preventing garbage collection of the delegate</span>
            dontGCthis = <span class="kwrd">new</span> WndProc(Callback);
            wc.lpfnWndProc = dontGCthis;

            <span class="rem">// Note that you need to ensure unique names </span>
            <span class="rem">// for each registered class.</span>
            <span class="rem">// For example, if you open the same plugin </span>
            <span class="rem">// in two different tabs of the browser,</span>
            <span class="rem">// you still should not end up with </span>
            <span class="rem">// two registered classes with identical names.</span>
            wc.lpszClassName = <span class="str">&quot;foobar&quot;</span> + (<span class="kwrd">new</span> Random()).Next();

            RegisterClass(wc);

            IntPtr createResult = CreateWindowEx(0, wc.lpszClassName,
                <span class="str">&quot;Window title&quot;</span>, 0, 100, 100, 500, 500,
                IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0);
        }
    }
}</font></pre>
<pre class="csharpcode"><font size="1"></font></pre>
<pre class="csharpcode"><font size="1">This uses a class <span style="color: #2b91af">RemovableDriveDetectionArgs:</span></font></pre>
<pre class="csharpcode"><font size="1"></font></pre>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">RemovableDriveDetectionArgs
    </span>{

        <span style="color: blue">public string </span>Message { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

        <span style="color: blue">public </span>RemovableDriveDetectionArgs(<span style="color: blue">string </span>msg)
        {
            <span style="color: blue">this</span>.Message = msg;
        }
    }</pre>
<style type="text/css">
<p>.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>In your app, add an instance of <strong>RemoveDriveMonitor</strong>:</p>
<pre class="csharpcode"><font size="1"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// local member holding an instance of RemoveDriveMonitor in the host app/page/usercontrol</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="kwrd">private</span> RemovableDriveMonitor usbMonitor = <span class="kwrd">null</span>;</font></pre>
<style type="text/css">
<p>.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>Then make sure you create an instance of <strong>RemovableDriveMonitor</strong> and subscribe to the <strong>RemovableDriveStatusChanged</strong> event:</p>
<pre class="csharpcode"><font size="1">usbMonitor = <span class="kwrd">new</span> RemovableDriveMonitor();
usbMonitor.RemovableDriveStatusChanged +=
                   <span class="kwrd">new</span> RemovableDriveMonitor.RemovableDriveMonitorHandle
                   (usbMonitor_RemovableDriveStatusChanged);</font></pre>
<style type="text/css">
<p>.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>Implement an event sink function like so and present the e.Message in your UI:</p>
<pre class="csharpcode"><font size="1"><span class="kwrd">void</span> usbMonitor_RemovableDriveStatusChanged(<span class="kwrd">object</span> sender, RemovableDriveDetectionArgs e)
{
    usbMonitorStatusWidget.Text = e.Message;
}</font></pre>
<pre class="csharpcode">&#160;</pre>
<pre class="csharpcode">&#160;</pre>
<style type="text/css">
<p>.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>
]]></content:encoded>
			<wfw:commentRss>http://www.jonathanwax.com/2012/01/silverlight-5-pinvoke-usbremovable-drive-detector-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create shortcut to SL5 OOB App</title>
		<link>http://www.jonathanwax.com/2011/12/create-shortcut-to-sl5-oob-app/</link>
		<comments>http://www.jonathanwax.com/2011/12/create-shortcut-to-sl5-oob-app/#comments</comments>
		<pubDate>Sat, 31 Dec 2011 19:28:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.jonathanwax.com/?p=128</guid>
		<description><![CDATA[Hi, I’m loving the power of Silverlight 5 Out of Browser (OOB) applications, now with improved file access and pInvoke. Thinking about deploying an OOB app to my users, I was wondering if I could create an OOB app that would launch itself when the OS starts. Looking at how a user invokes the “Install [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>I’m loving the power of <a title="Silverlight official site link" href="http://www.silverlight.net" target="_blank">Silverlight</a> 5 Out of Browser (OOB) applications, now with improved file access and pInvoke. Thinking about deploying an OOB app to my users, I was wondering if I could create an OOB app that would launch itself when the OS starts. </p>
<p>Looking at how a user invokes the “Install SL OOB” operation by using the built in Silverlight Right Click menu, or a UI that the developer can create which calls the Application.Install() method, they are given 2 options: Desktop and/or Programs. Both of these essentially create a shortcut that launches the Silverlight OOB application using something like this:</p>
<p>&quot;C:\Program Files (x86)\Microsoft Silverlight\sllauncher.exe&quot; 2237722325.localhost</p>
<p>So I assumed I should be able to call the System.IO.File.Copy operation in my elevated trust SL5 OOB application and copy the link from the desktop or programs to the startup folder, but I was wrong. The System.IO.File.Copy operation throws a security exception if I try to write to the Startup folder?! I thought it was suppose to be able to do anything, but apparently NOT!.</p>
<h5>pInvoke to the rescue!</h5>
<p>Remembering that I could use Win32 APIs with the new pInvoke capabilities in SL5 elevated trust, I quickly replace the File.Copy with CopyFile from kernel32.dll and got it to work.</p>
<p>Enjoy the code.</p>
<p>JW.</p>
<p>&#160;</p>
<p>Add this declaration to your class:</p>
<pre class="csharpcode"><font size="1"> [DllImport(<span class="str">&quot;kernel32.dll&quot;</span>, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = <span class="kwrd">true</span>)]
 [<span class="kwrd">return</span>: MarshalAs(UnmanagedType.Bool)]
<span class="kwrd">static</span> <span class="kwrd">extern</span> <span class="kwrd">bool</span> CopyFile(
  [MarshalAs(UnmanagedType.LPWStr)]<span class="kwrd">string</span> lpExistingFileName,
  [MarshalAs(UnmanagedType.LPWStr)]<span class="kwrd">string</span> lpNewFileName,
  [MarshalAs(UnmanagedType.Bool)]<span class="kwrd">bool</span> bFailIfExists);</font></pre>
<pre class="csharpcode"><font size="1"></font></pre>
<pre class="csharpcode"><font size="1">Add this function:</font></pre>
<style type="text/css">
<p>.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>
<div align="left">
<pre class="csharpcode"><font size="1"><span class="kwrd">private</span> <span class="kwrd">void</span> CreateShortcutInStartUP()</font></pre>
<pre class="csharpcode"><font size="1">{
  <span class="kwrd">try</span>
  {
    Assembly app = Assembly.GetExecutingAssembly();
    <span class="rem">//string version = app.FullName.Split(',')[1];</span>
    <span class="rem">//string fullVersion = version.Split('=')[1];</span>

    <span class="kwrd">string</span> ApplicationName = <span class="kwrd">string</span>.Format(<span class="str">&quot;{0} Application&quot;</span>, app.FullName.Split(<span class="str">','</span>)[0]);

    <span class="kwrd">if</span> (ApplicationName != <span class="str">&quot;&quot;</span>)
    {
      <span class="kwrd">string</span> linkName = <span class="kwrd">string</span>.Format(<span class="str">&quot;{0}.lnk&quot;</span>, ApplicationName);

      <span class="kwrd">string</span> DesktopShortcutPath =             Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
      DesktopShortcutPath = Path.Combine(DesktopShortcutPath, linkName);

      <span class="kwrd">string</span> StartUpPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
      StartUpPath = Path.Combine(StartUpPath, <span class="str">&quot;Startup&quot;</span>);

      <span class="rem">//MessageBox.Show(string.Format(&quot;StartUpPath = {0}&quot;,StartUpPath));</span>
      <span class="rem">//MessageBox.Show(string.Format(&quot;DesktopShortcutPath = {0}&quot;, DesktopShortcutPath));</span>

      <span class="kwrd">if</span> (!System.IO.Directory.Exists(StartUpPath))
      {
        MessageBox.Show(<span class="kwrd">string</span>.Format(<span class="str">&quot;Cannot find: {0}&quot;</span>, StartUpPath));
        <span class="kwrd">return</span>;
      }

      <span class="kwrd">if</span> (!System.IO.File.Exists(DesktopShortcutPath))
      {
         MessageBox.Show(<span class="kwrd">string</span>.Format(<span class="str">&quot;Cannot find: {0}&quot;</span>, DesktopShortcutPath));
         <span class="kwrd">return</span>;
      }

      StartUpPath = Path.Combine(StartUpPath, linkName);
      <span class="rem">//System.IO.File.Copy(ShortcutPath, newShortcutPath, true);</span>
      <span class="kwrd">if</span> (CopyFile(DesktopShortcutPath, StartUpPath, <span class="kwrd">false</span>))
      {
        MessageBox.Show(<span class="kwrd">string</span>.Format(<span class="str">&quot;Copied to: {0}&quot;</span>, StartUpPath));
      }
      <span class="kwrd">else</span>
      {
        MessageBox.Show(<span class="str">&quot;Failed to create Startup Shortcut.&quot;</span>);
      }

    }
  }
  <span class="kwrd">catch</span> (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}</font></pre>
<pre class="csharpcode"><font size="1"></font></pre>
<pre class="csharpcode"><font size="1">Add call it from your startup code.</font></pre>
</div>
<style type="text/css">
<p>.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>
]]></content:encoded>
			<wfw:commentRss>http://www.jonathanwax.com/2011/12/create-shortcut-to-sl5-oob-app/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Silverlight 5 pInvoke USB/Removable Drive detector</title>
		<link>http://www.jonathanwax.com/2011/12/silverlight-5-pinvoke-usbremovable-drive-detector/</link>
		<comments>http://www.jonathanwax.com/2011/12/silverlight-5-pinvoke-usbremovable-drive-detector/#comments</comments>
		<pubDate>Sat, 31 Dec 2011 16:24:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[pInvoke]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight 5]]></category>

		<guid isPermaLink="false">http://www.jonathanwax.com/2011/12/silverlight-5-pinvoke-usbremovable-drive-detector/</guid>
		<description><![CDATA[Original post: http://www.netusup.com/2011/12/31/silverlight-5-pinvoke-usbremovable-drive-detector/ Hi, A friend of mine asked me if an elevated trust Silverlight 5 application could monitor windows events, specifically when a USB drive is inserted or removed. I naturally said YES, knowing that pInvoke is supported, but decided to take a few moments to write some code. After searching the web I [...]]]></description>
			<content:encoded><![CDATA[<p>Original post: <a href="http://www.netusup.com/2011/12/31/silverlight-5-pinvoke-usbremovable-drive-detector/" target="_blank"><font size="1">http://www.netusup.com/2011/12/31/silverlight-5-pinvoke-usbremovable-drive-detector/</font></a></p>
<p>Hi,</p>
<p>A friend of mine asked me if an elevated trust <a title="Silverlight official site link" href="http://www.silverlight.net" target="_blank">Silverlight</a> 5 application could monitor windows events, specifically when a USB drive is inserted or removed. I naturally said YES, knowing that pInvoke is supported, but decided to take a few moments to write some code.</p>
<p>After searching the web I found a great sample (written by <a href="http://social.msdn.microsoft.com/profile/alexandra%20rusina/" target="_blank">Alexandra Rusina</a>)     <br />here: <a href="http://blogs.msdn.com/b/silverlight_sdk/archive/2011/09/27/pinvoke-in-silverlight5-and-net-framework.aspx" target="_blank">http://blogs.msdn.com/b/silverlight_sdk/archive/2011/09/27/pinvoke-in-silverlight5-and-net-framework.aspx</a></p>
<p>I proceeded to create simple class <strong>RemovableDriveMonitor</strong> which monitors windows messages by creating an actual window class (<strong>WNDCLASS</strong>) and hooking into its WndProc message stream as Alexandra demonstrated and added a <strong>RemovableDriveStatusChanged</strong> event to notify the host app of any changes to USB drives.</p>
<p><strong>RemovableDriveMonitor</strong> is initialized by the host application which also subscribes to the <strong>RemovableDriveStatusChanged</strong> event. This even is fired with a different message for “USB Inserted” or “USB Removed”.</p>
<p>Enjoy,</p>
<p>JW.</p>
<h4>How to use?</h4>
<p>Add a class called <strong>RemovableDriveMonitor</strong> like so:</p>
<pre class="csharpcode"><font size="1"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Diagnostics;
<span class="kwrd">using</span> System.Runtime.InteropServices;

<span class="kwrd">namespace</span> SL5Oob
{
    <span class="kwrd">public</span> <span class="kwrd">class</span> RemovableDriveMonitor
    {

        <span class="rem">//Delegate</span>
        <span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">void</span> RemovableDriveMonitorHandler(<span class="kwrd">object</span> sender, RemovableDriveDetectionArgs e);

        <span class="rem">//Event</span>
        <span class="kwrd">public</span> <span class="kwrd">event</span> RemovableDriveMonitorHandler RemovableDriveStatusChanged;

        <span class="kwrd">private</span> <span class="kwrd">void</span> OnRemovableDriveStatusChanged(<span class="kwrd">string</span> msg)
        {
            <span class="kwrd">if</span> (<span class="kwrd">null</span> != RemovableDriveStatusChanged)
            {
                RemovableDriveStatusChanged(<span class="kwrd">this</span>, <span class="kwrd">new</span> RemovableDriveDetectionArgs(msg));
            }
        }

        <span class="rem">// Importing a set of necessary native methods from Win32 API.</span>
        [DllImport(<span class="str">&quot;User32&quot;</span>, EntryPoint = <span class="str">&quot;CreateWindowEx&quot;</span>,
            CharSet = CharSet.Auto, SetLastError = <span class="kwrd">true</span>)]
        <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr CreateWindowEx(<span class="kwrd">int</span> dwExStyle,
            <span class="kwrd">string</span> lpszClassName, <span class="kwrd">string</span> lpszWindowName, <span class="kwrd">int</span> style,
            <span class="kwrd">int</span> x, <span class="kwrd">int</span> y, <span class="kwrd">int</span> width, <span class="kwrd">int</span> height,
            IntPtr hWndParent, IntPtr hMenu, IntPtr hInst,
            [MarshalAs(UnmanagedType.AsAny)] <span class="kwrd">object</span> pvParam);

        [DllImport(<span class="str">&quot;user32.dll&quot;</span>)]
        <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr DefWindowProc(IntPtr hWnd, <span class="kwrd">int</span> uMsg,
            IntPtr wParam, IntPtr lParam);

        [DllImport(<span class="str">&quot;user32&quot;</span>, CharSet = CharSet.Auto, SetLastError = <span class="kwrd">true</span>)]
        <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> <span class="kwrd">short</span> RegisterClass(WNDCLASS wc);

        <span class="rem">// Marshaling the Window structure.</span>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        <span class="kwrd">public</span> <span class="kwrd">class</span> WNDCLASS
        {
            <span class="kwrd">public</span> <span class="kwrd">int</span> style;
            <span class="kwrd">public</span> WndProc lpfnWndProc;
            <span class="kwrd">public</span> <span class="kwrd">int</span> cbClsExtra;
            <span class="kwrd">public</span> <span class="kwrd">int</span> cbWndExtra;
            <span class="kwrd">public</span> IntPtr hInstance;
            <span class="kwrd">public</span> IntPtr hIcon;
            <span class="kwrd">public</span> IntPtr hCursor;
            <span class="kwrd">public</span> IntPtr hbrBackground;
            <span class="kwrd">public</span> <span class="kwrd">string</span> lpszMenuName;
            <span class="kwrd">public</span> <span class="kwrd">string</span> lpszClassName;
        }

        <span class="rem">//system detects USB insertion/removal</span>
        <span class="kwrd">const</span> <span class="kwrd">int</span> WM_DEVICECHANGE = 0x0219;
        <span class="rem">// system detects a new device</span>
        <span class="kwrd">const</span> <span class="kwrd">int</span> DBT_DEVICEARRIVAL = 0x8000;
        <span class="rem">// device removed</span>
        <span class="kwrd">const</span> <span class="kwrd">int</span> DBT_DEVICEREMOVECOMPLETE = 0x8004;

        <span class="rem">// Callbacks must have AllowReversePInvokeCalls attribute.</span>
        [AllowReversePInvokeCalls]
        <span class="kwrd">private</span> IntPtr Callback(
            IntPtr hWnd, <span class="kwrd">int</span> msg, IntPtr wparam, IntPtr lparam)
        {
            <span class="kwrd">if</span> (msg == WM_DEVICECHANGE)
            {
                <span class="kwrd">if</span> (wparam.ToInt32() == DBT_DEVICEARRIVAL)
                {
                    Debug.WriteLine(<span class="str">&quot;USB inserted&quot;</span>);                   <span class="rem">//&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</span>
                    OnRemovableDriveStatusChanged(<span class="str">&quot;USB Inserted&quot;</span>);
                }
                <span class="kwrd">if</span> (wparam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
                {
                    Debug.WriteLine(<span class="str">&quot;USB removed&quot;</span>);                    <span class="rem">//&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</span>
                    OnRemovableDriveStatusChanged(<span class="str">&quot;USB Removed&quot;</span>);
                }
            }
            <span class="kwrd">return</span> DefWindowProc(hWnd, msg, wparam, lparam);
        }

        <span class="kwrd">public</span> <span class="kwrd">delegate</span> IntPtr WndProc(
            IntPtr hWnd, <span class="kwrd">int</span> msg, IntPtr wParam, IntPtr lParam);

        <span class="rem">// Preventing garbage collection of the delegate</span>
        <span class="kwrd">private</span> <span class="kwrd">static</span> WndProc dontGCthis;

        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Default Constructor</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> RemovableDriveMonitor()
        {
            WNDCLASS wc = <span class="kwrd">new</span> WNDCLASS();

            <span class="rem">// Preventing garbage collection of the delegate</span>
            dontGCthis = <span class="kwrd">new</span> WndProc(Callback);
            wc.lpfnWndProc = dontGCthis;

            <span class="rem">// Note that you need to ensure unique names </span>
            <span class="rem">// for each registered class.</span>
            <span class="rem">// For example, if you open the same plugin </span>
            <span class="rem">// in two different tabs of the browser,</span>
            <span class="rem">// you still should not end up with </span>
            <span class="rem">// two registered classes with identical names.</span>
            wc.lpszClassName = <span class="str">&quot;foobar&quot;</span> + (<span class="kwrd">new</span> Random()).Next();

            RegisterClass(wc);

            IntPtr createResult = CreateWindowEx(0, wc.lpszClassName,
                <span class="str">&quot;Window title&quot;</span>, 0, 100, 100, 500, 500,
                IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0);
        }
    }
}</font></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>In your app, add an instance of <strong>RemoveDriveMonitor</strong>:</p>
<pre class="csharpcode"><font size="1"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// local member holding an instance of RemoveDriveMonitor in the host app/page/usercontrol</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="kwrd">private</span> RemovableDriveMonitor usbMonitor = <span class="kwrd">null</span>;</font></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>
<p>Then make sure you create an instance of <strong>RemovableDriveMonitor</strong> and subscribe to the <strong>RemovableDriveStatusChanged</strong> event:</p>
<pre class="csharpcode"><font size="1">usbMonitor = <span class="kwrd">new</span> RemovableDriveMonitor();
usbMonitor.RemovableDriveStatusChanged +=
                   <span class="kwrd">new</span> RemovableDriveMonitor.RemovableDriveMonitorHandle
                   (usbMonitor_RemovableDriveStatusChanged);</font></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>
<p>Implement an event sink function like so and present the e.Message in your UI:</p>
<pre class="csharpcode"><font size="1"><span class="kwrd">void</span> usbMonitor_RemovableDriveStatusChanged(<span class="kwrd">object</span> sender, RemovableDriveDetectionArgs e)
{
    usbMonitorStatusWidget.Text = e.Message;
}</font></pre>
<pre class="csharpcode">&#160;</pre>
<pre class="csharpcode">&#160;</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>
]]></content:encoded>
			<wfw:commentRss>http://www.jonathanwax.com/2011/12/silverlight-5-pinvoke-usbremovable-drive-detector/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Silverlight 5 (OOB) Win32 API GetLogicalDriveStrings</title>
		<link>http://www.jonathanwax.com/2011/12/silverlight-5-oob-win32-api-getlogicaldrivestrings/</link>
		<comments>http://www.jonathanwax.com/2011/12/silverlight-5-oob-win32-api-getlogicaldrivestrings/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 11:46:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[pInvoke]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight 5]]></category>

		<guid isPermaLink="false">http://www.jonathanwax.com/2011/12/silverlight-5-oob-win32-api-getlogicaldrivestrings/</guid>
		<description><![CDATA[Hi, Starting to use Silverlight 5 and enjoying P/Invoke! We needed the ability to list drive letters on the user’s computer. Using System.Runtime.InteropServices, we imported the GetLogicalDriveStrings method. Then we created our own GetLogicalDrives() method which extracts the drive letters from the buffer that is returned. Here’s the code: using System.Runtime.InteropServices; using System.Windows; using System.Windows.Controls; [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>Starting to use <a title="Silverlight official site link" href="http://www.silverlight.net" target="_blank">Silverlight</a> 5 and enjoying P/Invoke!     <br />We needed the ability to list drive letters on the user’s computer.</p>
<p>Using System.Runtime.InteropServices, we imported the GetLogicalDriveStrings method.    <br />Then we created our own GetLogicalDrives() method which extracts the drive letters from the buffer that is returned.</p>
<p>Here’s the code:</p>
<pre class="code"><font size="1"><span style="color: blue">using </span>System.Runtime.InteropServices;
<span style="color: blue">using </span>System.Windows;
<span style="color: blue">using </span>System.Windows.Controls;
<span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Collections.Generic;
<span style="color: blue">using </span>System.Diagnostics;

<span style="color: blue">namespace </span>SL5Oob
{
    <span style="color: blue">public partial class </span><span style="color: #2b91af">MainPage </span>: </font><font size="1"><span style="color: #2b91af">UserControl
    </span>{
       [<span style="color: #2b91af">DllImport</span>(<span style="color: #a31515">&quot;kernel32.dll&quot;</span>, CharSet = <span style="color: #2b91af">CharSet</span>.Unicode, SetLastError = <span style="color: blue">true</span>)]
<span style="color: blue">       static extern uint </span>GetLogicalDriveStrings(<span style="color: blue">uint </span>nBufferLength,                                                  </font><font size="1">[<span style="color: #2b91af">Out</span>] <span style="color: blue">char</span>[] lpBuffer);
        <span style="color: blue">public </span>MainPage()
        {
            InitializeComponent();
        }
        <span style="color: blue">private void </span>GetDrives_Click(<span style="color: blue">object </span>sender, <span style="color: #2b91af">RoutedEventArgs </span>e)
        {
            GetLogicalDrives();
        }
        <span style="color: blue">private static void </span>GetLogicalDrives()
        {
            <span style="color: blue">const int </span>size = 512;
            <span style="color: blue">char</span>[] buffer = <span style="color: blue">new char</span>[size];
            <span style="color: blue">uint </span>code = GetLogicalDriveStrings(size, buffer);

            <span style="color: blue">if </span>(code == 0)
            {
                <span style="color: #2b91af">MessageBox</span>.Show(<span style="color: #a31515">&quot;Call failed&quot;</span>);
                <span style="color: blue">return</span>;
            }

            <span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt; list = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt;();
            <span style="color: blue">int </span>start = 0;
            <span style="color: blue">for </span>(<span style="color: blue">int </span>i = 0; i &lt; code; ++i)
            {
                <span style="color: blue">if </span>(buffer[i] == 0)
                {
                    <span style="color: blue">string </span>s = <span style="color: blue">new string</span>(buffer, start, i - start);
                    list.Add(s);
                    start = i + 1;
                }
            }

            <span style="color: blue">foreach </span>(<span style="color: blue">string </span>s <span style="color: blue">in </span>list)
            {
                <span style="color: #2b91af">Debug</span>.WriteLine(s);
            }
        }
    }
}</font></pre>
<p>Enjoy,</p>
<p>JW.</p>
<p>Original post: <a href="http://www.netusup.com/2011/12/30/silverlight-5-oob-win32-api-getlogicaldrivestrings/" target="_blank">http://www.netusup.com/2011/12/30/silverlight-5-oob-win32-api-getlogicaldrivestrings/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jonathanwax.com/2011/12/silverlight-5-oob-win32-api-getlogicaldrivestrings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to set Foreground of DataGrid Column with ValueConverter</title>
		<link>http://www.jonathanwax.com/2010/10/how-to-set-foreground-of-datagrid-column-with-valueconverter/</link>
		<comments>http://www.jonathanwax.com/2010/10/how-to-set-foreground-of-datagrid-column-with-valueconverter/#comments</comments>
		<pubDate>Sun, 10 Oct 2010 12:14:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.jonathanwax.com/2010/10/how-to-set-foreground-of-datagrid-column-with-valueconverter/</guid>
		<description><![CDATA[If you need to change the Foreground (Color) of a DataGrid Column based on its value you will probably encounter a problem when you try to bind your DataGridTextColumn.Foreground property to a ValueConverter. I’ll show you how we do it and hopefully save you an hour or two. Tools used? Visual Studio 2010 Silverlight 4 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/SL_Logo1.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="SL_Logo" border="0" alt="SL_Logo" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/SL_Logo_thumb1.jpg" width="141" height="49" /></a> If you need to change the Foreground (Color) of a <a title="DataGrid" href="http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid(VS.95).aspx" target="_blank">DataGrid</a> Column based on its value you will probably encounter a problem when you try to bind your DataGridTextColumn.Foreground property to a ValueConverter. I’ll show you how we do it and hopefully save you an hour or two. </p>
<h3>Tools used?</h3>
<ul>
<li><a title="Visual Studio 2010" href="http://go.microsoft.com/?linkid=9725128" target="_blank">Visual Studio 2010</a> </li>
<li><a title="Silverlight 4 Tools for Visual Studio 2010" href="http://go.microsoft.com/fwlink/?LinkID=177428" target="_blank">Silverlight 4 Tools for Visual Studio 2010</a> </li>
<li><a title="Silverlight Toolkit" href="http://silverlight.codeplex.com/" target="_blank">Silverlight Toolkit</a> </li>
</ul>
<p>Download Code: <a title="Download NetUsUp_Silverlight_TipsAndTricks.zip" href="http://samples.netusup.com/NetUsUp_Silverlight_TipsAndTricks.zip" target="_blank">NetUsUp_Silverlight_TipsAndTricks.zip</a></p>
<h2>See How To:</h2>
<ol>
<li>Create a ValueConverter between DateTime? (Nullable DateTime) and Brush (Foreground property’s type).</li>
<li>Bind a ValueConverter to a DataGrid Column’s Foreground property.</li>
</ol>
<h3>Creating our ValueConverter:</h3>
<p>We create a ValueConverter which return a Black SolidColorBrush unless the DateTime value matches today or earlier, in which case it returns Red.</p>
<p>Note: Since we have no need to convert the value back, we just return the value in the ConvertBack() method.</p>
<table border="1" cellspacing="0" cellpadding="2" width="600">
<tbody>
<tr>
<td valign="top" width="600">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">   2:  </span>    <span class="rem">/// Converts between Nullable DateTime and Color Brush</span></pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">public</span> <span class="kwrd">class</span> DateTimeToColorValueConverter: IValueConverter</pre>
<pre class="alt"><span class="lnum">   5:  </span>    {</pre>
<pre><span class="lnum">   6:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="rem">/// Converts value (in our case DateTime?) into a Brush</span></pre>
<pre><span class="lnum">   8:  </span>        <span class="rem">/// for binding to Foreground of text element.</span></pre>
<pre class="alt"><span class="lnum">   9:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">  10:  </span>        <span class="rem">/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;</span></pre>
<pre class="alt"><span class="lnum">  11:  </span>        <span class="rem">/// &lt;param name=&quot;targetType&quot;&gt;&lt;/param&gt;</span></pre>
<pre><span class="lnum">  12:  </span>        <span class="rem">/// &lt;param name=&quot;parameter&quot;&gt;&lt;/param&gt;</span></pre>
<pre class="alt"><span class="lnum">  13:  </span>        <span class="rem">/// &lt;param name=&quot;culture&quot;&gt;&lt;/param&gt;</span></pre>
<pre><span class="lnum">  14:  </span>        <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span></pre>
<pre class="alt"><span class="lnum">  15:  </span>        <span class="kwrd">public</span> <span class="kwrd">object</span> Convert(<span class="kwrd">object</span> <span class="kwrd">value</span>, </pre>
<pre><span class="lnum">  16:  </span>                              Type targetType, </pre>
<pre class="alt"><span class="lnum">  17:  </span>                              <span class="kwrd">object</span> parameter, </pre>
<pre><span class="lnum">  18:  </span>                              System.Globalization.CultureInfo culture)</pre>
<pre class="alt"><span class="lnum">  19:  </span>        {</pre>
<pre><span class="lnum">  20:  </span>            SolidColorBrush result = <span class="kwrd">new</span> SolidColorBrush(Colors.Black);</pre>
<pre class="alt"><span class="lnum">  21:  </span>&#160;</pre>
<pre><span class="lnum">  22:  </span>            DateTime dt = DateTime.MinValue;</pre>
<pre class="alt"><span class="lnum">  23:  </span>            <span class="kwrd">if</span> (DateTime.TryParse(<span class="kwrd">value</span>.ToString(), <span class="kwrd">out</span> dt))</pre>
<pre><span class="lnum">  24:  </span>            {</pre>
<pre class="alt"><span class="lnum">  25:  </span>                <span class="kwrd">if</span> (dt &lt; DateTime.Now)</pre>
<pre><span class="lnum">  26:  </span>                {</pre>
<pre class="alt"><span class="lnum">  27:  </span>                    result = <span class="kwrd">new</span> SolidColorBrush(Colors.Red);</pre>
<pre><span class="lnum">  28:  </span>                }</pre>
<pre class="alt"><span class="lnum">  29:  </span>            }</pre>
<pre><span class="lnum">  30:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  31:  </span>            <span class="kwrd">return</span> result;</pre>
<pre><span class="lnum">  32:  </span>        }</pre>
<pre class="alt"><span class="lnum">  33:  </span>&#160;</pre>
<pre><span class="lnum">  34:  </span>        <span class="kwrd">public</span> <span class="kwrd">object</span> ConvertBack(<span class="kwrd">object</span> <span class="kwrd">value</span>, </pre>
<pre class="alt"><span class="lnum">  35:  </span>                                  Type targetType, </pre>
<pre><span class="lnum">  36:  </span>                                  <span class="kwrd">object</span> parameter, </pre>
<pre class="alt"><span class="lnum">  37:  </span>                                  System.Globalization.CultureInfo culture)</pre>
<pre><span class="lnum">  38:  </span>        {</pre>
<pre class="alt"><span class="lnum">  39:  </span>            <span class="rem">//We don't need to convert back, so we just return the value.</span></pre>
<pre><span class="lnum">  40:  </span>            <span class="kwrd">return</span> <span class="kwrd">value</span>;</pre>
<pre class="alt"><span class="lnum">  41:  </span>        }</pre>
<pre><span class="lnum">  42:  </span>    }</pre>
</p></div>
<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>
</td>
</tr>
</tbody>
</table>
<h3>Binding to the DataGridTextColumn Foreground property:</h3>
<p>If you try to bind your DataGridTextColumn Foreground property to this value converter, you will get an error in runtime which basically means that you cannot bind to the Foreground property.</p>
<p>A quick look in the MSDN documentation: <a title="DataGridTextColumn.Foreground documentation" href="http://msdn.microsoft.com/en-us/library/system.windows.controls.datagridtextcolumn.foreground(VS.95).aspx" target="_blank">DataGridTextColumn.Foreground</a> will show us that this property is NOT a dependency property. hmmm… why not? we’ll have to ask the <a title="Silverlight" href="http://www.silverlight.net" target="_blank">Silverlight</a> Team, but we need a solution, so what can we do?</p>
<h3>Binding to a DataGridTemplateColumn Foreground:</h3>
<p>The fastest solution, is to replace the DataGridTextColumn with a DataGridTemplateColumn. Inside this column we will use a TextBlock which has a Foreground property which IS a dependency property – yeay!</p>
<p>here is the Xaml:</p>
<table border="1" cellspacing="0" cellpadding="2" width="744">
<tbody>
<tr>
<td valign="top" width="742">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span>&lt;!--</pre>
<pre><span class="lnum">   2:  </span> PROBLEM:</pre>
<pre class="alt"><span class="lnum">   3:  </span>The DataGridTextColumn's Forground property <span class="kwrd">is</span> NOT a dependency </pre>
<pre><span class="lnum">   4:  </span> propert so we cannot bind our ValueConverter to it.</pre>
<pre class="alt"><span class="lnum">   5:  </span>                </pre>
<pre><span class="lnum">   6:  </span>SOLUTION:</pre>
<pre class="alt"><span class="lnum">   7:  </span>We use a DataGridTemplateColumn with a TextBlock <span class="kwrd">for</span> the <span class="kwrd">value</span>. </pre>
<pre><span class="lnum">   8:  </span> Foreground <span class="kwrd">is</span> a Dependency property on TextBlock so binding to a Value Converter works.</pre>
<pre class="alt"><span class="lnum">   9:  </span>                </pre>
<pre><span class="lnum">  10:  </span> TIP:</pre>
<pre class="alt"><span class="lnum">  11:  </span> You could also create your own DataGridTextColumn (<span class="kwrd">using</span> inheritance) and add your own</pre>
<pre><span class="lnum">  12:  </span>Dependency property <span class="kwrd">for</span> binding to Foreground...</pre>
<pre class="alt"><span class="lnum">  13:  </span> --&gt;</pre>
<pre><span class="lnum">  14:  </span>&lt;sdk:DataGridTemplateColumn x:Name=<span class="str">&quot;DateTime2&quot;</span> Header=<span class="str">&quot;Date Time 2&quot;</span> MinWidth=<span class="str">&quot;100&quot;</span>&gt;</pre>
<pre class="alt"><span class="lnum">  15:  </span>        &lt;sdk:DataGridTemplateColumn.CellTemplate&gt;</pre>
<pre><span class="lnum">  16:  </span>                &lt;DataTemplate&gt;</pre>
<pre class="alt"><span class="lnum">  17:  </span>                    &lt;TextBlock Text=<span class="str">&quot;{Binding Path=DateTime}&quot;</span> </pre>
<pre><span class="lnum">  18:  </span>                                       Foreground=<span class="str">&quot;{Binding Path=DateTime,</pre>
<pre class="alt"><span class="lnum">  19:  </span>                                       Converter={StaticResource dateTimeToColorValueConverter}}&quot;</span> </pre>
<pre><span class="lnum">  20:  </span>                                       VerticalAlignment=<span class="str">&quot;Center&quot;</span> /&gt;</pre>
<pre class="alt"><span class="lnum">  21:  </span>                 &lt;/DataTemplate&gt;</pre>
<pre><span class="lnum">  22:  </span>         &lt;/sdk:DataGridTemplateColumn.CellTemplate&gt;</pre>
<pre class="alt"><span class="lnum">  23:  </span>&lt;/sdk:DataGridTemplateColumn&gt;</pre>
</p></div>
<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>
</td>
</tr>
</tbody>
</table>
<p>So there we have it. A simple solution to a missing Dependency property.</p>
<p>Tip: You could have inherited DataGridTextColumn and created your own with a Bindable Foreground property – but I will leave that challenge to you, if you have the time.</p>
<p>Thanks for reading, please post any comments you may have.</p>
<p>Jonathan.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jonathanwax.com/2010/10/how-to-set-foreground-of-datagrid-column-with-valueconverter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF RIA Services, DataGrid Filters NO DomainDataSource</title>
		<link>http://www.jonathanwax.com/2010/10/wcf-ria-services-datagrid-filters-no-domaindatasource-2/</link>
		<comments>http://www.jonathanwax.com/2010/10/wcf-ria-services-datagrid-filters-no-domaindatasource-2/#comments</comments>
		<pubDate>Sun, 03 Oct 2010 12:25:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[Filter]]></category>
		<category><![CDATA[No DomainDataSource]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF RIA]]></category>

		<guid isPermaLink="false">http://www.jonathanwax.com/2010/10/wcf-ria-services-datagrid-filters-no-domaindatasource-2/</guid>
		<description><![CDATA[&#160; So many of the Silverlight samples use minimal code in an attempt to use controls, binding and commanding techniques to create application by just using markup. Although these techniques are cool and may be great for rapid prototyping of an application, our team prefers to write code that gives us access to the details [...]]]></description>
			<content:encoded><![CDATA[<h1>&#160;</h1>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/SL_Logo.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="SL_Logo" border="0" alt="SL_Logo" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/SL_Logo_thumb.jpg" width="141" height="49" /></a> So many of the <a href="http://www.silverlight.net" target="_blank">Silverlight</a> samples use minimal code in an attempt to use controls, binding and commanding techniques to create application by just using markup. Although these techniques are cool and may be great for rapid prototyping of an application, our team prefers to write code that gives us access to the details giving us more control and a better understanding of how things work and how to best use them for our customers.</p>
<p>We write business applications using <a title="Silverlight" href="http://www.silverlight.net" target="_blank">Silverlight</a>. Many business applications use the Silverlight DataGrid for presenting data. Most DataGrids need to be filtered either automatically or by the user.</p>
<h3>We will NOT use the DomainDataSource</h3>
<p>Why? Because more often than not, when we used the <a title="DomainDataSource" href="http://msdn.microsoft.com/en-us/library/ee707363(VS.91).aspx" target="_blank">DomainDataSource</a>, we had to replace it later on, loosing all the time spent on coding and testing in the process.</p>
<h3>Tools used?</h3>
<ul>
<li><a title="Visual Studio 2010" href="http://go.microsoft.com/?linkid=9725128" target="_blank">Visual Studio 2010</a> </li>
<li><a title="Silverlight 4 Tools for Visual Studio 2010" href="http://go.microsoft.com/fwlink/?LinkID=177428" target="_blank">Silverlight 4 Tools for Visual Studio 2010</a> </li>
<li><a title="Silverlight Toolkit" href="http://silverlight.codeplex.com/" target="_blank">Silverlight Toolkit</a> </li>
</ul>
<p>Download Code: <a title="Download WCFRia_DataGrid_NoDomainDataSource.zip" href="http://samples.netusup.com/WCFRia_DataGrid_NoDomainDataSource.zip" target="_blank">WCFRia_DataGrid_NoDomainDataSource.zip</a></p>
<h2>See How To:</h2>
<ul>
<li>Bind <a title="DataGrid" href="http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid(VS.95).aspx" target="_blank">DataGrid</a> to a <a title="WCF RIA Services" href="http://www.silverlight.net/getstarted/riaservices" target="_blank">WCF RIA Services</a> DomainService method result. </li>
<li>Pass a client side created Query to a DomainService method to filter the results on the server. </li>
<li>Create a Filter ComboBox that will use a DISTINCT list of values. </li>
<li>Use the Filter ComboBox value as a parameter in the client side created query. </li>
</ul>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb.png" width="480" height="307" /></a></p>
<p>Rename the aspx and html test pages from:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb1.png" width="244" height="33" /></a> </p>
<p>to:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image2.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb2.png" width="244" height="57" /></a> </p>
<p>then right click index.html and set it as the Default page so it launches when you run/debug the application.</p>
</p>
<p>Why? Because index.html and Default.aspx are automatically identified by the web server as the default pages for a web application – one thing less to worry about when you deploy your application.</p>
<p>Add a SampleDatabase to the Web application, App_Data folder.</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb3.png" width="244" height="157" /></a> </p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image4.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb4.png" width="244" height="72" /></a> </p>
<p>Double click SampleDatabase.mdf to get the Server Exporer.</p>
<p>Right click on Tables and select New Table</p>
<p>Create a Table called SampleRecord with the following columns and save it.</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image5.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb5.png" width="184" height="244" /></a> </p>
<p><strong>Why?</strong> You may be asking yourself, why the Category field is a string (nvarchar(50)) and not a foreign key to a Category table? The reason is, because we have seen this many times in systems (a non-normalized database) and have found that there may be cases where this is justified. So instead of judging… we decided to show you have we handle such a situation when we encounter it and cannot convince a customer to change it.</p>
<p>Right click the table you create and choose Show Table Data.</p>
<p>Fill the table with some sample data like so:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image6.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb6.png" width="244" height="88" /></a> </p>
<p>Add an ADO.NET Entity Data Model to our web project (called SampleDataModel):</p>
<p>Step 1:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image7.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb7.png" width="244" height="157" /></a> </p>
<p>Step 2:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image8.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb8.png" width="244" height="218" /></a> </p>
<p>Step 3:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb9.png" width="244" height="218" /></a> </p>
<p>Step 4:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image10.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb10.png" width="244" height="218" /></a> </p>
<p>Once the model is created, you should see the SampleRecord Entity in your SampleDatamodel.edmx design view.</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image11.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb11.png" width="223" height="244" /></a> </p>
<p>Build the project to make sure the Entity Model is valid.</p>
<p>Add a Domain Service to our web project (called SampleDomainService):</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image12.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb12.png" width="244" height="157" /></a> </p>
<p>In the Add New Domain Service Class dialog, remember to:</p>
<ul>
<li>Enable Editing </li>
<li>Check the Generate associated classes for metadata option. </li>
</ul>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image13.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb13.png" width="200" height="244" /></a> </p>
<p>Your web project should look like this:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image14.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb14.png" width="244" height="239" /></a> </p>
<p>including:</p>
<ul>
<li>SampleDatabase.mdf </li>
<li>SampleDataModel.edmx </li>
<li>SampleDomainService.cs </li>
<li>SampleDomainService.metadata.cs </li>
</ul>
<h3>Now we move to the Silverlight client application project.</h3>
<p>Add a new Silverlight UserControl to the Controls folder called FilteredDataGridControl:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image15.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb15.png" width="244" height="157" /></a> </p>
<p>In the FilteredDataGridControl do the following:</p>
<ul>
<li>Create 2 rows in the Grid (LayoutRoot) control. The top row for our filters and the bottom for our DataGrid. </li>
<li>Add a StackPanel with a Label and ComboBox to the top row (Grid.Row = “0”) </li>
<li>Add a DataGrid to the bottom row (Grid.Row = “1”) </li>
</ul>
<p>It should look like this:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image16.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb16.png" width="244" height="187" /></a> </p>
<p>and here is the Xaml inside this UserControl:</p>
<table border="1" cellspacing="0" cellpadding="2" width="489">
<tbody>
<tr>
<td valign="top" width="487">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">&lt;</span><span class="html">Grid</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;LayoutRoot&quot;</span> <span class="attr">Background</span><span class="kwrd">=&quot;White&quot;</span><span class="kwrd">&gt;</span></pre>
<pre><span class="lnum">   2:  </span>        <span class="kwrd">&lt;</span><span class="html">Grid.RowDefinitions</span><span class="kwrd">&gt;</span></pre>
<pre class="alt"><span class="lnum">   3:  </span>            <span class="kwrd">&lt;</span><span class="html">RowDefinition</span> <span class="attr">Height</span><span class="kwrd">=&quot;25&quot;</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="lnum">   4:  </span>            <span class="kwrd">&lt;</span><span class="html">RowDefinition</span> <span class="attr">Height</span><span class="kwrd">=&quot;*&quot;</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"><span class="lnum">   5:  </span>        <span class="kwrd">&lt;/</span><span class="html">Grid.RowDefinitions</span><span class="kwrd">&gt;</span></pre>
<pre><span class="lnum">   6:  </span>        <span class="rem">&lt;!-- Filter Area --&gt;</span></pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">&lt;</span><span class="html">StackPanel</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Orientation</span><span class="kwrd">=&quot;Horizontal&quot;</span><span class="kwrd">&gt;</span></pre>
<pre><span class="lnum">   8:  </span>            <span class="kwrd">&lt;</span><span class="html">sdk:Label</span> <span class="attr">Name</span><span class="kwrd">=&quot;CategoryCaption&quot;</span> </pre>
<pre class="alt"><span class="lnum">   9:  </span>                       <span class="attr">Height</span><span class="kwrd">=&quot;23&quot;</span> </pre>
<pre><span class="lnum">  10:  </span>                       <span class="attr">HorizontalAlignment</span><span class="kwrd">=&quot;Left&quot;</span> </pre>
<pre class="alt"><span class="lnum">  11:  </span>                       <span class="attr">VerticalAlignment</span><span class="kwrd">=&quot;Center&quot;</span> </pre>
<pre><span class="lnum">  12:  </span>                       <span class="attr">Margin</span><span class="kwrd">=&quot;5&quot;</span> </pre>
<pre class="alt"><span class="lnum">  13:  </span>                       <span class="attr">MinWidth</span><span class="kwrd">=&quot;120&quot;</span></pre>
<pre><span class="lnum">  14:  </span>                       <span class="attr">Content</span><span class="kwrd">=&quot;Category:&quot;</span><span class="kwrd">/&gt;</span></pre>
<pre class="alt"><span class="lnum">  15:  </span>            <span class="kwrd">&lt;</span><span class="html">ComboBox</span> <span class="attr">Name</span><span class="kwrd">=&quot;CategoryFilter&quot;</span> </pre>
<pre><span class="lnum">  16:  </span>                      <span class="attr">Height</span><span class="kwrd">=&quot;23&quot;</span> </pre>
<pre class="alt"><span class="lnum">  17:  </span>                      <span class="attr">HorizontalAlignment</span><span class="kwrd">=&quot;Left&quot;</span> </pre>
<pre><span class="lnum">  18:  </span>                      <span class="attr">VerticalAlignment</span><span class="kwrd">=&quot;Center&quot;</span> </pre>
<pre class="alt"><span class="lnum">  19:  </span>                      <span class="attr">MinWidth</span><span class="kwrd">=&quot;120&quot;</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="lnum">  20:  </span>            </pre>
<pre class="alt"><span class="lnum">  21:  </span>            <span class="kwrd">&lt;</span><span class="html">Button</span> <span class="attr">Name</span><span class="kwrd">=&quot;ApplyFilter&quot;</span> </pre>
<pre><span class="lnum">  22:  </span>                    <span class="attr">Content</span><span class="kwrd">=&quot;Filter&quot;</span> </pre>
<pre class="alt"><span class="lnum">  23:  </span>                    <span class="attr">Height</span><span class="kwrd">=&quot;23&quot;</span> </pre>
<pre><span class="lnum">  24:  </span>                    <span class="attr">Width</span><span class="kwrd">=&quot;75&quot;</span></pre>
<pre class="alt"><span class="lnum">  25:  </span>                    <span class="attr">Margin</span><span class="kwrd">=&quot;5,0,0,0&quot;</span><span class="kwrd">/&gt;</span></pre>
<pre><span class="lnum">  26:  </span>        <span class="kwrd">&lt;/</span><span class="html">StackPanel</span><span class="kwrd">&gt;</span></pre>
<pre class="alt"><span class="lnum">  27:  </span>        </pre>
<pre><span class="lnum">  28:  </span>        <span class="rem">&lt;!-- Data Area --&gt;</span></pre>
<pre class="alt"><span class="lnum">  29:  </span>        <span class="kwrd">&lt;</span><span class="html">sdk:DataGrid</span> <span class="attr">Name</span><span class="kwrd">=&quot;ResultGrid&quot;</span> </pre>
<pre><span class="lnum">  30:  </span>                      <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> </pre>
<pre class="alt"><span class="lnum">  31:  </span>                      <span class="attr">AutoGenerateColumns</span><span class="kwrd">=&quot;<strong>True</strong>&quot;</span> </pre>
<pre><span class="lnum">  32:  </span>                      <span class="attr">HorizontalAlignment</span><span class="kwrd">=&quot;Stretch&quot;</span></pre>
<pre class="alt"><span class="lnum">  33:  </span>                      <span class="attr">VerticalAlignment</span><span class="kwrd">=&quot;Stretch&quot;</span></pre>
<pre><span class="lnum">  34:  </span>                      <span class="attr">Background</span><span class="kwrd">=&quot;Beige&quot;</span><span class="kwrd">/&gt;</span></pre>
<pre class="alt"><span class="lnum">  35:  </span>&#160;</pre>
<pre><span class="lnum">  36:  </span>    <span class="kwrd">&lt;/</span><span class="html">Grid</span><span class="kwrd">&gt;</span></pre>
</p></div>
<style type="text/css">
<p>.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>
</td>
</tr>
</tbody>
</table>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
<p>Build the solution.</p>
<p>Add the FilteredDataGridControl onto the Views\Home.xaml page.</p>
<table border="1" cellspacing="0" cellpadding="2" width="604">
<tbody>
<tr>
<td valign="top" width="602">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span>                <span class="kwrd">&lt;</span><span class="html">my:FilteredDataGridControl</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;filteredDataGridControl1&quot;</span> </pre>
<pre><span class="lnum">   2:  </span>                                            <span class="attr">Height</span><span class="kwrd">=&quot;400&quot;</span><span class="kwrd">/&gt;</span></pre>
<pre class="alt"><span class="lnum">   3:  </span>            <span class="kwrd">&lt;/</span><span class="html">StackPanel</span><span class="kwrd">&gt;</span></pre>
<pre><span class="lnum">   4:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">   5:  </span>    <span class="kwrd">&lt;/</span><span class="html">ScrollViewer</span><span class="kwrd">&gt;</span></pre>
<pre><span class="lnum">   6:  </span>  <span class="kwrd">&lt;/</span><span class="html">Grid</span><span class="kwrd">&gt;</span></pre>
<pre class="alt"><span class="lnum">   7:  </span>&#160;</pre>
<pre><span class="lnum">   8:  </span><span class="kwrd">&lt;/</span><span class="html">navigation:Page</span><span class="kwrd">&gt;</span></pre>
</p></div>
<style type="text/css">
<p>.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>
</td>
</tr>
</tbody>
</table>
<p>Run the application to make sure the control loads and presents correctly</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image17.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb17.png" width="244" height="203" /></a> </p>
<p>Double click the ApplyFilter button to get to the code behind the form.</p>
<p>Add the following code to the code behind file:</p>
<table border="1" cellspacing="0" cellpadding="2" width="650">
<tbody>
<tr>
<td valign="top" width="648">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">using</span> System.ServiceModel.DomainServices.Client;</pre>
<pre><span class="lnum">   2:  </span><span class="kwrd">using</span> System.Windows;</pre>
<pre class="alt"><span class="lnum">   3:  </span><span class="kwrd">using</span> System.Windows.Controls;</pre>
<pre><span class="lnum">   4:  </span><span class="kwrd">using</span> WCFRia_DataGrid_NoDomainDataSource.Web;</pre>
<pre class="alt"><span class="lnum">   5:  </span>&#160;</pre>
<pre><span class="lnum">   6:  </span><span class="kwrd">namespace</span> WCFRia_DataGrid_NoDomainDataSource.Controls</pre>
<pre class="alt"><span class="lnum">   7:  </span>{</pre>
<pre><span class="lnum">   8:  </span>    <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> FilteredDataGridControl : UserControl</pre>
<pre class="alt"><span class="lnum">   9:  </span>    {</pre>
<pre><span class="lnum">  10:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  11:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">  12:  </span>        <span class="rem">/// Context represents an instance of the SampleDomainContext</span></pre>
<pre class="alt"><span class="lnum">  13:  </span>        <span class="rem">/// used to access to SampleDomainService methods from the client.</span></pre>
<pre><span class="lnum">  14:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt"><span class="lnum">  15:  </span>        <span class="kwrd">private</span> SampleDomainContext context = <span class="kwrd">null</span>;</pre>
<pre><span class="lnum">  16:  </span>        <span class="kwrd">internal</span> SampleDomainContext Context</pre>
<pre class="alt"><span class="lnum">  17:  </span>        {</pre>
<pre><span class="lnum">  18:  </span>            get { <span class="kwrd">return</span> context; }</pre>
<pre class="alt"><span class="lnum">  19:  </span>            set { context = <span class="kwrd">value</span>; }</pre>
<pre><span class="lnum">  20:  </span>        }</pre>
<pre class="alt"><span class="lnum">  21:  </span>&#160;</pre>
<pre><span class="lnum">  22:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alt"><span class="lnum">  23:  </span>        <span class="rem">/// Default Contructor</span></pre>
<pre><span class="lnum">  24:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt"><span class="lnum">  25:  </span>        <span class="kwrd">public</span> FilteredDataGridControl()</pre>
<pre><span class="lnum">  26:  </span>        {</pre>
<pre class="alt"><span class="lnum">  27:  </span>            InitializeComponent();</pre>
<pre><span class="lnum">  28:  </span>            <span class="kwrd">this</span>.Loaded += <span class="kwrd">new</span> RoutedEventHandler(OnLoaded);</pre>
<pre class="alt"><span class="lnum">  29:  </span>        }</pre>
<pre><span class="lnum">  30:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  31:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">  32:  </span>        <span class="rem">/// Called after UserControl is loaded</span></pre>
<pre class="alt"><span class="lnum">  33:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">  34:  </span>        <span class="rem">/// &lt;param name=&quot;sender&quot;&gt;&lt;/param&gt;</span></pre>
<pre class="alt"><span class="lnum">  35:  </span>        <span class="rem">/// &lt;param name=&quot;e&quot;&gt;&lt;/param&gt;</span></pre>
<pre><span class="lnum">  36:  </span>        <span class="kwrd">void</span> OnLoaded(<span class="kwrd">object</span> sender, RoutedEventArgs e)</pre>
<pre class="alt"><span class="lnum">  37:  </span>        {</pre>
<pre><span class="lnum">  38:  </span>            <span class="rem">//new a SampleDomainContext</span></pre>
<pre class="alt"><span class="lnum">  39:  </span>            Context = <span class="kwrd">new</span> SampleDomainContext();</pre>
<pre><span class="lnum">  40:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  41:  </span>            BindControls();</pre>
<pre><span class="lnum">  42:  </span>        }</pre>
<pre class="alt"><span class="lnum">  43:  </span>&#160;</pre>
<pre><span class="lnum">  44:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alt"><span class="lnum">  45:  </span>        <span class="rem">/// Set up binding between controls and their data (like Context).</span></pre>
<pre><span class="lnum">  46:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt"><span class="lnum">  47:  </span>        <span class="kwrd">private</span> <span class="kwrd">void</span> BindControls()</pre>
<pre><span class="lnum">  48:  </span>        {</pre>
<pre class="alt"><span class="lnum">  49:  </span>            <span class="rem">//Bind ResultGrid's ItemsSource to the context's SampleRecords EntityList</span></pre>
<pre><span class="lnum">  50:  </span>            ResultGrid.ItemsSource = context.SampleRecords;</pre>
<pre class="alt"><span class="lnum">  51:  </span>        }</pre>
<pre><span class="lnum">  52:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  53:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">  54:  </span>        <span class="rem">/// Called when ApplyFilter Button is clicked.</span></pre>
<pre class="alt"><span class="lnum">  55:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">  56:  </span>        <span class="rem">/// &lt;param name=&quot;sender&quot;&gt;&lt;/param&gt;</span></pre>
<pre class="alt"><span class="lnum">  57:  </span>        <span class="rem">/// &lt;param name=&quot;e&quot;&gt;&lt;/param&gt;</span></pre>
<pre><span class="lnum">  58:  </span>        <span class="kwrd">private</span> <span class="kwrd">void</span> ApplyFilter_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)</pre>
<pre class="alt"><span class="lnum">  59:  </span>        {</pre>
<pre><span class="lnum">  60:  </span>            DoApplyFilter();</pre>
<pre class="alt"><span class="lnum">  61:  </span>        }</pre>
<pre><span class="lnum">  62:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  63:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">  64:  </span>        <span class="rem">/// Construct filter and call DomainService to return filtered results.</span></pre>
<pre class="alt"><span class="lnum">  65:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">  66:  </span>        <span class="kwrd">private</span> <span class="kwrd">void</span> DoApplyFilter()</pre>
<pre class="alt"><span class="lnum">  67:  </span>        {</pre>
<pre><span class="lnum">  68:  </span>            <span class="rem">//Create an EntityQuery object</span></pre>
<pre class="alt"><span class="lnum">  69:  </span>            EntityQuery&lt;SampleRecord&gt; query = Context.GetSampleRecordsQuery();</pre>
<pre><span class="lnum">  70:  </span>            </pre>
<pre class="alt"><span class="lnum">  71:  </span>            <span class="rem">//Call Context.Load, pass it a Query and callback function.</span></pre>
<pre><span class="lnum">  72:  </span>            <span class="rem">//This is an Async call. Response will call the OnLoadCompleted </span></pre>
<pre class="alt"><span class="lnum">  73:  </span>            <span class="rem">//callback function</span></pre>
<pre><span class="lnum">  74:  </span>            Context.Load(query, OnLoadCompleted, <span class="kwrd">true</span>);</pre>
<pre class="alt"><span class="lnum">  75:  </span>        }</pre>
<pre><span class="lnum">  76:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  77:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">  78:  </span>        <span class="rem">/// Context's Load Completed Callback function.</span></pre>
<pre class="alt"><span class="lnum">  79:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">  80:  </span>        <span class="rem">/// &lt;param name=&quot;lo&quot;&gt;&lt;/param&gt;</span></pre>
<pre class="alt"><span class="lnum">  81:  </span>        <span class="kwrd">private</span> <span class="kwrd">void</span> OnLoadCompleted(LoadOperation lo)</pre>
<pre><span class="lnum">  82:  </span>        {</pre>
<pre class="alt"><span class="lnum">  83:  </span>            <span class="rem">//Handle errors</span></pre>
<pre><span class="lnum">  84:  </span>            <span class="kwrd">if</span> (lo.HasError)</pre>
<pre class="alt"><span class="lnum">  85:  </span>            {</pre>
<pre><span class="lnum">  86:  </span>                MessageBox.Show(lo.Error.Message.ToString());</pre>
<pre class="alt"><span class="lnum">  87:  </span>            }</pre>
<pre><span class="lnum">  88:  </span>            <span class="kwrd">else</span></pre>
<pre class="alt"><span class="lnum">  89:  </span>            {</pre>
<pre><span class="lnum">  90:  </span>                <span class="rem">//Data has been loaded into context at this point.</span></pre>
<pre class="alt"><span class="lnum">  91:  </span>            }</pre>
<pre><span class="lnum">  92:  </span>        }</pre>
<pre class="alt"><span class="lnum">  93:  </span>    }</pre>
<pre><span class="lnum">  94:  </span>}</pre>
</p></div>
<style type="text/css">
<p>.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>
</td>
</tr>
</tbody>
</table>
<p>What does this code do?</p>
<ul>
<li>We created a local member and property called Context to hold an instance of our SampleDataContext.<br />
    <br />SampleDataContext is the client side proxy generated by WCF RIA that we use to call/access the SampleDomainService methods and Entities. </li>
<li>In the Constructor, we subscribe to the Loaded event and in the OnLoaded() method we create a new instance of SampleDataContext and store it in our local Context member. After that we call a method BindControl(). </li>
<li>BindControls() set’s up the binding between our DataGrid (ResultGrid) and the Context.SampleRecords EntityList which represents a list of SampleRecord entities returned by the SampleDomainService. </li>
<li>DoApplyFilter() is a method called from the ApplyFilter_Click button click event handler. DoApplyFilter() contructs an EntityQuery and then calls the Context.Load method. </li>
<li>Context.Load(…) makes an Asynchronous call to our SampleDomainService. We pass it our EntityQuery and a callback function OnLoadCompleted(). </li>
<li>OnLoadCompleted() will be called when the SampleDomainService call completes (or times out) and if it was successful it will update the data in our SampleDataContext (local Context member) with the data returned. </li>
</ul>
<p>&#160;</p>
<h3>DomainContext – our disconnected client side data store</h3>
<p>It is important to understand the role of the DomainContext (or in our case SampleDataContext). This is a WCF RIA generated class that serves as a client proxy for calling the DomainService methods, but also serves as a client side data store (kind of like a disconnected DataSet) where data is collected when ever you load add/edit or delete entities.</p>
<p>One important thing to be aware of is that if you call Load on an Entity, every load will just Add/Append any returned records to the DataContext’s EntityList. If this is not what you want, you need to clear the relevant EntityList before calling a new load operation.</p>
<h3>Binding a ComboBox to a DISTINCT list of Categories</h3>
<p>In our sample, we need to get a distinct list of Category values to serve as the values for our FilterComboBox control. In SQL this would be something like SELECT DISCTINCT Category FROM SampleRecord. So how do we give our ComboBox a list of Distinct Category Values to bind to using WCF RIA Services?</p>
<p>First, we will create a method in our DomainService to get a list of Categories.</p>
<p>Tip: We have found that instead of adding custom methods to the generated SampleDomainService.cs class which would get overwritten if you had to create it again after adding or changing tables, we change it to be a partial class and create our own SampleDomainService.custom.cs class with our custom methods like so:</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image18.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb18.png" width="244" height="59" /></a> </p>
<p>Add a new [Invoke] method to SampleDomainService.custom.cs:</p>
<table border="1" cellspacing="0" cellpadding="2" width="592">
<tbody>
<tr>
<td valign="top" width="590">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd"><strong>partial</strong></span> <span class="kwrd">class</span> SampleDomainService</pre>
<pre><span class="lnum">   2:  </span>    {</pre>
<pre class="alt"><span class="lnum">   3:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">   4:  </span>        <span class="rem">/// Get's a Distinct list of Categories from the SampleRecord Table.</span></pre>
<pre class="alt"><span class="lnum">   5:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">   6:  </span>        <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span></pre>
<pre class="alt"><span class="lnum">   7:  </span>        <strong>[Invoke]</strong></pre>
<pre><span class="lnum">   8:  </span>        <span class="kwrd">public</span> List&lt;<span class="kwrd">string</span>&gt; FillCategoryList()</pre>
<pre class="alt"><span class="lnum">   9:  </span>        {</pre>
<pre><span class="lnum">  10:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  11:  </span>            <span class="kwrd">return</span> (from r <span class="kwrd">in</span> ObjectContext.SampleRecords</pre>
<pre><span class="lnum">  12:  </span>                        select r.Category).Distinct().ToList();</pre>
<pre class="alt"><span class="lnum">  13:  </span>&#160;</pre>
<pre><span class="lnum">  14:  </span>        }</pre>
<pre class="alt"><span class="lnum">  15:  </span>    }</pre>
</p></div>
</td>
</tr>
</tbody>
</table>
<p>Notice that this is a <strong>partial</strong> class (you need to make SampleDomainService.cs a partial class also) and the method is decorated with the [Invoke] attribute. The reason we made this an [Invoke] method is because it does NOT return an Entity and Query methods must return Entities. The method returns a List (System.Collections.Generics) of string.</p>
<p>Build your solution to regenerate the client side SampleDomainContext with this new method.</p>
<p>Now on the client, add an ObservableCollection that will be used as our CategoryFilter ItemsSource:</p>
<table border="1" cellspacing="0" cellpadding="2" width="600">
<tbody>
<tr>
<td valign="top" width="600">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">   2:  </span>        <span class="rem">/// Collection used as ItemsSource for CategoryFilter ComboBox</span></pre>
<pre class="alt"><span class="lnum">   3:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">   4:  </span>        <span class="kwrd">private</span> ObservableCollection&lt;<span class="kwrd">string</span>&gt; categoryFilterList;</pre>
<pre class="alt"><span class="lnum">   5:  </span>        <span class="kwrd">public</span> ObservableCollection&lt;<span class="kwrd">string</span>&gt; CategoryFilterList</pre>
<pre><span class="lnum">   6:  </span>        {</pre>
<pre class="alt"><span class="lnum">   7:  </span>            get { <span class="kwrd">return</span> categoryFilterList; }</pre>
<pre><span class="lnum">   8:  </span>            set { categoryFilterList = <span class="kwrd">value</span>; }</pre>
<pre class="alt"><span class="lnum">   9:  </span>        }</pre>
</p></div>
<style type="text/css">
<p>.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>
</td>
</tr>
</tbody>
</table>
<p>and add the DoPopulateFilter() method:</p>
<table border="1" cellspacing="0" cellpadding="2" width="713">
<tbody>
<tr>
<td valign="top" width="711">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">   2:  </span>        <span class="rem">/// Calls DomainService, gets a Distinct List of Categories</span></pre>
<pre class="alt"><span class="lnum">   3:  </span>        <span class="rem">/// from SampleRecord.Category and Binds the result</span></pre>
<pre><span class="lnum">   4:  </span>        <span class="rem">/// to the CategoryFilter ComboBox.</span></pre>
<pre class="alt"><span class="lnum">   5:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">   6:  </span>        <span class="kwrd">private</span> <span class="kwrd">void</span> DoPopulateFilter()</pre>
<pre class="alt"><span class="lnum">   7:  </span>        {</pre>
<pre><span class="lnum">   8:  </span>            <span class="rem">//Call Invoke Method to get a list of distinct categories</span></pre>
<pre class="alt"><span class="lnum">   9:  </span>            <strong>InvokeOperation</strong>&lt;IEnumerable&lt;<span class="kwrd">string</span>&gt;&gt; invokeOp = Context.<strong>FillCategoryList</strong>();</pre>
<pre><span class="lnum">  10:  </span>            invokeOp.Completed += (s, e) =&gt;</pre>
<pre class="alt"><span class="lnum">  11:  </span>                {</pre>
<pre><span class="lnum">  12:  </span>                    <span class="kwrd">if</span> (invokeOp.HasError)</pre>
<pre class="alt"><span class="lnum">  13:  </span>                    {</pre>
<pre><span class="lnum">  14:  </span>                        MessageBox.Show(<span class="str">&quot;Failed to Load Category Filter&quot;</span>);</pre>
<pre class="alt"><span class="lnum">  15:  </span>                    }</pre>
<pre><span class="lnum">  16:  </span>                    <span class="kwrd">else</span></pre>
<pre class="alt"><span class="lnum">  17:  </span>                    {</pre>
<pre><span class="lnum">  18:  </span>                        <span class="rem">//Populate Filter DataSource</span></pre>
<pre class="alt"><span class="lnum">  19:  </span>                        CategoryFilterList = <span class="kwrd">new</span> ObservableCollection&lt;<span class="kwrd">string</span>&gt;(invokeOp.Value);</pre>
<pre><span class="lnum">  20:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">  21:  </span>                        <span class="rem">//Add a Default &quot;[Select]&quot; value</span></pre>
<pre><span class="lnum">  22:  </span>                        CategoryFilterList.Insert(0, <span class="str">&quot;[Select]&quot;</span>);</pre>
<pre class="alt"><span class="lnum">  23:  </span>&#160;</pre>
<pre><span class="lnum">  24:  </span>                        CategoryFilter.ItemsSource = CategoryFilterList;</pre>
<pre class="alt"><span class="lnum">  25:  </span>                    }</pre>
<pre><span class="lnum">  26:  </span>                };</pre>
<pre class="alt"><span class="lnum">  27:  </span>        }</pre>
</p></div>
<style type="text/css">
<p>.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>
</td>
</tr>
</tbody>
</table>
<p>What does this method do?</p>
<p>9: Creates a new InvokeOperation with our new Method “FillCategoryList()”.</p>
<p>10: Is an inline delegate/callback for getting the results of the method call (you could have created a separate OnCompleted… method for this, we just wanted to show you this format which is sometimes useful and makes the code more readable.</p>
<p>18 – 24: We create a new ObservableCollection using the result of the method call (List&lt;string&gt;) in its constructor, then adding a dummy “[Select]” value (although this should probably be done on the server) and then set the resulting ObservableCollection as our CategoryFilter ComboBox’s ItemsSource.</p>
<p>In FilteredDataGridConrol.cs add a call to DoPopulateFilter() in the Onloaded() method:</p>
<table border="1" cellspacing="0" cellpadding="2" width="600">
<tbody>
<tr>
<td valign="top" width="600">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">void</span> OnLoaded(<span class="kwrd">object</span> sender, RoutedEventArgs e)</pre>
<pre><span class="lnum">   2:  </span>        {</pre>
<pre class="alt"><span class="lnum">   3:  </span>            <span class="rem">//new a SampleDomainContext</span></pre>
<pre><span class="lnum">   4:  </span>            Context = <span class="kwrd">new</span> SampleDomainContext();</pre>
<pre class="alt"><span class="lnum">   5:  </span>&#160;</pre>
<pre><span class="lnum">   6:  </span>            BindControls();</pre>
<pre class="alt"><span class="lnum">   7:  </span>&#160;</pre>
<pre><span class="lnum">   8:  </span>            <strong>DoPopulateFilter();</strong></pre>
<pre class="alt"><span class="lnum">   9:  </span>        }</pre>
</p></div>
<style type="text/css">
<p>.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>
</td>
</tr>
</tbody>
</table>
<p>Now, if you run the application, you will see that the category list is loaded into the ComboBox (CategoryFilter).</p>
<h3>Adding our Filters to the query on the client side:</h3>
<p>We want to construct a query based on the criteria selected by the user, send that query via WCF RIA Services to get the result. This is cool, because we don’t need to change our service method signatures every time we need to add additional criteria, we just pass a query object.</p>
<p>This is done in the following method:</p>
<table border="1" cellspacing="0" cellpadding="2" width="631">
<tbody>
<tr>
<td valign="top" width="629">
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span>        <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">   2:  </span>        <span class="rem">/// Construct filter and call DomainService to return filtered results.</span></pre>
<pre class="alt"><span class="lnum">   3:  </span>        <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">   4:  </span>        <span class="kwrd">private</span> <span class="kwrd">void</span> DoApplyFilter()</pre>
<pre class="alt"><span class="lnum">   5:  </span>        {</pre>
<pre><span class="lnum">   6:  </span>            <span class="rem">//Create an EntityQuery object</span></pre>
<pre class="alt"><span class="lnum">   7:  </span>            EntityQuery&lt;SampleRecord&gt; query = Context.GetSampleRecordsQuery();</pre>
<pre><span class="lnum">   8:  </span>&#160;</pre>
<pre class="alt"><span class="lnum">   9:  </span>            <span class="rem">//Get user selected Filter Criteria</span></pre>
<pre><span class="lnum">  10:  </span>            <span class="kwrd">if</span> (<span class="kwrd">null</span> != CategoryFilter.SelectedValue)</pre>
<pre class="alt"><span class="lnum">  11:  </span>            {</pre>
<pre><span class="lnum">  12:  </span>                <span class="kwrd">string</span> filterCategory = CategoryFilter.SelectedValue.ToString();</pre>
<pre class="alt"><span class="lnum">  13:  </span>                <span class="kwrd">if</span> (!<span class="kwrd">string</span>.IsNullOrWhiteSpace(filterCategory)</pre>
<pre><span class="lnum">  14:  </span>                    &amp;&amp; filterCategory != <span class="str">&quot;[Select]&quot;</span>)</pre>
<pre class="alt"><span class="lnum">  15:  </span>                {</pre>
<pre><span class="lnum">  16:  </span>                    query = query.Where(s =&gt; s.Category == filterCategory);</pre>
<pre class="alt"><span class="lnum">  17:  </span>                }</pre>
<pre><span class="lnum">  18:  </span>            }</pre>
<pre class="alt"><span class="lnum">  19:  </span>&#160;</pre>
<pre><span class="lnum">  20:  </span>         </pre>
<pre class="alt"><span class="lnum">  21:  </span>            <span class="rem">//Clear Context so we get new results</span></pre>
<pre><span class="lnum">  22:  </span>            Context.SampleRecords.Clear();</pre>
<pre class="alt"><span class="lnum">  23:  </span>            </pre>
<pre><span class="lnum">  24:  </span>            <span class="rem">//Call Context.Load, pass it a Query and callback function.</span></pre>
<pre class="alt"><span class="lnum">  25:  </span>            <span class="rem">//This is an Async call. Response will call the OnLoadCompleted </span></pre>
<pre><span class="lnum">  26:  </span>            <span class="rem">//callback function</span></pre>
<pre class="alt"><span class="lnum">  27:  </span>            Context.Load(query, OnLoadCompleted, <span class="kwrd">true</span>);</pre>
<pre><span class="lnum">  28:  </span>        }</pre>
</p></div>
<style type="text/css">
<p>.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>
</td>
</tr>
</tbody>
</table>
</p>
<p>Line 16: is interested. This format actually adds (concatenates) additional WHERE conditions to the query object so you could do this for each of the criteria options provided by your user interface.</p>
<p>Now, when you run the application and select a specific category you will notice that the data is filtered accordingly.</p>
<p><a href="http://www.jonathanwax.com/wp-content/uploads/2010/10/image19.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.jonathanwax.com/wp-content/uploads/2010/10/image_thumb19.png" width="244" height="132" /></a> </p>
<p>Hopefully some of the techniques shown here will help you get started or complete a task. </p>
<p>Please send us your comments so we can learn from you or answers any questions you may have.</p>
<p>Jonathan</p>
<p><a href="http://www.netusup.com">http://www.netusup.com</a></p>
<p><a href="http://www.jonathanwax.com">http://www.jonathanwax.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jonathanwax.com/2010/10/wcf-ria-services-datagrid-filters-no-domaindatasource-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Silverlight solves our deployment problems.</title>
		<link>http://www.jonathanwax.com/2009/05/silverlight-solves-our-deployment-problems/</link>
		<comments>http://www.jonathanwax.com/2009/05/silverlight-solves-our-deployment-problems/#comments</comments>
		<pubDate>Sun, 24 May 2009 19:39:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.jonathanwax.com/2009/05/silverlight-solves-our-deployment-problems/</guid>
		<description><![CDATA[Mature Architecture + Easy Deployment + Great UX = SILVERLIGHT When ever I am approached to help design or improve an architecture for a system, one of the first issues I ask about is deployment requirements. I generally like to choose the technologies that require writing the least amount of code to deliver a feature: [...]]]></description>
			<content:encoded><![CDATA[<p><strong><font color="#008080">Mature Architecture + Easy Deployment + Great UX = SILVERLIGHT</font></strong></p>
<p>When ever I am approached to help design or improve an architecture for a system, one of the first issues I ask about is <strong>deployment requirements</strong>. </p>
<p>I generally like to choose the technologies that require writing the least amount of code to deliver a feature: <strong>LESS CODE == LESS BUGS == LESS MAINTENANCE TIME == MORE REVENUES</strong>.</p>
<p>Packaging and deployment applications is one of those tasks that requires considerable time and resource to build, test and deliver so when ever I find a technology that helps me with deployment, I give it serious consideration.</p>
<p>A great user experience is what makes users love your applications and recommend it to friends and colleagues which is why my choice of framework focuses on its ability to deliver a <strong>great user experience FIRST</strong> and being <strong>easy to maintain and deploy SECOND</strong> – <strong>until now!</strong></p>
<p><a href="http://www.silverlight.net" target="_blank">Silverlight</a> is an evolution of the Microsoft.NET framework targeting rich user experiences with the easiest deployment model – All your users need is a web browser, all popular browsers on all popular operating systems, <strong>Yes, that’s right, windows type rich applications that your users access using their favorite browser!</strong></p>
<p>The development experience with <a href="http://www.silverlight.net" target="_blank">Silverlight</a> is very mature since it is an evolution of the Microsoft windows and web technologies, combined to provide Microsoft’s answer to RIA – Rich internet applications. Compared to the Adobe Flex/Flash platform. </p>
<p>I believe the mature back-end “story” offered by <a href="http://www.silverlight.net" target="_blank">Silverlight</a> is its primary advantage as far as Line of Business developers are concerned. Oh yeah, it’s also quickly gaining ground with designers allowing a great development story where the developers build the back-end and the designers focus on the user experience.</p>
<p>I am currently involved in several projects using <a href="http://www.silverlight.net" target="_blank">Silverlight</a> as the platform to build a next generation version of existing applications with:</p>
<ul>
<li>Improved User experience (UX).</li>
<li>Mature n-tier architecture.</li>
<li>Simple, cross platform deployment (without coding and testing installers)</li>
</ul>
<p><strong><font color="#008080">Mature Architecture + Easy Deployment + Great UX = SILVERLIGHT</font></strong></p>
<p>Stay tuned, I will share our experience with <a href="http://www.silverlight.net" target="_blank">Silverlight</a> as we progress.</p>
<p><u><a href="http://www.silverlight.net" target="_blank">Silverlight</a> resources:</u></p>
<ul>
<li><a href="http://www.silverlight.net">http://www.silverlight.net</a> – The official Silverlight website.</li>
<li><a title="http://videos.visitmix.com/MIX09/T40F" href="http://videos.visitmix.com/MIX09/T40F">http://videos.visitmix.com/MIX09/T40F</a> – Building Line of business applications (Brad A.)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jonathanwax.com/2009/05/silverlight-solves-our-deployment-problems/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

