Nov/20
2014

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)
                {
                    try
                    {
                        next = enumerator.MoveNext();
                    }
                    catch
                    {
                        continue;
                    }

                    if (next)
                    {
                        yield return enumerator.Current;
                    }
                }
            }
        }
    }</t></t></t></func></ienumerable></tsource></func></ienumerable></tsource></tresult></func></ienumerable></tsource></func></ienumerable></tsource></func></ienumerable></func></ienumerable></tsource></tsource></tsource></func></ienumerable>
Apr/09
2014

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)
        {
 
            MessageBox.Show(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.

Apr/04
2014

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">
     </output></getassemblyidentity>
   </target>  
   <propertygroup>
    <postbuildeventdependson>
      $(PostBuildEventDependsOn);
      PostBuildMacros;
    </postbuildeventdependson>
    <postbuildevent>   
      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
    </postbuildevent>
  
</propertygroup>
Jan/03
2013

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)
{
StartTimer();
}
else
{
ResetTimer();
}

_keysPressed = true;
base.OnKeyDown(e);
}
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;
base.OnTextChanged(e);
}
//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)
{
this.OnTextChanged(changed);
}


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

<controls:DelayTextBox 
x:Name="PART_SearchTextBox"
DelayTime="1500"    
BorderBrush="DarkGray"
BorderThickness="1,1,0,0"
AcceptsReturn="True"
MaxLines="4"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"/>

 

Attachments:

Jan/02
2013

Traversing any data sets or hierarchical tables known as the parent-child relationships table can be extremely daunting task, that’s difficult to manage in a consistent approach. Most common approaches use recursion for traversing hierarchical sets. A term, if you have ever taken a 101 class in Object Oriented Programming, describes a procedure calling its self until an expression is reached. The challenge is not simply traversing data but traversing it so that the approach is consistent, multifaceted, and efficient through your application. As a C# developer my approach leans on this type of design approach, but I am confident any example I provide in this post is transferable into other coding languages. For a C# code file download the following: traverse.zip

 

Id

Name

Member

Parent Id

1

Josh

Teacher

Null

2

Aaron

Student

1

3

Kelvin

Student

1

4

Kory

Student

5

5

Michael

Teacher

Null

 

Simple, now let’s review my approach to traversing any list both forward and backwards to manage different types of recursive functions.

RunRecursiveOn function will traverse forward on any list of objects and when a list of children are found it continues to run on this internal list as well. Using a Delegate allows manipulation of each item traversed in the list. Passing a Delegate into this traversing function allows you to pull out what you may want to do with each member or item in the list.

 

public static void RunRecursiveOn(this IEnumerable list, Delegate callback, string traverseListName = "Children", params object[] args)
        {
            if (list != null)
            {
                foreach (object record in list)
                {
                    callback.DynamicInvoke(record, args);
 
                    if (record.GetType().GetProperty(traverseListName) != null)
                    {
                        IEnumerable children = (IEnumerable)record.GetType().GetProperty(traverseListName).GetValue(record, null);
                        if (children != null)
                            children.RunRecursiveOn(callback, traverseListName, args);
                    }
                }
            }
        }

 

RunRecursiveOff function will traverse backward on any list of objects and when a list of children are found it continues to run on this internal list as well. Using a Delegate allows manipulation of each item traversed in the list. Passing a Delegate into this traversing function allows you to pull out what you may want to do with each member or item in the list.

 

public static void RunRecursiveOff(this IEnumerable list, Delegate callback, string traverseListName = "Children", params object[] args)
        {
            if (list != null)
            {
                foreach (object record in list)
                {
                    if (record.GetType().GetProperty(traverseListName) != null)
                    {
                        IEnumerable children = (IEnumerable)record.GetType().GetProperty(traverseListName).GetValue(record, null);
                        if (children != null)
                            children.RunRecursiveOff(callback, traverseListName, args);
                    }
                    callback.DynamicInvoke(record, args);
                }
            }
        }

 

Not really complicated, but consistent and reusable. This approach should help support developers considering hierarchal data tables as a design approach.

How to use this:

SomeListOfItems.RunRecursiveOn(new Action(OnTarget2), null);

private static void OnTarget2(SearchResult obj, object[] arg2)
{
    obj.IsSelected = true;
}

This will change each item in the List to true

 

Attachments: