<?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>zdima.net &#187; C#</title>
	<atom:link href="http://zdima.net/blog/archives/category/soft/dev/c/feed" rel="self" type="application/rss+xml" />
	<link>http://zdima.net/blog</link>
	<description></description>
	<lastBuildDate>Mon, 30 Jan 2012 11:42:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Deserializing ReCaptcha JSON with C#</title>
		<link>http://zdima.net/blog/archives/16375</link>
		<comments>http://zdima.net/blog/archives/16375#comments</comments>
		<pubDate>Mon, 01 Aug 2011 15:00:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>

		<guid isPermaLink="false">http://www.zdima.net/blog/?guid=c7e0a0b5967987175a236f8308fe8347</guid>
		<description><![CDATA[Turning a ReCaptcha request into a strongly-typed C# object on the fly

When requesting a ReCaptcha image, you send out this request:
http://www.google.com/recaptcha/api/challenge?k=your_public_key

You then receive this in return:
var RecaptchaState =...<p class="read-more"><a href="http://zdima.net/blog/archives/16375">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>Turning a ReCaptcha request into a strongly-typed C# object on the fly</h2>
<p>When requesting a ReCaptcha image, you send out this request:</p>
<blockquote><p><a href="http://www.google.com/recaptcha/api/challenge?k=your_public_key" class="autohyperlink" title="http://www.google.com/recaptcha/api/challenge?k=your_public_key" target="_blank" rel="nofollow">www.google.com/recaptcha/api/challenge?k=your_public_key</a></p></blockquote>
<p>
You then receive this in return:</p>
<pre>var RecaptchaState = {
    site : &#39;your_public_key&#39;,
    challenge : &#39;returned_challenge_key&#39;,
    is_incorrect : false,
    programming_error : &#39;&#39;,
    error_message : &#39;&#39;,
    server : &#39;http://www.google.com/recaptcha/api/&#39;,
    timeout : 18000
};

document.write(&#39;&lt;scr&#39;+&#39;ipt type=&quot;text/javascript&quot;
    s&#39;+&#39;rc=&quot;&#39; + RecaptchaState.server + &#39;js/recaptcha.js&quot;&gt;
    &lt;/scr&#39;+&#39;ipt&gt;&#39;);</pre>
<p>
Looking at that, you can pull the information you need into this object:</p>
<pre>[Serializable]
public class ReCaptchaState
{
    [DataMember]
    public string site { get; set; }

    [DataMember]
    public string challenge { get; set; }

    [DataMember]
    public bool is_correct { get; set; }

    [DataMember]
    public string programming_error { get; set; }

    [DataMember]
    public string error_message { get; set; }

    [DataMember]
    public string server { get; set; }

    [DataMember]
    public int timeout { get; set; }
}</pre>
<p>
By using this code:</p>
<pre>WebClient client = new WebClient();
string ret = client.DownloadString(google_url);
int start = ret.IndexOf(&#39;{&#39;);
int length = ret.IndexOf(&#39;}&#39;) - start + 1;
string json = ret.Substring(start, length);

ReCaptchaState state = new JavaScriptSerializer()
    .Deserialize&lt;ReCaptchaState&gt;(json);</pre>
<p>
Now you have a <strong>ReCaptchaState</strong> .net object you can use the values from; simple.
<p><iframe src="http://feedads.g.doubleclick.net/~ah/f/kijri0o2kgcv9o6a1kk1fsjgmk/300/250?ca=1&amp;fh=280#http://naspinski.net/post.aspx?id=3b60a44a-fcac-4085-8530-2b69b8e62ac1" width="100%" height="280" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=uc-izK4e_NQ:1UHRy7p2Iek:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=uc-izK4e_NQ:1UHRy7p2Iek:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=uc-izK4e_NQ:1UHRy7p2Iek:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=uc-izK4e_NQ:1UHRy7p2Iek:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=uc-izK4e_NQ:1UHRy7p2Iek:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/uc-izK4e_NQ" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/16375/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serializing and DeSerializing XML Objects in .Net</title>
		<link>http://zdima.net/blog/archives/15772</link>
		<comments>http://zdima.net/blog/archives/15772#comments</comments>
		<pubDate>Tue, 01 Mar 2011 05:50:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=15772</guid>
		<description><![CDATA[these two simple extension methods with have you switching between XML and objects in no time

First off, it is pretty well known that if you have any Object and want to convert it into an XML strong, you can use the XmlSerializer to do so.  I encapsul...<p class="read-more"><a href="http://zdima.net/blog/archives/15772">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>these two simple extension methods with have you switching between XML and objects in no time</h2>
<p>First off, it is pretty well known that if you have any Object and want to convert it into an XML strong, you can use the <strong>XmlSerializer</strong> to do so.  I encapsulated the process is a simple extension method that run from any object &#8211; this will work as long as the object has a constructor with no inputs (ie: new SomeObject()) as that is the constraint passed up from <strong>XmlSerializer</strong>.  Here is the method for converting from an object to an xml string:</p>
<pre>public static string ToXmlString(this Object o)
{
    StringWriter xml = new
        StringWriter(new StringBuilder());
    XmlSerializer xS = new XmlSerializer(o.GetType());
    xS.Serialize(xml, o);
    return xml.ToString();
}</pre>
<p>
With this, now all you need to do is:</p>
<pre>MyObject obj = new MyObject();
// a bunch of stuff here...
// now I want the xml representation of this:
string xml = obj.ToXmlString();</pre>
<p>
Now to go backwards, you can use the similar <strong>Deserialize</strong> along with the XmlSerializer with this method:</p>
<pre>public static T XmlToObject&lt;T&gt;(this string s)
{
    var xR = XmlReader.Create(new
        StringReader(s));
    XmlSerializer xS = new XmlSerializer(typeof(T));
    T obj = (T)xS.Deserialize(xR);
    return obj;
}</pre>
<p>
It is important to notice that this is taking in a raw xml string, which would not be web safe.  If you were taking in data from a web source, you would want to employ <strong>HttpUtility.UrlDecode(s)</strong> instead of just <strong>s</strong> above.<br />
Now if you want to turn your above string &#8216;xml&#8217; into an object again, simply call it like this:</p>
<pre>MyObject obj2 = xml.XmlToObject&lt;SomeObject&gt;();</pre>
<p><iframe src="http://feedads.g.doubleclick.net/~ah/f/kijri0o2kgcv9o6a1kk1fsjgmk/468/60#http://www.naspinski.net/post.aspx?id=05fcfd89-d331-438f-8802-d3068fe7876d" width="100%" height="60" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=PdY_5KfqTZw:kR8dFT3sCH4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=PdY_5KfqTZw:kR8dFT3sCH4:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=PdY_5KfqTZw:kR8dFT3sCH4:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=PdY_5KfqTZw:kR8dFT3sCH4:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=PdY_5KfqTZw:kR8dFT3sCH4:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/PdY_5KfqTZw" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/15772/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generate random values in C#</title>
		<link>http://zdima.net/blog/archives/15585</link>
		<comments>http://zdima.net/blog/archives/15585#comments</comments>
		<pubDate>Thu, 02 Dec 2010 23:34:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=15585</guid>
		<description><![CDATA[all sorts of random values including date, times, numbers, binary, bit, etc.
Nothing new here, but it's nice to have it all in one spot.
generate random values
public int Integer(int max = Int16.MaxValue)
{
    max = max &#62; Int16.MaxValue ? Int16.Max...<p class="read-more"><a href="http://zdima.net/blog/archives/15585">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>all sorts of random values including date, times, numbers, binary, bit, etc.</h2>
<p>Nothing new here, but it&#8217;s nice to have it all in one spot.</p>
<h4>generate random values</h4>
<pre>public int Integer(int max = Int16.MaxValue)
{
    max = max &gt; Int16.MaxValue ? Int16.MaxValue : max;
    return new Random().Next(-max, max);
}

public string Binary(int length = <img src='http://zdima.net/blog/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> {
    int decNum = new Random().Next(1000, int.MaxValue);
    return Convert.ToString(decNum, 2)
        .Substring(0, length);
}

public DateTime Date(int start_year = 1995)
{
    DateTime start = new DateTime(start_year, 1, 1);
    int range = ((TimeSpan)(DateTime.Today - start))
        .Days;
    start.AddDays(new Random().Next(range))
        .AddSeconds(new Random().Next(86400));
}

public TimeSpan Time()
{
    return Date().TimeOfDay;
}

public int Bit()
{
    return new Random().Next() % 2 == 0 ? 1 : 0;
}

public bool Bool()
{
    return new Random().Next() % 2 == 0 ? true : false;
}

public string String(int limit = 255)
{
    // added spaces so there will be
    // a higher chance of spacing words
    string legal = &quot;        abcdefghijklmnopqrstuvwxyz&quot; +
        &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789      &quot;;
    StringBuilder s = new StringBuilder();
    //Random length for the string
    limit = new Random().Next(1, limit);
    for (int i = 0; i &lt; limit; i++)
        s.Append(legal[new Random().Next(legal.Length)]);
    return s.ToString();
}</pre>
<p><iframe src="http://feedads.g.doubleclick.net/~ah/f/kijri0o2kgcv9o6a1kk1fsjgmk/300/250?ca=1&amp;fh=280#http://naspinski.net/post.aspx?id=fef0302a-b045-4c73-b4bc-10ef58cce80a" width="100%" height="280" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=b6Pz6XrNQUs:ghGnNJhpQRc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=b6Pz6XrNQUs:ghGnNJhpQRc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=b6Pz6XrNQUs:ghGnNJhpQRc:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=b6Pz6XrNQUs:ghGnNJhpQRc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=b6Pz6XrNQUs:ghGnNJhpQRc:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/b6Pz6XrNQUs" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/15585/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ServerInfo &#8211; Easily scan a Machine/Server Farm for Information</title>
		<link>http://zdima.net/blog/archives/15249</link>
		<comments>http://zdima.net/blog/archives/15249#comments</comments>
		<pubDate>Wed, 28 Jul 2010 15:48:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=15249</guid>
		<description><![CDATA[new open-source project in Asp.Net MVC 2


More than once I have been asked what databases are on what server, if server X is running application Y or what websites server ABC is running.  These are are relatively simple things to accomplish, and there...<p class="read-more"><a href="http://zdima.net/blog/archives/15249">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>new open-source project in <a href="http://Asp.Net" class="autohyperlink" title="http://Asp.Net" target="_blank" rel="nofollow">Asp.Net</a> MVC 2</h2>
<p><a href="http://serverinfo.codeplex.com/"><img src="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=serverinfo&amp;DownloadId=138799" style="width:480px"></a></p>
<p>More than once I have been asked what databases are on what server, if server X is running application Y or what websites server ABC is running.  These are are relatively simple things to accomplish, and there are tools available to get this information, but this is an extremely simple and portable solution &#8211; all the data is kept in xml, so there is no need to install a backend.</p>
<p>All that it is required to get all this information is to enter ip addresses and the user has the rights to scan the machines requested.</p>
<p>In addition, this can keep track of all of the owners of the machines and has a GUI for running <a href="javascript:void(0);">WMI Queries</a>, which is extremely powerful if you know how to use it.</p>
<p>This is written with <a href="http://Asp.Net" class="autohyperlink" title="http://Asp.Net" target="_blank" rel="nofollow">Asp.Net</a> MVC 2, C# and xml; it requires .Net 4.0 framework.  I will be updating this to MVC 3/Razor in the near future.</p>
<div>
            <a href="http://serverinfo.codeplex.com/" rel="enclosure">ServerInfo on CodePlex</a>
        </div>
<p><a href="http://feedads.g.doubleclick.net/~a/qe9IeRhNB_n9-zHIQLZbw5z4lUI/0/da"><img src="http://feedads.g.doubleclick.net/~a/qe9IeRhNB_n9-zHIQLZbw5z4lUI/0/di" border="0" ismap></a><br />
<a href="http://feedads.g.doubleclick.net/~a/qe9IeRhNB_n9-zHIQLZbw5z4lUI/1/da"><img src="http://feedads.g.doubleclick.net/~a/qe9IeRhNB_n9-zHIQLZbw5z4lUI/1/di" border="0" ismap></a></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=iQuxCWmjmGk:4U_aXqNAfrM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=iQuxCWmjmGk:4U_aXqNAfrM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=iQuxCWmjmGk:4U_aXqNAfrM:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=iQuxCWmjmGk:4U_aXqNAfrM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=iQuxCWmjmGk:4U_aXqNAfrM:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/iQuxCWmjmGk" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/15249/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>using Server.MapPath() in an Generic Handler (.ashx)</title>
		<link>http://zdima.net/blog/archives/15222</link>
		<comments>http://zdima.net/blog/archives/15222#comments</comments>
		<pubDate>Thu, 22 Jul 2010 12:50:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=15222</guid>
		<description><![CDATA[if you need to get a local file path in your ashx
Instead of using:
Server.MapPath()
Simply use:
System.Web.HttpContext.Current.Server.MapPath()


  
<p class="read-more"><a href="http://zdima.net/blog/archives/15222">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>if you need to get a local file path in your ashx</h2>
<p>Instead of using:</p>
<pre>Server.MapPath()</pre>
<p>
Simply use:</p>
<pre>System.Web.HttpContext.Current.Server.MapPath()</pre>
<p><a href="http://feedads.g.doubleclick.net/~a/VEEddDBAa24jrIdEcBBRsJ14fOI/0/da"><img src="http://feedads.g.doubleclick.net/~a/VEEddDBAa24jrIdEcBBRsJ14fOI/0/di" border="0" ismap></a><br />
<a href="http://feedads.g.doubleclick.net/~a/VEEddDBAa24jrIdEcBBRsJ14fOI/1/da"><img src="http://feedads.g.doubleclick.net/~a/VEEddDBAa24jrIdEcBBRsJ14fOI/1/di" border="0" ismap></a></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=EF7lfUp6d1w:9ww-M0jLzuc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=EF7lfUp6d1w:9ww-M0jLzuc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=EF7lfUp6d1w:9ww-M0jLzuc:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=EF7lfUp6d1w:9ww-M0jLzuc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=EF7lfUp6d1w:9ww-M0jLzuc:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/EF7lfUp6d1w" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/15222/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inline AJAX DropDown and Text Editing with Asp.Net MVC and jQuery</title>
		<link>http://zdima.net/blog/archives/15195</link>
		<comments>http://zdima.net/blog/archives/15195#comments</comments>
		<pubDate>Mon, 12 Jul 2010 09:31:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=15195</guid>
		<description><![CDATA[including how to use a database to populate the dropdown


First thing is first, you will need to download 
jQuery 
and the 
Jeditable 
plugin (I prefer to refer to it as the Jedi-Table!).
Be sure to put these references in your View (or Masterpage).
N...<p class="read-more"><a href="http://zdima.net/blog/archives/15195">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>including how to use a database to populate the dropdown</h2>
<p><img src="http://naspinski.net/image.axd?picture=clicked.JPG" alt=""><br />
First thing is first, you will need to download<br />
<a href="http://jquery.com/">jQuery</a><br />
and the<br />
<a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a><br />
plugin (I prefer to refer to it as the Jedi-Table!).<br />
Be sure to put these references in your View (or Masterpage).<br />
Next, you have to set up a view on which to use an inline edit.<br />
I find that I often want to use this approach on tables of information.<br />
For this View, I will set it to use an IEnumerable of an Item I have called &#8216;ItemOwner&#8217; (this is arbitrary and does not really matter).<br />
It will be a simple table that lists the Name and the Country of the owner, both of which will be editable inline.<br />
Here is the Index in my ExampleController.cs:</p>
<pre>myDataContext db = new myDataContext();
public ActionResult Index()
{
    // get the info for the &#39;Countries&#39; dropdown:
    ViewData[&quot;countries&quot;] = db.Countries
        .Select(x =&gt; new SelectListItem()
        {
            Text = x.Name,
            Value = x.Id.ToString()
        }).ToJson();

    // get the &#39;ItemOwners&#39; I am interested in:
    var owners = db.ItemOwners.Take(3);

    return View(owners);
}</pre>
<p>
As you can see there, I am also pulling the countries from the database and throwing them into the ViewState &#8211; we will get to this later.<br />
Since the Country is actually a foreign key relation, the value is set to an integer which is the identity field in the database.<br />
It is also using a .ToJson() extension which takes a IEnumerable&lt;SelectListItem&gt; and<br />
    puts it into a simple JSON string that I use which is here:</p>
<pre>public static string
    ToJson(this IEnumerable&lt;SelectListItem&gt; slis)
{
    string output = &quot;{&quot;;
    if (slis != null)
    {
        for (int i = 0; i &lt; slis.Count(); i++)
        {
            output += &quot; &#39;&quot; + slis.Skip(i)
            .First().Value + &quot;&#39;: &#39;&quot; +
            slis.Skip(i).First().Text + &quot;&#39;&quot; +
            (i == slis.Count() - 1 ? &quot; &quot; : &quot;,&quot;);
        }
    }
    return output += &quot;}&quot;;
}</pre>
<p>
There is probably a better way to do that&#8230; but I don&#8217;t know it?!</p>
<p>I am also pulling 3 ItemOwners from the database, I know this is silly, but it  just an example.<br />
Here is how I am displaying them in the view:</p>
<pre>&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Country&lt;/th&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
        &lt;% foreach(var owner in Model) { %&gt;
        &lt;tr&gt;
            &lt;td&gt;&lt;%= <a href="http://owner.Name" class="autohyperlink" title="http://owner.Name" target="_blank" rel="nofollow">owner.Name</a> %&gt;&lt;/td&gt;
            &lt;td&gt;&lt;%= owner.Country.Abbreviation %&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;% } %&gt;
    &lt;/tbody&gt;
&lt;/table&gt;</pre>
<p>
Now that there is a simple table we want to make it a bit more interactive.<br />
Since we aregoing to make all of these fields editable, we need to add in a way to distinguish exactly what they are.<br />
To do that, we will need two things: the id of the item they are editing, and the type of inline editing we will be doing (i.e. dropdown or text input).<br />
So to do that, let&#8217;s add in a few css classes and an identifieng ID:</p>
<pre>&lt;td id=&quot;name&lt;%= owner.Id %&gt;&quot; class=&quot;editable text&quot;&gt;
    &lt;%= <a href="http://owner.Name" class="autohyperlink" title="http://owner.Name" target="_blank" rel="nofollow">owner.Name</a> %&gt;&lt;/td&gt;
&lt;td id=&quot;ctry&lt;%= owner.Id %&gt;&quot; class=&quot;editable dropdown&quot;&gt;
    &lt;%= owner.Country.Abbreviation %&gt;&lt;/td&gt;</pre>
<p> <br />
And now add a little css to make them appear to be clickable:</p>
<pre>td.editable:hover
{ cursor:pointer; background-color:Orange; }</pre>
<p>
Now they all look like you can click on them, so we can move on to making the click actually do something.<br />
<br />
<img src="http://naspinski.net/image.axd?picture=hover.JPG" alt=""><br />
<br />
This is where the jQuery comes in, and it is very simple.<br />
I have made these &#8216;helper&#8217; methods in Javascript to make all of my inline calls centrally controllable, I keep this in my sites script folder so if I change one inline edit, I change them all; it also makes for more readable Javascript on each page.</p>
<pre>function InlineDropdown(collectionToDropDown, ajaxAddress, dropDownDataSet) {
    collectionToDropDown.editable(ajaxAddress,
    {
        data: dropDownDataSet,
        type: 'select',
        indicator: 'saving...',
        tooltip: 'click to edit...',
        submit: 'Save',
        style: 'inherit',
        placeholder: 'click to edit'
    });
}

function InlineTextbox(collectionToInline, ajaxAddress) {
    collectionToInline.editable(ajaxAddress,
    {
        indicator: 'saving...',
        tooltip: 'click to edit...',
        style: 'inherit',
        placeholder: 'click to edit'
    });
}

function InlineTextarea(collectionToInline, ajaxAddress) {
    collectionToInline.editable(ajaxAddress,
    {
        type        : 'textarea',
        rows        : 4,
        indicator   : 'saving...',
        tooltip     : 'click to edit...',
        style       : 'inherit',
        submit      : 'Save',
        onblur      : 'ignore',
        placeholder : 'click to edit'
    });
}</pre>
<p>
Obviously you can read all about the options on the <a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a><br />
page, but this is how I set them.<br />
Also notice I have a InineTextarea included as well for a textarea which is not covered here but works the exact same.</p>
<p>Now the jQuery calls are almost trivial:</p>
<pre>InlineTextbox(
    $(&#39;td.editable.text&#39;),
    &quot;&lt;%= Url.Content(&quot;~/Ajax/ItemOwner.ashx&quot;) %&gt;&quot;
);

InlineDropdown(
    $(&#39;td.editable.dropdown&#39;),
    &quot;&lt;%= Url.Content(&quot;~/Ajax/ItemOwner.ashx&quot;) %&gt;&quot;,
    &lt;%= ViewData[&quot;countries&quot;].ToString() %&gt;
);</pre>
<p>
What that is doing is sending the POST requests to the specified address.<br />
The POST contains a few things:</p>
<ul>
<li><b>id</b> &#8211; the id of the element that sent the request</li>
<li><b>value</b> &#8211; the new value passed by the element</li>
</ul>
<p>We are also passing more information there &#8211; remember that we passed both the type of field to edit <em>and</em> the id of the ItemOwner to edit, ie [name837] which emans we want to edit the Name field of ItemOwner 837.<br />
So we simply set up an ashx handler (which we specified above) to do the dirty work:</p>
<pre>public void ProcessRequest(HttpContext context)
{
    string newValue;
    try
    {
        myDataContext db = new myDataContext();
        string elementId = context.Request.Form[&quot;id&quot;];

        // since we made the first 4 of the id the &#39;field&#39; whic to edit
        // we can just pull the first 4 letters for use in our switch:
        string fieldToEdit = elementId.Substring(0, 4);

        //now take anything after those 4 and it is the Id:
        int idToEdit = Convert.ToInt32(elementId.Remove(0, 4));

        // the value is simply a string:
        newValue = context.Request.Form[&quot;value&quot;].Trim();

        // now that we have the id, get the ItemOwner from the db
        ItemOwner owner = db.ItemOwners.FirstOrDefault(x =&gt; x.Id == idToEdit);

        // after all is said and done, we will return newValue to the user so the field
        // looks as if the change has taken place (which it has)

        // using the field we pulled above, decide what to do:
        switch (fieldToEdit)
        {
            // name is easy
            case &quot;name&quot;: <a href="http://owner.Name" class="autohyperlink" title="http://owner.Name" target="_blank" rel="nofollow">owner.Name</a> = newValue; break;

            // since the country is an integer foreign key, we need to Convert.ToInt32:
            case &quot;ctry&quot;:
                owner.CountryId = Convert.ToInt32(newValue);
                // now that we have recorded the value, we want to return the text to
                // the user and not the id value which would make no sense
                newValue = db.Countries.FirstOrDefault(x =&gt; x.Id == owner.CountryId).Abbreviation;
                break;
            // if it wasn&#39;t caught, something is wrong:
            default: throw new Exception(&quot;invalid fieldToEdit passed&quot;);
        }

        db.SubmitChanges(); // save it
    }
    // now if an exceptions were reported, the user can see what happened
    // this also inform the user nothing was saved
    // you could easily make this not reported to the user and logged elsewhere
    catch (Exception ex)
    { newValue = &quot;Error: &quot; + ex.Message + &quot; [nothing written to db]&quot;; }

    //now return what you want in the element:
    context.Response.Write(newValue);
}</pre>
<p>
And that is all it takes.
<p><iframe src="http://feedads.g.doubleclick.net/~ah/f/kijri0o2kgcv9o6a1kk1fsjgmk/300/250?ca=1&amp;fh=280#http://naspinski.net/post.aspx?id=9c3a446e-35f3-442d-8031-d129914635bd" width="100%" height="280" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=2N4iwE_dArk:Exnkys-LL1g:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=2N4iwE_dArk:Exnkys-LL1g:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=2N4iwE_dArk:Exnkys-LL1g:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=2N4iwE_dArk:Exnkys-LL1g:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=2N4iwE_dArk:Exnkys-LL1g:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/2N4iwE_dArk" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/15195/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Edit an Object Property Value Dynamically at Run Time</title>
		<link>http://zdima.net/blog/archives/15069</link>
		<comments>http://zdima.net/blog/archives/15069#comments</comments>
		<pubDate>Tue, 01 Jun 2010 16:13:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=15069</guid>
		<description><![CDATA[<h2>no need to write a huge switch statement to make a run time decision</h2>

Imagine you have an Object with 50 properties, and at runtime, you only need to change the value of one of them.  You could write a switch statement to run through all of them, but there is a better way. This is how it would be done with a switch:
<pre>switch(propertyName)
{
    case "Name": obj.Name = newVal; break;
    case "Phone": obj.Phone = newVal; break;
    ///and so on...</pre>
<br />
That sounds like a terrible idea.  With Reflection, it was easy to build an extension to update any object with a new value at runtime (provided it can be written to) with the following code:
<pre>public static void SetPropertyValue(this object o, 
    string propertyName, object newValue)
{
    PropertyInfo pi;
    pi = o.GetType().GetProperty(propertyName);
    if (pi == null)
        throw new Exception("No Property [" + 
            propertyName + "] in Object [" + 
            o.GetType().ToString() + "]");
    if (!pi.CanWrite)
        throw new Exception("Property [" + 
            propertyName + "] in Object [" + 
            o.GetType().ToString() + 
            "] does not allow writes");
    pi.SetValue(o, newValue, null);
}</pre>
<br />
Now, instead of that 50+ line mess above, all you need to do to change the "Phone" property to 'newVal' is:
<pre>
obj.SetPropertyValue("Phone", newVal);
</pre>
<br />
I added this to my <a href="http://naspinski.codeplex.com">Naspinski.Utilities</a> Set on CodePlex as well.<p></p><div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=hSPE2LcA5yc:Y77-LWeo67Y:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=hSPE2LcA5yc:Y77-LWeo67Y:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=hSPE2LcA5yc:Y77-LWeo67Y:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=hSPE2LcA5yc:Y77-LWeo67Y:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=hSPE2LcA5yc:Y77-LWeo67Y:F7zBnMyn0Lo" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/naspinski/~4/hSPE2LcA5yc" height="1" width="1"><p class="read-more"><a href="http://zdima.net/blog/archives/15069">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>no need to write a huge switch statement to make a run time decision</h2>
<p>Imagine you have an Object with 50 properties, and at runtime, you only need to change the value of one of them.  You could write a switch statement to run through all of them, but there is a better way. This is how it would be done with a switch:</p>
<pre>switch(propertyName)
{
    case "Name": <a href="http://obj.Name" class="autohyperlink" title="http://obj.Name" target="_blank" rel="nofollow">obj.Name</a> = newVal; break;
    case "Phone": obj.Phone = newVal; break;
    ///and so on...</pre>
<p>
That sounds like a terrible idea.  With Reflection, it was easy to build an extension to update any object with a new value at runtime (provided it can be written to) with the following code:</p>
<pre>public static void SetPropertyValue(this object o,
    string propertyName, object newValue)
{
    PropertyInfo pi;
    pi = o.GetType().GetProperty(propertyName);
    if (pi == null)
        throw new Exception("No Property [" +
            propertyName + "] in Object [" +
            o.GetType().ToString() + "]");
    if (!pi.CanWrite)
        throw new Exception("Property [" +
            propertyName + "] in Object [" +
            o.GetType().ToString() +
            "] does not allow writes");
    pi.SetValue(o, newValue, null);
}</pre>
<p>
Now, instead of that 50+ line mess above, all you need to do to change the &#8220;Phone&#8221; property to &#8216;newVal&#8217; is:</p>
<pre>
obj.SetPropertyValue("Phone", newVal);
</pre>
<p>
I added this to my <a href="http://naspinski.codeplex.com">Naspinski.Utilities</a> Set on CodePlex as well.
<p><iframe src="http://feedads.g.doubleclick.net/~ah/f/kijri0o2kgcv9o6a1kk1fsjgmk/468/60#http%3A%2F%2Fwww.naspinski.net%2Fpost.aspx%3Fid%3D380a3be0-2048-4b6d-901c-732ec4cb35db" width="100%" height="60" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=hSPE2LcA5yc:Y77-LWeo67Y:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=hSPE2LcA5yc:Y77-LWeo67Y:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=hSPE2LcA5yc:Y77-LWeo67Y:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=hSPE2LcA5yc:Y77-LWeo67Y:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=hSPE2LcA5yc:Y77-LWeo67Y:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/hSPE2LcA5yc" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/15069/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>string.ToNullable() Extension for Converting a string into a Nullable Object of Type T</title>
		<link>http://zdima.net/blog/archives/10727</link>
		<comments>http://zdima.net/blog/archives/10727#comments</comments>
		<pubDate>Mon, 14 Dec 2009 18:15:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[my projects]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=10727</guid>
		<description><![CDATA[<h2>save time with a simple conversion that works for all nullable Types</h2>
For a while, I have used a ToNullable method (that I found somewhere on the intertubes) that required the input of a TryParse delegate like this:
<pre>int? eight = &#34;8&#34;.ToNullable&#60;T&#62;(int.TryParse);
int? nInt = &#34;&#34;.ToNullable&#60;T&#62;(int.TryParse);//null</pre>
<br />
Which wasn't bad in any way, but I realized that every time I was using this method, I would have to type in the TryParse of the Type I was trying to get; clearly there is a better way, and I found it using <b>TypeConverter</b>.
Now I can use my new ToNullable method in a cleaner, less repetitive way:
<pre>int? eight = &#34;8&#34;.ToNullable&#60;T&#62;();
int? nInt = &#34;&#34;.ToNullable&#60;T&#62;();//null</pre>
<br />
Here is the code:
<pre>public static Nullable&#60;T&#62; 
  ToNullable&#60;T&#62;(this string s) where T : struct
{
  T? result = null; 
  if (!string.IsNullOrEmpty(s.Trim())) 
  {
    TypeConverter converter = TypeDescriptor
      .GetConverter(typeof(T?)); 
    result = (T?)converter.ConvertFrom(s); 
  }
  return result;
}</pre>
<br />
This has been added to my <a href="http://naspinski.codeplex.com">Utilities Library</a> on <a href="http://codeplex.com">CodePlex</a>.
<span>
convert integer to nullable ?Int32
convert int to nullable ?int
convert double to nullable ?double
convert bool to nullable ?bool
convert decimal to nullable ?decimal
convert long to nullable ?long
</span><p></p><div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=B0hYjF0Sh2M:Ti22D7xJwxY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=B0hYjF0Sh2M:Ti22D7xJwxY:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=B0hYjF0Sh2M:Ti22D7xJwxY:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=B0hYjF0Sh2M:Ti22D7xJwxY:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=B0hYjF0Sh2M:Ti22D7xJwxY:F7zBnMyn0Lo" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/naspinski/~4/B0hYjF0Sh2M" height="1" width="1"><p class="read-more"><a href="http://zdima.net/blog/archives/10727">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>save time with a simple conversion that works for all nullable Types</h2>
<p>For a while, I have used a ToNullable method (that I found somewhere on the intertubes) that required the input of a TryParse delegate like this:</p>
<pre>int? eight = &quot;8&quot;.ToNullable&lt;T&gt;(int.TryParse);
int? nInt = &quot;&quot;.ToNullable&lt;T&gt;(int.TryParse);//null</pre>
<p>
Which wasn&#8217;t bad in any way, but I realized that every time I was using this method, I would have to type in the TryParse of the Type I was trying to get; clearly there is a better way, and I found it using <b>TypeConverter</b>.<br />
Now I can use my new ToNullable method in a cleaner, less repetitive way:</p>
<pre>int? eight = &quot;8&quot;.ToNullable&lt;T&gt;();
int? nInt = &quot;&quot;.ToNullable&lt;T&gt;();//null</pre>
<p>
Here is the code:</p>
<pre>public static Nullable&lt;T&gt;
  ToNullable&lt;T&gt;(this string s) where T : struct
{
  T? result = null;
  if (!string.IsNullOrEmpty(s.Trim()))
  {
    TypeConverter converter = TypeDescriptor
      .GetConverter(typeof(T?));
    result = (T?)converter.ConvertFrom(s);
  }
  return result;
}</pre>
<p>
This has been added to my <a href="http://naspinski.codeplex.com">Utilities Library</a> on <a href="http://codeplex.com">CodePlex</a>.<br />
<span><br />
convert integer to nullable ?Int32<br />
convert int to nullable ?int<br />
convert double to nullable ?double<br />
convert bool to nullable ?bool<br />
convert decimal to nullable ?decimal<br />
convert long to nullable ?long<br />
</span>
<p><iframe src="http://feedads.g.doubleclick.net/~ah/f/kijri0o2kgcv9o6a1kk1fsjgmk/468/60#http%3A%2F%2Fnaspinski.net%2Fpost.aspx%3Fid%3D4d27345a-df53-4a04-8e87-f33bf2a42296" width="100%" height="60" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=B0hYjF0Sh2M:Ti22D7xJwxY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=B0hYjF0Sh2M:Ti22D7xJwxY:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=B0hYjF0Sh2M:Ti22D7xJwxY:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=B0hYjF0Sh2M:Ti22D7xJwxY:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=B0hYjF0Sh2M:Ti22D7xJwxY:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/B0hYjF0Sh2M" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/10727/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Universal Get() accessor for any Linq-to-SQL Table</title>
		<link>http://zdima.net/blog/archives/10803</link>
		<comments>http://zdima.net/blog/archives/10803#comments</comments>
		<pubDate>Thu, 10 Dec 2009 18:18:00 +0000</pubDate>
		<dc:creator>naspinski</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[my projects]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=10803</guid>
		<description><![CDATA[<h2>never write a Linq-to-SQL Get accessor again</h2>
<div>
I don't even want to know how many times I have written something like this:
<pre>var p = db.Products.FirstOrDefault(x =&#62; x.Id == someId);</pre>
<br />
Then 4 lines down, do it again almost exactly the same, over and over, at least once for each table.
Well... no more! 
Now that I am able to <a href="http://naspinski.net/post/Get-the-Primary-Key-PropertyInfo-of-any-Linq-to-SQL-Table.aspx">get the Primary Key of any Linq-to-SQL talbe</a>, it is trival to be able to write a universal get statement so I can simply do this when I want to grab an object by it's Primary Key:
<pre>Product p = db.Get&#60;Product&#62;(someId);</pre>
<br />
What if I want to get an item that has a <b>Guid</b> as a primary key?
Same thing, it doesn't matter:
<pre>Guid gId = 
  new Guid(&#34;4fcc0b82-b137-4e4b-935e-872ed662ba53&#34;);
Gizmo g = db.Get&#60;Gizmo&#62;(gId);</pre>
<br />
If you you give the wrong Type of Key, it will tell you in a nice <b>ArgumentException</b>:
<pre>Gizmo g = db.Get&#60;Gizmo&#62;(5);</pre><br />
Error:
<p>Primary Key of Table and primaryKey argument are not of the same Type; Primary Key of Table is of Type: System.Guid, primaryKey argument supplied is of Type: System.Int32</p>
<br /><br />
Here is the code without any error handling:
<pre>public static T Get&#60;T&#62;(this DataContext dataContext,
  object primaryKey) 
    where T : class, INotifyPropertyChanged
{
  return dataContext.GetTable(typeof(T))
    .Cast&#60;T&#62;()
    .Where(GetPrimaryKey&#60;T&#62;()
    .Name + &#34;.Equals(@0)&#34;, primaryKey)
    .FirstOrDefault();
}</pre><br />
The full code is available in my <a href="http://naspinski.codeplex.com">Utilities class</a> on CodePlex.
This requires <b>System.Linq.Dynamic</b>.
</div><p></p><div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=TIzmXswn1G0:nMa9CDLa4fs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=TIzmXswn1G0:nMa9CDLa4fs:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=TIzmXswn1G0:nMa9CDLa4fs:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=TIzmXswn1G0:nMa9CDLa4fs:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=TIzmXswn1G0:nMa9CDLa4fs:F7zBnMyn0Lo" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/naspinski/~4/TIzmXswn1G0" height="1" width="1"><p class="read-more"><a href="http://zdima.net/blog/archives/10803">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<h2>never write a Linq-to-SQL Get accessor again</h2>
<div>
I don&#8217;t even want to know how many times I have written something like this:</p>
<pre>var p = db.Products.FirstOrDefault(x =&gt; x.Id == someId);</pre>
<p>
Then 4 lines down, do it again almost exactly the same, over and over, at least once for each table.<br />
Well&#8230; no more!<br />
Now that I am able to <a href="http://naspinski.net/post/Get-the-Primary-Key-PropertyInfo-of-any-Linq-to-SQL-Table.aspx">get the Primary Key of any Linq-to-SQL talbe</a>, it is trival to be able to write a universal get statement so I can simply do this when I want to grab an object by it&#8217;s Primary Key:</p>
<pre>Product p = db.Get&lt;Product&gt;(someId);</pre>
<p>
What if I want to get an item that has a <b>Guid</b> as a primary key?<br />
Same thing, it doesn&#8217;t matter:</p>
<pre>Guid gId =
  new Guid(&quot;4fcc0b82-b137-4e4b-935e-872ed662ba53&quot;);
Gizmo g = db.Get&lt;Gizmo&gt;(gId);</pre>
<p>
If you you give the wrong Type of Key, it will tell you in a nice <b>ArgumentException</b>:</p>
<pre>Gizmo g = db.Get&lt;Gizmo&gt;(5);</pre>
<p>
Error:</p>
<p>Primary Key of Table and primaryKey argument are not of the same Type; Primary Key of Table is of Type: System.Guid, primaryKey argument supplied is of Type: System.Int32</p>
<p>Here is the code without any error handling:</p>
<pre>public static T Get&lt;T&gt;(this DataContext dataContext,
  object primaryKey)
    where T : class, INotifyPropertyChanged
{
  return dataContext.GetTable(typeof(T))
    .Cast&lt;T&gt;()
    .Where(GetPrimaryKey&lt;T&gt;()
    .Name + &quot;.Equals(@0)&quot;, primaryKey)
    .FirstOrDefault();
}</pre>
<p>
The full code is available in my <a href="http://naspinski.codeplex.com">Utilities class</a> on CodePlex.<br />
This requires <b>System.Linq.Dynamic</b>.
</div>
<p><iframe src="http://feedads.g.doubleclick.net/~ah/f/kijri0o2kgcv9o6a1kk1fsjgmk/300/250?ca=1&amp;fh=280#http%3A%2F%2Fwww.naspinski.net%2Fpost.aspx%3Fid%3Dd00c13b0-ba53-441c-a55f-cded2c836935" width="100%" height="280" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe></p>
<div>
<a href="http://feeds.feedburner.com/~ff/naspinski?a=TIzmXswn1G0:nMa9CDLa4fs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/naspinski?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=TIzmXswn1G0:nMa9CDLa4fs:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/naspinski?i=TIzmXswn1G0:nMa9CDLa4fs:gIN9vFwOqvQ" border="0"></a> <a href="http://feeds.feedburner.com/~ff/naspinski?a=TIzmXswn1G0:nMa9CDLa4fs:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/naspinski?i=TIzmXswn1G0:nMa9CDLa4fs:F7zBnMyn0Lo" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/naspinski/~4/TIzmXswn1G0" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/10803/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with the MVVM Pattern in Silverlight Applications</title>
		<link>http://zdima.net/blog/archives/10284</link>
		<comments>http://zdima.net/blog/archives/10284#comments</comments>
		<pubDate>Wed, 09 Dec 2009 07:30:06 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[MVVM]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=10284</guid>
		<description><![CDATA[<p></p>  <p>With the increasing popularity of Silverlight as an application development framework the discussion of patterns has grown louder and louder. Fortunately the majority of developers building Silverlight applications have agreed on a pattern that fits well in the Silverlight world called Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced testing capabilities. This post will explain key concepts found in the MVVM pattern and attempt to present them in a way that is easy to understand. I’ll show some code along the way to demonstrate how the MVVM pattern can be used and provide a few alternatives when it comes to binding data. The code shown later in the post can be <a href="http://www.xmlforasp.net/CodeBank/Download/Blog/Silverlight3/ViewModelSample.zip">downloaded here</a>.</p>  <h3>Getting Started with the MVVM Pattern</h3>  <p>The MVVM pattern defines three key parts including the Model, the View and the ViewModel. The following image shows a slide from a Silverlight course <a href="http://www.thewahlingroup.com">we offer</a> that sums up the role of each part of the MVVM pattern in a concise way:    <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image002_5D087867.jpg"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="clip_image002" src="http://weblogs.asp.net/blogs/dwahlin/clip_image002_thumb_62E31C00.jpg" width="374" height="280"></a></p>  <p>   <br />Looking through the description of each part you can see that the Model represents the business domain which includes the model classes used (Customer, Order, etc.), data access code and business rules. In general you can think of the Model as representing the entities that live on the server as well as the objects that are responsible for interacting with the data store your application uses and filling entities with data. While some people feel that the Model represents only the model classes (classes like Customer, Order, etc.) used in the application I personally think of it more broadly and include data access code and business rules in the Model definition. Silverlight applications will call into the Model code through services written using WCF, ASMX, REST or even custom solutions.</p>  <p>The View in MVVM represents the Silverlight screens that you build. This includes the XAML files and the code-beside files that are responsible for showing data to end users. The View's responsibilities include displaying data and collecting data from end users. A given View isn't responsible for retrieving data, performing any business rules or validating data.</p>  <p>The ViewModel acts as the middle-man between the View and the Model. It&#39;s responsible for aggregating and storing data that will be bound to a View. For example, a ViewModel may contain a List&#60;State&#62; property and a List&#60;Person&#62; property that may be bound to two ComboBox controls in a View. The ViewModel will retrieve the values held by these two properties from the Model. By using a ViewModel the View doesn&#39;t have to worry about retrieving data and knows nothing about where data comes from. </p>  <p>Additional players may be added into the Model-View-ViewModel mix to help segregate code even further. For example, I normally create a service agent class that is responsible for making calls from Silverlight to remote services. The service agent is responsible for initiating the service call, capturing the data that's returned and forwarding the data back to the ViewModel. By doing this the ViewModel classes can delegate data gathering responsibilities to the service agent. A given service agent can also be re-used across multiple ViewModel classes as needed. The following image shows how the service agent can be integrated into the MVVM pattern:   <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image004_7A9A5366.jpg"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="clip_image004" src="http://weblogs.asp.net/blogs/dwahlin/clip_image004_thumb_12BDBDC2.jpg" width="393" height="298"></a></p>  <p> </p>  <p>When developers first start building Silverlight applications they typically add all of the code for the application into the XAML's code-beside file (MainPage.xaml.cs for example). Although this approach certainly works, by following the MVVM pattern you can take advantage of several inherent benefits including better code re-use, simplified maintenance, more modular code and enhanced testing support. I'll focus on the overall benefits achieved by building applications that are based on the MVVM pattern throughout the rest of this article.   <br /></p>  <h3>The Model</h3>  <p>There are many different ways that the Model can be created including using Microsoft&#39;s Entity Framework or LINQ to SQL technologies, nHibernate, PLINQO, SubSonic, custom solutions and more. The technology chosen is generally unique to a given company&#39;s development policies so I&#39;m not going to go into a discussion of the pros and cons of each technology here. What&#39;s important is that one or more classes used by a Silverlight application are &#34;modeled&#34; using tools or by writing code by hand. This involves defining all of the properties that each class will expose. A simple example of a Model class is shown next:   <br /></p>  <pre><span style="color:blue">public class </span><span style="color:#2b91af">Person
</span>{
    <span style="color:blue">public string </span>FirstName { <span style="color:blue">get</span>;<span style="color:blue">set</span>;}
    <span style="color:blue">public string </span>LastName { <span style="color:blue">get</span>;<span style="color:blue">set</span>; }
    <span style="color:blue">public int </span>Age { <span style="color:blue">get</span>; <span style="color:blue">set</span>; }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>Once the Model classes are in place they'll need to be populated with data from a data store which can be done by writing custom code or using ORM frameworks that handle mapping query results to object instances. Services will also need to be written to expose one or more of the Model classes used in a Silverlight application which can be done using WCF, ASMX or even custom REST services.
  <br /></p>

<h3>The View and ViewModel Classes</h3>

<p>Once the Model is ready to go the View and ViewModel classes can be created. As mentioned earlier, a View represents a Silverlight screen that end users interact with which includes the XAML file and the associated code-beside file. Rather than adding all of the code to call the Model and retrieve data directly into the View's code-beside file, the View will rely on a ViewModel class to retrieve data and then bind to the properties of the ViewModel.</p>

<p>ViewModel classes should implement an interface that's available in Silverlight called INotifyPropertyChanged which defines a single event named PropertyChanged. This event is used to notify different Silverlight bindings that data has changed for one or more properties so that controls can be updated automatically. Although INotifyPropertyChanged can be implemented directly on a ViewModel class, your application may have multiple ViewModel classes in it and writing the same code over and over tends to get old. Creating a base ViewModel class that handles implementing INotifyPropertyChanged is useful to minimize code and allow more re-use to occur in applications. The following code shows a class named ViewModelBase that implements the INotifyPropertyChanged interface. The class also provides an OnNotifyPropertyChanged method that can be used to raise the PropertyChanged event.
  <br /></p>

<pre><span style="color:blue">public class </span><span style="color:#2b91af">ViewModelBase </span>: <span style="color:#2b91af">INotifyPropertyChanged
</span>{
    <span style="color:blue">protected void </span>OnNotifyPropertyChanged(<span style="color:blue">string </span>p)
    {
        <span style="color:blue">if </span>(PropertyChanged != <span style="color:blue">null</span>)
        {
            PropertyChanged(<span style="color:blue">this</span>, <span style="color:blue">new </span><span style="color:#2b91af">PropertyChangedEventArgs</span>(p));
        }
    }

    <span style="color:blue">public bool </span>IsDesignTime
    {
        <span style="color:blue">get
        </span>{
            <span style="color:blue">return </span>(<span style="color:#2b91af">Application</span>.Current == <span style="color:blue">null</span>) &#124;&#124; (<span style="color:#2b91af">Application</span>.Current.GetType() == <span style="color:blue">typeof</span>(<span style="color:#2b91af">Application</span>));
        }
    }

    <span style="color:blue">#region </span>INotifyPropertyChanged Members

    <span style="color:blue">public event </span><span style="color:#2b91af">PropertyChangedEventHandler </span>PropertyChanged;

    <span style="color:blue">#endregion
</span>}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>A ViewModel class can derive from ViewModelBase and automatically take advantage of the INotifyPropertyChanged interface. An example of a ViewModel class named PeopleViewModel that derives from the ViewModelBase class and defines several properties and methods is shown next:
  <br /></p>

<pre><span style="color:blue">public class </span><span style="color:#2b91af">PeopleViewModel </span>: <span style="color:#2b91af">ViewModelBase
</span>{
    <span style="color:#2b91af">IServiceAgent </span>_ServiceAgent;
    <span style="color:#2b91af">Person </span>_Person;
    <span style="color:#2b91af">ObservableCollection</span>&#60;<span style="color:#2b91af">Person</span>&#62; _People;

    <span style="color:blue">public </span>PeopleViewModel() : <span style="color:blue">this</span>(<span style="color:blue">new </span><span style="color:#2b91af">ServiceAgent</span>()) {}

    <span style="color:blue">public </span>PeopleViewModel(<span style="color:#2b91af">IServiceAgent </span>serviceAgent)
    {
        <span style="color:blue">if </span>(!IsDesignTime)
        {
            _ServiceAgent = serviceAgent;
            GetPeople();
        }
    }

    <span style="color:blue">#region </span>Properties

    <span style="color:blue">public </span><span style="color:#2b91af">Person </span>Person
    {
        <span style="color:blue">get
        </span>{
            <span style="color:blue">return </span>_Person;
        }
        <span style="color:blue">set
        </span>{
            <span style="color:blue">if </span>(_Person != <span style="color:blue">value</span>)
            {
                _Person = <span style="color:blue">value</span>;
                OnNotifyPropertyChanged(<span style="color:#a31515">&#34;Person&#34;</span>);
            }
        }
    }

    <span style="color:blue">public </span><span style="color:#2b91af">ObservableCollection</span>&#60;<span style="color:#2b91af">Person</span>&#62; People {
        <span style="color:blue">get
        </span>{
            <span style="color:blue">return </span>_People;
        }
        <span style="color:blue">set
        </span>{
            <span style="color:blue">if </span>(_People != <span style="color:blue">value</span>)
            {
                _People = <span style="color:blue">value</span>;
                OnNotifyPropertyChanged(<span style="color:#a31515">&#34;People&#34;</span>);
            }
        }

    }

    <span style="color:blue">#endregion        
    
    public void </span>GetPeople()
    {
        _ServiceAgent.GetPeople((s,e) =&#62; <span style="color:blue">this</span>.People = e.Result);
    }

    <span style="color:blue">public void </span>UpdatePerson()
    {
        _ServiceAgent.UpdatePerson(<span style="color:blue">this</span>.Person, (s, e) =&#62;
        {
            <span style="color:#2b91af">PeopleEventBus</span>.OnOperationCompleted(<span style="color:blue">this</span>, <span style="color:blue">new </span><span style="color:#2b91af">OperationCompletedEventArgs </span>{ OperationStatus = e.Result });
        });
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>
  <br />Looking through the code you&#39;ll see that PeopleViewModel defines two fields, two properties and two methods. Each property raises the PropertyChanged event as the set block is called by calling the OnNotifyPropertyChanged method defined in ViewModelBase. This notifies any controls bound to the properties that the values have changed which allows them to update the data they display automatically.  </p>

<p>Looking at the first constructor in PeopleViewModel you'll see that it forwards the call to a secondary constructor that accepts a parameter of type IServiceAgent. Why have two constructors? This approach allows testing frameworks to pass in different types of service agents to the ViewModel when running tests. When the ViewModel is called at runtime the parameterless constructor will be called and an instance of a ServiceAgent class (shown next) will be passed as the IServiceAgent parameter. From there, once the service agent object is passed into the ViewModel's constructor a call to a method named GetPeople is made which invokes a method on the service agent and passes a callback delegate. The WCF service is then called by the service agent and the results are assigned to the People property. </p>

<p> </p>

<pre><span style="color:blue">public interface </span><span style="color:#2b91af">IServiceAgent
</span>{
    <span style="color:blue">void </span>GetPeople(<span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">GetPeopleCompletedEventArgs</span>&#62; callback);
    <span style="color:blue">void </span>UpdatePerson(<span style="color:#2b91af">Person </span>p, <span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">UpdatePersonCompletedEventArgs</span>&#62; callback);
}

<span style="color:blue">public class </span><span style="color:#2b91af">ServiceAgent </span>: <span style="color:#2b91af">IServiceAgent
</span>{
    <span style="color:blue">public void </span>GetPeople(<span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">GetPeopleCompletedEventArgs</span>&#62; callback)
    {
        <span style="color:#2b91af">PeopleServiceClient </span>proxy = <span style="color:blue">new </span><span style="color:#2b91af">PeopleServiceClient</span>();
        proxy.GetPeopleCompleted += callback;
        proxy.GetPeopleAsync();
    }

    <span style="color:blue">public void </span>UpdatePerson(<span style="color:#2b91af">Person </span>p, <span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">UpdatePersonCompletedEventArgs</span>&#62; callback)
    {
        <span style="color:#2b91af">PeopleServiceClient </span>proxy = <span style="color:blue">new </span><span style="color:#2b91af">PeopleServiceClient</span>();
        proxy.UpdatePersonCompleted += callback;
        proxy.UpdatePersonAsync(p);
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<h3><strong>Binding a ViewModel to a View</strong></h3>

<p>Now that the ViewModel class is defined it can be bound to a View. This can be done declaratively in XAML or imperatively through code in the View's code-beside file. Imperative (or code-based) binding is typically accomplished by assigning a ViewModel instance to the layout root's DataContext property as shown next:
  <br /></p>

<p><font face="Courier New">this.LayoutRoot.DataContext = new PeopleViewModel();
    <br /></font></p>

<p>An example of declaratively binding a ViewModel (which is my personal preference) to a View is shown next:
  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">UserControl </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Class</span><span style="color:blue">=&#34;ViewModelExample.MainPage&#34;
    </span><span style="color:red">xmlns</span><span style="color:blue">=&#34;http://schemas.microsoft.com/winfx/2006/xaml/presentation&#34; 
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">x</span><span style="color:blue">=&#34;http://schemas.microsoft.com/winfx/2006/xaml&#34;
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">d</span><span style="color:blue">=&#34;http://schemas.microsoft.com/expression/blend/2008&#34; </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">mc</span><span style="color:blue">=&#34;http://schemas.openxmlformats.org/markup-compatibility/2006&#34; 
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">converter</span><span style="color:blue">=&#34;clr-namespace:ViewModelExample&#34;
    </span><strong><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">viewModel</span></strong><span style="color:blue"><strong>=&#34;clr-namespace:ViewModelExample.ViewModel&#34;</strong>
    </span><span style="color:red">mc</span><span style="color:blue">:</span><span style="color:red">Ignorable</span><span style="color:blue">=&#34;d&#34; </span><span style="color:red">d</span><span style="color:blue">:</span><span style="color:red">DesignWidth</span><span style="color:blue">=&#34;640&#34; </span><span style="color:red">d</span><span style="color:blue">:</span><span style="color:red">DesignHeight</span><span style="color:blue">=&#34;480&#34;&#62;
    &#60;</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;
        <strong>&#60;</strong></span><strong><span style="color:#a31515">viewModel</span><span style="color:blue">:</span><span style="color:#a31515">PeopleViewModel </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Key</span></strong><span style="color:blue"><strong>=&#34;ViewModel&#34; /&#62;</strong>
    &#60;/</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Grid </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Name</span><span style="color:blue">=&#34;LayoutRoot&#34; </span><strong><span style="color:red">DataContext</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Source</span><span style="color:blue">={</span><span style="color:#a31515">StaticResource </span><span style="color:red">ViewModel</span></strong><span style="color:blue"><strong>}}&#34;</strong>&#62;
</span><span style="color:blue">    &#60;/</span><span style="color:#a31515">Grid</span><span style="color:blue">&#62;
&#60;/</span><span style="color:#a31515">UserControl</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>The ViewModel namespace is first referenced using an XML namespace prefix of &#34;viewModel&#34;. The ViewModel is then defined in the UserControl&#39;s Resources section and given a key of &#34;ViewModel&#34; (note that any name can be chosen for the key). The key is important since it&#39;s used to hook the ViewModel to the DataContext of the layout root using the {Binding Source={StaticResource ViewModel}} syntax. The declarative binding will cause a new PeopleViewModel instance to be created at runtime which is then bound to the layout root&#39;s DataContext. Child controls of the layout root can then bind to properties on the ViewModel. An example of binding a ListBox to the ViewModel&#39;s People property and a StackPanel to the Person property is shown next:
  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">StackPanel </span><span style="color:red">Margin</span><span style="color:blue">=&#34;20&#34;&#62;
    &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;Binding Controls to a ViewModel&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;20,0,0,0&#34; </span><span style="color:red">FontWeight</span><span style="color:blue">=&#34;Bold&#34; </span><span style="color:red">FontSize</span><span style="color:blue">=&#34;12&#34; /&#62;
        &#60;</span><span style="color:#a31515">ListBox </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Name</span><span style="color:blue">=&#34;lbPeople&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;0,10,0,0&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;250&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;300&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;
                 </span><strong><span style="color:red">ItemsSource</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">People</span></strong><span style="color:blue"><strong>}&#34;</strong> </span><span style="color:red">ScrollViewer.HorizontalScrollBarVisibility</span><span style="color:blue">=&#34;Hidden&#34;
                 </span><strong><span style="color:red">SelectedItem</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Person</span><span style="color:blue">, </span><span style="color:red">Mode</span></strong><span style="color:blue"><strong>=TwoWay}&#34;</strong>&#62;
            &#60;</span><span style="color:#a31515">ListBox.ItemTemplate</span><span style="color:blue">&#62;
                &#60;</span><span style="color:#a31515">DataTemplate</span><span style="color:blue">&#62;
                    &#60;</span><span style="color:#a31515">Grid</span><span style="color:blue">&#62;
                        &#60;</span><span style="color:#a31515">Grid.ColumnDefinitions</span><span style="color:blue">&#62;
                            &#60;</span><span style="color:#a31515">ColumnDefinition </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; /&#62;
                            &#60;</span><span style="color:#a31515">ColumnDefinition </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; /&#62;
                            &#60;</span><span style="color:#a31515">ColumnDefinition </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; /&#62;
                        &#60;/</span><span style="color:#a31515">Grid.ColumnDefinitions</span><span style="color:blue">&#62;
                        &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Grid.Column</span><span style="color:blue">=&#34;0&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;10&#34; </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">FirstName</span><span style="color:blue">}&#34; /&#62;
                        &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Grid.Column</span><span style="color:blue">=&#34;1&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;10&#34; </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">LastName</span><span style="color:blue">}&#34; /&#62;
                        &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Grid.Column</span><span style="color:blue">=&#34;2&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;10&#34; </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Age</span><span style="color:blue">}&#34; /&#62;
                    &#60;/</span><span style="color:#a31515">Grid</span><span style="color:blue">&#62;
                &#60;/</span><span style="color:#a31515">DataTemplate</span><span style="color:blue">&#62;
            &#60;/</span><span style="color:#a31515">ListBox.ItemTemplate</span><span style="color:blue">&#62;
        &#60;/</span><span style="color:#a31515">ListBox</span><span style="color:blue">&#62;
        &#60;</span><span style="color:#a31515">StackPanel </span><strong><span style="color:red">DataContext</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Person</span></strong><span style="color:blue"><strong>}&#34;</strong>&#62;
            &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;First Name&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;0,10,0,0&#34; /&#62;
            &#60;</span><span style="color:#a31515">TextBox </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">FirstName</span><span style="color:blue">,</span><span style="color:red">Mode</span><span style="color:blue">=TwoWay}&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;25&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;/&#62;
            &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;Last Name&#34; /&#62;
            &#60;</span><span style="color:#a31515">TextBox </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">LastName</span><span style="color:blue">,</span><span style="color:red">Mode</span><span style="color:blue">=TwoWay}&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;25&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;/&#62;
            &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;Age&#34; /&#62;
            &#60;</span><span style="color:#a31515">TextBox </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Age</span><span style="color:blue">,</span><span style="color:red">Mode</span><span style="color:blue">=TwoWay}&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;25&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;/&#62;
        &#60;/</span><span style="color:#a31515">StackPanel</span><span style="color:blue">&#62;
        &#60;</span><span style="color:#a31515">Button </span><span style="color:red">Margin</span><span style="color:blue">=&#34;0,10,0,0&#34; </span><span style="color:red">Click</span><span style="color:blue">=&#34;Button_Click&#34; </span><span style="color:red">Content</span><span style="color:blue">=&#34;Submit&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;20&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34; /&#62;
&#60;/</span><span style="color:#a31515">StackPanel</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>The MVVM pattern provides a flexible way to work with data that encourages code re-use and simplifies maintenance. There's much more that can be discussed with regard to the MVVM pattern in Silverlight such as event buses, commanding and dependency injection but I hope this post helps jumpstart the process of architecting and developing Silverlight applications. If you have specific Silverlight development concepts you'd like to see covered in future posts tweet me at <a href="http://www.twitter.com/danwahlin">@DanWahlin</a> or add a comment below.</p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7274398" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/10284">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[</p>
<p>With the increasing popularity of Silverlight as an application development framework the discussion of patterns has grown louder and louder. Fortunately the majority of developers building Silverlight applications have agreed on a pattern that fits well in the Silverlight world called Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced testing capabilities. This post will explain key concepts found in the MVVM pattern and attempt to present them in a way that is easy to understand. I’ll show some code along the way to demonstrate how the MVVM pattern can be used and provide a few alternatives when it comes to binding data. The code shown later in the post can be <a href="http://www.xmlforasp.net/CodeBank/Download/Blog/Silverlight3/ViewModelSample.zip">downloaded here</a>.</p>
<h3>Getting Started with the MVVM Pattern</h3>
<p>The MVVM pattern defines three key parts including the Model, the View and the ViewModel. The following image shows a slide from a Silverlight course <a href="http://www.thewahlingroup.com">we offer</a> that sums up the role of each part of the MVVM pattern in a concise way:    </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image002_5D087867.jpg"><img  title="clip_image002" border="0" alt="clip_image002" src="http://weblogs.asp.net/blogs/dwahlin/clip_image002_thumb_62E31C00.jpg" width="374" height="280"></a></p>
<p>Looking through the description of each part you can see that the Model represents the business domain which includes the model classes used (Customer, Order, etc.), data access code and business rules. In general you can think of the Model as representing the entities that live on the server as well as the objects that are responsible for interacting with the data store your application uses and filling entities with data. While some people feel that the Model represents only the model classes (classes like Customer, Order, etc.) used in the application I personally think of it more broadly and include data access code and business rules in the Model definition. Silverlight applications will call into the Model code through services written using WCF, ASMX, REST or even custom solutions.</p>
<p>The View in MVVM represents the Silverlight screens that you build. This includes the XAML files and the code-beside files that are responsible for showing data to end users. The View&#8217;s responsibilities include displaying data and collecting data from end users. A given View isn&#8217;t responsible for retrieving data, performing any business rules or validating data.</p>
<p>The ViewModel acts as the middle-man between the View and the Model. It&#39;s responsible for aggregating and storing data that will be bound to a View. For example, a ViewModel may contain a List&lt;State&gt; property and a List&lt;Person&gt; property that may be bound to two ComboBox controls in a View. The ViewModel will retrieve the values held by these two properties from the Model. By using a ViewModel the View doesn&#39;t have to worry about retrieving data and knows nothing about where data comes from. </p>
<p>Additional players may be added into the Model-View-ViewModel mix to help segregate code even further. For example, I normally create a service agent class that is responsible for making calls from Silverlight to remote services. The service agent is responsible for initiating the service call, capturing the data that&#8217;s returned and forwarding the data back to the ViewModel. By doing this the ViewModel classes can delegate data gathering responsibilities to the service agent. A given service agent can also be re-used across multiple ViewModel classes as needed. The following image shows how the service agent can be integrated into the MVVM pattern:   </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image004_7A9A5366.jpg"><img  title="clip_image004" border="0" alt="clip_image004" src="http://weblogs.asp.net/blogs/dwahlin/clip_image004_thumb_12BDBDC2.jpg" width="393" height="298"></a></p>
<p> </p>
<p>When developers first start building Silverlight applications they typically add all of the code for the application into the XAML&#8217;s code-beside file (MainPage.xaml.cs for example). Although this approach certainly works, by following the MVVM pattern you can take advantage of several inherent benefits including better code re-use, simplified maintenance, more modular code and enhanced testing support. I&#8217;ll focus on the overall benefits achieved by building applications that are based on the MVVM pattern throughout the rest of this article.   </p>
<h3>The Model</h3>
<p>There are many different ways that the Model can be created including using Microsoft&#39;s Entity Framework or LINQ to SQL technologies, nHibernate, PLINQO, SubSonic, custom solutions and more. The technology chosen is generally unique to a given company&#39;s development policies so I&#39;m not going to go into a discussion of the pros and cons of each technology here. What&#39;s important is that one or more classes used by a Silverlight application are &quot;modeled&quot; using tools or by writing code by hand. This involves defining all of the properties that each class will expose. A simple example of a Model class is shown next:   </p>
<pre><span >public class </span><span >Person
</span>{
    <span >public string </span>FirstName { <span >get</span>;<span >set</span>;}
    <span >public string </span>LastName { <span >get</span>;<span >set</span>; }
    <span >public int </span>Age { <span >get</span>; <span >set</span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>Once the Model classes are in place they&#8217;ll need to be populated with data from a data store which can be done by writing custom code or using ORM frameworks that handle mapping query results to object instances. Services will also need to be written to expose one or more of the Model classes used in a Silverlight application which can be done using WCF, ASMX or even custom REST services.<br />
  </p>
<h3>The View and ViewModel Classes</h3>
<p>Once the Model is ready to go the View and ViewModel classes can be created. As mentioned earlier, a View represents a Silverlight screen that end users interact with which includes the XAML file and the associated code-beside file. Rather than adding all of the code to call the Model and retrieve data directly into the View&#8217;s code-beside file, the View will rely on a ViewModel class to retrieve data and then bind to the properties of the ViewModel.</p>
<p>ViewModel classes should implement an interface that&#8217;s available in Silverlight called INotifyPropertyChanged which defines a single event named PropertyChanged. This event is used to notify different Silverlight bindings that data has changed for one or more properties so that controls can be updated automatically. Although INotifyPropertyChanged can be implemented directly on a ViewModel class, your application may have multiple ViewModel classes in it and writing the same code over and over tends to get old. Creating a base ViewModel class that handles implementing INotifyPropertyChanged is useful to minimize code and allow more re-use to occur in applications. The following code shows a class named ViewModelBase that implements the INotifyPropertyChanged interface. The class also provides an OnNotifyPropertyChanged method that can be used to raise the PropertyChanged event.<br />
  </p>
<pre><span >public class </span><span >ViewModelBase </span>: <span >INotifyPropertyChanged
</span>{
    <span >protected void </span>OnNotifyPropertyChanged(<span >string </span>p)
    {
        <span >if </span>(PropertyChanged != <span >null</span>)
        {
            PropertyChanged(<span >this</span>, <span >new </span><span >PropertyChangedEventArgs</span>(p));
        }
    }

    <span >public bool </span>IsDesignTime
    {
        <span >get
        </span>{
            <span >return </span>(<span >Application</span>.Current == <span >null</span>) || (<span >Application</span>.Current.GetType() == <span >typeof</span>(<span >Application</span>));
        }
    }

    <span >#region </span>INotifyPropertyChanged Members

    <span >public event </span><span >PropertyChangedEventHandler </span>PropertyChanged;

    <span >#endregion
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>A ViewModel class can derive from ViewModelBase and automatically take advantage of the INotifyPropertyChanged interface. An example of a ViewModel class named PeopleViewModel that derives from the ViewModelBase class and defines several properties and methods is shown next:<br />
  </p>
<pre><span >public class </span><span >PeopleViewModel </span>: <span >ViewModelBase
</span>{
    <span >IServiceAgent </span>_ServiceAgent;
    <span >Person </span>_Person;
    <span >ObservableCollection</span>&lt;<span >Person</span>&gt; _People;

    <span >public </span>PeopleViewModel() : <span >this</span>(<span >new </span><span >ServiceAgent</span>()) {}

    <span >public </span>PeopleViewModel(<span >IServiceAgent </span>serviceAgent)
    {
        <span >if </span>(!IsDesignTime)
        {
            _ServiceAgent = serviceAgent;
            GetPeople();
        }
    }

    <span >#region </span>Properties

    <span >public </span><span >Person </span>Person
    {
        <span >get
        </span>{
            <span >return </span>_Person;
        }
        <span >set
        </span>{
            <span >if </span>(_Person != <span >value</span>)
            {
                _Person = <span >value</span>;
                OnNotifyPropertyChanged(<span >&quot;Person&quot;</span>);
            }
        }
    }

    <span >public </span><span >ObservableCollection</span>&lt;<span >Person</span>&gt; People {
        <span >get
        </span>{
            <span >return </span>_People;
        }
        <span >set
        </span>{
            <span >if </span>(_People != <span >value</span>)
            {
                _People = <span >value</span>;
                OnNotifyPropertyChanged(<span >&quot;People&quot;</span>);
            }
        }

    }

    <span >#endregion        

    public void </span>GetPeople()
    {
        _ServiceAgent.GetPeople((s,e) =&gt; <span >this</span>.People = e.Result);
    }

    <span >public void </span>UpdatePerson()
    {
        _ServiceAgent.UpdatePerson(<span >this</span>.Person, (s, e) =&gt;
        {
            <span >PeopleEventBus</span>.OnOperationCompleted(<span >this</span>, <span >new </span><span >OperationCompletedEventArgs </span>{ OperationStatus = e.Result });
        });
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />Looking through the code you&#39;ll see that PeopleViewModel defines two fields, two properties and two methods. Each property raises the PropertyChanged event as the set block is called by calling the OnNotifyPropertyChanged method defined in ViewModelBase. This notifies any controls bound to the properties that the values have changed which allows them to update the data they display automatically.  </p>
<p>Looking at the first constructor in PeopleViewModel you&#8217;ll see that it forwards the call to a secondary constructor that accepts a parameter of type IServiceAgent. Why have two constructors? This approach allows testing frameworks to pass in different types of service agents to the ViewModel when running tests. When the ViewModel is called at runtime the parameterless constructor will be called and an instance of a ServiceAgent class (shown next) will be passed as the IServiceAgent parameter. From there, once the service agent object is passed into the ViewModel&#8217;s constructor a call to a method named GetPeople is made which invokes a method on the service agent and passes a callback delegate. The WCF service is then called by the service agent and the results are assigned to the People property. </p>
<p> </p>
<pre><span >public interface </span><span >IServiceAgent
</span>{
    <span >void </span>GetPeople(<span >EventHandler</span>&lt;<span >GetPeopleCompletedEventArgs</span>&gt; callback);
    <span >void </span>UpdatePerson(<span >Person </span>p, <span >EventHandler</span>&lt;<span >UpdatePersonCompletedEventArgs</span>&gt; callback);
}

<span >public class </span><span >ServiceAgent </span>: <span >IServiceAgent
</span>{
    <span >public void </span>GetPeople(<span >EventHandler</span>&lt;<span >GetPeopleCompletedEventArgs</span>&gt; callback)
    {
        <span >PeopleServiceClient </span>proxy = <span >new </span><span >PeopleServiceClient</span>();
        proxy.GetPeopleCompleted += callback;
        proxy.GetPeopleAsync();
    }

    <span >public void </span>UpdatePerson(<span >Person </span>p, <span >EventHandler</span>&lt;<span >UpdatePersonCompletedEventArgs</span>&gt; callback)
    {
        <span >PeopleServiceClient </span>proxy = <span >new </span><span >PeopleServiceClient</span>();
        proxy.UpdatePersonCompleted += callback;
        proxy.UpdatePersonAsync(p);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<h3><strong>Binding a ViewModel to a View</strong></h3>
<p>Now that the ViewModel class is defined it can be bound to a View. This can be done declaratively in XAML or imperatively through code in the View&#8217;s code-beside file. Imperative (or code-based) binding is typically accomplished by assigning a ViewModel instance to the layout root&#8217;s DataContext property as shown next:<br />
  </p>
<p><font face="Courier New">this.LayoutRoot.DataContext = new PeopleViewModel();<br />
    <br /></font></p>
<p>An example of declaratively binding a ViewModel (which is my personal preference) to a View is shown next:<br />
  </p>
<pre><span >&lt;</span><span >UserControl </span><span >x</span><span >:</span><span >Class</span><span >=&quot;ViewModelExample.MainPage&quot;
    </span><span >xmlns</span><span >=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    </span><span >xmlns</span><span >:</span><span >x</span><span >=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    </span><span >xmlns</span><span >:</span><span >d</span><span >=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; </span><span >xmlns</span><span >:</span><span >mc</span><span >=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    </span><span >xmlns</span><span >:</span><span >converter</span><span >=&quot;clr-namespace:ViewModelExample&quot;
    </span><strong><span >xmlns</span><span >:</span><span >viewModel</span></strong><span ><strong>=&quot;clr-namespace:ViewModelExample.ViewModel&quot;</strong>
    </span><span >mc</span><span >:</span><span >Ignorable</span><span >=&quot;d&quot; </span><span >d</span><span >:</span><span >DesignWidth</span><span >=&quot;640&quot; </span><span >d</span><span >:</span><span >DesignHeight</span><span >=&quot;480&quot;&gt;
    &lt;</span><span >UserControl.Resources</span><span >&gt;
        <strong>&lt;</strong></span><strong><span >viewModel</span><span >:</span><span >PeopleViewModel </span><span >x</span><span >:</span><span >Key</span></strong><span ><strong>=&quot;ViewModel&quot; /&gt;</strong>
    &lt;/</span><span >UserControl.Resources</span><span >&gt;
    &lt;</span><span >Grid </span><span >x</span><span >:</span><span >Name</span><span >=&quot;LayoutRoot&quot; </span><strong><span >DataContext</span><span >=&quot;{</span><span >Binding </span><span >Source</span><span >={</span><span >StaticResource </span><span >ViewModel</span></strong><span ><strong>}}&quot;</strong>&gt;
</span><span >    &lt;/</span><span >Grid</span><span >&gt;
&lt;/</span><span >UserControl</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>The ViewModel namespace is first referenced using an XML namespace prefix of &quot;viewModel&quot;. The ViewModel is then defined in the UserControl&#39;s Resources section and given a key of &quot;ViewModel&quot; (note that any name can be chosen for the key). The key is important since it&#39;s used to hook the ViewModel to the DataContext of the layout root using the {Binding Source={StaticResource ViewModel}} syntax. The declarative binding will cause a new PeopleViewModel instance to be created at runtime which is then bound to the layout root&#39;s DataContext. Child controls of the layout root can then bind to properties on the ViewModel. An example of binding a ListBox to the ViewModel&#39;s People property and a StackPanel to the Person property is shown next:<br />
  </p>
<pre><span >&lt;</span><span >StackPanel </span><span >Margin</span><span >=&quot;20&quot;&gt;
    &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;Binding Controls to a ViewModel&quot; </span><span >Margin</span><span >=&quot;20,0,0,0&quot; </span><span >FontWeight</span><span >=&quot;Bold&quot; </span><span >FontSize</span><span >=&quot;12&quot; /&gt;
        &lt;</span><span >ListBox </span><span >x</span><span >:</span><span >Name</span><span >=&quot;lbPeople&quot; </span><span >Margin</span><span >=&quot;0,10,0,0&quot; </span><span >Height</span><span >=&quot;250&quot; </span><span >Width</span><span >=&quot;300&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;
                 </span><strong><span >ItemsSource</span><span >=&quot;{</span><span >Binding </span><span >People</span></strong><span ><strong>}&quot;</strong> </span><span >ScrollViewer.HorizontalScrollBarVisibility</span><span >=&quot;Hidden&quot;
                 </span><strong><span >SelectedItem</span><span >=&quot;{</span><span >Binding </span><span >Person</span><span >, </span><span >Mode</span></strong><span ><strong>=TwoWay}&quot;</strong>&gt;
            &lt;</span><span >ListBox.ItemTemplate</span><span >&gt;
                &lt;</span><span >DataTemplate</span><span >&gt;
                    &lt;</span><span >Grid</span><span >&gt;
                        &lt;</span><span >Grid.ColumnDefinitions</span><span >&gt;
                            &lt;</span><span >ColumnDefinition </span><span >Width</span><span >=&quot;100&quot; /&gt;
                            &lt;</span><span >ColumnDefinition </span><span >Width</span><span >=&quot;100&quot; /&gt;
                            &lt;</span><span >ColumnDefinition </span><span >Width</span><span >=&quot;100&quot; /&gt;
                        &lt;/</span><span >Grid.ColumnDefinitions</span><span >&gt;
                        &lt;</span><span >TextBlock </span><span >Grid.Column</span><span >=&quot;0&quot; </span><span >Margin</span><span >=&quot;10&quot; </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >FirstName</span><span >}&quot; /&gt;
                        &lt;</span><span >TextBlock </span><span >Grid.Column</span><span >=&quot;1&quot; </span><span >Margin</span><span >=&quot;10&quot; </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >LastName</span><span >}&quot; /&gt;
                        &lt;</span><span >TextBlock </span><span >Grid.Column</span><span >=&quot;2&quot; </span><span >Margin</span><span >=&quot;10&quot; </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >Age</span><span >}&quot; /&gt;
                    &lt;/</span><span >Grid</span><span >&gt;
                &lt;/</span><span >DataTemplate</span><span >&gt;
            &lt;/</span><span >ListBox.ItemTemplate</span><span >&gt;
        &lt;/</span><span >ListBox</span><span >&gt;
        &lt;</span><span >StackPanel </span><strong><span >DataContext</span><span >=&quot;{</span><span >Binding </span><span >Person</span></strong><span ><strong>}&quot;</strong>&gt;
            &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;First Name&quot; </span><span >Margin</span><span >=&quot;0,10,0,0&quot; /&gt;
            &lt;</span><span >TextBox </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >FirstName</span><span >,</span><span >Mode</span><span >=TwoWay}&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >Height</span><span >=&quot;25&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;/&gt;
            &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;Last Name&quot; /&gt;
            &lt;</span><span >TextBox </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >LastName</span><span >,</span><span >Mode</span><span >=TwoWay}&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >Height</span><span >=&quot;25&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;/&gt;
            &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;Age&quot; /&gt;
            &lt;</span><span >TextBox </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >Age</span><span >,</span><span >Mode</span><span >=TwoWay}&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >Height</span><span >=&quot;25&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;/&gt;
        &lt;/</span><span >StackPanel</span><span >&gt;
        &lt;</span><span >Button </span><span >Margin</span><span >=&quot;0,10,0,0&quot; </span><span >Click</span><span >=&quot;Button_Click&quot; </span><span >Content</span><span >=&quot;Submit&quot; </span><span >Height</span><span >=&quot;20&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot; /&gt;
&lt;/</span><span >StackPanel</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>The MVVM pattern provides a flexible way to work with data that encourages code re-use and simplifies maintenance. There&#8217;s much more that can be discussed with regard to the MVVM pattern in Silverlight such as event buses, commanding and dependency injection but I hope this post helps jumpstart the process of architecting and developing Silverlight applications. If you have specific Silverlight development concepts you&#8217;d like to see covered in future posts tweet me at <a href="http://www.twitter.com/danwahlin">@DanWahlin</a> or add a comment below.</p>
<p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7274398" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/10284/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

