Wednesday, November 7, 2007

Soma introduces VS2008 Release at TechEd

Microsoft has committed themselves to delivering a release of their Visual Studio 2008 product family in November 2007. Read the press release here! Jibbeee!

Suddenly my VS2008 Beta2 VPC problems don't feel as grave as they felt yesterday!

The .NET Framework 3.5, this is the .NET Framework 2.0SP1, adding the new C# 3.0 features, support and assemblies and the .NET Framework 3.0 assemblies, will be released with the VS2008 but will also be available to end-users through Windows Update (it's an optional download to start with?!).

Tuesday, November 6, 2007

My VS2008 Beta 2 expired!

I was in the middle of developing a little sample using my Visual Studio 2008 Beta 2 VPC, which I got from Microsoft this summer as a Beta tester, when suddenly a dialog opened up and said something like This version of Windows 2003 Server that you are using will expire in 24 hours and will stop working (or something like that, this is from memory).

Frustrated, but I still went into the Microsoft Beta program again and started downloading the ISO image of the Visual Studio 2008
Professional Beta 2
(note, I'm not downloading the VPC again).

Anyways, the file has an extension of .img and now I just have to get it opened somehow so that I can install it (project of tomorrow). Anyways, I also noticed that ScottGu wrote about this a couple of days before the end of last month, in his Important Notice: VS 2008 Beta2 VPC Images Expiring on Nov 1st weblog.

Sunday, November 4, 2007

C# program formatter for weblog

I was looking for a way of formatting my C# code and I finally found it. This is a webpage that allows me to copy my source code into a textarea and get back a nicely formatted HTML to paste directly into my weblog. It's pointed out by Scott Cate where he refers to an online c# code format site. So I'm trying it out. What do you think?
public class MyClass
{
public string this[int index]
{
get
{
return m_Names[index];
}
protected set
{
m_Names[index] = value;
}
}
string[] m_Names;
//Rest of the class
}
06/11/2007 author added: I have now converted the last couple of weblogs and reformatted the code snippets using the above mentioned formatter. It works ok, but a few times I had to manually change the resulting HTML for it to work correctly. Especially if a line ends with a // comment that contains a couple of quote-marks. I also noticed that the formatter doesn't recognize 'var', 'for', 'select' and other C# 3.0 keywords - otherwise, it works fine and will probably support the new keywords as time goes by.

Saturday, November 3, 2007

Things you might not know about C# 2.0

When writing my Yet another C# 3.0 new feature listing... and browsing the web I ran into the following interesting things I had not realized about C# 2.0. Thought I might share them with you.

a) Delegate inference

Did you know that the C# compiler can infer the delegate type? This means that you can write code like this:
SomeDelegate del = SomeMethod;
and the 'SomeMethod' is inferred to be of type SomeDelegate.

So you don't have to write it the old-style:
SomeDelegate del = new SomeDelegate(SomeMethod);
...saves a few keystrokes.

b) Property/Indexer get/set visibility

You can easily make indexers in C# and even make a getter more visible than a setter, like this sample shows:
public class MyClass
{
public string this[int index]
{
get
{
return m_Names[index];
}
protected set
{
m_Names[index] = value;
}
}
string[] m_Names;
//Rest of the class
}
Just remember that the get/set visibility can only narrow the visibility of the actual Property/Indexer.

c) yield return in IEnumerable

When writing IEnumerables you can use the 'yield return' statment to simplify your coding, as shown in this sample:
public class CityCollection : IEnumerable<string>
{
string[] m_Cities = { "New York", "Paris", "London" };

public IEnumerator<string> GetEnumerator()
{
for (int i = 0; i < m_Cities.Length; i++)
{
yield return m_Cities[i];
}
}
//Rest of the class
}
The code will continue running from the 'yield return' point when the return value has been used and the next item of the IEnumerable is required.

We use the IEnumerable like this:
CityCollection cityCollection = new CityCollection();
foreach (string city in cityCollection)
{
Console.WriteLine("City: " + city);
}
Could be helpful to know!

d) suppress compiler warnings inline

If the compilation of your code always returns a warning and you would like to suppress it, but not all such warnings, then you can use 'pragmas', like this:
// Disable 'field never used' warning
#pragma warning disable 169
public class MyClass
{
int m_Number;
}
#pragma warning restore 169
However, after the 'warning restore' statement you may still get the warning. Could be convenient.

more stuff...

See more cool stuff at Create Elegant Code With Anonymous Methods, Iterators, And Partial Classes

Yet another C# 3.0 new feature listing...

I blogged about .NET 3.0, .NET 3.5, VS2008 "Orcas", C# 3.0 and more in my .NET Framework 3.0, Implicitly typed local variables and the Extension Methods weblogs.

There are many sites that have collected information and written about the new features of C# 3.0, like developer.com, Wikipedia and most notibly Scott Guthrie in his New C# "Orcas" Language Features weblogs: part-1, part-2 and part-3. If you haven't read Guthries, you should!

Anyways, from all of these weblogs and sites (and even more than those mentioned above) I have compiled the following descriptions of each feature. I have created my own samples but also copied some from the sites above, so if you require more information on any of the samples or features, please read the references above.

a) Automatic Properties

...which allows you to create simple properties without
declaring the storage variables and the simple (and futile) getters and setters.

Sample:
// Automatic Properties
public class Person
{
public string ID { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public int Age { get; set; }
}
public class Address
{
public string Street { get; set; }
public int Number { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
The compiler will automatically generate a private instance variable and the appropriate getter and setter.

b) Object initializers

...allowing the construction of objects and members using
the default constructor and appropriate member setters in one easy go.

Sample:
// Object initialization
Person p1 = new Person
{
ID = "P0001",
Name = "Davíð",
Age = 39,
Address = new Address
{
Street = "Bakkagerði",
Number = 2,
City = "Reykjavík",
Country = "Iceland"
}
};
This syntax is a lot simpler to write than using the default constructor and then all the necessery setter method calls.

c) Collection initializers

...now made as simple as array
initialization, without any additional programming.

Sample:
// Collection initialization
List<Person> persons = new List<Person>
{
new Person { ID="P0002", Name="Alfred", Age=39,
Address=new Address { Street="Seilugrandi" } },

new Person { ID="P0003", Name="Aðalsteinn", Age=38 },
new Person { ID="P0004", Name="Sveinn", Age=38 },
new Person { ID="P0005", Name="Eymundur", Age=43 },
new Person { ID="P0006", Name="Markús", Age=39 },
new Person { ID="P0007", Name="Guðmundur", Age=38 },
new Person { ID="P0008", Name="Bjarni", Age=38 },
new Person { ID="P0008", Name="Richard", Age=20 }
};
You can use this syntax for all classes that implement the IEnumerable interface and has an Add method. For example, instead of MyList list = new MyList(); list.Add(1); list.Add(2); you can now write MyList list = new MyList { 1, 2 };. Simple and convenient.

d) Implicitly typed local variables

...which permits the type of local variables
to be inferred from the expressions used to initialize them.

Sample:
// Inferred variable types
var txt1 = "Implicitly txt becomes a 'string'";
string txt2 = "Same as above";
var i = 7; // Implicit declaration of an integer
int j = 7; // Same as above
This does not make C# anything but a stronly type language because you can only use this feature for local variables and each variable is always of the same type. This feature was necessery for it is required for the declaration of anonymously typed variables (coming below).

e) Implicitly typed local arrays

...are a form of array creation and initialization
that infers the element type of the array from an array initializer.

Sample:
// Inferred array types
// Same as int[] intArray = new int[]...
var intArray = new[] { 10, 9, 4, 7 };
var txtArray = new[] { "a","sldkj","oowu","9837","ls" };
Nice new feature, also necessery as mentioned for implicitly typed local variables above.

f) Anonymous types

...allowing classes to be automatically created, behind the scenes,
when you require a storage for a set of data instead of a single element of data.

Sample:
// Anonymous types
var h = new { hair="black", skin="green", teethCount=64 }
var u = new { Name = "James" }
The instantiation new { ... } will be construct a new class that is created behind the scenes. This class is unknown to the programmer so its name obviously can't be written out in the declaration of the variable, hence the var keyword as mentioned for implicitly typed local variables above.

g) Extension methods

...which allows developers to add new methods
to existing class without having to extend it or compile it. This is done by including the this keyword in the first parameter of a method on another static class.

Sample:
// Simple Extension Method
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
This method extends all strings because the 'this keyword parameter' is of type string. The implementation of the method simply checks if the content of the 'this' string is in the format of an email address.

The usage:
// Simple Extension Method Usage
string email = "alfred@ruedenet.is";
// Prints "True"
Console.WriteLine(email + " is an email? " +
email.IsValidEmailAddress());
// Prints "False"
Console.WriteLine("alfred@ruedenet is an email? " +
"alfred@ruedenet".IsValidEmailAddress());
It's as simple as that.

Sample:
// Another Extension Method
public static bool In(this object o, List<Person> c)
{
foreach (object i in c)
{
if (i.Equals(o))
{
return true;
}
}
return false;
}
This method extends all objects because the 'this keyword parameter' is of type string. In addition, the extension method requires a single parameter of type List. The implementation checks if the 'this' object is contained within the list provided as parameter.

The usage:
// Another Extension Method Usage
Console.WriteLine("Davíð is in persons? " +
"Davíð".In(persons)); // Prints "False"
Console.WriteLine("Guðmundur is in persons? " +
"Guðmundur".In(persons)); // Prints "True"
Now, for your information the string "Davíð" is not in the list of persons, however "Guðmundur" is. So, the two lines above will print out 'False' and 'True' in that order.

When you have Extension methods some may think that C# is stretching a bit too far into Duck typing land. This is understandable because with Extension methods the use of a type becomes a little more about what methods an object exposes and little less about what type the object is.

Don't get too defensive, C# is still strongly typed and Extension methods are just another shortcut programming. What I mean is that the 'IsValidEmailAddress' method above could also have been written as an old-style 'public static' method like this:
// Simple Static Method
public static bool IsValidEmailAddress(string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
Note that all I did wat take the 'this' keyword out and we have a regular old-style 'public static' method as we have all done them through the years.

Now, instead of doing "alfred@ruedenet.is".IsValidEmailAddress() - as I did above using the Extension method - I would simple do IsValidEmailAddress("alfred@ruedenet.is"). IMHO, this old-style simply doesn't have the elegance introduced into C# with the Extension methods! Also, the old-style doesn't show the 'IsValidEmailAddress' method in the IntelliSense autocompletion drop-down, but Extension methods do! ...and that is cool!

h) Partial methods

...allow us to create partial classes that contain methods that may
or may not become part of the public interface of the class - this depends
on whether some other partial class will actually override it.

There are a few comments on using partial methods: 1) they are only allowed in partial types; either classes or structs, 2) they always return void and 3) forget it, there are no other kinds of partial members (no partial variables, no partial properties, etc. :-)

File1.cs:
// MyPartialClass
public partial class MyPartialClass
{
public void DoA()
{
LogA("A-Begin");
// Do something
LogA("A-End");
}
public void DoB()
{
LogB("B-Begin");
// Do something
LogB("B-End");
}
partial void LogA(string txt);
partial void LogB(string txt);
}
Note the two partial methods at the bottom. Without anything else, if we simple instantiate this 'MyPartialClass' and call the 'DoA' and 'DoB' methods, nothing will happen because 'LogA' and 'LogB' have not been implemented. The compiler will simply remove the declarations of the methods and all usages of them. The compiler can actually allow it self to do that because partial methods never return values.

However, if we add the following second file:File2.cs:
// MyPartialClass
public partial class MyPartialClass
{
partial void LogA(string txt)
{
Console.WriteLine(txt);
}
}
All we have don't is add the 'LogA' method to the class. Now the compiler wont remove the calls to this method. Now, if we instantiate the 'MyPartialClass' and call the 'DoA' and 'DoB' methods, 'DoB' will continue to do nothing, but 'DoA' will call the 'LogA' method twice and therefore print a couple of text lines.

It took me a little while to get used to the idea of partial types (introduced in C# 2.0) being necessery to simplify the development tools generation of the GUI designer classes. I'm still not completely at ease with this approach and I still think it can be, and should have been, solved using good old inheritence. So I guess it will take me a while to get use to the idea of partial methods :-)

i) Lambda expressions

...are an evolution of anonymous methods that provides improved
type inference and conversions to both delegate types and expression trees.

There are many places that can give you good descriptions of the Lambda functionality in C# 3.0. A very good introduction would be the Lambda Expressions and Expression Trees: An Introduction feature on The Code Project website. But you can also continue reading below before jumping to the references :-) Lets start with a delegate example:

Sample using delegates:
// Declare the AFilter delegate type
public delegate bool AFilter(string str);

// Define a user of the AFilter delegate type
public string findFirstMatch(List<string> list,AFilter filter) {
foreach(string str in list) {
if (filter(str)) return str;
}
return null;
}

// Define an anonymous delegate of the AFilter type
AFilter myFilter=delegate(string str) {
return str.StartsWith("A");
};

// Define a list of values
var strings = new List<string> {
"John", "Kane", "Krugman", "Andrea", "Hornby"
};

// Prints "Andrea"
Console.WriteLine(findFirstMatch(strings,myFilter));
This is the old-style, without lambda expressions.

Sample using Lambda-style:
// Defining an anonymous delegate of the AFilter type
AFilter myFilter = str => str.StartsWith("H");
And now I can use the 'myFilter' anywhere that the AFilter delegate is required.

In addition the C# 3.0 compiler can infer the translation of Lambda expressions to either strongly-typed function delegates (as above) or strongly-typed expression trees.

Expression sample:
// Defining the same filter as an expression
Expression<AFilter> filtExpr = str => str.StartsWith("J");

// Prints "str"
foreach(ParameterExpression param in filtExpr.Parameters) {
Console.WriteLine(param.Name);
}

// Prints "str.StartsWith("J")"
Console.WriteLine(filtExpr.Body);
Console.WriteLine(findFirstMatch(strings,
filtExpr.Compile())); // Prints "John"
This constructs the 'aFilterExpression' into an Expression object that can't be sent directly into the 'findFirstMatch' function above but can be used to, for example, make SQL syntax. How this works is that the C# 3.0 compiler actually knows about the Expression class (part of System.Linq.Expressions) and can handle it specifically to compile our source code into a data structure as well as a function. The last line of code above calls the 'Compile' method of the expression to get the function pointer and sents it into the 'findFirstMatch' method, which uses the compiled expression to print out "John".

This new feature of the C# 3.0 compiler, to compile into a data structure is not that new and has been available in LISP for a long time. To learn more about that see Ian Griffiths take on C# 3.0 and LINQ - Expression Trees. Ian also talks about how to use these Lambda expressions to make code on the run, see his Generating Code with LINQ weblog.

j) Language Integrated Query (LINQ) expressions

...provideS a language integrated syntax for
queries that is similar to relational and hierarchical query languages such as SQL and XQuery.

I think Linq is propably the reason for most of the new features mentioned above. Linq is an extensive add-on the language with it's SQL-like syntax and features. Below I will be making three samples to explain the overall concept but the whole thing would be way to long for this weblog so I will start by referring you to the LINQ Introduction features at The Code Project website: Part 1, Part 2 and Part 3.

Linq is a collection of extensions methods that can be used to make queries on specific classes. We will start by looking at queries on normal classes stored in lists, then we will look at making Linq queries on XML documents and end by looking at making queries on traditional database structures.

Sample 1, Object queries:
// Linq queries on the persons list initialized earlier
IEnumerable<Person> young = persons.Where(p => p.Age<39);
Console.WriteLine("How many persons are younger than 39? " +
young.Count()); // Prints "5"
Console.WriteLine("The oldest person is how old? " +
persons.Max(p => p.Age)); // Prints "43"
Console.WriteLine("What is the average age of all persons? " +
persons.Average(p => p.Age)); // Prints "36,625"
var allAlfredHomes = persons.Where(p =>
p.Name.Equals("Alfred")).Select(p =>
new { p.Name, p.Address.Street });
foreach (object h in allAlfredHomes)
{
Console.WriteLine(h); // Prints "Seilugrandi"
}
Allows queries directly into the object structure of your program.

Sample 2, XML queries:
// Linq queries on the following XML document
XDocument people = XDocument.Parse(""+
"<people>"+
"<person age='32'>"+
"<firstname>Scott</firstname>"+
"<lastname>Guthrie</lastname>"+
"</person>"+
"<person age='32'>"+
"<firstname>Susanne</firstname>"+
"<lastname>Guthrie</lastname>"+
"</person>"+
"<person age='50'>"+
"<firstname>Bill</firstname>"+
"<lastname>Gates</lastname>"+
"</person>"+
"</people>");

// All persons whos names start with "S"
IEnumerable<XElement> sElements =
people.Descendants("person").Where(p =>
p.Element("firstname").Value.StartsWith("S"));

// Prints "Scott" and "Susan"
foreach (XElement p in sElements)
{
Console.WriteLine(p.Element("firstname").Value);
}

// All persons whos names starts with "S", more info returned
IEnumerable<Person> sPersons = people.Descendants("person").Where(p =>
p.Element("firstname").Value.StartsWith("S")).Select(p =>
new Person { Name = p.Element("firstname").Value + " " +
p.Element("lastname").Value,
Age=Convert.ToInt32(p.Attribute("age").Value) } );

// Prints "Scott Guthrie (32)" and "Susan Guthrie (32)"
foreach (Person p in sPersons)
{
Console.WriteLine(p.ToString());
}
The interesting thing here is that the Linq XML feature requires you to use the System.Xml.Linq.XDocument but not the System.Xml.XmlDocument.

Sample 3, SQL queries:
// Linq queries into a database
BankAccountsDataContext bankAccountsDB = new BankAccountsDataContext();
IEnumerable<BankAccount> bankAccounts =
bankAccountsDB.BankAccounts.Where(p =>
p.Name.StartsWith("B"));

foreach (BankAccount b in bankAccounts.AsEnumerable())
{
Console.WriteLine(b.Name+" "+b.Balance);
}

// Prints "900,0000"
Console.WriteLine("Min:" +
bankAccountsDB.BankAccounts.Min(p => p.Balance));

// Prints "1000,0000"
Console.WriteLine("Avg:" +
bankAccountsDB.BankAccounts.Average(p => p.Balance));

// Prints "1100,0000"
Console.WriteLine("Max:" +
bankAccountsDB.BankAccounts.Max(p => p.Balance));
The simplest way of getting the 'BankAccountsDataContext' created is to use the new VS2008 feature of adding a "LINQ to SQL Classes" (DBML) project item to your project.

k) The new LINQ syntax

...allows us to write our queries without using the 'Where' and 'Select' extension methods used above.

Extension-style:
IEnumerable<Person> sPersons =
people.Descendants("person").Where(p =>
p.Element("firstname").Value.StartsWith("S")).Select(p =>
new Person {
Name = p.Element("firstname").Value + " " +
p.Element("lastname").Value,
Age=Convert.ToInt32(p.Attribute("age").Value)
}
);
Can be converted to the following.

Query-style:
var sPersons2 = from p in people.Descendants("person")
where p.Element("firstname").Value.StartsWith("B")
select new Person {
Name = p.Element("firstname").Value + " " +
p.Element("lastname").Value,
Age = Convert.ToInt32(p.Attribute("age").Value)
};
Isn't that cool!?