Windows Applications Development with Microsoft .NET Framework 4

I am prepping for my first .NET 4.0 upgrade exam (70-521) that I want to take in a couple of weeks.  I purchased the Microsoft “official” training kit and worked my way though it over the last 7 days.  In a word – “terrible”.  In two words – “really terrible”.  In three words – well, you get the idea.  Why do I think this book is a waste of time?

  • There are little, if any, code samples to explain a concept
  • The material is not cumulative, nor is there a unifying application/project to tie concepts together
  • The actual explanations are overly wordy and opaque
  • The code samples, when they exist, are examples of anti-practices.  Consider this nugget from the first chapter:
  • foreach(FontFamily F in Fonts.SystemFontFamilies) { ListBoxItem l = new ListBoxItem(); l.Content = F.ToString(); l.FontFamily = F; listBox1.Items.Add(l); }

(Yup, this was written by someone who considers themselves a professional programmer)

  • The book’s size is due to listing each enumeration value in chart form – basically unreadable.
  • The pictures are in black and white
  • Each chapter ends with helpful “exercises” like “Build a calculator program” or “Practice creating resources” without any guidance on how to do the task or any final answer to check against.

I ordered some other WPF books that were recommended – I’ll spin through them in the coming weeks.  Until then, I am just puttering around with WPF – which is my new BFF (sorry WF)….

Parallelism Labs From Microsoft

 

I did the PLINQ Lab this morning.  The lab itself is fairly short and givers a great overview of both the power of Parallelism and the ease of use in C#.  In addition, the last exercise shows how use Extension Methods on your IEnermable sources to further manipulate the data.  My only gripe is that the VM screen real estate is very small:

image

And you can’t change the resolution on the VM desktop to see more of the code.  The other gripe I have (only) is that the performance on the VM stinks – you literally wait 1-2 seconds after typing a character to see the intellisense to come up.  This kind of context delay makes it harder to retain the information in the lab.

I then started the Introducing .NET4 Parallel Extensions lab.  The screen delays were even worse so I took matters into my own hands.  I took some screen shots of the lab created a local project based on the starting solution.  One of the 1st tasks was to create a set of 20 random Employees.  Instead of hard-coding values into the list, and limiting the list to only 20 employees, I decided to create a random employee generator as a WCF Service.  That is the subject of this blog post

I had fun recreating the lab.  I then went through each exercise.  It did a good job explaining each of the aspects of Parallelism syntax.  I have 1 note and 1 gripe.  The note is that in the PLINQ,  you can see how the TaskManager split the dataset in two process  1 took the 1st 50% and process 2 took the last 50%.  Presumably, if I had a quad machine, it would be divided into four:

image

My 1 gripe has to do with the overuse of the ‘var’ keyword and the use of unreadable code in a public project.  Take a swing though this syntax:

            var q = employeeList.AsParallel()
                .Where(x => x.Id % 2 == 0)
                .OrderBy(x => x.Id)
                .Select(x => PayrollServices.GetEmployeeInfo(x))
                .ToList();
            foreach (var e in q)
            {
                Console.WriteLine(e);
            }

 

foreach(var e in q)??? Ugh!  A little more thought about variable names (q should be employeeListQuery, x should be employee, e should also be employee).  Oh well, the struggle continues…

Applying Domain Driven Design and Patterns

I read Applying Domain-Driven Design and Patterns over the last week.

clip_image001

Nilsson synthesized thoughts from pretty much every other book in the Fowler series and then gave his own spin on creating an enterprise-read application. The book is the first that I have seen for such an ambitious goal – actually applying DDD to a real-world example. I thought he did a good job in exploring the different possibilities when confronted with design decisions. In addition, he writing style was clear and on-point.

The only problem I have with his book is that some of the patterns he selected are out of date (not his fault at the time of his writing, his fault for not releasing a new edition). For example, he spends a whole lot of time with NHibernate (Chapter 8-9), which has been eclipsed by Entity Frameworks. Also, his implementation of a validation pattern is obsolete (chapter 7) with the new constructs in .NET 4.0. I would use the validation patterns found in the Scotts’ Nerd Dinner solution. In addition, he spends a lot of time with the implementation of the query object pattern – which is LINQ to you and me now.

Finally, the separation into a Factory and Builder pattern, although still accepted in some parts of the community, is too much SOC. I believe that a single factory that is responsible for the creation (rehydration or new) and updating of a class makes much more intuitive sense.

The two patterns that I am planning to implement in the my next POC application is the State pattern and the Specification Patten. His description and implementation was a guide for me to follow. I am leaning to re-writing the Hurricane solution using these patterns.

Test Driven Development by Example By Kent Beck

image

 

I spent some time working though TDD using C# over the last week. I thought the book was well-organized. Each chapter has small-enough chunks of logic broken down and demonstrating his points was great. Also, his wrap up at the end of the book had some really good pointers. I actually wrote his samples in C# twice. The 1st time I organized and coded my tests more along the lines of The Art of Unit Testing. However, many of his examples depend on multiple asserts in the same unit test and his naming and organization was so tightly coupled to the solution that I went through a second time and followed his testing code exactly (except for the differences between Java and C#). It made his story easier to follow – though I would not use his test naming and organization in a real project.

Some of his pointers I thought were useful:

  • Having the glass of water by your workstation to force you to take breaks (and it’s healthy too).
  • TDD is not TFD – though that is how Kent coded up his solutions. I am still in the camp that you create interfaces and stub out your classes using the built-in tools of VS2010 and then write your tests. You get all of the intelli-sense goodness with red-green-refactor paradigm intact.
  • I like Kent’s pragmatic approach to testing – tests are mutable and expendable. If they no longer have a use – get rid of them. Also, his iterative approach to development was spot on.
  • The advice about cheap desk and nice chair was made sense. It is amazing how those little things can add up to large productive gains.
  • “Failure is progress. Now we have a concrete measure of failure”
  • I follow Kent’s “Fake It” strategy for testing more often than not. I get the red, throw in anything to get green, and then slowly refactor to a better green.
  • Finally, TDD is the exact opposite of architectural-driven development (the mythical man month). You need to drive development with specification, tests, or hope. Everything you write code, you are using one of those three. You might as well be explicit in your choice…. Also, he mentions that TDD assumes that if you write better code, the more likely your project will be successful. That is often a faulty assumption…

Multiple Entity Framework Models in the same project

Continuing my journey though Entity Frameworks 4.0 Recipes, I have 1 EF Model in a project (Example 2-2). I then added a new model (example 2-4) with a different namespace.

image

Everything works fine.

I then added a third model with a different namespace

image

When I try and compile I get a bunch of nasty errors:

image

I double checked the properties of each of the second and third model – note that the namespace properties are different:

image

image

Seeing that they each shared the same Entity Container Name, I changed them and then ran into this error:

image

I then found my answer – I re-used the connection string. Unfortunately, there is context-specific information in the connection string. When I copy/pasted the connection string:

1 <add name="ProductEntities" 2 connectionString="metadata=res://*/Poetry.csdl|res://*/Poetry.ssdl|res://*/Poetry.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.;Initial Catalog=EFRecipies;Integrated Security=True;MultipleActiveResultSets=True&quot;" 3 providerName="System.Data.EntityClient" />

I found that .csdl, etc… were still referencing the original context. Changing that to the new context (or re-generating the model using a different connection string) did the trick:

image

Entity Frameworks 4.0 Recipes

I am working though Entity Frameworks 4.0 Recipes. I love the concept and the examples look great. I started on page 20 with and simple and select from EF. Here is the first code sample:

1 static void InsertData() 2 { 3 using (var context = new EFRecipiesEntities()) 4 { 5 var poet =new Poet {FirstName="John", LastName="Milton"}; 6 var poem = new Poem {Title = "Paradise Lost"}; 7 var meter = new Meter{MeterName="Iambic PentameterXXXX"}; 8 poem.Meter = meter; 9 poem.Poet = poet; 10 context.Poems.AddObject(poem); 11 context.SaveChanges(); 12 } 13 } 14 15 static void ViewDataFromTables() 16 { 17 using (var context = new EFRecipiesEntities()) 18 { 19 var poets = from p in context.Poets select p; 20 foreach (var poet in poets) 21 { 22 Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName); 23 foreach (var poem in poet.Poems) 24 { 25 Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName); 26 } 27 } 28 29 } 30 } 31

Some initial thoughts:

The misuse of the keyword var – it is everywhere.

He is using poor variable names, for example, “p”

I would re-write his select query as so:

1 static void ViewDataFromTables() 2 { 3 using (var context = new EFRecipiesEntities()) 4 { 5 ObjectSet<Poet> poetQuery = from poet in context.Poets select poet; 6 foreach (Poet poet in poetQuery) 7 { 8 Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName); 9 foreach (var poem in poet.Poems) 10 { 11 Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName); 12 } 13 } 14 15 } 16 } 17

Also, check out something wicked cool (or dangerous) from EF. I changed the insert to have a Meter Name that is not already part of the Meter table. Instead of throwing a referential constraint error when the new value came in, EF silently added it:

image

And once I run this:

 

1 static void InsertData() 2 { 3 using (var context = new EFRecipiesEntities()) 4 { 5 var poet =new Poet {FirstName="John", LastName="Milton"}; 6 var poem = new Poem {Title = "Paradise Lost"}; 7 var meter = new Meter{MeterName="XXX"}; 8 poem.Meter = meter; 9 poem.Poet = poet; 10 context.Poems.AddObject(poem); 11 context.SaveChanges(); 12 } 13 } 14

Here are the post-Insert values:

image

Eating the IT Elephant

I started reading Eating the IT Elephant two weeks ago based on its subtitle: “Moving from Greenfield Development to Brownfield.”

 

I am interested in anything regarding Brownfield development after reading Brownfield Application Development and finding it to be a great book.  Unfortunately, the word ‘Brownfield’ is the only similarity between the two books. 

Eating was written by a couple of IBM folks – and I have a pretty dim view of IBM’s products after being forced to use them on my day job (the fact that IBM’s growth strategy is in product development next year makes me laugh – they better keep feeding that Mainframe/Consulting Service monster…).  Undaunted about IBM black mark, I cracked it open.  I quickly became lost in their dense prose (almost academic paper-like quality), obscure points, and convoluted connective rational.  The authors might have some great things to say, but I could find any. They identify the common problems of why software projects fail (pretty much the same as all of the other software development books out there) and then devise some solutions (Views, Hilbert Space, buy more IBM products?) that I can’t understand. 

If you need to get something done, don’t read this book.  If you want to expand your mind in some kind of academic gymnastic exercise and have already done the crossword this morning, then have a go.

ASP.NET MVC2 In Action

I started working through ASP MVC2 In Action

 

A couple of nit-pciks

1) They abuse the var keyword and don’t follow best practices in terms of variable naming.  For example, on page 18:

            var model = new GuestBookEntry();

            return View(model)

 

Using var here is just lazy and using the variable “model” leads to confusion– it should be:

            GuestBookEntry guestBookEntry = new GuestBookEntry();

            return View(guestBookEntry);

 

Because that is what the controller is actually returning

2) They don’t fully-qualify the model on the views.  For example, on page 18 again:

<%@ Page Title=""

    Language="C#"

    MasterPageFile="~/Views/Shared/Site.Master"

    Inherits="System.Web.Mvc.ViewPage<GuestBookEntry>" %>

 

It should be

<%@ Page Title=""

    Language="C#"

    MasterPageFile="~/Views/Shared/Site.Master"

    Inherits="System.Web.Mvc.ViewPage<Com.Tff.GuestBook.Models.GuestBookEntry>" %>

 

I don’t know any way to NOT use the namespace using MVC (they must, unless their book code doesn’t compile OR they are putting everything in the same namespace – Ugh!)

I DO like the fact that they put line breaks in the View definition – it is much more readable.

Aside from the nit-picks, I have 1 larger beef.

I believe that having more models (DTOs, POCOs, whatever you want to call them) is better than have 1 uber-model that you shoe horn into all situations.  In fact, having a use-case specific model follows the single-responsibility principle very well.  I DON’T agree with the use of nested classes.  For example, on page 29 they recommend (constructor is mine – I put it in the get the View to match their screen shots)

    public class CustomerSummary

    {

public CustomerSummary(string name, string serviceLevel, string orderCount, string mostRecentOrderDate, bool active)

        {

            this.Name = name;

            this.ServiceLevel = serviceLevel;

            this.OrderCount = orderCount;

            this.MostRecentOrderDate = mostRecentOrderDate;

            this.Input = new CustomerSummaryInput();

            this.Input.Active = active;

        }

 

        public string Name { get; set; }

        public string Active { get; set; }

        public string ServiceLevel { get; set; }

        public string OrderCount { get; set; }

        public string MostRecentOrderDate { get; set; }

        public CustomerSummaryInput Input { get; set; }

 

    }

 

    public class CustomerSummaryInput

    {

        public int Number { get; set; }

        public bool Active { get; set; }

    }

 

Yuck!

There should be a CustomerSummary class and a CustomerInput class.  If you need to link the two – that is what primary keys are for (heck, they start that with the Number property in CustomerSummaryInput.  This nested class combines 2 different things (displaying the customer and getting new customer info).  If there needs to be a customer base class (FirstName, LastName, Active) and then derived classes with the ServiceLevel, etc…, that is much more cleaner.

 

 

Mythical Man Month and Software Project Survuval Guide

I finished two books over the last week.  The first is the Mythical Man-Month.  An oldie-but-goodie, it was surprising to me about how many problems that were written about in the last 30 years are still with us.  Of course, they are human problems and it is much easier to change a computer than a person.  Brooks’s hypothesis of Time Versus Number of Workers in a task with complex interrelationships is still spot on – and companies are still re-learning this lesson even today.  The interesting thing is that his solutions are not really relevant – most have been tried, modified, or discarded (the specialization of labor and the parallel documentation has been largely discredited) but the problems of conceptual integrity and communicating outside of the system are still with us.  I chuckled when he wrote “this technical fad of object oriented programming…”.

The other book I read was Software Project Survival Guide by Steve McConnell.  A PMP light read, this book is showing its age.  I enjoyed his discussion on how to treat developers and how to get them to avoid context switching (something my current employer still hasn’t figured out) and the stages in planning.  If I have to lead a project in an overly bureaucratic organization that is behind the curve in terms of industry best practices, I would certainly reach for this book.  If I have the ability to lead a project in an agile and flexible organization, this book would stay on the shelf.

Death March

 

I read Death March over the weekend.  There were some interesting points about  Death March projects:

·         There are a number of good, in fact, necessary reasons to work on Death March project.

·         The fact that the software industry employs many young people who have both the time and energy to work on a Death March project

·         The absolute necessity to get away from the overall bureaucracy when working on a Death March project – esp the methodology police, the physical plant police, etc..

·         The importance of negotiation in the project –esp with the stakeholders

·         The law of diminishing returns – after a certain point the overtime that is put in works to the detriment to the code base and the overall project. 

·         The team is critical – you need people who can and like to work together

·         I liked his suggestions to separate the team: “skunk works”, telecommute, and graveyard shift are all good ways to give the team a physical separation they need from the normal bureaucracy.

·         The most important point of the book: Triage.  All external constraints need to be filtered before they get to the project (including requirements!)   I liked his 80/20 rule – 20 of the “required” functionality will not be delivered, so triage to filter it out early.  The project will still be considered a success.

·         One more interesting point: the author seems to embrace XP (and many of the processes in Agile like daily/continuous builds, etc…) to solve Death March problems.  After reading this book, I would agree with him.