Isaac's profileIsaac's IT spacePhotosBlogListsMore Tools Help

Isaac's IT space

.NET and Windows software issues and comments...

Isaac Abraham

Occupation
Location
Interests
I work as a C# .NET software consultant / developer for an IT consultancy based in the centre of London.
View Isaac Abraham's profile on LinkedIn
June 29

Using LINQ queries instead of “for” loops

LINQ can easily replace for each loops, but when it comes to replacing old-style for loops, it’s a bit trickier – what exactly are you enumerating over? Nothing but a fictional set of integers.

Luckily the System.Linq.Enumerable namespace comes with a handy static method for just such these occasions. Consider the following code: -

var list = new List <int> ();
for (int i = 0; i < 10; i++)
    list.Add (i * i);

 

You can actually easily rewrite this as a LINQ query like so: -

var list = from i in System.Linq.Enumerable.Range (0, 9)
           select i * i;

 

The Range () method generates an IEnumerable <int> collection of sequential numbers as per the parameters passed in from which you can select data over.

I think it’s very nice :-)

June 08

Smart Client Software Factory – Day Two

So, I’ve managed to get through most of the problems and actually worked through a few of the labs! Some of what SCSF gives you seems quite good – a lot of the stuff that you do (or would like to do) in projects but generally do in a different way each time. Things like the following, which I have done in the last few projects in a bespoke manner that you get pretty much for free with SCSF: -

  • Model-View-Presenter framework
  • Commands / multicast delegates (nothing you don’t get in C# anyway except that you can do it quite elegantly using attributes on methods)
  • Decoupling between your form’s shell and inner modules / views
  • View management
  • Inter-view messaging

I’m sure that there’s lots more to see. But I’ve also found a few more annoying things about it: -

  • When you try to create a new View in VS2008 SP1, if your Infrastructure assembly is not named Infrastructure.Assembly but instead <root namespace>.Infrastructure.Assembly, the option won’t appear in VS! Why???
  • Namespaces of views that you create do not obey folder hierarchy rules e.g. a View + Presenter living inside MySolution/MyProject/Views/MyView should have a namespace something like MySolution.MyProject.Views.MyView.MyView.cs and MyPresenter.cs etc.. Instead, it’s simply in MySolution.MyProject. This is (IMHO) just plain wrong. VS automatically pads on the namespace for new classes based on the folder structure, so why doesn’t SCSF? Even worse, any other classes that you create will obey the “proper” rules so you end up with classes in the same folder with different namespaces!

So generally I think SCSF looks quite nice, albeit it seems like they haven’t updated it in a while and that it’s got a few issues with it that could have been fixed relatively easily but they just haven’t been bothered / had time (note – last version of SCSF WinForms was April 2008)??

June 05

Smart Client Software Factory Review - Day One

Its looking like we’re going to use Smart Client Software Factory (SCSF) 2008 as the UI framework for writing my next project. As part of that, I’m spending the next few days getting up to speed on SCSF (since I’ve never “really” used it before in anger)… here’s my thoughts as I go through the install process and the guiding SCSF Lab sessions…

12.15: OK. Firstly, the default install we have on my PC doesn’t work – when I try to create a new SCSF project type (Guidance Packages/Smart Client Development) it comes up with a warning about a missing registration to a VB dll – not a good start. Drop a colleague an email to ask about this… seems like it’s a known problem with our builds and I need to reinstall it.

12.25: Reinstalled the SCSF framework off the network.

12.30: Open up the Lab sessions word document, and successfully create a new Project.

12.35: Firstly thing I notice is that assembly Titles, assembly Names, and Namespaces in those assemblies do not match e.g.

  • Assembly name: AdventureWorks.Infrastructure.Shell
  • Namespace: AdventureWorks.Infrastructure.Shell
  • Assembly Title: Shell

Why is the Title not the same as the other two (Title is what you see in Solution Explorer)??

12.40: Following the instructions in the word document, I hit F5 to run the project. It crashes immediately:

Assembly file C:\Dev\AdventureWorksCyclesEx\bin\Debug\Infrastructure.Module.dll was not found.

I email a colleague again and then go for lunch.

13.45: I find out how to fix this problem – it’s actually related to that mismatch of assembly names etc..

There’s a config file called ProfileCatalog.xml which lists the different modules of your application. It puts in the Infrastructure module automatically, except it does it wrongly – it puts in the Assembly Title instead of it’s Name e.g. “Infrastructure.Module.dll” instead of “AdventureWorks.Infrastructure.dll”. Change this and it works:

<Modules>
    <ModuleInfo  AssemblyFile="AdventureWorks.Infrastructure.Module.dll"/>
</Modules>

14.00: Try to add a new smart part to the Shell, but the toolbox doesn’t yet have the controls in there, so I have to add them myself (Microsoft.Practices.CompositeUI.Winforms.dll).

14.05: I drag a Tab workspace onto the Form. Visual Studio complains that I already have a reference to the above WinForms dll. I have to remove the reference from the project and then it works. Why??

14.20: More problems with assembly references. It seems that the project by default references one version of the CompositeUi dlls whereas the one I added above is a different version, so I’m now getting version mismatches. I have to go through all the projects in the solution, remove the references to the old version and add the references to the new one.

To be continued…

May 27

Scott Guthrie’s talk on LIDNUG

Finished the webcast a couple of hours ago. Great session with lots of interesting questions and answers – thanks Scott!

The most important question from my point of view (and judging by the number of people that asked it, not just me – this was by far the most common one), was Scott’s take on Linq to SQL and how it sits alongside Entity Framework - and what’s the future of L2S. Whilst Scott doesn’t work directly on the ADO .NET team, he was able to largely answer this anyway:

L2S is definitely a part of the future of .NET and that they have no plans to kill it off (at the moment!). Microsoft see Entity Framework as hopefully taking a number of the best bits out of L2S and incorporating them into EF (which should be included in .NET 4), but they also plan on keeping L2S going, too. He also addressed for the much-publicised blog that the ADO .NET team put out which has been largely mis-interpreted by the public – they never meant to suggest that L2S is dead. He also mentioned that they will be putting a new blog post out in the near future addressing this issue further.

So, glad that’s been cleared up :-)

For what it’s worth – I see L2S as being an excellent ORM tool for rapid application development, small applications, prototypes etc. – essentially anything where you are working with e.g. a 1-to-1 mapping between your database and your domain model – whilst you might prefer to look at EF for more complex object models. However, from what I have seen of EF (which admittedly is not a great deal) and from other blogs out there, there’s still much work to be done on it before it’s going to be adopted by the majority of the L2S crowd.

May 24

VS2010 Professional Review Part 2 – Dynamic Typing in C#4.0

Visual Studio 2010 comes with the next version of C# – version 4.0. The most controversial feature of this version seems to be the dynamic typing features that are built on top of the DLR (also part of the .NET 4). No, that’s not the Docklands Light Railway – it’s actually the Dynamic Language Runtime. The DLR is a new layer that sits on top of the Common Language Runtime (CLR) in .NET and provides some of the sorts of features available in existing dynamic languages (Python, Ruby) in existing CLR languages such as C# and VB as well as some of the newer .NET languages that are appearing.

My (hugely limited) understanding of dynamic language are that they are primarily weakly typed languages i.e. little or no compile-time checking that e.g. you are accessing properties that exist or not etc.. Think how in JavaScript you can simply do something like assign a value to a property without having explicitly declared that property first etc.. In some languages, like Ruby, this is a fundamental part of the language and you can do things in those languages that look positively weird to a C# coder the first time you see them.

So, what is dynamic typing in the C# sense? Something like this (albeit a contrived example, as usual). Here are two classes, Employee and Person. They have nothing in relation in terms of class hierarchies:

class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
class Person
{
public string Name { get; set; }
public Gender Gender { get; set; }
public int Age { get; set; }
}
Suppose we wanted to print to the Console the Name and Age of all Persons and all Employees. We would probably write two methods which takes in either an Employee or a Person, which would print the Name and Age of either a Person or an Employee and let the compiler choose which method to call depending on the type of object we’re dealing with. Or we might have a single method which does an if / then statement on the type (ugly :-). Or maybe we’d have a single method which used reflection to get the two common properties out of these types and print the details:
 
static void PrintDetails(object detailsContainer)
{
object Name = detailsContainer.GetType().GetProperty ("Name").GetValue (detailsContainer, null);
object Age = detailsContainer.GetType().GetProperty("Age").GetValue(detailsContainer, null);

System.Console.WriteLine("{0} is {1} years old.", Name, Age);
}

Obviously, this is weakly typed – we’re passing in objects. At first glance, this is completely against what most C# coders have been taught to do. But consider – in some ways this is nicer than e.g. having two separate methods which do 99% the same thing – it’s easier to see what’s going on i.e. a single method which prints out the details of the object to the console rather than two methods which at first glance do the same thing. But the problems are: -
  1. Weak typing. Let’s leave this discussion for later on…
  2. The syntax to get the properties is ugly. Let’s deal with this now :-)

Reflection is Ugly!

Using reflection to get the value of a property isn’t hard to do in .NET, but it is a little strange to look at.

  1. Get the Type of the object you want to interrogate e.g. MyObject.GetType ();
  2. Get the PropertyInfo of the Property that you want e.g. MyType.GetProperty (“ThePropertyIWant");
  3. Get the Value from the PropertyInfo given a particular object of that type e.g. MyProperty.GetValue (MyObject, null);

So that’s a chain of three method calls to get any given property – at a glance, it’s all a bit "weird” to see what’s going on.

Here’s how we would write the same PrintDetails method in C# using Dynamic typing:

static void PrintDetails(dynamic detailsContainer)
{
System.Console.WriteLine("{0} is {1} years old.", detailsContainer.Name, detailsContainer.Age);
}

The main difference is the use of the “dynamic” type instead of “object” as the type of the method parameter. “dynamic” is a new type in C# which is in reality just plain old object. But it tells the compiler to not check any method invocations or property accessors until runtime, I presume using reflection (and you therefore get no intellisense when manipulating dynamic objects). So it’s no more or less weakly type than the reflection-based example, just a whole lot easier to read.

You can cast any type as Dynamic and then do what you want with it – but you can of course get this “wrong” e.g. if I called a property or method that did not exist, I’d get a runtime error – just like you would with reflection (Mike Taulty has a good blog posting about resolution of overloaded methods using dynamic types and overloads).

And just to clarify – dynamic is NOT the same as var! Dynamic is a 100% weakly typed object, you don’t even get the Object methods like ToString() and GetType on them (which every type has). Var is a always strongly typed object, even if it’s an anonymous type.

image image

Static versus Dynamic Typing

Coming from a C# or C++ background, you might be wondering “why do we want features like this? Isn’t statically typing better than dynamic typing?”. Well, the impression I get from some of the interviews with people involved in the development and evolution of .NET is that they see C# and VB .NET becoming more of a hybrid language in the future, offering “best of breed” features from static and dynamic languages, just as in C# 3 they took declarative features from e.g. SQL which became LINQ and merged them with imperative language features like for loops.

So, I think the answer to “is dynamic typing a good thing” is something like “yes, in its right place”. I wouldn’t expect us to chuck interfaces and class hierarchies etc. out of the window just because we can – but dynamic typing can be used in a few places in C# to make our lives a lot easier (and more readable!). Here are some examples: -

  • Making code more readable by hiding Reflection. Talking of reflection, a lot of the time (always?) you will be able to avoid using reflection-style calls to get properties and methods and simply use the dynamic features in C# 4 instead.
  • Interacting with dynamic languages. You can already have C# and VB .NET classes talk to one another, because they are both built on .NET. However, there are now some languages cropping up in the .NET world such as IronPython and IronRuby (I think?) which are .NET versions of Python and Ruby. So, in order to interact from the C# world with .NET assemblies written in those languages, you need to have support for dynamic typing in C#.
  • Talking to COM libraries. There are some great examples on the Internet showing how much easier it is to interact with COM methods using dynamic typing than using Reflection. If you’ve ever done COM interop, such as Excel or Word document manipulation, you’ll know that this is a nightmare – using the dynamic keyword makes your code a lot more readable! This is also especially useful when interacting with e.g. JavaScript in Silverlight.

However, there’s also a risk that people stop using "proper” static typing concepts such as interfaces and class hierarchies etc. simply because they cannot be bothered with it and using dynamic is “easier”. I’m not saying that this approach is something out of the “dark side” – I’m sure that there are times where it’ll be a real timesaver. And, provided you’re doing lots of good unit tests, you can probably get away with dynamic typing when required – but it’s not an excuse for breaking OO rules!

If you want to find out more about dynamic, there are some decent videos on Channel9 and MSDN – there’s one in particular by Anders Heijlsberg who goes through the feature in great depth – worth checking out.

 
ASP.NET 3.5 Ajax Unleashed
Pro WPF in C# 2008: Windows Presentation Foundation with .NET 3.5, 2nd Edition: Windows Presentation Foundation with .NET 3.5 (P
Visual Studio Team System: Better Software Development for Agile Teams (Microsoft .Net Development)
Agile Estimating and Planning (Robert C. Martin)
Scrum and XP from the Trenches
Extreme .NET: Introducing EXtreme Programming Techniques to .NET Developers (Microsoft.NET Development)
Agile Principles, Patterns, and Practices in C# (Robert C. Martin)
Code Complete: A Practical Handbook of Software Construction
XAML in a Nutshell (In a Nutshell (O'Reilly))
Thanks for visiting!
Please wait...
Sorry, the comment you entered is too long. Please shorten it.
You didn't enter anything. Please try again.
Sorry, we can't add your comment right now. Please try again later.
To add a comment, you need permission from your parent. Ask for permission
Your parent has turned off comments.
Sorry, we can't delete your comment right now. Please try again later.
You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
Complete the security check below to finish leaving your comment.
The characters you type in the security check must match the characters in the picture or audio.