Fabrice's weblog

Tools and Source

News


Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET

The views expressed on this weblog are mine alone and do not necessarily reflect the views of my employer. The content of this weblog is independent from Microsoft or any other company. transatlantys hot news

Contact

Me

Others

Selected content

January 2007 - Posts

Exception handling and resource protection with try..finally

Paul Sheriff has just published an example he uses to recommend the use of try..finally blocks. Here is his example:

private void CreateLogFile()
{
  try
  {
    StreamWriter sw =
      new StreamWriter(@"D:\Samples\Test.txt",
      true, System.Text.UTF8Encoding.UTF8);

    sw.WriteLine("This is some text");
    sw.Close();
  }
  catch(Exception ex)
  {
    throw ex;
  }
}

Here is how I'd rewrite this example if we want to stick to try..finally:

private void CreateLogFile()
{
  StreamWriter writer;

  writer = new StreamWriter(@"D:\Test.txt",
    true, System.Text.UTF8Encoding.UTF8);
  try
  {
    writer.WriteLine("This is some text");
  }
  finally
  {
    writer.Dispose();
  }
}

Why would I rewrite the example this way?

  1. No need to protect resources that haven't been allocated. The finally block is useful only if the creation of the writer works. So the try..finally block should start immediately after that, not before.
    See http://weblogs.asp.net/fmarguerie/archive/2004/08/13/214135.aspx
  2. Use "throw", not "throw ex". If you use "throw ex", you lose the original stack trace.
    See http://www.tkachenko.com/blog/archives/000352.html
  3. The "catch" block is useless here because it does nothing except letting the exception flow.
  4. No need to test if (writer != null) because if we are in the finally block the writer has been created successfully. If the writer is not created, the finally block is never executed because we'd get out of the method due to an exception before the try..finally block.
  5. It's better to use Dispose in most cases. It calls Close and may perform other cleaning operations. Close is just fine in this example, though.

Of course, we can use the using pattern to make the code even better:

private void CreateLogFile()
{
  using (StreamWriter writer = new StreamWriter(@"D:\Test.txt",
    true, System.Text.UTF8Encoding.UTF8))
  {
    writer.WriteLine("This is some text");
  }
}

Note that VB has Using too now.

LINQ to XSD - Typed XML programming with LINQ

I haven't written about LINQ to XSD yet on this blog. So, here goes...

LINQ to XML has been revealed with the first versions of LINQ. It was known as XLinq at that time. LINQ to XML allows querying and creating XML trees and documents. The limitation is that it works on generic XML. You deal with elements and attributes, but not in a strongly-typed way.

LINQ to XSD has been created to improve this. It allows typed XML programming on top of LINQ to XML.
LINQ to XSD, as you would expect, requires an XML Schema (XSD). This schema is used to generate an object model that can then be used to manipulate XML data through LINQ, while enforcing types and the various validation constraints specified in the XML schema.

To show you how LINQ to XSD makes the query syntax much safer and cleaner, let's look at a simple example.
Here is a LINQ to XML query:

from item in purchaseOrder.Elements("Item")
select (double)item.Element("Price") * (int)item.Element("Quantity")

Here is the same query as above, but written using LINQ to XSD:

from item in purchaseOrder.Item
select item.Price * item.Quantity

LINQ to XSD's benefits compared to LINQ to XML include:

  • Improved readability
  • Type-checking at compile time
  • IntelliSense support (completion)

You can get the details on the announcement post by Microsoft's XML team.
As Steve points out, Ralf Lämmel - who is working on LINQ to XSD - has papers on the subject if you want to learn more.


Cross-posted from http://linqinaction.net
Posted: Jan 15 2007, 07:44 PM by Fabrice Marguerie | with no comments
Filed under: ,
Visual Studio Orcas January 2007 CTP

The new pre-release of Visual Studio "Orcas" is now available!

Here is what concerns LINQ in this CTP:

  • ADO.NET is fully integrated with LINQ and offers many options for using LINQ in various scenarios: LINQ to SQL provides direct access to database tables from the programming environment, LINQ to Entities enables developers to use LINQ over EDM models, and LINQ to DataSet allows the full expressivity of LINQ to be used over DataSets.
  • C# 3.0 Language Support. This CTP implements all of the C#3.0 language features from the May LINQ CTP including:
    • Query Expressions
    • Object and Collection Initializers
    • Extension Methods
    • Local Variable Type Inference and Anonymous Types
    • Lambdas bound to Delegates and Expression trees
  • LINQ to Objects. The LINQ to Objects API supports queries over any .NET collection, such as arrays and Generic Lists. This API is defined in the System.Linq namespaces inside System.Core.dll.
  • LINQ over XML (XLinq)
    • Enable further LINQ over XML feature support (in addition to the functionality available in the Oct 2006 CTP) such as the ability to apply XLST to transform into and out of XLinq trees, support for System.XML reader/writer interfaces for improved XML sharing with DOM applications and System.XML schema validation for XLinq nodes.

Improved support for LINQ to SQL should be available in the next CTP, which is planned for February.

The January CTP is available as a Virtual PC image or as a self-extracting install.


Cross-posted from http://linqinaction.net
Am I just a blog chain victim?
Looks like I've been dragged in this blog chain thing since Steve tagged me...
Ok, here are my five things:
  • Like many others I destroyed my joystick playing at Decathlon.
    My first computer was an Amstrad CPC 464. I hardly wrote more than two lines of Locomotive BASIC on it. It was probably something like 10 PRINT "Hello World!" and 20 GOTO 10.
    Actually I spent much more time trying to load games from the cassette deck than programming. Too many games to name them all, but names like Fruity Frank, Ikari Warriors, Ghosts 'n Goblins or Arkanoid should bring back nice memories to some.
    Like many, my first computer language was BASIC... The computers I learned programming on were the Thomson MO5 and TO7. Those had light pens!
  • Although I've been living in Paris for 14 years now, I come from a small corner of Normandy.
  • The first book I read in English was The Lord of the Rings. I enjoyed it. Of course this little challenge took me some time. Well, ok, I don't actually read books in French much faster. But this one required carrying an English dictionary with me...
  • My cat's name is Bob. And no, I didn't choose that name.
  • Not a lot of people actually know but I got married last year. The poor victim is Miss Comics.
  • I'm writing a great book with Steve Eichert about LINQ.
  • At the end of this month, I'm quitting my job at an IT services company to create my own company and become a freelance. This will allow me to continue my own projects (SharpToolbox, JavaToolbox, PageMethods, the LINQ in Action book) and start new ones (like a new site for .NET and Java). 2007 will with no doubt be another great and busy year!

Ok, well actually that makes more than five points. I guess one thing I could add is that I don't know how to count correctly. Math and me, you know...

Who could I tag? What about Charlie, Troy and Keith (maybe he'll bring his weblog back to life)? What about some French guys?: Sami (from DotNetGuru), Jb (Mono and db4objects), Pierrick (look at his WPF Sudoku and WPF/WCF/WF Tetris!) and Mitsu (from Microsoft).
More than five again? I told you!

Posted: Jan 08 2007, 02:41 PM by Fabrice Marguerie | with 4 comment(s)
Filed under: ,
Wes Dyers' reports from the C# compiler front

If you are the kind of guy fascinated by the C# language and LINQ who wants to know more about what's happening under the hood and how Microsoft is building these new toys, you should read Wes Dyer's blog. Wes is a developer on the C# compiler team. On his blog he relates his journey with the C# compiler towards version 3.0.

Wes Dyers' posts let you know how LINQ to Objects queries work, how to test the correctness of the compiler's interpretation of query expressions, why it is difficult to generate understandable compilation error messages and how to fix thathow transparent identifiers are used in query expressions, and many more subjects along the same lines.

It's always fascinating to see how these guys are building powerful and smart tools that we'll use everyday without having to worry about all technical difficulties they deal with for us.


Cross-posted from http://linqinaction.net
Posted: Jan 08 2007, 12:32 PM by Fabrice Marguerie | with no comments
Filed under: ,
Converting a CSV file to XML using LINQ to XML and Functional Construction

Steve has published on his blog a sample from the book we are working on together. This example shows how LINQ to XML makes it easy to convert a CSV file into an XML document.

Going from CSV to XML doesn't require something more complicated than this:

XElement xml =
  new XElement("books",
    from line in File.ReadAllLines("books.txt")
    where !line.StartsWith("#")
    let items = line.Split(',')
    select new XElement("book",
      new XElement("title", items[1]),
      new XElement("authors",
        from authorFullName in items[2].Split(';')
        let authorNameParts = authorFullName.Split(' ')
        select new XElement("author",
          new XElement("firstName", authorNameParts[0]),
          new XElement("lastName", authorNameParts[1])
        )
      ),
      new XElement("publisher", items[3]),
      new XElement("publicationDate", items[4]),
      new XElement("price", items[5]),
      new XElement("isbn", items[0])
    )
  );

If you haven't taken a look at LINQ to XML before, let's bet that this short example will entice you to!

Cross-posted from http://linqinaction.net
Hooked on LINQ

Troy Magennis has started a community resource web site about LINQ: Hooked on LINQ.

I've uploaded and started to prime content on what I hope will become the community repository for all things LINQ related.
My motivation is simple; I want one place that I can go to get my hands on official and community based LINQ resources.

The site already has some content and pointers to LINQ resources from everywhere. It's a wiki so you'll be able to participate and publish content as well. Go there and contribute.

Oh, and don't forget to visit Troy's blog. It also has very interesting content about LINQ.


Cross-posted from http://linqinaction.net
More Posts