Tech Tock

Time is of the essence.

the async we’ve been awaiting for

Watched the build async await talk.  Async await does look like the finally Task++ answer to asynchrony and the syntax is as I expected and better.  Funny thing about the video is that the occasional applause makes it sound like an infomercial.

Its new in .Net 4.5 but you can use it in .Net 4 with this Targeting Pack.

 

February 4, 2013 Posted by | Uncategorized | | Leave a comment

Freakin’ Moq

While I, like many developers,  appreciate Moq immensely, its not perfect.

Here’s an interesting way to freak out Moq 3.1:

It seems that if you use a 2 dimensional array as a parameter (a common scenario in fixed income) Moq will throw an error when accessing the Moq’d object.

This code:

public interface IFreakOutMoq { void FooBar(string[,] Strings); }

var badMock = new Mock<IFreakOutMoq>();
var badMockObj = badMock.Object;   //exception here

Will throw one of these exceptions (I’ve seen both on different systems):

System.TypeLoadException: System.TypeLoadException: Signature of the body and declaration in a method implementation do not match.

System.TypeLoadException: Method ‘FooBar’ does not have an implementation..

A simple solution is to use a Moq friendly object instead of the 2D array:

public class TwoDArray<T> {
private readonly T[,] _array;

public TwoDArray(T[,] array)     {    _array = array;     }

public T this[int x, int y]     {         get { return _array[x, y]; }     }
public T[,] Array     {         get { return _array; }     }   }
}

Here’s a test class that shows a working and failing example:

using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using TestProject;   namespace TestProject {   /// <summary> /// an array implementation that doesn't ///     freak Moq out on MockObj.Obj /// /// if you put a 2d array as a param and call mockedObj.Object /// moq will throw exception: ///     System.TypeLoadException: System.TypeLoadException: ///             Signature of the body and declaration ///             in a method implementation do not match. ///     or  System.TypeLoadException: Method 'FooBar' ///             does not have an implementation.. /// /// this object can be used instead and moq is fine /// </summary> /// <typeparam name="T"></typeparam> public class TwoDArray<T> {
private readonly T[,] _array;       public TwoDArray(T[,] array)     {         _array = array;     }
public T this[int x, int y]     {         get { return _array[x, y]; }     }
public T[,] Array     {         get { return _array; }     }
}   }
/// <summary> /// mocking this interface causes: /// System.TypeLoadException: ///         Method 'FooBar' in type ///         'IFreakOutMoqProxy2dec23fc008646958fc3bae70cbe067b' ///         does not have an implementation.. /// </summary> public interface IFreakOutMoq { void FooBar(string[,] Strings); }     public interface IMoqOK { void FooBar(TwoDArray<string> Strings); }   /// <summary> /// Summary description for UnitTest1 /// </summary> [TestClass] public class UnitTest1 {   [TestMethod] public void TestMethod1() {
var goodMock = new Mock<IMoqOK>();
var mockObj = goodMock.Object;
var badMock = new Mock<IFreakOutMoq>();
var badMockObj = badMock.Object; //exception will be thrown here
Assert.IsNotNull(mockObj);
Assert.IsNotNull(badMockObj);   } }

September 9, 2010 Posted by | Uncategorized | , , , | Leave a comment

How To Kill Regions

If you are as annoyed by regions as I am do this in Visual Studio 2008:

Tools / Options / Text Editor / C# / Advanced

Uncheck “Enter outlining mode when files open”

August 16, 2010 Posted by | Uncategorized | , | Leave a comment

4 C# Things You Might Not Have Heard Of

Partial Interfaces

Just learned that Interfaces can be partial.  Not sure how I’ll use this info but it is interesting.

This compiles:

namespace NameSpace
{
    partial interface IInterface
    {
    }
    partial interface IInterface
    {
    }
}

Partial Methods

Some folks were unaware that methods can be partial.  But I’ve seen this in my favorite DAL for quite a while.  Its seems most useful in (usually autogenerated) shared code situations as a replacement for virtual functions.  Code calling a partial method is removed from the compiled binary if the method isn’t implemented.  In that way it seems somewhat similar to events as well.

        partial void OnMyMethod();
        private MyMethod()
        {
            OnMymethod();
        }

If OnMyMethod were virtual or an event call, the functionality would be very similar.

Assignment Is A Value

The return value of an assignment expression is the assigned value itself.

            //set both x and y = 5
            int x = (y = 5);

I saw this feature years ago in C/C++ but never thought of using it in C#.

Coalesce

Here’s a use for the return value of assignment with the C# null coalescing operator (another little known feature – coalesce will return the first non null value).  This compresses the code for a common operation while (some would argue) not losing clarity.

private object _aProperty;
public object AProperty
{
    get { return _aProperty ??
            (_aProperty = new object()); }
}

January 23, 2010 Posted by | Uncategorized | , , | 3 Comments

Functional Homework

MejerTShirtAs I mentioned last month, I want to learn a functional programming language.  Lucky for me, Dr. Erik Meijer (and his electric t-shirt) gave a course on Haskell in October and its posted on Channel 9.

I watched the first lecture over a week ago but haven’t had time to do the homework till now.

Here it is in C#.  Its quicksort written as he described it in Haskell.  It doesn’t feel that different from the programming I usually do, but it is recursive (which I generally avoid), so maybe that’s something.  At least I did my homework, now I can go on to the second lecture :).

As long as I was making a program, I figured I’d expand my WPF horizons and used an attached behavior for the button.  Of course its MVVM which is just a habit now.

Attached Behaviors

It wasn’t obvious how to link the static attached behavior to the instance properly.

A guy on StackOverflow recommended getting the DataContext from the sender in the event:

private static void ButtonOnClick(object sender, RoutedEventArgs args)
{

var fxElem = sender as FrameworkElement;

var vm = (VM) ((FrameworkElement)args.OriginalSource).DataContext;

Most other explanations of attached behaviors are limited to working with the control itself and not the ViewModel:

http://eladm.wordpress.com/2009/04/02/attached-behavior/
http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

You can download the code here.

image

Here’s the homework code:

public  IEnumerable<IComparable>
    Sort(IEnumerable<IComparable> listToSort)
{
    if (listToSort == null)
        throw new InvalidOperationException
            ("Cannot sort a null list.");
    if (listToSort.Count() == 0)
        return listToSort;
    var result = new List<IComparable>();
    var start = listToSort.First();
    //smaller on left
    result.AddRange(Sort(listToSort.Skip(1)
        .Where(e => e.CompareTo(start) <= 0)));
    //val in middle
    result.Add(start);
    //larger on right
    result.AddRange(Sort(listToSort.Skip(1)
        .Where(e => e.CompareTo(start) > 0)));
    return result;
}

Here’s some highlights of the attached behavior class:

public static class SortStarter

{

// // RegisterAttached for attached behaviors

public static readonly DependencyProperty SortBehaviorProperty =

DependencyProperty.RegisterAttached(“SortBehavior”, typeof(bool), typeof(SortStarter), new UIPropertyMetadata(false, SortBehaviorChanged));

// Get/Set Methods for the attached behaviors:

public static bool GetSortBehavior(DependencyObject obj){

return (bool)obj.GetValue(SortBehaviorProperty);}

public static void SetSortBehavior(DependencyObject obj, bool value){

obj.SetValue(SortBehaviorProperty, value);}

// Method to hook the event

private static void SortBehaviorChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args){

var button = dpo as ButtonBase;

if (button != null){

if ((bool) args.NewValue)

button.Click += ButtonOnClick;

else

button.Click -= ButtonOnClick;

}

// Button Click Handler:

private static void ButtonOnClick(object sender, RoutedEventArgs args){

// Don’t process calls from up the visual tree

if (!Object.ReferenceEquals(sender, args.OriginalSource))  return;

//get VM from DC

var fxElem = sender as FrameworkElement;

var vm = ((FrameworkElement) args.OriginalSource).DataContext as VM;

// process with VM and new Sorter class

}

Hooking up the button in XAML is simple:

<Window x:Class=”WpfApplication1.Window1″

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

xmlns:local=”clr-namespace:WpfApplication1″

Title=”Window1″ Height=”129″ Width=”300″>

<Button local:SortStarter.SortBehavior=”True” >Sort</Button>

December 26, 2009 Posted by | Uncategorized | , , , | 1 Comment

“Throwing exceptions can negatively impact performance” – Believe it.

I was parsing a ton of strings (don’t ask) and catching FormatException (a lot).  By a ton, I mean several hundred thousand parsed into dates and doubles. By a lot of exceptions, I mean 90% of the data was blank.  Let’s just call it sparse.  The process was taking about 30 seconds.  I changed the code to avoid the FormatException:

    if (!string.IsNullOrEmpty(value))
    {
        o = double.Parse(value);
    }

Performance improved by at least 10 times to under 3 seconds.  Problem solved.

Turns out this is a bona fide pattern.  The tester-doer pattern.

December 1, 2009 Posted by | Uncategorized | , , , , , , | 3 Comments

C# beats C++ in Job Market. Both lose to Java

The number of jobs on Dice for C# is now higher than the number of jobs for C++.  They were about even last year, but it seems C# has taken the lead and C++ is on the decline.  C# fans rejoice.  On the other hand Java has as many postings as C# and C++ combined:

C# 5,014
C++ 4,532
Java 10,568

November 20, 2009 Posted by | Uncategorized | , , , | Leave a comment

LINQ Group By With Multiple Aggregates

It appears that LINQ does not support a query that outputs multiple group by aggregate fields.  For example, there’s Min() and a Max() functions, so to get both min & max from a list, you seem to need to make 2 LINQ queries:

 var min = (from d in data select d).Min();
 var max = (from d in data select d).Max();

In SQL, the 2 values would pop out easily from a single query:

 Select min(d), max(d) from data

LINQ has all the power of SQL and works similarly, just the syntax is different.  To achieve this result we have to use a group by.  But we’ll be grouping by nothing, including all items in the set in a single bucket. I usually group by “1”, which makes a single grouping of all the elements (grouping by any single object will do the same):

 var minMax = from d in values
    group d by 1 into g
    select new { Min = g.Min(x => x),
     Max = g.Max(x => x) };

 

minMax.First() now contains the min and max for the set of values.

November 18, 2009 Posted by | Uncategorized | , , , , , , , , , | 7 Comments

LINQ To C# – Drop Dead

What’s up with no edit & continue support for methods with Lambda Expressions(mostly from LINQ queries).

Error    7    Modifying a ‘method’ which contains a lambda expression will prevent the debug session from continuing while Edit and Continue is enabled.

Originally this post was going to be “LINQ Vs. Edit and Continue”, but then I found this article on MSDN saying how it works just fine in Visual Basic.  Visual Basic!  WTF!!!

The details for VB are a little cagey though:

You can add or remove code before the LINQ statement…. Your Visual Basic debugging experience for non-LINQ code remains the same as it was before LINQ was introduced.

Does this mean if you add or remove code after a LINQ statement it stops edit and continue, or does this mean MSDN needs a better editorial staff?  The “before” seems to cast doubt on the statement that “debugging experience for non-LINQ code remains the same ”  Not that I really care since I like my languages with curly brackets.

If you want to know what you can’t do in C# edit and continue, read this article.  I personally have no interest in what I can’t do. I only want to know when I’ll be able to do it and I couldn’t find any articles on that.  I heard from a friend that its not fixed in C# 4.0.   😦

LINQ is too good to give up, but this is really getting annoying.

I’m almost (getting this close) ready to make my own solution, or horrors, switching to VB.

November 18, 2009 Posted by | Uncategorized | , , , , , , , , , , , | Leave a comment

Charting Update – XCeed Still Going Strong in 3D

I overcame the 3D charting slowness by (duh) changing the point style to inverted pyramid from sphere. Obviously, the graphics hardware (I hope its in hardware) is drawing tons of polygons to show tiny spheres and only a few for pyramids. Why inverted? I don’t really know, but my best guess is that it has to do with lighting and shading, which I’m sure to investigate one day soon. Funny that these tiny dots (up to 22,000 now) are trying to draw themselves in 3D when I can barely see them.

Funny enough, the speed advantage is not apparent on the old MacBook I was planning to demo on.  If I had tried this on the wrong machine, I never would have known it works.

November 12, 2009 Posted by | Uncategorized | , , , , , , , | Leave a comment