I thought I post a conversation I am having with the team I work for about WPF vs Winforms

Their question stated, is WPF built on the premise of usability by providing easy to use styling in XAML with resource styling and theming?

My response: There is a learning curve with WPF, but styling is really not the major concern if you plan to use component like DevExpress. A drawback to WPF is developers (me included) can become overly concerned about styling, leading to misuse. WPF is designed to separate design/presentation concerns from the development/business concerns and so on. The real learning curve in “data-binding”. WPF can minimize concerns around user experience (UX) and styling. Of course, users learning any new application really has nothing to do with the underlying technology choices. It’s really the psychology around how people think, behave, their “way of work”, and their interactions with specific interface components, hence the concepts around UX. UX is about whether particular components improves user experience, drive new behaviors, or how it may achieve business related benchmarks. It really has nothing to do with the underlying technology. On the other hand, UX may influence a decision around what to use at the component level, but not around the governing technology, like whether to go with WPF, Winform, or ASP.NET.

There is quick guide about layering and Separation of Concerns at the following URL if you’re interested in learning more: https://msdn.microsoft.com/en-us/library/ee658124.aspx

Their question stated, What are to pros lists out with MVVM specifically. Is this just an example, or are we considering other design patterns as well?

Mike’s response: Agreed, MVVM is about the way WPF is implemented. But that is the point. WPF/MVVM is symbiotic conveying the importance of WPF as an enterprise team oriented technology. The goals of MVVM vs MVC are different. The MVC, used primarily by ASP.NET, implements “controllers” that invoke server defined views associated with a model. ASP.NET MVC use this for good reasons when streaming views through any number of “throttled” internet connections. In WPF this would lead to unnecessary duplication, a dependence on models, and a lack of command/notification driven approach. WPF/MVVM is concerned about providing scalability, maintainability, and making allowances for reusable components.



Hi all! Here's some quick code to support linq and try...catch scenarios. In an attempt to traverse a list, the results should be string array of values, really simple. By unraveling a property chain on an object it could result in a NullReferenceException. I really wanted a Linq expression that provided a try…catch scenario and execute an "Or” type expression if an exception occurs.

Let’s review the extension class. First, I built a tree of expressions from the start of my .Try() method, then my .Or() method finalizes to result. For example, I have a list of conditions and each condition has a left expression, operand, and right expression. The lambda expressions could throw an exception so my Try..Or expression uses an alternative way to handle potential exceptions.

enumerable.Where(x => x.LeftExpression.Value.Equals("SomeData"))
.Try(x => x.RightExpression.Value).Or(x => string.Empty)

This quickly solves the need to test or catch errors, within each property also a quick way to extend the ability return a result set. HEADS UP!! I also included an OrElse statement as well.

enumerable.Where(x => x.LeftExpression.Value.Equals("SomeData") )
.Try(x => x.RightExpression.Value).OrElse(x => x.LeftExpression.Value)
.Or(x => string.Empty)

Here's the code: (also below is some erroneous html, sorry just delete it)

    public static class IEnumerableExtension
        public static Tuple<ienumerable <TSource>, IEnumerable<func <TSource, TResult>>> Try<tsource , TResult>(this IEnumerable<tsource> source, Func<tsource , TResult> selector)
            return new Tuple<ienumerable <TSource>, IEnumerable<func <TSource, TResult>>>(source, new[] { selector });

        public static Tuple<ienumerable <TSource>, IEnumerable<func <TSource, TResult>>> OrElse<tsource , TResult>(this Tuple<ienumerable <TSource>, IEnumerable<func <TSource, TResult>>> source, Func<tsource , TResult> selector)
            return new Tuple<ienumerable <TSource>, IEnumerable<func <TSource, TResult>>>(source.Item1, source.Item2.Concat(new[] { selector }));

        public static IEnumerable<tresult> Or<tsource , TResult>(this Tuple<ienumerable <TSource>, IEnumerable<func <TSource, TResult>>> source, Func<tsource , TResult> selector)
            var finalized = new Tuple<ienumerable <TSource>, IEnumerable<func <TSource, TResult>>>(source.Item1, source.Item2.Concat(new[] { selector }));
            return finalized.Item2.SelectMany(method => source.Item1.Select(method).Catch());

        private static IEnumerable<t> Catch<t>(this IEnumerable<t> source)
            using (var enumerator = source.GetEnumerator())
                bool next = true;

                while (next)
                        next = enumerator.MoveNext();

                    if (next)
                        yield return enumerator.Current;

Writing test is simple. Pick a class or object; start writing a test to the functionality, and use assertion to see if my test assumptions are right or wrong. If they are wrong re-write the test to fix it. This viewpoint to writing a test can lead to mistakes in so many areas. Considered a classes function, purpose, does the test cover all dependencies on classes or even how “deep” the functionality should be to complete a test. What about inherited classes or COM objects that can run in a unit of code or work?

Have you considered if the test covers all the possibility of this specific unit? What is my intent to write an “implementation test“. If your intent is to write a more functional or implementation test great, but beware it is not a distributive unit test.

In this next series of blogs, I will discuss how to start and finish a good unit test and the difference between implementation test and unit test and avoiding the pitfall associated with each approach, and finally on mocks in Visual Studio.

A unit test is by definition a single test designed to assess a unit of code in combination with diverse inputs and output with the unit. Code is written in the concept of units, such as a mathematically class which may contain a “unit” of code to add two numbers. This class provides a “function” or “method” specifically designed for a single purpose. The code may call on external functions to develop into a unit of work, but we should attempt to ignore influence on the unit. The school of thought for unit test is to maintain only my unit of work and to avoid maintaining external units of work. Here are a few tenets to help you get started.

  • Tenet #1: Only test one unit, the function or method called is the only code to test
  • Tenet #2: Refactor code that creates dependencies on external units
  • Tenet #3: Mock all dependencies on external units
  • Tenet #4: Try to go no more than one level deep into any one unit
  • Tenet #5: Each unit test should cover one scenario of the unit; build another test to cover different scenarios of the same unit. Such as expected errors from a try…catch block

dependencies are at times unavoidable; refactoring your code can help. When code is considered untestable, it’s probably due to a dependency on another class or function, use common design patters to help resolved these issue. For example, when writing WPF applications, Model-View-ViewModel (MVVM) pattern is a dependency separation model to a view and event from this view. One example is the MessageBox control. When a unit test is tested the process of running the test may stop to show a message box, and this inadvertently causes or test process to wait for user response. Using the builder patterned, (see. Builder Pattern (www.dofactory.com), I can create a class named MsgBoxBuilder. This class will ultimately call the System.Window.MessageBox, now my code is testable. When passing MsgBoxBuilder as interface to the constructor of a View Model, I can use a “mock” to remove the dependencies on the MessageBox control, and I am ready to test my code.

Example : Refactored code in MVVM style for a MessageBox

    public class MyManagerViewModel : IMyManagerViewModel 
        private readonly IViewModelFactory _factory;
        private IMsgBoxBuilder  _msgBox;
        public WellboreManagerViewModel(IMsgBoxBuilder msgBox = null, 
            IViewModelFactory factory = null)
            _factory = factory ?? new ViewModelFactory();
            _msgBox = msgBox ?? new MsgBoxBuilder();

    public class MsgBoxBuilder : IMsgBoxBuilder 
        public void Show(string message)

        public void Show(string message, string title)
            MessageBox.Show(message, title, MessageBoxButton.OK);

My Next Blog we will discuss Tenet #3 using only Visual Studio 2012.


If you looking to create a clickonce package in Visual Studio that is created using Team Foundation Server's Automated Builds(MSBuild), here's an idea I found worked really well for me. Basically, the goal is 1) to create a ClickOnce package from the Build server, and 2) to create a bat file that can move the files into a version-ed folder upon request. If you add this to your project file, use "mage.exe" -

The Clickonce packager within Visual Studio is available for every project, but it does not account for the build that needs to pull dll's into a Release folder post the build, and any non-referenced dll's in your project. Geek moment, I'm done.

For additional help with mage.exe, go to MSDN Mage.exe (Manifest Generation and Editing Tool)

Review the code below it should help.

   <target Name="PostBuildMacros">
     <getassemblyidentity AssemblyFiles="$(TargetPath)">
       <output TaskParameter="Assemblies" ItemName="Targets">
      del /Q "$(TargetDir)*.application"
      del /Q "$(TargetDir)*.docx"
      del /Q "$(TargetDir)*.manifest"
      call "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe" -ClearApplicationCache
      call "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe" -New Application -FromDirectory "$(TargetDir)." -Name "$(TargetName)" -Processor "$(PlatformName)" -Version @(Targets-&gt;'%(Version)') -ToFile "$(TargetDir)$(TargetFileName).manifest" -IconFile "Resources\EMfinditLogsLogo.ico" -TrustLevel "FullTrust" -Publisher "YourCompany" -UseManifestForTrust "true" -CertFile  "$(TargetDir)$(ProjectName)_TemporaryKey.pfx"
      call "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe" -New Deployment -AppManifest "$(TargetDir)$(TargetFileName).manifest" -Name "$(TargetName)" -Processor "$(PlatformName)" -Version @(Targets-&gt;'%(Version)') -ToFile "$(TargetDir)$(TargetFileName).application"  -Install "true"  -CertFile  "$(TargetDir)$(ProjectName)_TemporaryKey.pfx" -Publisher "ExxonMobil"
      call "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe" -New Deployment -AppManifest "$(TargetDir)$(TargetFileName).manifest" -Name "$(TargetName)" -Processor "$(PlatformName)" -Version @(Targets-&gt;'%(Version)') -ToFile "$(TargetDir)$(TargetName).ctp.application"  -Install "true"  -CertFile  "$(TargetDir)$(ProjectName)_TemporaryKey.pfx" -Publisher "YourCompany" -AppCodeBase "@(Targets-&gt;'%(Version)')\$(TargetFileName).manifest"

      echo \$(TargetName).ctp.application\ &gt; exclude.txt
      echo $(TargetFileName).application &gt;&gt; exclude.txt
      echo \MakeReadyFor.ctp.bat\ &gt;&gt; exclude.txt
      echo \exclude.txt\ &gt;&gt; exclude.txt

      echo mkdir "../LogAvailability_CTP/@(Targets-&gt;'%(Version)')" &gt; MakeReadyFor.ctp.bat
      echo xcopy . "../LogAvailability_CTP/@(Targets-&gt;'%(Version)')" /s/i/q/y/exclude:exclude.txt &gt;&gt; MakeReadyFor.ctp.bat
      echo xcopy "$(TargetName).ctp.application" "../LogAvailability_CTP" /s/i/q/y &gt;&gt; MakeReadyFor.ctp.bat

Well I got out yesterday and watched live in Houston, TX, my favourite sport, Basketball.  The Houston Rocket’s James Harden is a “beast”. He moved, crossed over and outshot the entire New Orleans roster. What a game.  Well, for those who love a good game now a then you can appreciate just watching great people shine.  Speaking of great people, if you’re interested in MVVM (Model-View-ViewModel) for WPF/MVC you need to take a look at my friend Mike Brown’s new book.  MVVM Unleashed.  This one is a must read. http://www.amazon.com/MVVM-Unleashed-Michael-Brown/dp/0672334380.

Of course, for the WPF Fans, I got a great little control for you to help with delaying inputs from a textbox. If you need to provide a search capability that delays a few milliseconds and then displays the results this quick control will help you tremendously.  It’s pretty simple, I added a Timer, if the user hits a button, it resets the timer.  If the use waits or delays a second or two the textbox is forced to call the OnTextChanged Event. 
Of course here is the code:  delaytextbox.zip

If you interested, these functions show what takes place if you hit any key.

protected override void OnKeyDown(KeyEventArgs e)
if (!IsTimerActive)

_keysPressed = true;
protected override void OnTextChanged(TextChangedEventArgs e)
// if the timer elapsed or text was changed by something besides a keystroke
// fire base.OnTextChanged
if (_timerElapsed || !_keysPressed)
_timerElapsed = false;
_keysPressed = false;
//save the last eventarg
_textchangedevent = e;

One challenge was the Recalling the OnTextChanged event after the timer elapses. I needed a true TextChangedEventArgs from the OnTextChanged event, without it I could not route the event back to the same instance of the class.  I fixed this by providing delegate called DelayOverHandler, then calling the Dispatcher.Invoke method to get back to the UI.  Using the _textchangedevent field also to sending the last event called on the OnTextChaneged event.

public delegate void DelayOverHandler(TextChangedEventArgs changed);

private void DelayTimerElapsed(object sender, ElapsedEventArgs e)
// stop timer.
_delayTimer.Enabled = false;

// set timer elapsed to true, so the OnTextChange knows to fire
_timerElapsed = true;

// use invoke to get back on the UI thread.
base.Dispatcher.Invoke(new DelayOverHandler(DelayOver), _textchangedevent);


private void DelayOver(TextChangedEventArgs changed)

Here how to use it in your WPF XAML file, notice the new DependecyProperty  DelayTime, beaware its in Milliseconds.