Jonathan Birkholz

Virtual Brown Bag 10/22/09

Today was a great virtual brown bag. Claudio will have a more exhaustive list of what was discussed, but I thought I would share some links to stuff I talked about.

Creating a Generic Type using Reflection

http://geekswithblogs.net/marcel/archive/2007/03/24/109722.aspx

1
2
3
4
5
public static object CreateGeneric(Type generic, Type innerType, params object[] args)
{
System.Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
return Activator.CreateInstance(specificType, args);
}

StackOverflow Question from Marvin

http://stackoverflow.com/questions/1532991/help-with-a-windows-service-scheduled-task-that-must-use-a-web-browser-and-file-d

As Marvin and Claudio talked, I threw together an example on how I would solve the problem. Hopefully we can hear back from Marvin on whether it worked. :)

The code snippet is here : http://codesnippets.joyent.com/posts/show/2345

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var url = "http://www.codinghorror.com/blog/files/exported-font-and-colors-for-jeff-atwood-sept-19.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
var response = request.GetResponse();
var readStream = response.GetResponseStream();
var fileStream = new FileStream(@"C:\temp\dlZip.zip", FileMode.Create);
int readByte = readStream.ReadByte();
while(readByte != -1)
{
fileStream.WriteByte((byte)readByte);
readByte = readStream.ReadByte();
}
fileStream.Flush();
fileStream.Close();

Using StructureMap with Castle Dynamic Proxy for INotifyPropertyChanged AOP

For creating the DynamicProxy interceptor I based my code off of : http://serialseb.blogspot.com/2008/05/implementing-inotifypropertychanged.html

The entire solution can be found here : http://github.com/RookieOne/StructureMapAopNotify

All in all, a darn good Virtual Brown Bag. :)

My New Career at Code / EPS

It’s been over a week since I started at Code / EPS and I have to say I am loving it here.

My computer came in on Friday and I spent most of the day setting it up. Everyone knows the drill of installing Visual Studio, Office, third party tools, etc. It’s a ritual of blessing a new computer for programming work. The picture on the right was taken with my iPhone. The two 24 inch monitors are freakin awesome!

There are a lot of intangibles that make working at EPS fun and a perfect fit for me at this time. Sharing an office with Claudio is a huge perk. Having Markus as a boss is also a pleasant change. Most bosses can be disconnected from the current pulse on software development. Markus stays up to date and is also passionate about being cutting edge. Its nice working with people you respect and can learn from.

I also like that I am not working at the client. Having worked at the clients offices for several years, I began to dislike the random commutes, unknown work conditions, and random hardware configurations. :(

Here I have an office, with a window. I have a nice computer setup so that I can maximize my productivity. I know where I will be 2-3 months out. All in all, a nice change that adds peace of mind. I can now focus on my next phase in my career.

Catapult -> EPS

If you have not heard already, I am leaving Catapult Systems to go join the team at EPS Consulting.

Catapult Systems is a fantastic company. They are a NSI (National Systems Integrator) and have 12 Microsoft competencies. They were awarded the 2009 Microsoft Worldwide Partner Conference Award for Custom Development Solutions.

http://www.catapultsystems.com/About/News/Articles/Pages/CatapultSystemsWinsEliteMicrosoftWorldwidePartneroftheYearAward.aspx

I will have to put a little plug in here and say I was part of the team at Wisenbaker. :)

My departure has nothing to do with an exodus from Catapult. Catapult has positioned itself as a Microsoft Consulting company. I focus on Custom Application Development. What that means is I have very little interest in Sharepoint, EPM, Infrastructure, etc. I view selling and producing custom software products as a very different task than rolling out Windows 7.

I also really want to focus more on training, presenting, and overall community activity. While Catapult encouraged this behavior (particularly Mark Whitmire), it was all done outside my normal duties. With EPS and some changes Markus has in store, we hope to make that part of my duties and expectations.

My move is about my goals being slightly different than Catapult’s goals while EPS’s goals are more aligned with what I want to achieve. For example, at Houston TechFest I had some EPS coworkers come up and offer their support and advice. It was greatly appreciated. Their attendance and conversations made it clear they are pleased to have me on the team and are there to make me better at what I want to do.

I still have lots of good friends at Catapult : Ryan Riley, David Morton, John McPherson, Apollo Gonzalez, Rafael Perez, etc.

They have great ideas on revolutionizing the Application Development practice and I wish them the best of luck.

For me, I am really looking forward to working with the team at EPS. I’ve gotten to know Markus and Claudio (and others at EPS) over the past couple of months and am really impressed with them. This is my first time to be going to a company where I already know people (and respect their professionalism and skill level).

I will still be doing Virtual Brown Bags with Claudio and will now be in a situation where it should be easier for me to participate. Before I had to arrange rooms with the client and never knew if I could have privacy, etc. It was a pain.

My last day at Catapult will be Sept 30th. I then go on a brief vacation to Colorado to visit my Dad at the family mountain home. I come back on the 7th and start the new gig on the 8th. :D

Houston Techfest 2009

Wow! That was lots of fun! I got the chance to see and talk to a lot of my friends who I haven’t seen in awhile.

Also, it was nice to be finally finished with my two presentations. Both were fun but I will admit to liking my Evolve Your Code material a bit more than the WPF Input Validation. They were both a lot of work. Be sure to thank presenters. I knew work went into the presentations but I didn’t appreciate how much until I tried to do two. I learned a lesson with that decision. Never do 2 new presentations. It’s way too much work and both suffer from neglect. I will write a post on all my presentation lessons later.

Without the 2 presentations looming over me and my new job, I should be able to get back to blogging more. I love sharing what I know, even if its just to myself months from now when I forget everything. :)

For the slides I am trying out slideshare and am also using Git Hub for the slides and solutions.

Evolve Your Code:

http://www.slideshare.net/RookieOne/evolve-your-code

http://github.com/RookieOne/Evolve-Your-Code

WPF Input Validation:

http://www.slideshare.net/RookieOne/wpf-validation

http://github.com/RookieOne/WPF-Input-Validation

Monads

Ryan is the monad king. Ok.. well maybe not the king. But he has a big megaphone and drops a ‘monad’ bomb daily. He has been doing some fantastic work in F# and C# using monads. He shares his code and I just stare… going WTF is this!

I know the basic concepts of what a monad is mostly due to random discussions. I never put any solid research time into what it is… why I would use it… and where does it fit into the larger scheme of my personal development toolkit.

I started my adventure in learning where I normally start… wikipedia.

http://en.wikipedia.org/wiki/Monad_%28functional_programming%29

Whoa.. lots of new terms thrown at me. Here are some random notes and crazy thoughts I am pulling out (mostly for myself).

a monad is a kind of abstract data type used to represent computations (instead of data in the domain model)

That sparks some ideas. Anyone who talks to me on a regular basis knows I am a huge Greg Young CQS fan. I think I’ve always been circling around these ideas but Greg’s insights just pulled away the haze and brought into focus the essence of what always bothered me.

For more information on Greg Young’s CQS, I would suggest http://jonathan-oliver.blogspot.com/2009/03/dddd-and-cqs-getting-started.html

Jonathan has compiled a great set of links to get introduced to the ideas. I am by no means an expert, but I consider myself a CQS disciple. :)

Back to monads.

The idea of the ‘domain’ being a ‘computation’ or ‘action’ more than data makes me think there might be a connection to explore.

Monads allow the programmer to chain actions together to build a pipeline, in which each action is decorated with additional processing rules provided by the monad.

This makes me think of the ‘reconstruction’ of a domain object by processing its events. That would be a neat POC to put together.

The return operation puts a value from a plain type into a monadic container of type M. The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline.

I am still unclear on the whole wrapping business. I think I will revisit this again after going to another location to learn about monads.

So I moved over to Channel 9 and began to watch:

http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-The-Zen-of-Expressing-State-The-State-Monad/

Here are some random notes / quotes:

Only two types of variables. A bound variable and a free variable. Bound variable is a function argument. A free variable has to be looked up somewhere else.

State monad takes a state and spits out a state, content pair.

Composition is good :)

Mathematics is the art of abstraction and precision

Is functional programming and monads a disruptive technology? Although it technically isn’t that ‘new’. I think it might be. The comments around an army of OO programmers and the difficulty for learning to think functionally just resonates with the idea that functional programming is a disruptive technology (even though functional programming isn’t new).

Ok… That was a pretty rough first day. Lots of terms and pictures and strange code thrown my way. It’s time to process the information. I’m pretty sure I will need to watch that video about 5 times in-between coding this stuff. I plan on trying Brian’s exercises along with watching ‘Don’t Fear the Monad’ (another Brian Beckman presentation).

Ryan already has completed the first exercise in C# and F#. I will work on my own version of the C# exercise and then look at his code. I don’t think I will dive into F# right now. I played with the language about 2 weeks ago but all I did was create ‘Hello World’. There is a F# user group meeting on August 27th where I ‘might’ try to code these exercises.

How Do I Hide Columns With a Wpf GridView

In my current project we ran across a problem where we wanted to hide certain columns in a grid view based on domain criteria.

We looked into custom grid headers, attached properties, custom controls, etc. Every path lead to a very complex and more importantly custom solution.

I spent an afternoon playing around and came up with this solution which we are using today.

It’s simple, easy to follow, and doesn’t require any custom code. All it uses is the power of style and triggers. The biggest knock is OH NOES! you have a bit of duplication in your xaml.

What is it?

Well, you set the ‘View’ property in your style. Then you utilize style triggers to swap out the View.

Yup.. easy.. simple… no mess.

Example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<Style x:Key="listViewStyle" TargetType="ListView">
<Setter Property="View">
<Setter.Value>
<GridView>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Salary"
DisplayMemberBinding="{Binding Salary}" />
</GridView>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding HideCols}" Value="True">
<Setter Property="View">
<Setter.Value>
<GridView>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}" />
</GridView>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>

Virtual Brown Bag Summary 8/6/09

Today’s Brown Bag was lots of fun.

Claudio was off educating the masses (I believe in Denver when I talked to him last). I gladly picked up the MC duties again. Although I love doing it, there is a good deal of stress preparing for the brown bag.

Will people show? Will I have to talk all by myself? What the hell am I going to say?!

But today went great. I read Matthew Podwysocki’s blog post Spec# and Boogie Released on CodePlex and decided I would do a brief demo of Spec#. I spent around 30-40 minutes just playing with the older version of Spec# I found at the Microsoft Research site in preparation for the BB.

I was surprised at how much I picked up. Granted I have played with CodeContracts before so I was familiar with some of the concepts. Design by Contract is definitely a new school of coding thought. Its taking some time for me to assimilate the termniology and intentions. I know I have barely begun the journey necessary to fully understand and leverage this coding methodology.

For the BB, I just opened a Spec# Console project and we just started to code the stuff I learned just 30 minutes ago. I think it went well. We played with the non-null ! … we set the reference types to default to non null. We setup some pre-conditions using ‘requires’ and tested some post conditions with ‘ensures’. We didn’t really use ‘modifies’ and our one attempt at invariant worked for a simple scenario but failed with another scenario.

I forgot to record the BB. So I plan on using the new 2009 release of Spec# and doing a screencast covering the same material. At least we can record the same material if not the exact BB.

Thanks to everyone who attended and especially those who asked questions! I hope to chat with you guys again next week. I always look forward to Brown Bag Thursdays!

MVVM - the No Code Behind Challenge

Glenn Block has an excellent post titled “The spirit of MYYM, it’s not a code counting exercise”. The post can be found at CodeBetter.

I thoroughly enjoyed the post and greatly appreciate practical discussions on WPF/SL application patterns. I am a bit of a WPF nut having lived and breathed xaml for over 2 years. I’ve been a part of 2 successful WPF projects (both in production). In both scenarios I acted as the defacto WPF guru.

This last project was a typical line of business application and we used the ViewModel pattern with Prism. I bring all this up to share my background with WPF and ViewModels.

Concerning the content of the post, I agree with Glenn on the majority of the content. The Commands and Parameters especially rings true. I found that whenever I went with option A [using element binding to a command parameter] I ended up refactoring it to option B [binding the ‘selected’ item to a property on the ViewModel]. Although a neat use of xaml, in practice the binding to the property just allowed more flexibility that indubitable becomes necessary with future changes and demands (not to mention testing opportunities).

With both projects we didn’t have the luxury of a full time designer. In both scenarios I argued there was plenty of work for a designer, but alas the resources just weren’t there. We were able to use a designer for a decent chunk of hours, but more could have been done. The applications were definitely better off for having every hour we could get from any designer resource. I believe the last project persuaded many that indeed there was enough work for a full time designer, so maybe I can hope for a designer with a future application.

I say this because I can not speak towards what its like having a designer in Blend all the time working on Views. When we used a designer resource, they would work in Blend and then a go-between developer / designer would take the xaml and integrate it with our ResourceDictionaries.

What I would like to address is the ‘no code behind’ philosophy compared to the code behind practicality.

Two years ago when I was floundering for WPF information and blogs, I ran across a blog post (I want to say it was Josh Smith) where the writer stated something like : “if something is easier to do in the code behind then its okay to do it in the code behind.”

He was arguing that a crap load of xaml vs a couple lines of code behind isn’t an argument at all. The code behind is the best choice. Naturally clearer intentions and code maintainability takes precedence over having a dogmatic “everything in xaml” approach.

With this last LoB Prism application, we had some choices to make when we were deciding on how the client should be made up.

Do we use UserControls as Views or (as Ryan Riley brought up) do we use Data Templates as views. I felt at the time the team wasn’t ready for that leap to Data Templates as views. I considered the code behind of a User Control as a placebo safety net for a team struggling with the WPF learning curve. What I did do was firmly encouraged a no code behind policy. A “no code behind” challenge if you will.

If I were to go back to the beginning and make that View decision again, I would go with the Data Templates as views. The team did very well without using the code behind. A Data Template view would have brought more benefits than the cost of having no code behind. Often we found ourselves thinking.. if this view was a data template and not a user control, then we could more easier do X.

I have championed the “no code behind” stance internal to Catapult and to other developers. Yes you can legitimately use the code behind to accomplish certain tasks. More often than not though (in my experience), the use of the code behind has more to do with the prejudices carried over from WinForms development. Having a strict no code behind stance forces developers to learn and change the way they think about coding functionality into the UI.

Glenn came up with a scenario (albiet a overly simplified one) of where he felt a code behind had some value. The scenario described is:

‘”The user clicks a Save button on the Edit Order screen which requires some UI cue to the user such as an hourglass while the order is saving, and another cue once the Order has saved.”

He argues that the code in the xaml is less testable. He even suggests the solution I made. He also recognizes others my disagree. Count me in the disagreement camp.

I created a simple project that uses Attached Dependency properties to accomplish this simple scenario. This isn’t a “throw down the gauntlet” sort of thing and I didn’t really write it for Glenn. A coworker emailed Glenn’s blog and I responded in an email describing my solution. He then asked to see it in action. So I coded it up.

He also asked me to post a comment on Glenn’s post, but I don’t really see the point especially since I agree with the information Glenn is sharing and his opinions are built on experience & expertise. I really had no disagreement and the solution Glenn already knows of. /shrug

Anyway.. you can find the solution here : http://github.com/RookieOne/AttachedAnimation/tree/master

How to Bind Custom ICommands to Input Bindings

If you are developing using any sort of V-VM-M pattern, you are already loving the awesome binding powers of Wpf.

And you should also be loving ICommand and binding buttons to ICommand properties on your VM.

What you might have discovered is that binding ICommands to Keys and other input gestures is not as easy as it was with vanilla Routed Commands.

But have no fear! There is a solution.

By utilizing Josh Smith’s Element Spy trick and creating a custom InputBinding, we can gain the functionality of binding an ICommand to a Key, etc.

Here is my custom input binding :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class MyInputBinding : KeyBinding
{
#region Fields
private static readonly DependencyProperty BoundCommandProperty =
DependencyProperty.Register("BoundCommand",
typeof (ICommand),
typeof (MyInputBinding),
new PropertyMetadata(OnBoundCommandChanged));
#endregion
#region Properties
public ICommand BoundCommand
{
get { return GetValue(BoundCommandProperty) as ICommand; }
set { SetValue(BoundCommandProperty, value);}
}
#endregion
#region Methods
private static void OnBoundCommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
MyInputBinding binding = obj as MyInputBinding;
if (binding == null) return;
binding.Command = e.NewValue as ICommand;
}
#endregion
}

Then when you combine the use of the ElementSpy, your xaml looks like:

1
2
3
4
5
6
7
8
<Window.Resources>
<InputBindingSandbox:ElementSpy x:Key="spy" />
</Window.Resources>
<Window.InputBindings>
<InputBindingSandbox:MyInputBinding BoundCommand="{Binding Source={StaticResource spy},
Path=Element.DataContext.MyCommand}"
Key="Enter" />
</Window.InputBindings>

Naturally the custom input binding is very simple and does not expose the Command Parameter nor the Command Target, etc. But the basic pattern is there so feel free to utilize and extend.

Happy coding!

ItemsSourceChanged Event Using Attached Dependency Properties

If you stumble across this blog, you might have been searching for the non-existent ItemsSourceChanged event on a ListBox or ListView in Wpf.

Yeah… it isn’t there and it sucks.

But, there is a workable that I wouldn’t define as a hack. More of a Wpf extension. :D

I am a huge fan of Attached Dependency Properties. They are a perfect tool to extend the functionality of closed controls. Attached Dependency Properties also circumvent the pain of created your own custom control.

I am going to use an attached dependency property to mimic an ItemsSource Changed event.

The full code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/// <summary>
/// ItemsSourceChanged Behavior uses an Attached Dependency Property
/// to add and raise a rotued event whenever an ItemsControl's ItemsSource property
/// changes. Also looks for INotifyCollectionChanged on the ItemsSource and raises the
/// event on every collection changed event
/// </summary>
public static class ItemsSourceChangedBehavior
{
/// <summary>
/// ItemsSourceChanged Attached Dependency Property with Callback method
/// </summary>
public static readonly DependencyProperty ItemsSourceChangedProperty =
DependencyProperty.RegisterAttached("ItemsSourceChanged",
typeof(bool), typeof(ItemsSourceChangedBehavior),
new FrameworkPropertyMetadata(false, OnItemsSourceChanged));
/// <summary>
/// Static Get method allowing easy Xaml usage and to simplify the
/// GetValue process
/// </summary>
/// <param name="obj">The dependency obj.</param>
/// <returns>True or False</returns>
public static bool GetItemsSourceChanged(DependencyObject obj)
{
return (bool)obj.GetValue(ItemsSourceChangedProperty);
}
/// <summary>
/// Static Set method allowing easy Xaml usage and to simplify the
/// Setvalue process
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="value">if set to <c>true</c> [value].</param>
public static void SetItemsSourceChanged(DependencyObject obj, bool value)
{
obj.SetValue(ItemsSourceChangedProperty, value);
}
/// <summary>
/// Dependency Property Changed Call Back method. This will be called anytime
/// the ItemsSourceChangedProperty value changes on a Dependency Object
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnItemsSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
ItemsControl itemsControl = obj as ItemsControl;
if (itemsControl == null)
return;
bool oldValue = (bool)e.OldValue;
bool newValue = (bool)e.NewValue;
if (!oldValue && newValue) // If changed from false to true
{
// Create a binding to the ItemsSourceProperty on the ItemsControl
Binding b = new Binding
{
Source = itemsControl,
Path = new PropertyPath(ItemsControl.ItemsSourceProperty)
};
// Since the ItemsSourceListenerProperty is now bound to the
// ItemsSourceProperty on the ItemsControl, whenever the
// ItemsSourceProperty changes the ItemsSourceListenerProperty
// callback method will execute
itemsControl.SetBinding(ItemsSourceListenerProperty, b);
}
else if (oldValue && !newValue) // If changed from true to false
{
// Clear Binding on the ItemsSourceListenerProperty
BindingOperations.ClearBinding(itemsControl, ItemsSourceListenerProperty);
}
}
#endregion
#region Items Source Listener Property
/// <summary>
/// The ItemsSourceListener Attached Dependency Property is a private property
/// the ItemsSourceChangedBehavior will use silently to bind to the ItemsControl
/// ItemsSourceProperty.
/// Once bound, the callback method will execute anytime the ItemsSource property changes
/// </summary>
private static readonly DependencyProperty ItemsSourceListenerProperty =
DependencyProperty.RegisterAttached("ItemsSourceListener",
typeof(object), typeof(ItemsSourceChangedBehavior),
new FrameworkPropertyMetadata(null, OnItemsSourceListenerChanged));
/// <summary>
/// Dependency Property Changed Call Back method. This will be called anytime
/// the ItemsSourceListenerProperty value changes on a Dependency Object
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnItemsSourceListenerChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
ItemsControl itemsControl = obj as ItemsControl;
if (itemsControl == null)
return;
INotifyCollectionChanged collection = e.NewValue as INotifyCollectionChanged;
if (collection != null)
{
collection.CollectionChanged += delegate
{
itemsControl.RaiseEvent(new RoutedEventArgs(ItemsSourceChangedEvent));
};
}
if (GetItemsSourceChanged(itemsControl))
itemsControl.RaiseEvent(new RoutedEventArgs(ItemsSourceChangedEvent));
}
#endregion
#region Items Source Changed Event
/// <summary>
/// Routed Event to raise whenever the ItemsSource changes on an ItemsControl
/// </summary>
public static readonly RoutedEvent ItemsSourceChangedEvent =
EventManager.RegisterRoutedEvent("ItemsSourceChanged",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(ItemsControl));
#endregion
}

By setting the ItemsSourceChanged property on any ItemsControl to true, the ItemsSourceListener property will be bound to the ItemsSource property. The ItemsSourceListener callback will be executed anytime the ItemsSource changes and therefore can raise the ItemsSourceChanged routed event.

Also if the ItemsSource implements INotifyCollectionChanged, I added a delegate so that on the CollectionChanged event, the ItemsSourceChanged event will also be raised.

Feel free to use the code and adapt it to your needs.

Peace out!