Toolbox

Easy LINQ Queries, Becoming A Better Developer, And Logging Help

Scott Mitchell

All prices were confirmed on July 14, 2008 and are subject to change. The opinions expressed in this column are solely those of the author and do not necessarily reflect the opinions of Microsoft.

Contents

Hone Your LINQ Skills with LINQPad
Blogs of Note
Logging Important Information, Warnings, and Errors

Hone Your LINQ Skills with LINQPad

One of the major additions to the Microsoft® .NET Framework 3.5 is LINQ, a set of classes and language enhancements designed to offer a universal data-querying syntax. With LINQ to Objects, LINQ to XML, and LINQ to SQL, you can query arrays and collections, XML documents, and database tables using a similar syntax with rich features like IntelliSense® and compile-time type checking. LINQ syntax, however, can be downright confusing for developers who have spent the better part of their programming careers using SQL to query data.

To learn LINQ, I recommend buying a book on the topic. Diligently work through each chapter, keying in each example, and reviewing the results. While you can certainly implement LINQ examples in Visual Studio® 2008, I'm a big fan of LINQPad (version 1.24). LINQPad is a free, standalone program for writing and testing LINQ queries that was created by Joseph Albahari.

LINQPad's user interface is divided into four panes. The upper-left pane presents a list of database servers, which you can drill into to view the databases and their tables, views, and stored procedures. To test a LINQ query, type it into the top-right pane. You can enter a LINQ query directly or type in the C# or Visual Basic® code that executes a LINQ query. When writing and testing LINQ to SQL queries, you can select the database from the upper-left pane to query against.

The bottom-right pane displays the results of the query. There are three views: the results, the corresponding lambda expression, and an equivalent SQL statement. The bottom-left pane serves as a workspace to organize your frequently used queries. This pane also includes a Samples tab with more than 200 C# and Visual Basic LINQ examples from Albahari's book, C# 3.0 in a Nutshell (O'Reilly, 2007). For those new to LINQ, these examples are invaluable learning tools, as is the ability to view the LINQ query's equivalent SQL statement.

You can think of LINQPad as a scaled-down, LINQ-based implementation of SQL Server® Management Studio. When writing a SQL query to display data in an application, it is usually easier to write the query in Management Studio and then copy and paste it into your code in Visual Studio than it is to write the query from scratch in Visual Studio. This is due to the fact that testing the query from Visual Studio requires running the application. Much in the same manner, I find it easier to write and test my LINQ queries in LINQPad.

While the LINQPad editor color codes keywords, variables, strings, and comments and underlines errors with red or blue squiggly lines just as Visual Studio does, it does not yet support IntelliSense. (This is a planned future enhancement.) Despite the lack of IntelliSense, LINQPad's intuitive and lightweight user interface, its many features, and the plethora of examples make it an excellent tool for learning, writing, and testing LINQ queries.

Price: Free.

LINQPad.net

mitchell.linqpad.gif

The LINQPad.net User Interface (Click the image for a larger view)

Blogs of Note

Everyday I make a conscious effort to take steps to become a better developer and to improve my technical competency and programming savvy. I may peruse a respected developer's blog for coding tips and tricks, read a chapter from a computer trade book, or ask and answer questions at an online forum. But as blogger Rob Waling will tell you, becoming a better developer means more than learning new technical skills.

Rob has worked extensively with the .NET Framework and now runs a small development company that consults and sells assorted ASP.NET applications. He's also an avid blogger. Most developer-focused blogs examine the latest technologies or showcase programming tips and tricks. Rob's blog is unique in that it addresses the business and interpersonal aspects of being a successful developer. His 11-part series on that topic discusses areas such as team building, understanding your role in the company and in your projects, knowing your strengths and weaknesses, and constructively criticizing a coworker's code. Every developer, regardless of his position or experience, will get something out of this well-written and thought-provoking list.

Rob's blog is full of great information for those who have ever considered becoming a freelance developer or have thought about turning an idea, tool, or application into a product for sale. There is advice on structuring a one-man business, guidelines on how much to charge for your time and products, and suggested tools and business processes that can help ensure your success as a freelance developer or micro-ISV.

softwarebyrob.com

Logging Important Information, Warnings, and Errors

When an error occurs in a production environment, it's important that the details are logged to some persistent store so that the developers can later explore and correct the error. I discussed this in the April 2008 Toolbox column (see msdn.mi­cro­soft.com/magazine/cc500592.aspx) where I looked at two different systems for automatically logging errors in an ASP.NET Web application: the ASP.NET Health Monitoring system and Error Logging Modules and Handlers (ELMAH). But what tools are available for logging error details in desktop applications? What about logging non-error information? Many government, financial, and healthcare applications need to maintain audit logs that record who has accessed the system and what data was viewed or changed.

There are many logging libraries available for .NET-based applications, and among the most mature and widely used are the Enterprise Library and log4net. The Enterprise Library is a set of application blocks created by the Microsoft patterns & practices group. Each application block is a set of classes that help perform a common enterprise development task, such as logging, data access, and exception handling. The Logging Application Block makes it easy to record information to any number of log stores.

Before you can log information from your application, you first need to configure the Logging Application Block and specify, at minimum, what trace listeners to use. A trace listener is an object that receives and stores information from some source and is the mechanism by which a log entry gets written to a specific log store. The Enterprise Library ships with built-in trace listeners that store log entries to the Windows® Event Log, a database, a text file, an e-mail message, and so on. You can also create and plug in your own custom trace listeners.

The Logging Application Block's configuration can also include categories, filters, and formatters. Categories can be used to define a classification of log entry types, such as "Data Access Errors" or "Debugging Messages." Each log entry is associated with a category as well as with a number of properties, such as priority and severity. On the staging server you may be interested in only logging those entries with a priority of 5 or greater, for instance. On the production server you may want to omit log entries belonging to the Debugging Messages category. Filters can be used to limit what log entries get recorded. Formatters can be used to customize how the details of a log entry get serialized to text when being recorded.

After configuring the application, use the Logging Application Block's API to create log entries programmatically. For example, to log the details of an exception you could create a new LogEntry object in the catch portion of a try/catch block, set the LogEntry's properties to capture the exception's details, and log the entry by calling the Logger class's Write method, passing in the LogEntry instance. The Logging Application Block would then evaluate the log entry against its filters, categories, and formatters to determine whether to store the log entry and, if so, how to format it.

Log4net is an open-source logging library maintained by the Apache Software Foundation. It is a .NET port of the log4j, a logging library for applications written in Java. Many of the core concepts present in the Logging Application Block are also found in log4net, although different terminology may be used. For example, log entries in log4net are recorded by objects called appenders (rather than trace listeners). Log4net ships with many more appenders than the Enterprise Library. There are appenders for logging to a number of sources, such as an ADO.NET data source, the ASP.NET trace, a console window, the Windows Event Log, a buffer in memory, an e-mail message, or a text file. Log4net offers filters and layouts, which are similar to the Logging Application Block's formatters.

Within the log4net configuration you can define multiple loggers. One key area where log4net differs from the Logging Application Block (and many other logging systems) is the ability to create a hierarchy of loggers. To log information from within the application, call the API's GetLogger method, passing in the name or type of the logger to access. The loggers offer a variety of methods that, when called, create a log entry of a particular level. The levels, which have values such as DEBUG, INFO, WARN, and FATAL, indicate the priority of a log entry. In the log4net configuration you can indicate that certain loggers should only respond to log entries with certain levels.

Logging is an important aspect of any application. At a minimum, you should log error details. But logging can also be helpful during debugging and for maintaining an audit trail. The Logging Application Block and log4net are two mature, open-source logging systems that can be used with new .NET-targeted applications or integrated into existing ones.

Price: Free. Open source.

Enterprise Library 4.0:
go.microsoft.com/fwlink/?LinkId=122895
log4net: logging.apache.org/log4net

mitchell.toolbox.entlib.gif

Configuring Enterprise Library 4.0 (Click the image for a larger view)

Send your questions and comments for Scott to toolsmm@microsoft.com.

Scott Mitchell, author of numerous books and founder of 4GuysFromRolla.com, is an MVP who has been working with Microsoft Web technologies since 1998. Scott is an independent consultant, trainer, and writer. Reach him at Mitchell@4guysfromrolla.com or via his blog at ScottOnWriting.NET.