Tuesday, December 30, 2008

Windows Presentation Foundation Unleashed (WPF) by Adam Nathan

I have read (or tried to read) other WPF books but this one is by far the easiest one to learn from, both in terms of readability (the colors really make a difference) and contents. It feels like each page has a gem of information. If I were to buy only one book about WPF, this would be the one.

Friday, December 26, 2008

Unity

I am trying to use the Composite Application Guidance (aka Prism or Composite WPF) for an application at work. It all sounded very interesting and easy to use, but when the rubber hit the road it turned out that I needed to be educated in some of the concepts it uses. For instance, I was not familiar with Dependency Injection. Prism uses Unity as the DI container and I thought I'd highlight some examples on how to use the Unity container:

Type Mapping - registered class:

container.RegisterType<IModule, ConcreteModule>();
IModule ModuleA = container.Resolve(<IModule>);


The first line is a type mapping. Anytime you need IModule, the container will return a ConcreteModule. the ModuleA object will have an instance of ConcreteModule.


Type Mapping - non-registered class:

The following class needs an instance of IModule:

Class ModuleA
{
ModuleA(IModule module)
{
...
}
}

Using Unity you can do the following:
container.RegisterType<IModule, ConcreteModule>();
ModuleA modA = container.Resolve<ModuleA>();


The first line is a type mapping. Anytime you need IModule, the container will return a ConcreteModule.
The second line requests a new instance of ModuleA. ModuleA is not registered with the container. But Unity will look at ModuleA's constructor and see that it needs a IModule. It will then inject an instance of ConcreteModule because of the 1st line's mapping.

Type Mapping - Singleton:
container.RegisterType<IModule, ConcreteModule>(new ContainerControlledLifetimeManager());
Every time you ask for an new instance, the same one is returned.

Named instances:
container.RegisterType<Database, SQLDatabase>("Sql");
container.RegisterType<
Database, OracleDatabase>("Oracle");
This will register two mappings of type Database and name these mappings for future use.

You can access the type by the name like so:
Database db = container.Resolve<Database>("Sql");
In this case, db will be a SQLDatabase.

Resolving all named instances
container.RegisterType<Database, SQLDatabase>("Sql");
container.RegisterType<
Database, OracleDatabase>("Oracle");
IEnumerable<
Database> databases = container.ResolveAll<Database>();
The object databases will contain two objects; one of type SQLDatabase and one of type OracleDatabase.

Adding instances to the container
Use container.RegisterInstance to add pre-created objects to the container. Unity assumes that these objects are to be kept as singleton.
container.RegisterInstance<Database>(new SQLDatabase());
container.RegisterInstance<Database>("Oracle", new OracleDatabase());


Adding dependencies to pre-existing objects with attributes

Assume the following class:

public class ModuleA: Module
{
[Dependency]
public IModuleInfo ModuleInfo {get; set; }
}

In this case, ModuleA has IModuleInfo as a dependency.

Below we're registering the IModuleInfo type with the container, instantiating a new ModuleA and asking Unity to add dependencies to the object:

container.RegisterType<IModuleInfo, TISModuleInfo>();
ModuleA modA = new ModuleA();
container.BuildUp(modA);


modA will then get an instance of TISModuleInfo in its ModuleInfo property.

Specifying dependencies through configuration (no attributes)

Assume the following class:
public class GenericDatabase: Database
{
private string connectionString;
public ILogger Logger { get; set; }
public GenericDatabase(string connectionString)
{
this.connectionString = connectionString;
}
container.RegisterType<ILogger, NullLogger>();
container.RegisterType<
Database, GenericDatabase>();
string connStrFromAppConfig = ConfigurationManager.ConnectionStrings["MyConnectionString"];
container.Configure<
InjectedMembers>().ConfigureInjectionFor<GenericDatabase>( new InjectionConstructor(connStrFromAppConfig), new InjectionProperty("Logger"));
Database db = container.Resolve<Database>();
container.RegisterInstance<Database>("Oracle", new OracleDatabase());


Here we're injecting dependencies through the Configure method of the container. Since the connection string is constructor parameter, we must use the InjectionConstructor class, and because Logger is just a property in GenericDatabase, we use the InjectionProperty class.

Nested containers

If the child container doesn't have what you're asking from it, it will look at the parent container.
To register child containers:
UnityContainer parent = new UnityContainer();
IUnityContainer child1 = parent.CreateChildContainer();
IUnityContainer child2 = parent.CreateChildContainer();

parent.RegisterType<IModule, GenericModule>(new ContainerControlledLifetimeManager());
child1.RegisterType<
IModule, ModuleA>(new ContainerControlledLifetimeManager());

IModule module1 = child1.Resolve<IModule>();
IModule module2 = child2.Resolve<IModule>();


In the code above, module1 will be of type ModuleA, and module2 will be of type GenericModule, since child2 looks at the parent container because it doesn't have the type IModule registered.

Tuesday, March 25, 2008

Object Initializers and LINQ


I first saw the C#3.0's "object initializers" in March 2007, at the Microsoft MVP Summit in Redmond, WA. The feature didn't strike me as a big deal. Ok, you can save lots of lines of code
and make your code more readable, but I thought, that's about it.
After some time learning about LINQ, lambda expressions, expression trees, etc, I now realize that object initializers are a fundamental and important part of C# 3.0.
They aren't just syntactical sugar. Take a look at an example:

Class Person is a plain old class:

public class Person

{
public string FName { get; set; }
public string Country { get; set; }
}



Before C# 3.0, in order to create a list of Person and populate with 5 new Person with the properties initialized, I would have do the following:

List people = new List();
Person p1 = new Person();
p1.FName = "Mary";
p1.Country = "United States";
people.Add(p1);
Person p2 = new Person();
p2.FName = "Raul";
p2.Country = "Argetina";
people.Add(p2);
Person p3 = new Person();
p3.FName = "Sergio";
p3.Country = "Brazil";
people.Add(p3);
Person p4 = new Person();
p4.FName = "Giuseppe";
p4.Country = "Italy";
people.Add(p4);
Person p5 = new Person();
p5.FName = "Jean";
p5.Country = "France";
people.Add(p5);


With C# 3.0 we can initialize a collection of Person like so:

var people = new List {
new Person { FName="Mary", Country="United States" },
new Person { FName="Raul", Country="Argentina" },
new Person { FName="Sergio", Country="Brazil" },
new Person { FName="Giuseppe", Country="Italy" },
new Person { FName="Jean", Country="France" } };



As you can see, using object (and collection) initializers results in a much more compact and readable code. Notice that the code in between the {} is actually an expression. Therefore, we can say that object initializers give us the "ability to initialize an object in an expression context".

Now, let's see how this feature relates to LINQ. I am assuming you know what LINQ is and have at least seen LINQ queries. The result of a LINQ query is a "projection", or in other words, it is a brand new object created on the fly. The structure of the object is really unknown, and that's the reason the "var" keyword is so important in LINQ (see Anonymous Types).

You can project the entire object as is:

var FrenchPeople = from p in people
where p.Country == "France"
select p;


Or project a completely different object. In the case below, I am projecting a string (Person's first name) preceded by "Mr. ":

var FrenchPeople = from p in people
where p.Country == "France"
select "Mr. " + p.FName;

When you do these projections, all you're really doing is using an "expression that creates a new object out of existing objects".

The point I am trying to make is that, when we use expressions like these in LINQ, we are inherently using object initializers. Without them, projections in LINQ the way we know them would be impossible. The whole LINQ feature would be a lot clunkier and the code would look a lot messier.

Wednesday, March 5, 2008

Implicitly-typed variables in Resharper 4.0

By now, most of us already know that Linq is everywhere, and therefore, also are anonymous types. To make anonymous types usable with Linq, implicitly-typed variables are required.

The "var" keyword tells the compiler to infer the type from what's on the right-side of the attribution. C# is a statically-typed language, and the “var” keyword doesn't change this.

When you compile the code into IL, you'll see the type explicitly used there. So what's the harm of using "var" all over the place?

Before jumping to the answer right away, I would like to refer you to Steve McConnell's Code Complete, where he reminds us that one should strive to write code that's easy to read. it sure is nice when code is both easy to write and read (like the newly added "automatic properties" C# 3.0 feature). But readability always prevails.

So, to answer my question about the harm of using "var" everywhere, I would say that it can be really harmful to readability.

Sure, if a variable declaration is like the following, there's no problem in using "var":


var baby = new Person();


It is obvious that the variable baby is of type Person. But imagine some method, badly named GetNewOne, returning a new Person object.


var baby = GetNewOne();


How in the world would you know that baby is of type Person? I know if you're using Visual Studio, you can simple hover the mouse over it. But I think I shouldn't rely on a tool to provide me with code readability.

In the example above I definitely want my code to be like this:


Person baby = GetNewOne(); //TODO: Refactor this method name please!!!

I've been playing with ReSharper 4.0 nightly builds on Visual Studio 2008 targeting .Net 3.5, and interestingly enough, every time you use something like "Person baby = GetNewOne()", ReSharper 4.0 will put a squiggly line small green line (hint) under Person, suggesting I should use the "var" keyword instead. See below.



ReSharper 4.0 is not out yet, and maybe (hopefully) this code suggestion will not be in the final version, but I thought it was interesting and wanted to share.

Thursday, February 28, 2008

MSDN Event here in Fresno!

Last night at the user group meeting I mentioned the launch event of Windows Server 2008, Visual Studio 2008 and SQL Server 2008. I forgot to mention that all attendees will get a promotional pack containing all three new products. You can go ahead and register for it here.

C# 3.0 Cookbook 3rd Edition - I Recommend!

I had the pleasure to work as a technical reviewer on C# 3.0 Cookbook 3rd Edition, by Jay Hilyard, Stephen Teilhet (O'Reilly).
It is a wonderful book with a pragmatic approach to solve common interesting problems.
Thank you O'Reilly for inviting me to work on this book.

C# 3.0 Presentation source code

JD Conley was kind enough to post the source code on his blog of the presentation he did last night, at Fresno State, for our Central California .Net User Group.
Thank you JD!

Saturday, February 23, 2008

Central California .Net User Grop meeting - Feb/27/2008

I am looking forward to next user group meeting, which will be presented by JD Conley, who will talk about C#3.0.
For more information visit www.centralcaldotnet.com

Friday, February 22, 2008

Problem with CD/DVD drive in Vista

I am not proud of having my inaugural blog post on how to fix a bug in Windows Vista.
I have been using Vista 64 and have encountered a few problems.
It started with my old logitech webcam, which I cannot find a vista driver for. I bought a Microsoft Lifecam to replace it, and, guess what, the thing didn't work right out of the box. I had to run a patch to fix something on the USB drivers of Vista 64 bits. It worked. It was funny to buy a brand new Microsoft peripheral incompatible with Vista 64.
The next problem I had was with my CD/DVD drive. After some windows update it appeared with a warning sign in Device Manager, saying that the driver was missing. I spent several minutes trying to find a more up-to-date driver for my drive (TSSTcorp TS-L632H - came in a Inspiron 1520). Also, my U3 thumb drive didn't work.

It turns out that the solution for this problem has nothing to do with driver, after all. All you have to do is
a) Go to the registry and find [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E965-E325-11CE-BFC1-08002BE10318}
b) Make sure the class = CDROM
c) Delete both UpperFilter and LowerFilter keys.
d) reboot.

After I did this, both my CD/DVD drive and my U3 thumb drive (which works like a CD) work fine!

Other than these, and not being able to run my McAfee Viruscan on Vista, I haven't had any problems with Vista 64.