<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3884961837046000063</id><updated>2022-12-08T12:53:18.229-08:00</updated><category term="C#"/><category term=".NET"/><category term="WPF"/><category term="Visual Studio 2010"/><category term="Azure"/><category term="MESH"/><category term="Speaking"/><category term="Standards"/><category term="Windows 7"/><category term=".NET 4.0"/><category term="LINQ"/><category term="PDC"/><category term="Patterns"/><category term="SQL"/><category term="Silverlight"/><category term="Unit Test"/><title type='text'>Notes in Modern Programming</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.joeseymour.net/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>23</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-4591668318847606892</id><published>2010-02-16T08:55:00.000-08:00</published><updated>2010-02-16T08:56:29.525-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Standards"/><title type='text'>Sending messages in your application</title><content type='html'>I got a question from a friend the other day that went something like this:&lt;br /&gt;&lt;blockquote&gt;I have an application that has n modules, and I need to communicate between them.&amp;nbsp; I have been using some messaging stuff for a while now, and as my application has gotten more complicated, it has become messy.&amp;nbsp; How are you doing this?&lt;/blockquote&gt;&lt;br /&gt;Communication between modules in any application is always tricky, and can always get messy.&amp;nbsp; Think of it this way.&amp;nbsp; What if I wanted to send a text message to somebody.&amp;nbsp; Only, instead of sending it to somebody, I had to hope the right person / people were expecting my message, and would act appropriately.&amp;nbsp; And, conversely, i would also hope people who were not supposed to be listening were not, and didn’t do anything when I sent the message.&amp;nbsp; See Twitter and it’s incredible reliability.&lt;br /&gt;&lt;br /&gt;So how do you solve this problem?&amp;nbsp; Well, the quickest way is to download a messaging framework like &lt;a href=&quot;http://courier.codeplex.com/&quot;&gt;Courier&lt;/a&gt; (thanks &lt;a href=&quot;http://www.bradcunningham.net/&quot;&gt;Brad&lt;/a&gt;!).&amp;nbsp; Now you can send messages where ever you want!&amp;nbsp; Although I am not a fan of the messaging idea, I really like everything in my application to be as defined as possible.&amp;nbsp; I have never really felt comfortable sending a message “SelectedItem” with the item selected attached to it as an object.&amp;nbsp; I just don’t like it when I have to count on my subscriber to convert my object to the right thing (boxing and unboxing concerns aside).&lt;br /&gt;&lt;br /&gt;My preferred way to solve this problem is to created an object who&#39;s sole responsibility is to keep track of the selected item.&amp;nbsp; Then, using my favorite dependency injection framework, I would register the ItemSelector and anything that needed a reference to my item selection object could get at it.&amp;nbsp; Here’s what the interface would look like:&lt;br /&gt;&lt;script class=&quot;brush: csharp&quot; type=&quot;syntaxhighlighter&quot;&gt;public interface IItemSelector { event EventHandler ItemSelectionChanged;  void SelectItem(int item);  public int SelectedItem { get; } } &lt;/script&gt;&lt;br /&gt;This defines all the pieces we need for the selection, now for the implementation of the interface:&lt;br /&gt;&lt;script class=&quot;brush: csharp&quot; type=&quot;syntaxhighlighter&quot;&gt;public class ItemSelector : IItemSelector { int _selectedItem;  public int SelectedItem { get { return _selectedItem; } private set { if (_selectedItem != value) { _selectedItem = value; OnItemSelectionChanged(); } } }  public event EventHandler ItemSelectionChanged; void OnItemSelectionChanged() { if (ItemSelectionChanged != null) { ItemSelectionChanged(this, EventArgs.Empty); } }  public void SelectItem(int item) { SelectedItem = item; } } &lt;/script&gt;&lt;br /&gt;Now, any part of my code that might need to know about selection change, just needs to have a reference to the instance of ItemSelector (or, if you are using dependency injection, would just need to be injected with the IItemSelector interface).&amp;nbsp; Of course, the standard cautions apply to subscribing and then UNSUBSCRIBING from events.&amp;nbsp; But this should work fine, and can be expanded to fit the needs of your complexity.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/4591668318847606892/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2010/02/communicating-in-your-application.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4591668318847606892'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4591668318847606892'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2010/02/communicating-in-your-application.html' title='Sending messages in your application'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-8885468095223668043</id><published>2009-11-18T13:16:00.000-08:00</published><updated>2009-11-18T13:16:34.409-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="PDC"/><title type='text'>PDC, Day 1</title><content type='html'>&lt;h3&gt;Keynote&lt;/h3&gt;&lt;p&gt;In the keynote, there was a ton of talk about Windows Azure, which wasn’t really very new from last year.&amp;#160; Microsoft is going live with Azure starting at the beginning of this year, followed by the start of billing in February.&amp;#160; Again, not really new stuff, but I think everything will eventually end up in the cloud.&amp;#160; If Microsoft can continue to separate the implementation of this so I don’t have to think about which platform to target as a developer, it’s going to be a nice win.&lt;/p&gt;&lt;h3&gt;Sessions&lt;/h3&gt;&lt;h4&gt;&lt;a href=&quot;http://microsoftpdc.com/Sessions/FT11&quot;&gt;Future Directions of C# and Visual Basic&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;First, Luca is a great guy to listen to talk.&amp;#160; I heard him once before talking about F# at a code camp and he is a fun guy to listen to.&amp;#160; Good stuff here about languages.&amp;#160; Really enjoyed the talk about dynamic stuff.&amp;#160; I have to admit I have been a bit of a pessimist about the general use of var, and dynamic only took that further.&amp;#160; This really helped me understand how the dynamic type works, was well as how the compiler treats the dynamic type.&amp;#160; Good stuff also about how the DLR caches the use of run time binding.&amp;#160; Also, Microsoft is toying with the notion of not only writing the compiler in their native languages, but opening up the compilers for use by you and me!&lt;/p&gt;&lt;h4&gt;&lt;a href=&quot;http://microsoftpdc.com/Sessions/SVC52&quot;&gt;SQL Azure Database: Present and Future&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;One word to describe this: overwhelming.&amp;#160; The SQL Azure team has done a great job of abstracting the implementation of this service.&amp;#160; There is still some stuff left to be desired, but this is getting really nice.&amp;#160; Lots of talking about low level implementations and how the SQL Azure encrypts and blocks out hacks.&amp;#160; Kind of confusing and this pretty much fried my brain.&lt;/p&gt;&lt;h4&gt;&lt;a href=&quot;http://microsoftpdc.com/Sessions/CL23&quot;&gt;Sketchflow: Prototyping to the rescue&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;I am now a huge fan of SketchFlow.&amp;#160; Great tool.&amp;#160; If you are prototyping anything XAMLy, this is for you.&amp;#160; Great new font that purposefully dumbs down the look of the application so users can focus on functionality, not why the button font isn’t Arial Bold with a Green to Blue radial gradient.&amp;#160; Check out this session.&amp;#160; Definitely my surprise favorite session of the day. &lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/8885468095223668043/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/11/pdc-day-1.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/8885468095223668043'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/8885468095223668043'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/11/pdc-day-1.html' title='PDC, Day 1'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-145837185678509909</id><published>2009-11-04T14:15:00.000-08:00</published><updated>2009-11-04T14:24:55.356-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Unit Test"/><title type='text'>Unit Tests and the PrivateObject, Part 1</title><content type='html'>&lt;p&gt;As a developer, it’s hard to stick to writing unit tests.&amp;#160; It’s really awesome if you do test driven development and write them first, but a lot of the times I find it hard to sick to this plan for various reasons.&amp;#160; No, it’s not cause I don’t want to….sort of.&lt;/p&gt;&lt;p&gt;One of the really cool things about the unit test framework built into visual studio, is the ability to create a unit test that will test even your private methods.&amp;#160; You can do this by right clicking in the .cs and selecting the “Create Private Accessor” option, which will then offer you the list of test projects to generate this class in.&amp;#160; Here is the menu:&lt;/p&gt;&lt;p&gt;&amp;#160; &lt;a href=&quot;http://lh3.ggpht.com/_GoKl4mvOMtw/SvH8wda0NEI/AAAAAAAAEG8/_BzsO-hXQII/s1600-h/image%5B13%5D.png&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px&quot; title=&quot;image&quot; border=&quot;0&quot; alt=&quot;image&quot; src=&quot;http://lh4.ggpht.com/_GoKl4mvOMtw/SvH8xvBoTYI/AAAAAAAAEHA/7zHvIsVJLc4/image_thumb%5B7%5D.png?imgmax=800&quot; width=&quot;194&quot; height=&quot;369&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;You can read more about doing this &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms184796(VS.80).aspx&quot;&gt;here&lt;/a&gt;.&amp;#160; Now, we should be able create an instance of you new accessor in the unit test by instantiating MyObject_Accessor.&amp;#160; In the instance of the object, you should now have access to all of the fields and methods of the original object that are not public.&amp;#160; Sweet.&lt;/p&gt;&lt;p&gt;Hanging off of this accessor object, you will see a property called &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject_members(VS.80).aspx&quot;&gt;Target&lt;/a&gt;, of type Object.&amp;#160; This holds something called a &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject(VS.80).aspx&quot;&gt;PrivateObject&lt;/a&gt;, which should be a wrapper around your original object, MyObject.&amp;#160; I have been doing a ton of Dependency Injection in my projects lately using Unity to decouple my projects from eachother.&amp;#160; Using the PrivateObject is critical to creating a mock version of my dependency injector for the purposes of unit testing.&lt;/p&gt;&lt;p&gt;In a follow up to this, I will post some code showing how to create a mock injector, and how to make use of the PrivateObject in that injector.&amp;#160; Now go test!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/145837185678509909/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/11/unit-tests-and-privateobject-part-1.html#comment-form' title='10 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/145837185678509909'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/145837185678509909'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/11/unit-tests-and-privateobject-part-1.html' title='Unit Tests and the PrivateObject, Part 1'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/_GoKl4mvOMtw/SvH8xvBoTYI/AAAAAAAAEHA/7zHvIsVJLc4/s72-c/image_thumb%5B7%5D.png?imgmax=800" height="72" width="72"/><thr:total>10</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-8321704206162748550</id><published>2009-10-21T16:59:00.000-07:00</published><updated>2010-01-09T14:35:42.885-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Dynamic DataTemplates in WPF</title><content type='html'>&lt;p&gt;A while back, I had to do some tricky stuff with WPF. The WPF application need to have a new data type deployed to it on the fly, and then have a set of dynamic data templates deployed to the same application for that new data type. The first pass I made to accomplish this was to make myself an attached property and markup extension to funnel information into a singleton object I would use to manage all of the dynamic styles. Let me expand a little more on my design choice before going into the details.&lt;/p&gt;&lt;p&gt;First, I wanted to have something be in charge of managing all of my data templates. This needed to be the keeper of everything that is styles. This class should be in charge of registration of styles, as well as handing these styles out when they are asked for. Second, I would need to come up with some way of uniquely identifying these data templates, or create a key if you will. After all, we can&#39;t have duplicate templates for whatever reason. Lastly, I need some way to give all of this information to WPF so I could leverage it in my XAML. My markup would need to be able to bind to this information so it can be resolved during runtime.&lt;/p&gt;&lt;p&gt;So, like I was saying, my first pass involved using a markup extension in some XAML resource dictionary that would be dynamically merged into the main resource dictionary. This was mostly working fine, but I had this syntax that was bothering me quite a bit. What I essentially had was a attached property referencing my custom markup extension. The thing that got annoying was WPF was requiring me to fill in x:Key for the DataTemplate anyway, even though I wasn&#39;t using it. What was happening was my x:Key value was turning out to be the textual representation of my custom markup value. That was dumb to me because I was passing the same information twice. I tried putting my markup extension into the x:Key value, but WPF kept barfing at me when I did this. I stumbled onto &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.windows.datatemplatekey.aspx&quot;&gt;this&lt;/a&gt; gem, which should have been much easier to find.&amp;#160; My very own custom DataTemplateKey!!&lt;/p&gt;&lt;p&gt;Lets start with the new key object I created to be my unique value for each DataTemplate:&lt;/p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;&gt;public struct DynamicTemplateKey { #region Fields string _instanceType; string _name; #endregion  #region Properites public string InstanceType { get { return _instanceType; } } public string Name { get { return _name; } } #endregion  #region Construction public DynamicTemplateKey(string instanceType, string name) { _instanceType = instanceType; _name = name; } #endregion  #region System.Object public override bool Equals(object obj) { ... } bool Equals(DynamicTemplateKey key) { ... } bool Equals(string instanceType, string name) { ... } public override int GetHashCode() { ... } #endregion }&lt;/script&gt;&lt;br /&gt;&lt;p&gt;A quick summary about this.&amp;#160; I have a name value that is a string and a instanceType value that is also a string.&amp;#160; This should sound very familiar to you if you have used WPF.&amp;#160; I have made sure to override the standard System.Object overrides for equality.&amp;#160; Next, our markup extension:&lt;/p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;&gt;[MarkupExtensionReturnType(typeof(DynamicTemplateKey))] public class DynamicTemplateResource : DataTemplateKey { #region Fields string _instanceType = string.Empty; string _name = string.Empty; #endregion  #region Properties public string InstanceType { ... } public string Name { ... } #endregion  #region Overrides public override object ProvideValue(IServiceProvider serviceProvider) { DynamicTemplateKey key = new DynamicTemplateKey(InstanceType, Name);              DynamicTemplateManager.Instance.Add(key);  return key; } #endregion }&lt;/script&gt;&lt;br /&gt;&lt;p&gt;Notice the base class of DataTemplateKey.&amp;#160; This allows us to place our markup in the x:Key field of the XAML.&amp;#160; The XAML markup will map to our key now, so we have the same fields here as strings, name and instanceType.&amp;#160; The really important part here is the override of ProvideValue that will get called when the XAML if parsed.&amp;#160; We are going to use our new key class to create a key.&amp;#160; Then, we pass the key to the DynamicTemplateManager.&amp;#160; Here is the code listing for that class:&lt;/p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;&gt;public class DynamicTemplateManager : DependencyObject { #region Singleton ... #endregion  #region Dictionaries Dictionary&amp;lt;string, Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt;&amp;gt; _typedNamedTemplates = new Dictionary&amp;lt;string, Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt;&amp;gt;(); Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt; _typedTemplates = new Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt;(); Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt; _namedTemplates = new Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt;(); #endregion  #region Indexers public DataTemplate this[DynamicTemplateKey key] { get { ... } } public DataTemplate this[string instanceType, string name] { get { ... } } #endregion  #region Methods public List&amp;lt;DynamicTemplateKey&amp;gt; this[string instanceType] { ... } public IEnumerable&amp;lt;string&amp;gt; UntypedStyleNames { ... } public void Add(DynamicTemplateKey style) { if (string.IsNullOrEmpty(style.Name)) { if (_typedTemplates.ContainsKey(style.InstanceType)) { throw new ApplicationException(string.Format(&amp;quot;Duplicate Dynamic Template Instance Type found, {0}&amp;quot;, style.InstanceType)); } _typedTemplates[style.InstanceType] = style; } else if (string.IsNullOrEmpty(style.InstanceType)) { if (_namedTemplates.ContainsKey(style.Name)) { throw new ApplicationException(string.Format(&amp;quot;Duplicate Dynamic Template Name found, {0}&amp;quot;, style.Name)); } _namedTemplates[style.Name] = style; } else { Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt; templates = new Dictionary&amp;lt;string, DynamicTemplateKey&amp;gt;(); if (_typedNamedTemplates.ContainsKey(style.InstanceType)) { templates = _typedNamedTemplates[style.InstanceType]; }  templates[style.Name] = style; _typedNamedTemplates[style.InstanceType] = templates; } } #endregion  #region Construction private DynamicTemplateManager() { } #endregion }&lt;/script&gt;&lt;br /&gt;&lt;p&gt;I left out some of what I consider to be the fluff of this class for readability.&amp;#160; First thing to notice is the DependencyObject as the base class.&amp;#160; This helps to allow us to use our new template manager in the XAML, so we could bind to it if we wanted.&amp;#160; Cool stuff of note are the two indexers that should aid in the binding process, particularly the string, string indexer.&amp;#160; The key to the whole class is the Add method and the different dictionaries declared locally.&amp;#160; The dictionaries are going to keep all of my templates keys based on how I register them.&amp;#160; We have one each for typed templates, named templates, and typed and named templates.&amp;#160; Now, as long as our dynamic XAML is merged in with our visual tree, and using our keys, we should be able to find our DataTemplate using a App.Current.TryFindResource(object) passing the DynamicTemplateKey as the parameter.&lt;/p&gt;&lt;p&gt;You can download the source code for this &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/DynamicDataTemplates.zip&quot;&gt;here&lt;/a&gt;.&amp;#160; I haven’t posted any examples in it of how to use the key in XAML, but if you are familiar with DataTemplates and MarkupExtensions, it shouldn’t be a problem for you.&amp;#160; If I get a fair about of interest in using this in an example, I may post a part 2 to this post.&amp;#160; Please feel free to let me know if you would like to see an example.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/8321704206162748550/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/10/dynamic-datatemplates-in-wpf.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/8321704206162748550'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/8321704206162748550'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/10/dynamic-datatemplates-in-wpf.html' title='Dynamic DataTemplates in WPF'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-7775617551916510392</id><published>2009-10-16T08:38:00.000-07:00</published><updated>2009-10-16T08:39:53.805-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="LINQ"/><category scheme="http://www.blogger.com/atom/ns#" term="SQL"/><title type='text'>Using SQL Full Text with LINQ</title><content type='html'>Working with a database is a fairly common scenario for many business applications.&amp;nbsp; You have to store that data somewhere right?&amp;nbsp; It’s been a while since I have done any database work at my awesome &lt;a href=&quot;http://www.interknowlogy.com/&quot;&gt;job&lt;/a&gt;, so I took it upon myself to play with SQL Server a few days ago for fun.&amp;nbsp; I have been getting more and more familiar with LINQ, so I chose to use some of the LINQ to SQL goodness. Let’s start with this piece of code to find some customer orders:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;IQueryable&amp;lt;OrderEntity&amp;gt; orders = from order in _context.OrderEntities&lt;br /&gt;where Description = &quot;computer&quot;&lt;br /&gt;select order;&lt;/pre&gt;I set up LINQ statement, and it’s going to select all of my orders that have a description of computer.&amp;nbsp;&amp;nbsp; But what I really want is to find all of the orders with the word computer IN them.&amp;nbsp; So let’s switch our statement now to use the LINQ translation of SQL contains:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;IQueryable&amp;lt;OrderEntity&amp;gt; orders = from order in _context.OrderEntities&lt;br /&gt;where Description.Contains(&quot;computer&quot;)&lt;br /&gt;select order;&lt;/pre&gt;Great.&amp;nbsp; Now we are searching for all of the orders that have a description containing the word computer in it.&amp;nbsp; This is a great improvement over what we had before, but to be blunt, it still sucks.&amp;nbsp; Why?&amp;nbsp; Because everybody expects all searches to work like a Google search.&amp;nbsp; If I search for computer, it should bring back all things related to computer.&amp;nbsp; This is where full text search comes in.&amp;nbsp; You can read more about full text search &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms142571.aspx&quot;&gt;here&lt;/a&gt; if you would like, but the summary of it is that it does a more linguistic search instead of a black and white search.&amp;nbsp; So let’s combine full text search into our LINQ statement.&lt;br /&gt;&lt;br /&gt;……&lt;br /&gt;&lt;br /&gt;Crap.&amp;nbsp; It’s not supported by LINQ.&amp;nbsp; What to do.&amp;nbsp; Well, after some pondering, I realize that what I’m doing in 99% of my time with full text search is using the CONTAINSTABLE function.&amp;nbsp; From a high level, CONTAINSTABLE is based on whatever search term(s) you pass in, and gives back as a result a table with the key, in this case our table primary key, and a rank of how closely the search term was able to match to the column(s) you searched against.&amp;nbsp; Unfortunately, this still doesn’t really get me any further because I still can’t call this from LINQ.&amp;nbsp; Hmmmm.&lt;br /&gt;&lt;br /&gt;GOT IT!&amp;nbsp; What I can do is create a table based function and call that from LINQ.&amp;nbsp; So, I create a table based function called Orders_FullTextSearch and drag it into my LINQ data context.&amp;nbsp; I can now update my LINQ to SQL statement:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;IQueryable&amp;lt;OrderEntity&amp;gt; orders = from order in _context.OrderEntities&lt;br /&gt;join fts in _context.Order_FullTextSearch(&quot;computer&quot;)&lt;br /&gt;on order.Id equals fts.Key&lt;br /&gt;select order;&lt;/pre&gt;There we go, full text searching in LINQ.&amp;nbsp; You can expand on this example to use the FREETEXTTABLE as well.&amp;nbsp; I purposefully glossed over the SQL implementation of this because I wanted to focus on the coding part, but you can read more the functions I mentioned &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms142583.aspx&quot;&gt;here&lt;/a&gt;.&amp;nbsp; Full text searching can be complicated to set up, but it’s really cool in action and can add some pretty nice features to any searching you might be doing in your code or database.&amp;nbsp; I should also mention that it may take some type of SQL guru to optimize and administrate the full text stuff.&amp;nbsp; But you can make your end user happy!</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/7775617551916510392/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/10/using-sql-full-text-with-linq.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/7775617551916510392'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/7775617551916510392'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/10/using-sql-full-text-with-linq.html' title='Using SQL Full Text with LINQ'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-4411075906693920526</id><published>2009-08-06T18:14:00.000-07:00</published><updated>2009-08-07T13:53:00.113-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term=".NET 4.0"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Visual Studio 2010"/><title type='text'>C# 4.0 and Variance</title><content type='html'>Variance was&amp;nbsp; a tough thing for me to figure out.&amp;nbsp; I recently gave a &lt;a href=&quot;http://joeseymour.blogspot.com/2009/07/san-diego-code-camp-part-2-c-40.html&quot;&gt;talk&lt;/a&gt; on the features of C# 4.0 and this was one of the topics I covered.&amp;nbsp; I’d like to start out with a common scenario I have always had trouble understanding.&amp;nbsp; Take the following code snippet:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;IList&amp;lt;object&amp;gt; stuff = new List&amp;lt;string&amp;gt;();&lt;/pre&gt;This will not compile in any existing version of the .NET framework.&amp;nbsp; I have always struggled to understand why this wouldn’t work.&amp;nbsp; The System.String type is certainly something that can fulfill all the requirements of the System.Object.&amp;nbsp; Well, here’s why this doesn’t work.&amp;nbsp; The generic List is a reference type.&amp;nbsp; What this means, is that every time somebody references that object in the code, they will get a pointer to some location on the heap.&amp;nbsp; It doesn’t matter how many times you use the List, you always get the same reference to the pointer, hence reference type.&amp;nbsp; So, let’s expand on our previous example:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;IList&amp;lt;object&amp;gt; stuff = new List&amp;lt;string&amp;gt;();&lt;br /&gt;stuff.Add(&quot;Joe is awesome&quot;);&lt;br /&gt;stuff.Add(9);&lt;br /&gt;stuff.Add(false);&lt;/pre&gt;Here is where the problem lies.&amp;nbsp; As far as we are concerned, the declaration of stuff is an IList&amp;lt;object&amp;gt;.&amp;nbsp; This means that we can add any object to it, including an int or bool.&amp;nbsp; But let’s go back to what we just established.&amp;nbsp; The .NET framework is storing a reference to the underlying declaration, which is actually a List&amp;lt;string&amp;gt;.&amp;nbsp; We cannot add a int or bool to this list because they are not strings.&amp;nbsp; This cleared up something for me I had been wondering for a long time.&amp;nbsp; Let’s elaborate on this:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;IEnumerable&amp;lt;object&amp;gt; stuff = new List&amp;lt;string&amp;gt;();&lt;/pre&gt;Currently, just as stated before, .NET will not allow us to do this.&amp;nbsp; But wait you say?&amp;nbsp; It should?&amp;nbsp; I would have to agree.&amp;nbsp; Here’s the reason.&amp;nbsp; IEnumerable is a special class.&amp;nbsp; The reason it is so special is that IEnumerable doesn’t accept modifications.&amp;nbsp; The only thing IEnumerable is responsible for is returning objects, or rather objects coming out.&amp;nbsp; This throws a wrench into what we stated before.&amp;nbsp; Here is a perfectly valid scenario where you should be able to assign this because we will not be making any internal modifications, and could therefore avoid any such typing problems stated in the previous case.&lt;br /&gt;&lt;br /&gt;Here, IEnumerable&amp;lt;string&amp;gt; can definitely fill the role of an IEnumerable&amp;lt;object&amp;gt;, because string is said to be the more specific type and object the more generic.&amp;nbsp; To put it another way, string is covariant to object.&amp;nbsp; The only problem is, .NET 3.5 and earlier had no way to deal with this situation.&amp;nbsp; Enter .NET 4.0.&amp;nbsp; Here are a couple interface definitions:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public interface IEnumerable&amp;lt;out T&amp;gt; : IEnumerable&lt;br /&gt;{&lt;br /&gt;    IEnumerator&amp;lt;T&amp;gt; GetEnumerator();&lt;br /&gt;}&lt;br /&gt;public interface IEnumerator&amp;lt;out T&amp;gt; : IEnumerator&lt;br /&gt;{&lt;br /&gt;    bool MoveNext();&lt;br /&gt;    T Current { get; }&lt;br /&gt;}&lt;/pre&gt;The new keyword you see, “out”, is specifying that we are only ever going to allow T to come out of our interface.&amp;nbsp; This will allow our previous attempt of assigning IEnumerable&amp;lt;string&amp;gt; to IEnumberable&amp;lt;object&amp;gt; because we just told the compiler that T will never be coming in to our interface.&lt;br /&gt;&lt;br /&gt;Of course, there is the opposite scenario as well where a type is only going into your interface.&amp;nbsp; This is best demonstrated by looking at the following class:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;class Program&lt;br /&gt;{&lt;br /&gt;    void Manipulate(object obj)&lt;br /&gt;    {    &lt;br /&gt;    }&lt;br /&gt;    void ContravariantGoodness()&lt;br /&gt;    {&lt;br /&gt;        Action&amp;lt;object&amp;gt; manipulateObject = Manipulate;&lt;br /&gt;&lt;br /&gt;        Action&amp;lt;string&amp;gt; manipulateString = Manipulate;&lt;br /&gt;&lt;br /&gt;        manipulateString = manipulateObject;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;The only thing you don’t see here is that the Action definition in C# 4.0 contains the in keyword for the generic parameter.&amp;nbsp; As stated previously, this will not work in .NET 3.5 or earlier.&amp;nbsp; In this example, object is contravariant to string because it is going from a more generic type to a more specific type.&amp;nbsp; Because in this case the variable coming in is an object, we can really pass anything (almost) in .NET that will fulfill that contract, including a string.&amp;nbsp; Pretty cool stuff.&lt;br /&gt;&lt;br /&gt;One major thing to remember is that this is all based around reference types.&amp;nbsp; Something like can never be involved in either of the scenarios:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public struct Parent&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;    public T GetT()&lt;br /&gt;    {    &lt;br /&gt;        ...&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;I am really excited to see this in .NET 4.0, and I personally think it is the best of the new features added.&amp;nbsp; Now go check it out.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/4411075906693920526/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/08/c-40-and-variance.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4411075906693920526'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4411075906693920526'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/08/c-40-and-variance.html' title='C# 4.0 and Variance'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-1810309238920440281</id><published>2009-07-15T18:20:00.000-07:00</published><updated>2009-07-29T10:33:29.363-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Snoop 64 bit</title><content type='html'>I can&#39;t really take much credit for this because I didn&#39;t do that much work for it, but &lt;a href=&quot;http://team.interknowlogy.com/blogs/danhanan/archive/2009/07/15/64-bit-snoop-for-wpf-development.aspx&quot;&gt;here&lt;/a&gt; is&amp;nbsp;a link to his post on 64 bit snoop.&amp;nbsp; You can thank my coworker &lt;a href=&quot;http://team.interknowlogy.com/blogs/danhanan/default.aspx&quot;&gt;Dan&lt;/a&gt; for 99% of this.&lt;br /&gt;&lt;br /&gt;If you are doing any WPF development, you NEED this tool.&amp;nbsp; Dan has taken the time to throw some pretty nice additions into this version of the tool, so even if you already using snoop, you should take a look at his modified version.&lt;br /&gt;&lt;br /&gt;Happy snooping!</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/1810309238920440281/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/07/snoop-64-bit.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1810309238920440281'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1810309238920440281'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/07/snoop-64-bit.html' title='Snoop 64 bit'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-4584671697803981298</id><published>2009-07-15T15:41:00.000-07:00</published><updated>2009-08-07T13:54:36.398-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><title type='text'>Two great .NET features</title><content type='html'>I always like it when I come across a nice little feature I find in the .NET Framework.&amp;nbsp; If I find two in one day, it’s even better.&amp;nbsp; This is exactly what happened to me yesterday.&amp;nbsp; We’ll start out with the first feature, actually the only feature I intended to learn about yesterday, the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx&quot;&gt;yield&lt;/a&gt; keyword.&lt;br /&gt;I use dependency injection on a lot of my projects, including implementing some type of container.&amp;nbsp; Sometimes I use Unity, sometimes I roll my own.&amp;nbsp; Regardless of what I use, I end up with a project full of interfaces, including IDataProvider.&amp;nbsp; For the most part, I end up implementing a MockDataProvider and an XmlDataProvider.&amp;nbsp; I find this case very common inside of a DataProvider method:&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public IEnumerable&amp;lt;IStoredObject&amp;gt; GetStoredObjects()&lt;br /&gt;{&lt;br /&gt;    List&amp;lt;IStoredObject&amp;gt; objects = new List&amp;lt;IStoredObject&amp;gt;();&lt;br /&gt;&lt;br /&gt;    foreach (XElement objectElement in XDocument.Elements(&quot;Objects&quot;))&lt;br /&gt;    (&lt;br /&gt;        objects.Add(CreateStoredObject(objectElement));&lt;br /&gt;    )&lt;br /&gt;&lt;br /&gt;    return objects;&lt;br /&gt;}&lt;/pre&gt;This always irritates me to no end because I am just creating this List&amp;lt;&amp;gt; so that I can return these values.&amp;nbsp; I wish I could just return them.&amp;nbsp; But alas, you can.&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public IEnumerable&amp;lt;IStoredObject&amp;gt; GetStoredObjects()&lt;br /&gt;{&lt;br /&gt;    foreach (XElement objectElement in XDocument.Elements(&quot;Objects&quot;))&lt;br /&gt;    (&lt;br /&gt;        yield return CreateStoredObject(objectElement);&lt;br /&gt;    )&lt;br /&gt;}&lt;/pre&gt;Bam.&amp;nbsp; This simple statement will tell the compiler to return something it can enumerate through.&amp;nbsp; There are other uses for this keyword as well, but for me, I will use this case all of the time.&amp;nbsp; &lt;a href=&quot;http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/&quot;&gt;Here&lt;/a&gt; and &lt;a href=&quot;http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html&quot;&gt;here&lt;/a&gt; are articles with some more information.&lt;br /&gt;Now for part 2.&amp;nbsp; Coincidentally, this subject was on the next page in a book I was reading to find out about yield, which is why I found out about it. I frequently have need for the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.icloneable.aspx&quot;&gt;ICloneable&lt;/a&gt; interface.&amp;nbsp; There is a well known debate in the development world about this interface.&amp;nbsp; Some think ICloneable should be a deep clone, some think it should be a shallow clone.&amp;nbsp; Regardless, all the way down in System.Object, is a protected method called &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx&quot;&gt;MemberwiseClone&lt;/a&gt;.&amp;nbsp; This does a shallow copy for you.&amp;nbsp; What?&amp;nbsp; Yeah, I know.&amp;nbsp; I had no idea either.&amp;nbsp; It will copy all of your fields in your class for you and return the object.&amp;nbsp; Like everything else in .NET, if it’s a value type, you get a copy, if it’s a reference type, you get the same reference.&amp;nbsp; Pretty sweet.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/4584671697803981298/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/07/two-great-net-features.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4584671697803981298'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4584671697803981298'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/07/two-great-net-features.html' title='Two great .NET features'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-2401578413139623880</id><published>2009-07-14T16:07:00.001-07:00</published><updated>2009-07-14T16:10:29.443-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>WPF Screen Transition</title><content type='html'>One of my favorite things about WPF is the ability to use gratuitous animations in places where it would have been difficult in previous technologies.&amp;nbsp; We threw in one of these animations on our last project.&amp;nbsp; The project was using a Surface, but since it is just WPF, the idea is the same.&lt;br /&gt;Here is the high level concept.&amp;nbsp; You start out with a main window in your application.&amp;nbsp; In this main window, you want to change some content.&amp;nbsp; Instead of having a jumpy screen jerk, you get a nice animation from screen to screen.&amp;nbsp; This could be a fade in and fade out, or it could be a slide in and slide out.&amp;nbsp; It’s totally up to you as to how far you want to go.&amp;nbsp; So let’s get started.&lt;br /&gt;First, we have our main window.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: xml;&quot;&gt;&amp;lt;Window x:Class=&quot;ScreenTransition.MainWindow&quot;&lt;br /&gt;xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;&lt;br /&gt;xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&lt;br /&gt;Title=&quot;The Transition Window&quot;&lt;br /&gt;Height=&quot;300&quot;&lt;br /&gt;Width=&quot;450&quot;&amp;gt;&lt;br /&gt;&amp;lt;Canvas x:Name=&quot;TransitionContainer&quot; /&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;This is going to be where all of the work is done.&amp;nbsp; This is all you will see in the Xaml view of your window.&amp;nbsp; We are going to use the Canvas later on to add and remove UIElements from.&amp;nbsp; Let’s jump to the code behind.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;namespace ScreenTransition&lt;br /&gt;{&lt;br /&gt;/// &amp;lt;summary&amp;gt;&lt;br /&gt;/// Interaction logic for Window1.xaml&lt;br /&gt;/// &amp;lt;/summary&amp;gt;&lt;br /&gt;public partial class MainWindow : Window&lt;br /&gt;{&lt;br /&gt;readonly Duration _animationDuration = new Duration(TimeSpan.FromSeconds(1.0));&lt;br /&gt;&lt;br /&gt;DoubleAnimation CreateDoubleAnimation(double from, double to, EventHandler completedEventHandler)&lt;br /&gt;{&lt;br /&gt;DoubleAnimation doubleAnimation = new DoubleAnimation(from, to, _animationDuration);&lt;br /&gt;&lt;br /&gt;if (completedEventHandler != null)&lt;br /&gt;{&lt;br /&gt;doubleAnimation.Completed += completedEventHandler;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;return doubleAnimation;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public MainWindow()&lt;br /&gt;{&lt;br /&gt;InitializeComponent();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;This is the start of our window.&amp;nbsp; First, our Duration.&amp;nbsp; Just to keep some consistency, we are going to make a single Duration.&amp;nbsp; This way, we don’t have to keep making one, and the times will be the same to give our end user a consistent experience.&amp;nbsp; The CreateDoubleAnimation method is just a helper for us.&amp;nbsp; This will create the double animation and hook up to the completed event hander that we pass to it (could be an anonymous delegate…).&amp;nbsp; Now, lets take a look at the two animations I chose to create as a starting point.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;void FadeAnimation(UIElement newContent, UIElement oldContent, EventHandler completedEventHandler)&lt;br /&gt;{&lt;br /&gt;newContent.Opacity = 0;&lt;br /&gt;&lt;br /&gt;TransitionContainer.Children.Add(newContent);&lt;br /&gt;&lt;br /&gt;DoubleAnimation outAnimation = CreateDoubleAnimation(1, 0, null);&lt;br /&gt;DoubleAnimation inAnimation = CreateDoubleAnimation(0, 1, completedEventHandler);&lt;br /&gt;&lt;br /&gt;oldContent.BeginAnimation(UIElement.OpacityProperty, outAnimation);&lt;br /&gt;newContent.BeginAnimation(UIElement.OpacityProperty, inAnimation);&lt;br /&gt;}&lt;br /&gt;void SlideAnimation(UIElement newContent, UIElement oldContent, EventHandler completedEventHandler)&lt;br /&gt;{&lt;br /&gt;double leftStart = Canvas.GetLeft(oldContent);&lt;br /&gt;Canvas.SetLeft(newContent, leftStart - Width);&lt;br /&gt;&lt;br /&gt;TransitionContainer.Children.Add(newContent);&lt;br /&gt;&lt;br /&gt;if (double.IsNaN(leftStart))&lt;br /&gt;{&lt;br /&gt;leftStart = 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;DoubleAnimation outAnimation = CreateDoubleAnimation(leftStart, leftStart + Width, null);&lt;br /&gt;DoubleAnimation inAnimation = CreateDoubleAnimation(leftStart - Width, leftStart, completedEventHandler);&lt;br /&gt;&lt;br /&gt;oldContent.BeginAnimation(Canvas.LeftProperty, outAnimation);&lt;br /&gt;newContent.BeginAnimation(Canvas.LeftProperty, inAnimation);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Each of these methods are going to take two UIElements, the old element (current content) and the new element (content to be shown).&amp;nbsp; The methods also take the same completed event handler so we can pass it on to our helper method we just created.&amp;nbsp; The FadeAnimation is going to set the opacity of the new element to 0, add it to the TransitionContainer (our only item in our Window, remember from before?).&amp;nbsp; Then, we animation our new elements opacity from 0 to 1, and the old elements opacity from 1 to 0, creating a smooth fade in / fade out effect.&amp;nbsp; Cool huh?&amp;nbsp; Same idea for the slide animation, except we are going to animate the Canvas.Left property of each UIElement.&amp;nbsp; Only tricky part here is to make sure that the Canvas.Left property is actually set on the element, and if not, assume it is 0.&amp;nbsp; Next, the publicly exposed method that our application can call to change content.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public void ChangeContent(UIElement newContent)&lt;br /&gt;{&lt;br /&gt;if (TransitionContainer.Children.Count == 0)&lt;br /&gt;{&lt;br /&gt;TransitionContainer.Children.Add(newContent);&lt;br /&gt;return;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;if (TransitionContainer.Children.Count == 1)&lt;br /&gt;{&lt;br /&gt;TransitionContainer.IsHitTestVisible = false;&lt;br /&gt;UIElement oldContent = TransitionContainer.Children[0];&lt;br /&gt;&lt;br /&gt;EventHandler onAnimationCompletedHandler = delegate(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;TransitionContainer.IsHitTestVisible = true;&lt;br /&gt;TransitionContainer.Children.Remove(oldContent);&lt;br /&gt;if (oldContent is IDisposable)&lt;br /&gt;{&lt;br /&gt;(oldContent as IDisposable).Dispose();&lt;br /&gt;}&lt;br /&gt;oldContent = null;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;SlideAnimation(newContent, oldContent, onAnimationCompletedHandler);&lt;br /&gt;//FadeAnimation(newContent, oldContent, onAnimationCompletedHandler);&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;First up in this method, we check if there are any items in our Container.&amp;nbsp; If there are not, this is the first time into the screen and instead of a fade, we will just show the content right away.&amp;nbsp; If there are more than one item, we are going to do our fade.&amp;nbsp; We already went over the methods that do all of the animations, so we can ignore those calls.&amp;nbsp; First, we want to make sure that our container can’t be interacted with while the content switch is happening, so we set the IsHitTestVisible to false for now.&amp;nbsp; Next, we are going to assume that the TransitionContainer’s first element is the old content and store a reference for use as our old content.&amp;nbsp; Next, the in line delegate.&amp;nbsp; When the animation completes, we want to set IsHitTestVisible back to true.&amp;nbsp; Next, we want to remove our old content.&amp;nbsp; Finally, we want to call dispose on our object if it implements IDisposable, and the set it to null.&amp;nbsp; After that is just the calls to our two methods.&amp;nbsp; That’s it!&amp;nbsp; &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/ScreenTransition.zip&quot;&gt;Here&lt;/a&gt; is a link to some sample code.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/2401578413139623880/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/07/wpf-screen-transition.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/2401578413139623880'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/2401578413139623880'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/07/wpf-screen-transition.html' title='WPF Screen Transition'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-1097802739053534745</id><published>2009-07-02T15:13:00.001-07:00</published><updated>2009-07-02T15:54:02.398-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Speaking"/><category scheme="http://www.blogger.com/atom/ns#" term="Visual Studio 2010"/><title type='text'>San Diego Code Camp Part 2 – C# 4.0</title><content type='html'>&lt;p&gt;Thanks to all the people who attended this code camp session.&amp;#160; &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/CSharp4.pptx&quot;&gt;Here&lt;/a&gt; is a link to my slide deck.&amp;#160; And &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/CSharp4.zip&quot;&gt;here&lt;/a&gt; is a link to my sample project.&amp;#160; Please feel free to email or send me any message if you have more questions about the presentation.&amp;#160; I am planning on posting some more detailed information about C# 4.0 features with maybe some more samples apps in the near future.&amp;#160; Sorry it has taken so long to get this stuff up there.&amp;#160; Thanks again!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/1097802739053534745/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/07/san-diego-code-camp-part-2-c-40.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1097802739053534745'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1097802739053534745'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/07/san-diego-code-camp-part-2-c-40.html' title='San Diego Code Camp Part 2 – C# 4.0'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-1000911042274133575</id><published>2009-07-01T21:29:00.001-07:00</published><updated>2009-07-01T21:50:22.242-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Speaking"/><category scheme="http://www.blogger.com/atom/ns#" term="Visual Studio 2010"/><title type='text'>San Diego Code Camp Part 1 – MEF and Visual Studio 2010 Plugins</title><content type='html'>&lt;p&gt;Thanks to all the people who attended this code camp session.&amp;#160; &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/MEF.pptx&quot;&gt;Here&lt;/a&gt; is a link to my slide deck.&amp;#160; And &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/VisualTwitterio.zip&quot;&gt;here&lt;/a&gt; is a link to my sample project, VisualTwitterio.&amp;#160; Please feel free to email or send me any message if you have more questions about the presentation.&amp;#160; I’ve been super busy getting ready for all of these talks lately so look for more posts soon.&amp;#160; Also, if you are looking for the information on the C# 4.0 session, I should be posting that soon.&amp;#160; Sorry it has taken so long to get this stuff up there.&amp;#160; Thanks again!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/1000911042274133575/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/07/san-diego-code-camp-part-1-mef-and.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1000911042274133575'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1000911042274133575'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/07/san-diego-code-camp-part-1-mef-and.html' title='San Diego Code Camp Part 1 – MEF and Visual Studio 2010 Plugins'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-9021242586423629954</id><published>2009-04-22T14:28:00.000-07:00</published><updated>2009-04-22T14:28:29.742-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Setting the DataContext of a Popup or MenuBase</title><content type='html'>&lt;div&gt;One of the great features of WPF is the concept of the visual tree.&amp;nbsp; Every element we see on the screen is some where in the visual tree.&amp;nbsp; It is pretty common in WPF to want to walk up this visual tree and grab some data for binding purposes.&amp;nbsp; A simple RelativeSource Binding:&lt;/div&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; style=&quot;background-color: #f4f4f4; border-style: none; color: black; direction: ltr; font-family: &#39;Courier New&#39;,courier,monospace; font-size: 8pt; line-height: 12pt; margin: 0em; overflow: visible; padding: 0px; text-align: left; width: 100%;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Path&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;Fill&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=Foreground}&quot;&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;/&amp;gt;&lt;/span&gt; &lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;This will walk up the visual tree, until if finds the first Button, and set the Path.Fill property to the Foreground property of the Button.&amp;nbsp; This works great, unless you want to find visual elements that are not in the same tree, as is the case with Popup or ContextMenu(which inherits from MenuBase).&amp;nbsp; These elements will not be in the same visual tree as the rest of an application so a binding like this will not work:&lt;/div&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; style=&quot;background-color: #f4f4f4; border-style: none; color: black; direction: ltr; font-family: &#39;Courier New&#39;,courier,monospace; font-size: 8pt; line-height: 12pt; margin: 0em; overflow: visible; padding: 0px; text-align: left; width: 100%;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ContextMenu&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;DataContext&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=DataContext}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;Maybe a little unexpectedly, our data context will be null.&amp;nbsp; However, we can get a reference to the visual element that opened the ContextMenu.&amp;nbsp; The XAML for this looks like so:&lt;/div&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; style=&quot;background-color: #f4f4f4; border-style: none; color: black; direction: ltr; font-family: &#39;Courier New&#39;,courier,monospace; font-size: 8pt; line-height: 12pt; margin: 0em; overflow: visible; padding: 0px; text-align: left; width: 100%;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ContextMenu&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;DataContext&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget.DataContext}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;Be it good or bad, this only allows access to the DataContext of the PlacementTarget. But what if we have a little more complex situation?&amp;nbsp; Let’s layout a hypothetical situation. Suppose we have a ListBox control that is data bound to a list of strings.&amp;nbsp; For each string, we would like to have a ContextMenu that will allow us to delete the string from the list.&amp;nbsp; Let’s start with this XAML:&lt;/div&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; style=&quot;background-color: #f4f4f4; border-style: none; color: black; direction: ltr; font-family: &#39;Courier New&#39;,courier,monospace; font-size: 8pt; line-height: 12pt; margin: 0em; overflow: visible; padding: 0px; text-align: left; width: 100%;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Window&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;x:Class&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;MultiBindingList.Window1&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;xmlns&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;xmlns:x&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;Title&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;Window1&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;Height&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;300&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;Width&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;300&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Grid&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;ItemsSource&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding Path=Items}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox.ItemTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;DataTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;Text&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock.ContextMenu&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ContextMenu&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;MenuItem&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;Header&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;Delete&quot;&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ContextMenu&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock.ContextMenu&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;DataTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox.ItemTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Grid&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Window&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;We have our ListBox, and we have it bound to a list of items, and we have put a ContextMenu in the ItemTemplate.&amp;nbsp; So far so good.&amp;nbsp; Now, let’s switch to our code behind:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre id=&quot;codeSnippet&quot; style=&quot;background-color: #f4f4f4; border-style: none; color: black; direction: ltr; font-family: &#39;Courier New&#39;,courier,monospace; font-size: 8pt; line-height: 12pt; margin: 0em; overflow: visible; padding: 0px; text-align: left; width: 100%;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;partial&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;class&lt;/span&gt; Window1 : Window&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;public&lt;/span&gt; Window1()&lt;br /&gt;{&lt;br /&gt;InitializeComponent();&lt;br /&gt;&lt;br /&gt;Items = &lt;span style=&quot;color: blue;&quot;&gt;new&lt;/span&gt; ObservableCollection&amp;lt;&lt;span style=&quot;color: blue;&quot;&gt;string&lt;/span&gt;&amp;gt;(&lt;span style=&quot;color: blue;&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;string&lt;/span&gt;[] { &lt;span style=&quot;color: #006080;&quot;&gt;&quot;Item 1&quot;&lt;/span&gt;, &lt;span style=&quot;color: #006080;&quot;&gt;&quot;Item 2&quot;&lt;/span&gt;, &lt;span style=&quot;color: #006080;&quot;&gt;&quot;Item 3&quot;&lt;/span&gt; });&lt;br /&gt;&lt;br /&gt;RemoveItemCommand = &lt;span style=&quot;color: blue;&quot;&gt;new&lt;/span&gt; DelegateCommand&amp;lt;&lt;span style=&quot;color: blue;&quot;&gt;string&lt;/span&gt;&amp;gt;(RemoveItemCommandExecutedHandler);&lt;br /&gt;&lt;br /&gt;DataContext = &lt;span style=&quot;color: blue;&quot;&gt;this&lt;/span&gt;;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;public&lt;/span&gt; ObservableCollection&amp;lt;&lt;span style=&quot;color: blue;&quot;&gt;string&lt;/span&gt;&amp;gt; Items&lt;br /&gt;{&lt;br /&gt;get;&lt;br /&gt;set;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;public&lt;/span&gt; ICommand RemoveItemCommand&lt;br /&gt;{&lt;br /&gt;get;&lt;br /&gt;set;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;void&lt;/span&gt; RemoveItemCommandExecutedHandler(&lt;span style=&quot;color: blue;&quot;&gt;string&lt;/span&gt; item)&lt;br /&gt;{&lt;br /&gt;Items.Remove(item);&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;The only thing of note here is the DelegateCommand.&amp;nbsp; It’s a class that implements ICommand and is frequently used in WPF to forward a command from a view to a view model.&amp;nbsp; Now, in order to get the ContextMenu Command and CommandParameter property set correctly, we will have to pass in two object.&amp;nbsp; The first will be whatever the ListBoxItem.DataContext property has been set to by WPF.&amp;nbsp; The second will be the ICommand in the code behind, which we will get by walking the visual tree.&amp;nbsp; But we can’t walk the visual tree you say?&amp;nbsp; Enter the MultiValueBagConverter.&amp;nbsp; First, let’s look at the code and then walk through it:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre id=&quot;codeSnippet&quot; style=&quot;background-color: #f4f4f4; border-style: none; color: black; direction: ltr; font-family: &#39;Courier New&#39;,courier,monospace; font-size: 8pt; line-height: 12pt; margin: 0em; overflow: visible; padding: 0px; text-align: left; width: 100%;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;class&lt;/span&gt; MultiValueBagConverter : IMultiValueConverter&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: #cc6633;&quot;&gt;#region&lt;/span&gt; IMultiValueConverter Members&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;object&lt;/span&gt; Convert(&lt;span style=&quot;color: blue;&quot;&gt;object&lt;/span&gt;[] values, Type targetType, &lt;span style=&quot;color: blue;&quot;&gt;object&lt;/span&gt; parameter, System.Globalization.CultureInfo culture)&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;new&lt;/span&gt; List&amp;lt;&lt;span style=&quot;color: blue;&quot;&gt;object&lt;/span&gt;&amp;gt;(values);&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;object&lt;/span&gt;[] ConvertBack(&lt;span style=&quot;color: blue;&quot;&gt;object&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;value&lt;/span&gt;, Type[] targetTypes, &lt;span style=&quot;color: blue;&quot;&gt;object&lt;/span&gt; parameter, System.Globalization.CultureInfo culture)&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;new&lt;/span&gt; NotImplementedException();&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: #cc6633;&quot;&gt;#endregion&lt;/span&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;Here, we are using a IMultiValueConverter to transform all of our MultiBinding values to a List&amp;lt;object&amp;gt;.&amp;nbsp; This should allow us to pass in any number of parameters, and use them by calling an index on our newly created list.&amp;nbsp; Let’s update our XAML with the converter, setting the correct data contexts:&lt;/div&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt;&lt;pre id=&quot;codeSnippet&quot; style=&quot;background-color: #f4f4f4; border-style: none; color: black; direction: ltr; font-family: &#39;Courier New&#39;,courier,monospace; font-size: 8pt; line-height: 12pt; margin: 0em; overflow: visible; padding: 0px; text-align: left; width: 100%;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Window&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;x:Class&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;MultiBindingList.Window1&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;xmlns&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;xmlns:x&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;xmlns:Local&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;clr-namespace:MultiBindingList&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;Title&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;Window1&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;Height&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;300&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;Width&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;300&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Window.Resources&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ResourceDictionary&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Local:MultiValueBagConverter&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;x:Key&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;MultiValueBag&quot;&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ResourceDictionary&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Window.Resources&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Grid&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;ItemsSource&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding Path=Items}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox.ItemTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;DataTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;Text&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding Path=[0]}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock.DataContext&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;MultiBinding&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;Converter&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{StaticResource MultiValueBag}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Binding&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Binding&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;Path&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;DataContext.RemoveItemCommand&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;RelativeSource&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}&quot;&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;MultiBinding&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock.DataContext&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock.ContextMenu&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ContextMenu&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;DataContext&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget.DataContext}&quot;&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;MenuItem&lt;/span&gt; &lt;span style=&quot;color: red;&quot;&gt;Header&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;Delete&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;Command&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding Path=[1]}&quot;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: red;&quot;&gt;CommandParameter&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;=&quot;{Binding Path=[0]}&quot;&lt;/span&gt; &lt;span style=&quot;color: blue;&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ContextMenu&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock.ContextMenu&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;TextBlock&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;DataTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox.ItemTemplate&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;ListBox&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Grid&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span style=&quot;color: maroon;&quot;&gt;Window&lt;/span&gt;&lt;span style=&quot;color: blue;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;First, we added a reference to our namespace, xmlns:Local.&amp;nbsp; Second, we added a ResourceDictionary and added our converter to it, giving it a key of MultiValueBag.&amp;nbsp; Hop down to the TextBlock, and we had to change our code around a bit.&amp;nbsp; First, the Text property is now bound to index o of our list.&amp;nbsp; Second, we set the DataContext of the TextBlock to the output of our converter, passing it in the ListBoxItem value, as well as the RemoveItemCommand we got from walking up to our Window and getting the DataContext from that.&amp;nbsp; Now, our ContextMenu has it’s DataContext set to the PlacementTarget.DataContext, but now we have a list of all the items we need to execute the command.&amp;nbsp; Right click to bring up the ContextMenu, push the delete menu item, an you will see the item’s disappear out of the list!&amp;nbsp; Here is the &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/MultiBindingList.zip&quot; target=&quot;_blank&quot;&gt;source&lt;/a&gt;.&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/9021242586423629954/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/04/setting-datacontext-of-popup-or.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/9021242586423629954'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/9021242586423629954'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/04/setting-datacontext-of-popup-or.html' title='Setting the DataContext of a Popup or MenuBase'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-7746878707126242434</id><published>2009-04-01T15:26:00.001-07:00</published><updated>2009-04-01T15:27:04.027-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Background Worker, Part 3</title><content type='html'>&lt;p&gt;In the final post of the three part series, we are going to finish up or BackgroundMethod class.  In &lt;a href=&quot;http://joeseymour.blogspot.com/2009/03/background-worker-part-1.html&quot; target=&quot;_blank&quot;&gt;Part 1&lt;/a&gt;, we covered the basics of the class.  In &lt;a href=&quot;http://joeseymour.blogspot.com/2009/04/background-worker-part-2.html&quot; target=&quot;_blank&quot;&gt;Part 2&lt;/a&gt;, we started building the core of our class.  In this final part, we are going to handle three things:  the DoWork event, the RunWorkerCompleted event, and Unhooking our event subscriptions.&lt;/p&gt;  &lt;p&gt;Okay, lets start with the DoWork event.  What we want here is to grab our entry delegate and invoke it, passing a parameter to it if necessary.&lt;/p&gt;  &lt;div&gt;   &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; DoWorkHandler(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; sender, DoWorkEventArgs e)&lt;br /&gt;{&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;try&lt;/span&gt;&lt;br /&gt;   {&lt;br /&gt;       &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt;[] parameters = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;;&lt;br /&gt;       &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (_parameter != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;       {&lt;br /&gt;           parameters = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt;[] { _parameter };&lt;br /&gt;       }&lt;br /&gt;       e.Result = _entryDelegate.Method.Invoke(_entryDelegate.Target, parameters);&lt;br /&gt;   }&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;catch&lt;/span&gt; (Exception ex)&lt;br /&gt;   {&lt;br /&gt;       e.Result = ex;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   BackgroundWorker worker = sender &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; BackgroundWorker;&lt;br /&gt;   e.Cancel = worker.CancellationPending;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, like we said before, create the parameters, and call invoke.  In the event args, we are going to pass our result, if we get one.  As well, if we throw an exception we will set the result of the work to the exception.  Finally, we grab the background worker, check if somebody has set the work to be cancelled, and set Cancel to true if need be.  In the handler for work completed, we are going to use this result to complete the processing if necessary.&lt;br /&gt;&lt;/div&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt; &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; RunWorkerCompletedHandler(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; sender, RunWorkerCompletedEventArgs e)&lt;br /&gt;{&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.Error != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;   {&lt;br /&gt;       _errorAction(e.Error);&lt;br /&gt;   }&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;else&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (!e.Cancelled &amp;amp;&amp;amp; e.Error == &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;   {&lt;br /&gt;       &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.Result &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;is&lt;/span&gt; Exception)&lt;br /&gt;       {&lt;br /&gt;           _errorAction(e.Result &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; Exception);&lt;br /&gt;       }&lt;br /&gt;       &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;else&lt;/span&gt;&lt;br /&gt;       {&lt;br /&gt;           &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (_callbackDelegate != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;           {&lt;br /&gt;               &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt;[] parameters = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;;&lt;br /&gt;               &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.Result != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;               {&lt;br /&gt;                   parameters = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt;[] { _parameter };&lt;br /&gt;               }&lt;br /&gt;               _callbackDelegate.Method.Invoke(_callbackDelegate.Target, parameters);&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   Dispose();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;First, check for an error.  Our error action is finally coming into play here for the exception.  This way, if the background method didn’t work for some reason, pass the exception back up to the main thread so we can log it or handle it gracefully.  If there was no error and the background worker hasn’t been cancelled, check for the result as an exception, calling the error action again if so.&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;Finally, if our method ran okay, we are going to check for a callback delegate.  As previously stated, we are covering the most complex scenario in which we have a callback delegate.  In more simple scenarios, you may not want to do anything we the method is completed.  Here we do, so we are going to create a set or parameters, and if the DoWork handler gave us a value (our entry method could return void), we call invoke on the callback delegate.&lt;/div&gt;&lt;br /&gt;&lt;div&gt;Last, and certainly not least, we are going to call Dispose.  In the dispose method somewhere, we will call this method.&lt;br /&gt;&lt;/div&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt; &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; UnhookBackgroundWorker(BackgroundWorker bw)&lt;br /&gt;{&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (bw.IsBusy)&lt;br /&gt;   {&lt;br /&gt;       bw.CancelAsync();&lt;br /&gt;   }&lt;br /&gt;   bw.DoWork -= DoWorkHandler;&lt;br /&gt;   bw.RunWorkerCompleted -= RunWorkerCompletedHandler;&lt;br /&gt;   bw.Dispose();&lt;br /&gt;   bw = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Just some cleanup here.  Unhook the methods, call dispose on the background worker.  And that’s it!  We now have a fully reusable class that is fairly simple to use.  You can find an example of the usage attached &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/BackgroundMethod.zip&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;, as well as the full BackgroundMethod class.&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;Talk soon.&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/7746878707126242434/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/04/background-worker-part-3.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/7746878707126242434'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/7746878707126242434'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/04/background-worker-part-3.html' title='Background Worker, Part 3'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-3530129357787374128</id><published>2009-04-01T15:02:00.001-07:00</published><updated>2009-04-01T15:04:31.535-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Background Worker, Part 2</title><content type='html'>&lt;p&gt;In my &lt;a href=&quot;http://joeseymour.blogspot.com/2009/03/background-worker-part-1.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt;, I talked about the need to be able run a piece of work in WPF on a background thread, leaving a responsive UI in the process.  I am going to start walking through how to create a reusable class that will easily allow a method to be run in the background.&lt;/p&gt;  &lt;p&gt;The first thing I want to do is figure out how I want to use this class.  I’d like to be able to pass my class a method that may or may not take a parameter to kick off the process, and may or may not return a value.  Once the work has been completed, I’d like my class to call another method that also may or may not have a parameter, possibly the result of the previous method .  Finally, I want to be able to handle exceptions in my code gracefully.&lt;/p&gt;  &lt;p&gt;Let’s discuss the first requirement.  This seems to fit nicely with some basics that are built into .NET.  The first is the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.action.aspx&quot; target=&quot;_blank&quot;&gt;Action&lt;/a&gt; object.  This is a &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.delegate.aspx&quot; target=&quot;_blank&quot;&gt;Delegate&lt;/a&gt; for a method that has no parameters and no return value.  Luckily, &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/018hxwa8.aspx&quot; target=&quot;_blank&quot;&gt;Action(T)&lt;/a&gt; is an alternate implementation of a &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.delegate.aspx&quot; target=&quot;_blank&quot;&gt;Delegate&lt;/a&gt;, that allows a method that takes one parameter, T, and returns no parameters.  So we have the delegates for methods that return no values.  But what about methods that return values?  Enter &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb534960.aspx&quot; target=&quot;_blank&quot;&gt;Func(TResult)&lt;/a&gt;.  This &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.delegate.aspx&quot; target=&quot;_blank&quot;&gt;Delegate&lt;/a&gt; requires a method that has no parameters and returns one value, of type T.  And you guessed it, there is an alternate implementation, &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb549151.aspx&quot; target=&quot;_blank&quot;&gt;Func(T, TResult)&lt;/a&gt;, that allows one parameter and one return value.  The combination of all of these should cover the starting method.&lt;/p&gt;  &lt;p&gt;The second requirement is a little simpler.  We want to call a method when the code is completed that may or may not have a parameter.  Well, we already covered &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.action.aspx&quot; target=&quot;_blank&quot;&gt;Action&lt;/a&gt; and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/018hxwa8.aspx&quot; target=&quot;_blank&quot;&gt;Action(T)&lt;/a&gt; which fits perfect for this.  The same goes for the exception handling, except in this case we know we are going to have an Action(Excetion), since we will presumably be handing an &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.exception.aspx&quot; target=&quot;_blank&quot;&gt;System.Exception&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;So, looking back on the requirements, you may have noticed they all have something in common.  Each of the delegates inherit from &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.delegate.aspx&quot; target=&quot;_blank&quot;&gt;Delegate&lt;/a&gt;.  Great!  This means our references to these methods are general and only store instances of Delegate, eliminating the need for a Generic class!  We can now just call Invoke on the delegate.&lt;/p&gt;  &lt;p&gt;I’m a big fan of the &lt;a href=&quot;http://en.wikipedia.org/wiki/Factory_method_pattern&quot; target=&quot;_blank&quot;&gt;factory pattern&lt;/a&gt;, so I’ve made a decision that my constructors should all be private, forcing the person consuming our class to call some factory methods to create my class.&lt;/p&gt;  &lt;p&gt;Because it would take longer and we would be covering the same information, we’re not going to go through each of the cases specified above, but instead show only examples from the most complicated case.  We want to run some background work on a method that takes one parameter, returns one value, and then call a method that takes that returned value as a parameter.  Let’s start with the signature of the factory method.&lt;/p&gt;  &lt;div id=&quot;codeSnippetWrapper&quot;&gt;   &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; BackgroundMethod Create&amp;lt;T, U&amp;gt;(Func&amp;lt;U, T&amp;gt; entryFunc, Action&amp;lt;T&amp;gt; callbackAction, Action&amp;lt;Exception&amp;gt; errorAction, T parameter)&lt;br /&gt;{&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; BackgroundMethod();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Should be pretty straight forward considering what we discussed.  This takes three methods with various signatures, as well as the parameter for the entryMethod. We added some generic parameters here to make sure that all of the types will match when the methods are called.&lt;/div&gt;&lt;br /&gt;Based on what we need, our class will need to store some local values.  First, it will need to store all of the values passed into our method so we can access them later.  Second, we need the work horse, the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx&quot; target=&quot;_blank&quot;&gt;BackgroundWorker&lt;/a&gt; class.&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt; &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#region&lt;/span&gt; Fields&lt;br /&gt;BackgroundWorker _worker;&lt;br /&gt;Action&amp;lt;Exception&amp;gt; _errorAction;&lt;br /&gt;&lt;br /&gt;Delegate _entryDelegate;&lt;br /&gt;Delegate _callbackDelegate;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; _parameter;&lt;br /&gt;&lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#endregion&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;Remember, the two &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.delegate.aspx&quot; target=&quot;_blank&quot;&gt;Delegate&lt;/a&gt; declarations are storing the Func and Action since they both derive from Delegate.&lt;br /&gt;&lt;br /&gt;Now, at construction of the class, we will want to new up our &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx&quot; target=&quot;_blank&quot;&gt;BackgroundWorker&lt;/a&gt; and subscribe to the events on it.  As &lt;a href=&quot;http://joeseymour.blogspot.com/2009/03/background-worker-part-1.html&quot; target=&quot;_blank&quot;&gt;previously discussed&lt;/a&gt;, we will want the DoWork and RunWorkerCompleted events, as well as to allow the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx&quot; target=&quot;_blank&quot;&gt;BackgroundWorker&lt;/a&gt; to be cancelled.  And, to make it easier for later, we’ll add a couple overloads of our constructor.&lt;br /&gt;&lt;/div&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt; &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#region&lt;/span&gt; Construction&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;private&lt;/span&gt; BackgroundMethod()&lt;br /&gt;{&lt;br /&gt;   _worker = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; BackgroundWorker();&lt;br /&gt;   _worker.WorkerSupportsCancellation = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;true&lt;/span&gt;;&lt;br /&gt;   _worker.DoWork += DoWorkHandler;&lt;br /&gt;   _worker.RunWorkerCompleted += RunWorkerCompletedHandler;&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;private&lt;/span&gt; BackgroundMethod(Delegate entryDelegate, Delegate callbackDelegate, Action&amp;lt;Exception&amp;gt; errorAction)&lt;br /&gt;   : &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;this&lt;/span&gt;(entryDelegate, callbackDelegate, errorAction, &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;private&lt;/span&gt; BackgroundMethod(Delegate entryDelegate, Delegate callbackDelegate, Action&amp;lt;Exception&amp;gt; errorAction, &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; parameter)&lt;br /&gt;   : &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;this&lt;/span&gt;()&lt;br /&gt;{&lt;br /&gt;   _entryDelegate = entryDelegate;&lt;br /&gt;   _callbackDelegate = callbackDelegate;&lt;br /&gt;   _errorAction = errorAction;&lt;br /&gt;   _parameter = parameter;&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#endregion&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;We’re making use of our original constructor in our overloads by calling this(), as well as setting some of our local values.  Let’s update our static methods as well now to use our new constructor.&lt;br /&gt;&lt;/div&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt; &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; BackgroundMethod Create&amp;lt;T, U&amp;gt;(Func&amp;lt;U, T&amp;gt; entryFunc, Action&amp;lt;T&amp;gt; callbackAction, Action&amp;lt;Exception&amp;gt; errorAction, T parameter)&lt;br /&gt;{&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; BackgroundMethod(entryFunc, callbackAction, errorAction, parameter);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;We have all the information to do the work now, but before getting into the meat of our class, let’s wrap up some ancillary items.  First, a couple methods to run and cancel or work.&lt;br /&gt;&lt;/div&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt; &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; text-align: left; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; direction: ltr;font-family:&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#region&lt;/span&gt; Methods&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; Run()&lt;br /&gt;{&lt;br /&gt;   _worker.RunWorkerAsync();&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; Cancel()&lt;br /&gt;{&lt;br /&gt;   &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (!_isDisposed)&lt;br /&gt;   {&lt;br /&gt;       _worker.CancelAsync();&lt;br /&gt;       Dispose();&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#endregion&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;For run, we will tell our worker to start, and for cancel, we will tell our worker to cancel.  Also, we are going to implement &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.idisposable.aspx&quot; target=&quot;_blank&quot;&gt;IDisposable&lt;/a&gt; so there isn’t any bad stuff left hanging around when we are done with our background work.  If you are not used to using this, you should get used to it.&lt;/div&gt;&lt;br /&gt;Whew!  That’s it for now.  In part 3 of this series, we’re going to look at the guts of the class and finish up this object.  Talk soon.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/3530129357787374128/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/04/background-worker-part-2.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/3530129357787374128'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/3530129357787374128'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/04/background-worker-part-2.html' title='Background Worker, Part 2'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-3176586167989354471</id><published>2009-03-18T16:49:00.001-07:00</published><updated>2009-04-01T15:05:00.976-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Background Worker, Part 1</title><content type='html'>&lt;p&gt;Many times in many projects I have worked on, there have been requirements to go out and execute some long running method.  I have played with various methods of doing this before, like using &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx&quot; target=&quot;_blank&quot;&gt;IAsyncResult&lt;/a&gt;, with a fair amount of success.  After coming across this requirement again in my current project and having been a fair amount of time since I last used this pattern, I decided to explore some of the current options for WPF.&lt;/p&gt;  &lt;p&gt;In my research I came across and excellent &lt;a href=&quot;http://www.codeproject.com/&quot; target=&quot;_blank&quot;&gt;CodeProject&lt;/a&gt; &lt;a href=&quot;http://www.codeproject.com/KB/WPF/AsynchronousWPF.aspx&quot; target=&quot;_blank&quot;&gt;article&lt;/a&gt; with examples of the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx&quot; target=&quot;_blank&quot;&gt;BackgroundWorker&lt;/a&gt; object version the IAsyncResult pattern.  In the article is a nice sample project that shows how both of the ideas can be implemented as well.  For reasons unknown even to me, I settled on the BackgroundWorker object, I guess because I have never really liked using the IAsyncResult stuff.&lt;/p&gt;  &lt;p&gt;First, some information about the BackgroundWorker object.  This object definitely relies heavily on events.  If you haven’t used events or are not used to subscribing and unsubscribing from events, you may find it a bit easier to use the IAsyncResult pattern.  There are two (three really, but the third is for reporting progress) events that are of major importance, &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx&quot; target=&quot;_blank&quot;&gt;DoWork&lt;/a&gt; and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx&quot; target=&quot;_blank&quot;&gt;RunWorkerCompleted&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;The DoWork event is where you are going to execute your long running method.  This event is raised when the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkerasync.aspx&quot; target=&quot;_blank&quot;&gt;RunWorkerAsync&lt;/a&gt; method is called on the BackgroundWorker object.  The &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.doworkeventargs.aspx&quot; target=&quot;_blank&quot;&gt;DoWorkEventArgs&lt;/a&gt; that are passed in the event delegate an Argument you can use when starting your long running process and a Result that can be used to pass back a result of the long running method.&lt;/p&gt;  &lt;p&gt;You will be able to access this result when the RunWorkerCompleted event is raised, immediately after the completion of the DoWork event delegates.  In the parameters to the RunWorkerCompleted delegate, you will have access to result if some more processing needs to be done with it with the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.runworkercompletedeventargs.aspx&quot; target=&quot;_blank&quot;&gt;RunWorkerCompletedEventArgs&lt;/a&gt;.  You will also be able to see if there was an exception thrown in the DoWork delegates, or if the an outside process has requested to cancel the operation on the BackgroundWorker by calling the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.runworkercompletedeventargs.aspx&quot; target=&quot;_blank&quot;&gt;CancelAsync&lt;/a&gt; method.&lt;/p&gt;  &lt;p&gt;Cancelling the BackgroundWorker must be set up from the beginning by setting the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.workersupportscancellation.aspx&quot; target=&quot;_blank&quot;&gt;WorkerSupportsCancellation&lt;/a&gt; boolean to “true” before calling RunWorkerAsync .  The same goes for the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.reportprogress.aspx&quot; target=&quot;_blank&quot;&gt;ReportProgress&lt;/a&gt; method. &lt;/p&gt;  &lt;p&gt;If you are going to be doing something like running a for loop in you long running method where you are able to report progress, you will want to make sure that you also set &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.reportprogress.aspx&quot; target=&quot;_blank&quot;&gt;WorkerReportsProgress&lt;/a&gt; property to “true” as well.  The ReportProgress method simply takes a double value that should represent the percentage of progress.  The &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx&quot; target=&quot;_blank&quot;&gt;ProgressChanged&lt;/a&gt; delegate parameter will give you access to this percentage in the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.progresschangedeventargs.progresspercentage.aspx&quot; target=&quot;_blank&quot;&gt;ProgressPercentage&lt;/a&gt; property of the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.progresschangedeventargs.aspx&quot; target=&quot;_blank&quot;&gt;ProgressChangedEventArgs&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;And that&#39;s it.  Wiring this up can be a little tricky.  In part 2 of this series, I’ll be building a reusable class that should simplify this process a little bit.  Happy codes!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/3176586167989354471/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/03/background-worker-part-1.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/3176586167989354471'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/3176586167989354471'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/03/background-worker-part-1.html' title='Background Worker, Part 1'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-508430080432716673</id><published>2009-02-05T21:54:00.001-08:00</published><updated>2009-02-05T22:04:12.689-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Windows 7"/><title type='text'>SharedView and Windows 7</title><content type='html'>&lt;p&gt;Just as before with the &lt;a href=&quot;http://joeseymour.blogspot.com/2009/02/sonicwall-global-vpn-on-windows-7.html&quot;&gt;SonicWall VPN Client&lt;/a&gt;, I needed to run a piece of software on my beta install of Windows 7.  I can’t rant enough about this Windows build.  It’s the first beta, and I have converted all of my computers (well, almost all, my media center pc is not working because of a faulty HDMI port on my TV, but I digress) to running it.  One of the first tools I install on a clean dev machine is &lt;a href=&quot;http://connect.microsoft.com/site/sitehome.aspx?SiteID=94&quot;&gt;SharedView&lt;/a&gt;.  It’s an amazing tool that allows collaboration on a project when working remotely.  It’s super light weight, but has all of the essentials.  I couldn’t work remotely without it.  Unfortunately, upon running the install, it tells me I have an incompatible operating system.  Says who?  Well, I was at a brick wall until today.  A fabulous &lt;a href=&quot;http://team.interknowlogy.com/blogs/bradcunningham/default.aspx&quot;&gt;coworker&lt;/a&gt; of mine reminded me of a tool to modify an MSI called &lt;a href=&quot;http://www.technipages.com/download-orca-msi-editor.html&quot;&gt;Orca&lt;/a&gt; I used a while back.  So I opened up the SharedView MSI and found a ton of hardcoded references to Vista, so I got rid of them.  Installs fine, and so far no crashes.  &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/sharedview.msi&quot;&gt;Here&lt;/a&gt; it is.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/508430080432716673/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/02/sharedview-and-windows-7.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/508430080432716673'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/508430080432716673'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/02/sharedview-and-windows-7.html' title='SharedView and Windows 7'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-4020715330168462717</id><published>2009-02-05T14:10:00.001-08:00</published><updated>2009-02-05T21:58:37.225-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Windows 7"/><title type='text'>SonicWall Global VPN on Windows 7</title><content type='html'>&lt;p&gt;I love Windows 7.  I’ve been using it for a couple of weeks now as my primary OS, and recently formatted ALL of my computer to it.  It’s awesome.  I haven’t been able to use my SonicWall VPN client though.  After coming the forums, I found a solution (use at your own risk though).&lt;/p&gt;  &lt;p&gt;1)    Open Command Prompt &lt;br /&gt;2)    Type &quot;Set DEVMGR_SHOW_NONPRESENT_DEVICES=1&quot;, Enter  &lt;br /&gt;3)    Type &quot;devmgmt.msc&quot; to open the device manager, Enter  &lt;br /&gt;4)    In the menu, go to View -&amp;gt; Show Hidden Devices  &lt;br /&gt;5)    Expand the Non-Plug and Play node (expanded by default)  &lt;br /&gt;6)    Right click on the SonicWall IPSec Driver, Properties, Go to Drivers Tab  &lt;br /&gt;7)    Set Startup Type to Automatic  &lt;br /&gt;8)    Click OK  &lt;br /&gt;9)    Reboot and enjoy&lt;/p&gt;  &lt;p&gt;Optionally, you may want to also set the DEVMGR_SHOW_NONPRESENT_DEVICES=0 after you are done, but it’s beta anyway right?&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/4020715330168462717/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/02/sonicwall-global-vpn-on-windows-7.html#comment-form' title='22 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4020715330168462717'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/4020715330168462717'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/02/sonicwall-global-vpn-on-windows-7.html' title='SonicWall Global VPN on Windows 7'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>22</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-2188980255098580315</id><published>2009-01-30T10:45:00.001-08:00</published><updated>2009-01-30T14:19:54.322-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Standards"/><title type='text'>Using modern code standards</title><content type='html'>&lt;p&gt;I would like to touch on two things. Both of these things drive me absolutely insane because I enjoy reading nice code. Well written code should be really easy to understand at a high level. It should be clear and concise. These two things take away from it.&lt;/p&gt;  &lt;p&gt;The first is abbreviating variable names. Some people like to give me a load of crap for my naming conventions. It would not be uncommon for you to find this in my code:&lt;/p&gt;  &lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;   &lt;pre   style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; width: 100%; color: black; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; isIndicatorLightTurnOnDuringExecution = DetermineIndicatorLightStateDuringExecution();&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Some people would argue that this is wrong because of having to type so much, but let me tell you what&#39;s right. I know exactly what this variable is holding, and what this method is doing. I am extremely diligent and naming my variables and methods for EXACTLY what they do. Why don&#39;t I use abbreviations or chop out some words? Because, I want to know what is going on in my code, and there isn&#39;t a chance in hell of me writing a comment without somebody making me. And can you tell me what this means:&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre   style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; width: 100%; color: black; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; isLightOn = CheckLight();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Sort of. There&#39;s a light there. But that&#39;s all I can tell you. Yeah, I can go dig through the code, but who the hell wants to do that. This may have taken me a little less time to write, but that time savings is going to be lost when I come back through when my code breaks (WHAT?) and try to figure out what is going on. This is just laziness. Or how about his one:&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre   style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; width: 100%; color: black; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; isIndLgtTrnOnDurExe = DetIndLghtSteDurExe();&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Now, I have no idea what this means. I would argue that it probably takes less time to write the long form of this code than the abbreviate version of it, because I have to stop and try to figure out which letters to leave out and which to keep in. Also, am I coding in assembly language? Not last time I checked. That name is not taking up more or less space, so who care about shorting it. I wouldn&#39;t do it, ever. Take the time to write it out, and you&#39;ll be happier when you do.&lt;br /&gt;&lt;p&gt;The second thing that drives me nuts in the creation of the var in .NET 3.5. I hate using it. I hate seeing it. I hope it dies and goes away. Why? I am not gaining anything from it. Is it really hard to type out bool? Nope. Is it hard to type out ObservableCollection&amp;lt;objecct&amp;gt;? Maybe it used to be, but with intellisense, I don&#39;t type all of any word anyway, I hit only the first three or four keys and then move on. The thing that I lose with var is the ability to easily see what my variable is. Take this:&lt;br /&gt;&lt;/p&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre   style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; width: 100%; color: black; line-height: 12pt; background-color: rgb(244, 244, 244);font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;var item = DoSomething();&lt;br /&gt;var otherItem = DoSomethingElse();&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; item.Equals(otherItem);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;What is this doing? I have no idea. I now have to go look at the implementation of DoSomething() and DoSomethingElse() to figure it out. Totally unreadable. I hope the decision is made to eventually get rid of var.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/2188980255098580315/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/01/using-modern-code-standards.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/2188980255098580315'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/2188980255098580315'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/01/using-modern-code-standards.html' title='Using modern code standards'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-6358228518854200203</id><published>2009-01-26T16:18:00.001-08:00</published><updated>2009-01-30T10:55:16.253-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="MESH"/><category scheme="http://www.blogger.com/atom/ns#" term="Silverlight"/><title type='text'>Code Camp Part 2 – Mesh enabled Silverlight application</title><content type='html'>&lt;p&gt;Thanks to everybody who came out to my &lt;a href=&quot;http://www.socalcodecamp.com/&quot;&gt;code camp&lt;/a&gt; &lt;a href=&quot;http://www.socalcodecamp.com/session.aspx?sid=bceef79e-ad6c-47d7-abdf-d592003f3bfd&quot;&gt;presentation&lt;/a&gt;. &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/Silverlight_MESH.zip&quot;&gt;Here&lt;/a&gt; is a link to the sample Silverlight application I used.&amp;#160;&amp;#160; The project has the required assemblies in it already but unfortunately you won&amp;#8217;t be able to use it without a magical key from MS.&amp;#160; &lt;a href=&quot;http://joeseymour.blogspot.com/2009/01/code-camp-part-1-using-live-services.html&quot;&gt;Here&lt;/a&gt; is my previous post for the information on the WPF application I spoke about towards the end of the presentation.&lt;/p&gt;  &lt;p&gt;Check back on my &lt;a href=&quot;http://joeseymour.blogger.com&quot;&gt;blog&lt;/a&gt; within then next week, I should be posting a synopsis of the &lt;a href=&quot;http://www.mesh.com&quot;&gt;MESH&lt;/a&gt; and how it works, including where the Mesh enabled Silverlight applications fit in. If you have any more questions about the material, or any questions in general, let me know and I&amp;#8217;ll answer them as soon as I can. Again, thanks for coming out.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/6358228518854200203/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/01/code-camp-part-2-mesh-enabled.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/6358228518854200203'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/6358228518854200203'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/01/code-camp-part-2-mesh-enabled.html' title='Code Camp Part 2 – Mesh enabled Silverlight application'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-2545812722761969806</id><published>2009-01-25T11:26:00.001-08:00</published><updated>2009-01-30T10:55:52.938-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="MESH"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Code Camp Part 1 – Using Live Services API</title><content type='html'>&lt;p&gt;Thanks to everybody who came out to my &lt;a href=&quot;http://www.socalcodecamp.com/&quot;&gt;code camp&lt;/a&gt; &lt;a href=&quot;http://www.socalcodecamp.com/session.aspx?sid=0fae6549-d82f-44e1-84a6-b7307d2b43ac&quot;&gt;presentation&lt;/a&gt;. &lt;a href=&quot;http://joe.born2pwn.com/blogfiles/MESH_Datastore.zip&quot;&gt;Here&lt;/a&gt; is a link to the sample WPF project I used. The project has the required assemblies in it already but unfortunately you won&amp;#8217;t be able to use it without a magical key from MS.&lt;/p&gt;  &lt;p&gt;Check back on my &lt;a href=&quot;http://joeseymour.blogger.com&quot;&gt;blog&lt;/a&gt; within then next week, I should be posting a synopsis of the &lt;a href=&quot;http://www.mesh.com&quot;&gt;MESH&lt;/a&gt; and how it works, including where the Live Services API fits in. If you have any more questions about the material, or any questions in general, let me know and I&amp;#8217;ll answer them as soon as I can. Again, thanks for coming out.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/2545812722761969806/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/01/code-camp-part-1-using-live-services.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/2545812722761969806'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/2545812722761969806'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/01/code-camp-part-1-using-live-services.html' title='Code Camp Part 1 – Using Live Services API'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-6019726697742028109</id><published>2008-12-17T15:06:00.000-08:00</published><updated>2009-01-30T10:48:20.135-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>WPF Showdown - AppDomain.CurrentDomain.SetThreadPrincipal vs Thread.CurrentPrincipal</title><content type='html'>&lt;p&gt;Coming from the background of writing applications to support a business, I have become very familiar with the concept of logging in and the security around logging in.  I have been pushed deep into the world of WPF and visualization lately, so security and logging in has been lost to the depths of my mind.  A requirement came up a few weeks ago on my current project to mock up a login screen, and plan for it to work in the future.  I dug around in my brain and decided to go with a familiar method of logging in, utilizing the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx&quot;&gt;System.Threading.Principal&lt;/a&gt; and the concepts surrounding it.&lt;/p&gt;  &lt;p&gt;Since we spend most of our time here at &lt;a href=&quot;http://interknowlogy.com/&quot;&gt;IK&lt;/a&gt; working on prototypes and very new versions of software, this is not a super common scenario.  The IPrincipal and IIdentity have come far since the original release of .NET, including the addition of GenericIdentity and GenericPrincipal that allow semi-custom security, without having to buff out a your own implementation of of these interfaces.  Anyway, for those of you not familiar with the concept, the basic idea is you give this &quot;token&quot; to the application, and you access it via the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx&quot;&gt;Thread.CurrentPrincipal&lt;/a&gt;.  There are other specific situations, ActiveDirectory included as well as custom built that are a little more complicated, but the premise is the same in the end.&lt;/p&gt;  &lt;p&gt;So I set off on my merry way to do just this.  I used the GenericPrincipal and the GenericIdentity and set the Thread.CurrentPrincipal on login.  Fine.  One of the main purposed of using the IIdentity is the .IsInRole() method hanging off of it.  This was my main reason for using it in the application, I needed some role based security.  I put a couple lines in my code as follows:&lt;/p&gt;  &lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;   &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 128, 0);&quot;&gt;// blah blah&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (CurrentThread.CurrentPrincipal.Identity.IsInRole(&lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;Role1&quot;&lt;/span&gt;))&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 128, 0);&quot;&gt;// Do one thing&lt;/span&gt;&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (CurrentThread.CurrentPrincipal.Identity.IsInRole(&lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;Role2&quot;&lt;/span&gt;))&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 128, 0);&quot;&gt;// Do another thing&lt;/span&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 128, 0);&quot;&gt;// continue blah blah&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Pretty straight forward for the pattern.  Then I created a basic form with the following code at the heart of it:&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; DoLogin()&lt;br /&gt;{&lt;br /&gt;IPrincipal principal = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 128, 0);&quot;&gt;// Create new principal based on needs&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Thread.CurrentPrincipal = principal;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Again, standard concepts here.  I execute my login logic, create my IPrincipal based on the logic, then set the Thread.CurrentPrincipal to my newly created IPrincipal.&lt;br /&gt;&lt;br /&gt;&lt;p&gt;FALSE! Due to some security features of WPF, noted &lt;a href=&quot;http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/67bada95-2d3d-40fd-94e3-b910c1d823ef/&quot;&gt;here&lt;/a&gt;, this is not allowed.  Whenever I made the subsequent call to Thread.CurrentPrincipal, it was never set.  I followed the article fairly well, and decided to continue with the suggestion, using &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.appdomain.setthreadprincipal.aspx&quot;&gt;AppDomain.SetThreadPrincipal&lt;/a&gt;.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;This worked sort of as expected.  When I made my subsequent call to Thread.CurrentPrincipal, it was definitely set to the correct value.  Everything was going well until I tried to call logout:&lt;br /&gt;&lt;/p&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; DoLogout()&lt;br /&gt;{&lt;br /&gt;AppDomain.CurrentDomain.SetThreadPrincipal(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; GenericPrincipal(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; GenericIdentity(&lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;Anonymous&quot;&lt;/span&gt;), &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;));&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;I get this big ugly exception telling me I can&#39;t call this method twice.  Are you kidding me??  Pretty standard stuff to be able to login / logout of an application for different rights.  I was pretty upset at this point, and tried hacking around a bit for a solution.  Since I wasn&#39;t able to find one, I ended up implementing a static ApplicationContext class, which happened to have a Principal property hanging off of it.  I suppose this solution work as I wanted it to.  If I was writing an application from the ground up, which I knew had to target multiple platforms, I probably would have done this anyway (Web, Windows Form, WPF, etc.) since it provides a little more control.  Still a little disappointing to find the previous pattern I used is no longer a viable solution.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/6019726697742028109/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/01/wpf-showdown-appdomaincurrentdomainsett.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/6019726697742028109'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/6019726697742028109'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/01/wpf-showdown-appdomaincurrentdomainsett.html' title='WPF Showdown - AppDomain.CurrentDomain.SetThreadPrincipal vs Thread.CurrentPrincipal'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-3326189414744864323</id><published>2008-10-27T11:36:00.000-07:00</published><updated>2009-01-30T10:49:10.224-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><title type='text'>All things are not Equals()</title><content type='html'>&lt;p&gt;It seems like something so simple to do, that it often gets overlooked.  The Equals() method that has been hanging off of System.Object since the beginning of (.NET) time, so hopefully most are familiar with it by now. Start by creating a stub for the method.&lt;/p&gt;  &lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;   &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;class&lt;/span&gt; Person&lt;br /&gt;{&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;string&lt;/span&gt; _firstName;&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;string&lt;/span&gt; _lastName;&lt;br /&gt;&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;string&lt;/span&gt; FirstName&lt;br /&gt; {&lt;br /&gt;     get&lt;br /&gt;     {&lt;br /&gt;         &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; _firstName;&lt;br /&gt;     }&lt;br /&gt;     set&lt;br /&gt;     {&lt;br /&gt;         _firstName = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;value&lt;/span&gt;;&lt;br /&gt;     }&lt;br /&gt; }&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;string&lt;/span&gt; LastName&lt;br /&gt; {&lt;br /&gt;     get&lt;br /&gt;     {&lt;br /&gt;         &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; _lastName;&lt;br /&gt;     }&lt;br /&gt;     set&lt;br /&gt;     {&lt;br /&gt;         _lastName = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;value&lt;/span&gt;;&lt;br /&gt;     }&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;override&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; Equals(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; obj)&lt;br /&gt; {&lt;br /&gt;     &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt; }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Before we begin to try and figure out what makes one instance of an object equal to another instance of an object, we need to figure out what makes two objects of any type equal.  The most likely answer is nothing, unless there is some base classes or other complex inheritance schemes going.  Let&#39;s code for that by making an overload of Equals that takes a concrete object, in this case a Person, instead of a generalized object.&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;override&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; Equals(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; obj)&lt;br /&gt;{&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; Equals(Person person)&lt;br /&gt;{&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Now we have two methods that will have two distinct jobs.  The first, overridden from System.Object, is just going to make sure we have a valid Person, and nothing more.&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;override&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; Equals(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; obj)&lt;br /&gt;{&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (obj == &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt; || GetType() != obj.GetType())&lt;br /&gt; {&lt;br /&gt;     &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; Equals((Person)obj);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Pretty simple code here.  Make sure object isn&#39;t null and make sure GetType() matches our GetType().  This is going to eliminate any null reference exceptions and any type cast exceptions, two of my most hated exceptions.  Now to actually check if our objects are equal.&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; Equals(Person person)&lt;br /&gt;{&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (person != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt; {&lt;br /&gt;     &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; _firstName.Equals(person._firstName) &amp;amp;&amp;amp; _lastName.Equals(person._lastName);&lt;br /&gt; }&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;This code is again checking for null to make sure we don&#39;t have any null reference exceptions.  After that, we finally get to what the method is supposed to do, check if two objects are equal.  I chose a simple example here, check first name and last name, but the point is easily illustrated.  Whatever makes an object equal to another object gets checked here, and the result returned.  We&#39;re done.  But wait.  Not so fast.  The often overlooked, but equally (no pun intended) important override should done as well.&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;override&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;int&lt;/span&gt; GetHashCode()&lt;br /&gt;{&lt;br /&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; _firstName.GetHashCode() ^ _lastName.GetHashCode();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Why is this important?  First, GetHashCode() is supposed to be unique for different objects, and the return the same value for identical objects.  So, if we are overriding Equals(), or in other words, telling the framework what makes our object equal to another object, it&#39;s only proper to override GetHashCode().  Second, this code block would not execute as we think.&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;Hashtable table = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; Hashtable();&lt;br /&gt;&lt;br /&gt;Person person1 = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; Person();&lt;br /&gt;person1.FirstName = &lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;Joe&quot;&lt;/span&gt;;&lt;br /&gt;person1.LastName = &lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;Seymour&quot;&lt;/span&gt;;&lt;br /&gt;&lt;br /&gt;Person person2 = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; Person();&lt;br /&gt;person2.FirstName = &lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;Joe&quot;&lt;/span&gt;;&lt;br /&gt;person2.LastName = &lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;Seymour&quot;&lt;/span&gt;;&lt;br /&gt;&lt;br /&gt;table[person1] = person1;&lt;br /&gt;table[person2] = person2;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;What &lt;b&gt;should&lt;/b&gt; happen here, assuming that if first name and last name are equal, which they are, Equals() will return true so there should only be one person in this hash table, but there would be two.  Of course, our code will work correctly since we overrode GetHashCode().  Read more about GetHashCode() &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now we&#39;re done.  Also, if you want to override the equals operator, all you have to do is call your Equals() method.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/3326189414744864323/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/01/all-things-are-not-equals.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/3326189414744864323'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/3326189414744864323'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/01/all-things-are-not-equals.html' title='All things are not Equals()'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3884961837046000063.post-1271574081507047873</id><published>2008-10-16T07:49:00.001-07:00</published><updated>2009-01-30T10:50:00.415-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="WPF"/><title type='text'>Binding to a Collection that doesn&#39;t allow Binding</title><content type='html'>&lt;p&gt;Recently, I decided to give the DataGrid in the new &lt;a href=&quot;http://www.codeplex.com/wpf&quot;&gt;WPFToolkit&lt;/a&gt; a try in a project for a client.  Our client was looking for reordering columns, sorting columns, and some other features that the DataGrid takes care of pretty nicely out of the box.  One of the shortcomings that came up was the fact that the DataGrid doesn&#39;t natively support binding to its Columns property.  I&#39;m not sure the reasoning for this, but it turned out to be a pretty big gap for us, as we needed to pull the list of columns from a data store that would allow the user to drag around the columns, allowing the user to create a custom view they could save.  We could have handled this in code, calling the .Add() and .Remove() methods on the Columns property, but wouldn&#39;t have fit into our MV-V-M (read more &lt;a href=&quot;http://blogs.msdn.com/dancre/archive/tags/DM-V-VM/default.aspx&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://www.orbifold.net/default/?p=550&quot;&gt;here&lt;/a&gt;) pattern very well, since we try to keep as little code as possible in the view (hopefully none!).  We decided to accomplish this by extending the DataGrid to have a property we could bind to, allowing us to support the pattern. &lt;/p&gt;  &lt;p&gt;First step was to create a new control called BindableColumnsDataGrid to extend the functionality of the DataGrid.&lt;/p&gt;  &lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;   &lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;namespace&lt;/span&gt; BindableDataGrid.Controls&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;class&lt;/span&gt; BindableColumnsDataGrid : DataGrid&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Then, using a DependencyProperty, we created a BindableColumns property what will us to bind to a ObservableCollection&amp;lt;DataGridColumn&amp;gt;.&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%; height: 417px;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;        &lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#region&lt;/span&gt; BindableColumns DP&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;readonly&lt;/span&gt; DependencyProperty BindableColumnsProperty = DependencyProperty.Register(&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 96, 128);&quot;&gt;&quot;BindableColumns&quot;&lt;/span&gt;,&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;typeof&lt;/span&gt;(ObservableCollection&amp;lt;DataGridColumn&amp;gt;),&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;typeof&lt;/span&gt;(BindableColumnsDataGrid),&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; FrameworkPropertyMetadata(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnBindableColumnsPropertyChangedHandler)&lt;br /&gt;        );&lt;br /&gt;&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; SetBindableColumns(UIElement element, ObservableCollection&amp;lt;DataGridColumn&amp;gt; columns)&lt;br /&gt;    {&lt;br /&gt;        element.SetValue(BindableColumnsProperty, columns);&lt;br /&gt;    }&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; ObservableCollection&amp;lt;DataGridColumn&amp;gt; GetBindableColumns(UIElement element)&lt;br /&gt;    {&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; (ObservableCollection&amp;lt;DataGridColumn&amp;gt;)element.GetValue(BindableColumnsProperty);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; ObservableCollection&amp;lt;DataGridColumn&amp;gt; BindableColumns&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;return&lt;/span&gt; GetBindableColumns(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;this&lt;/span&gt;);&lt;br /&gt;        }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            SetBindableColumns(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;this&lt;/span&gt;, &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;value&lt;/span&gt;);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; OnBindableColumnsPropertyChangedHandler(DependencyObject d, DependencyPropertyChangedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 128, 0);&quot;&gt;// TODO: Handle changing&lt;/span&gt;&lt;br /&gt;    }&lt;br /&gt;    &lt;span style=&quot;color: rgb(204, 102, 51);&quot;&gt;#endregion&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;A couple of things to note in the DependencyProperty.  First, we set this property to bind two ways by default.  We want to make sure that if we make any underlying changes in the code, it will get published back out to the source.  Second, we create a PropertyChangedHandler.  We want to make sure we can hook up to some of the events that will be occurring in BindableColumns, mainly the CollectionChanged event in the ObservableCollection&amp;lt;&amp;gt;, so we need a spot to hook up to that.  The place to take care of this is in the PropertyChangedHandler.&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;        &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; OnBindableColumnsPropertyChangedHandler(DependencyObject d, DependencyPropertyChangedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        BindableColumnsDataGrid grid = d &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; BindableColumnsDataGrid;&lt;br /&gt;&lt;p&gt;            &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.OldValue != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;/p&gt;&lt;br /&gt;        {&lt;br /&gt;            ObservableCollection&amp;lt;DataGridColumn&amp;gt; oldColumns = e.OldValue &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; ObservableCollection&amp;lt;DataGridColumn&amp;gt;;&lt;br /&gt;            oldColumns.CollectionChanged -= grid.ColumnsCollectionChangedHandler;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        grid.Columns.Clear();&lt;br /&gt;&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.NewValue != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;        {&lt;br /&gt;            ObservableCollection&amp;lt;DataGridColumn&amp;gt; newColumns = e.NewValue &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; ObservableCollection&amp;lt;DataGridColumn&amp;gt;;&lt;br /&gt;&lt;br /&gt;            &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;foreach&lt;/span&gt; (DataGridColumn column &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;in&lt;/span&gt; newColumns)&lt;br /&gt;            {&lt;br /&gt;                grid.Columns.Add(column);&lt;br /&gt;            }&lt;br /&gt;            newColumns.CollectionChanged += grid.ColumnsCollectionChangedHandler;&lt;br /&gt;        }&lt;br /&gt;    &lt;br /&gt;    }&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;The most interesting part of the work here, clearing out all of the current columns in the Columns property and adding all of the BindableColumns to the DataGrid.  This takes care of the main functionality of the control.&lt;br /&gt;&lt;br /&gt;&lt;p&gt;As stated before, we are going to be interested in the CollectionChanged event.  We are hooking up to it here, as well as unhooking from it if the binding source is changed.  Now for the collection changed handler.&lt;br /&gt;&lt;/p&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; ColumnsCollectionChangedHandler(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; sender, NotifyCollectionChangedEventArgs e)&lt;br /&gt;{&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.OldItems != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;{&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;foreach&lt;/span&gt; (DataGridColumn oldItem &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;in&lt;/span&gt; e.OldItems)&lt;br /&gt;    {&lt;br /&gt;        Columns.Remove(oldItem);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.NewItems != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;{&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;foreach&lt;/span&gt; (DataGridColumn newItem &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;in&lt;/span&gt; e.NewItems)&lt;br /&gt;    {&lt;br /&gt;        Columns.Add(newItem);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Nothing super new here.  Looking for a change in the columns, and handling it accordingly.  Remove all the old items, add in all the new items.  That takes care of the case where the binding source has Add and Remove called on it (via the ObservableCollection&amp;lt;&amp;gt;).&lt;br /&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; BindableColumnsDataGrid()&lt;br /&gt;{&lt;br /&gt;AutoGenerateColumns = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;Simple constructor.  We just want to make sure that we set the AutoGenerateColumns property to false from the base DataGrid.  We don&#39;t want to generate columns because we won&#39;t be using them at all.&lt;br /&gt;&lt;p&gt;&lt;strong&gt;&lt;u&gt;BONUS&lt;/u&gt;&lt;/strong&gt;&lt;br /&gt;&lt;/p&gt;&lt;p&gt;Another pretty cool feature we had to support was column reordering, which, as stated before, the DataGrid natively supports.  However, the BindableColumns doesn&#39;t get any of this information natively, so we were not able to save this back out to our data store.  Here is the code updates for taking care of that.&lt;br /&gt;&lt;/p&gt;&lt;div   style=&quot;border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; line-height: 12pt; background-color: rgb(244, 244, 244); width: 97.5%; max-height: 200px; cursor: text;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;&quot;&gt;&lt;br /&gt;&lt;pre    style=&quot;border-style: none; margin: 0em; padding: 0px; overflow: visible; line-height: 12pt; background-color: rgb(244, 244, 244); width: 100%;font-family:consolas,&#39;Courier New&#39;,courier,monospace;font-size:8pt;color:black;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; OnBindableColumnsPropertyChangedHandler(DependencyObject d, DependencyPropertyChangedEventArgs e)&lt;br /&gt;{&lt;br /&gt;BindableColumnsDataGrid grid = d &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; BindableColumnsDataGrid;&lt;br /&gt;&lt;strong&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (!grid._syncronizingBindings)&lt;br /&gt;{&lt;/strong&gt;&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.OldValue != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;    {&lt;br /&gt;        ObservableCollection&amp;lt;DataGridColumn&amp;gt; oldColumns = e.OldValue &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; ObservableCollection&amp;lt;DataGridColumn&amp;gt;;&lt;br /&gt;        oldColumns.CollectionChanged -= grid.ColumnsCollectionChangedHandler;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    grid.Columns.Clear();&lt;br /&gt;&lt;br /&gt;    &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;if&lt;/span&gt; (e.NewValue != &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;null&lt;/span&gt;)&lt;br /&gt;    {&lt;br /&gt;        ObservableCollection&amp;lt;DataGridColumn&amp;gt; newColumns = e.NewValue &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;as&lt;/span&gt; ObservableCollection&amp;lt;DataGridColumn&amp;gt;;&lt;br /&gt;&lt;br /&gt;        &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;foreach&lt;/span&gt; (DataGridColumn column &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;in&lt;/span&gt; newColumns)&lt;br /&gt;        {&lt;br /&gt;            grid.Columns.Add(column);&lt;br /&gt;        }&lt;br /&gt;        newColumns.CollectionChanged += grid.ColumnsCollectionChangedHandler;&lt;br /&gt;    }&lt;br /&gt;&lt;strong&gt;}&lt;/strong&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;bool&lt;/span&gt; _syncronizingBindings = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;/strong&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;public&lt;/span&gt; BindableColumnsDataGrid()&lt;br /&gt;{&lt;br /&gt;AutoGenerateColumns = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt;&lt;strong&gt;    ColumnReordered += &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;new&lt;/span&gt; EventHandler&amp;lt;DataGridColumnEventArgs&amp;gt;(BindableColumnsDataGrid_ColumnReordered);&lt;/strong&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;void&lt;/span&gt; BindableColumnsDataGrid_ColumnReordered(&lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;object&lt;/span&gt; sender, DataGridColumnEventArgs e)&lt;br /&gt;{&lt;br /&gt;_syncronizingBindings = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;true&lt;/span&gt;;&lt;br /&gt;BindableColumns = Columns;&lt;br /&gt;_syncronizingBindings = &lt;span style=&quot;color: rgb(0, 0, 255);&quot;&gt;false&lt;/span&gt;;&lt;br /&gt;}&lt;/strong&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;First, hook up in the constructor to the ColumnReordered event.  Second, leveraging the fact that we decided to make the binding two way by default, in the event handler for the column reorder, we are going to set the columns back in the other direction, setting BindableColumns to the Columns which should be persisted back to our source collection.  Third, we were tripped up by some binding code.  It seems that when the binding is passed back the other direction, WPF doesn&#39;t seem to know we are going back in the other direction, so it tries to turn around and set our binding the other direction, creating a cycle.  Adding a _syncronizingBindings flag takes care of this, by simply bypassing the normal PropertyChangedHandler if we see the columns are currently being synchronized.  That&#39;s it, just slap our new BindableColumnsDataGrid into some Xaml, bind to the BindableColumns property and away it goes.</content><link rel='replies' type='application/atom+xml' href='http://www.joeseymour.net/feeds/1271574081507047873/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.joeseymour.net/2009/01/binding-to-collection-that-doesn-allow.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1271574081507047873'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3884961837046000063/posts/default/1271574081507047873'/><link rel='alternate' type='text/html' href='http://www.joeseymour.net/2009/01/binding-to-collection-that-doesn-allow.html' title='Binding to a Collection that doesn&amp;#39;t allow Binding'/><author><name>Joe Seymour</name><uri>http://www.blogger.com/profile/12576454039878301947</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='31' height='21' src='http://1.bp.blogspot.com/_GoKl4mvOMtw/SX-5x0dEHNI/AAAAAAAADpM/-Az4cYgHGDQ/S220/DSC_0775.JPG'/></author><thr:total>0</thr:total></entry></feed>