January 2008 - Posts
The PDF of our LINQ book has been finalized! You can buy it on Manning's website for $27.50.
There, you'll also find the following documents:
- About This Book
- Table of Contents
- Preface
- Foreword
- Index
We also have sample and bonus chapters awaiting you for free:
Finally, the same book home page contains links to the following resources:
- Author/Book Forum
- Book Support Site
- Source Code site
- The Author's blogs
In short, we offer you everything you need to become a LINQ champion :-)
If you bought the ebook during the MEAP (Manning's Early Access Program) and haven't received the updated PDF, you should contact Manning directly.
The paper book is just around the corner now. It's expected for January 31st. The earliest place for people to buy the book will be from Manning's website. The books should then arrive in bookstores and Amazon shortly after. Of course, you can already pre-order the paper book from these places.
Cross-posted from http://linqinaction.net
Here is the preface I wrote for LINQ in Action:
I chose software development as the way to make a living mainly because it’s a technology that is constantly evolving. There’s always something new to learn. No chance of getting bored in this line of work! In addition to learning, I also enjoy teaching software development. Writing LINQ in Action was a good opportunity to both learn and teach at the same time.
When we started writing this book, LINQ was still an early prototype. We followed its evolution as it was taking shape. There was a lot to discover and a lot to understand. This is part of a software developer’s everyday job. We have to stay up-to-date with the technologies we use and learn new ones as they come out. The software development environment is evolving at an increasingly fast pace, and I don’t see any signs that that’s going to change.
.NET is a fast-moving environment. Over the last couple of years, we’ve seen two major releases of the .NET Framework, and several companion technologies have appeared: Windows Presentation Foundation, Windows Communication Foundation, Windows Workflow Foundation, ASP.NET AJAX, Silverlight, and LINQ have joined our developer toolbox. Another trend in .NET is the multiplication of programming languages. F#, which will receive the same support as C# or VB.NET in Visual Studio, introduces functional programming in .NET. Dynamic languages, such as Python and Ruby, are going to be supported by the .NET Dynamic Language Runtime.
In coming years, we’ll have to deal with more programming languages than the ones we currently master. An advantage of C#, Visual Basic, and the other .NET languages is that they are constantly adapting. C# and VB.NET have been improved in their latest versions to offer support for language-integrated querying through LINQ.
In addition to offering novel approaches to deal with data, LINQ represents a shift toward declarative and functional programming. When people ask me for reasons to learn LINQ, I tell them that they should learn it in order to be able to use it with XML, relational data, or in-memory collections, but above all to be able to start using declarative programming, deferred execution, and lambda expressions.
Start learning LINQ now! When you do, you’ll not only learn how to use this new technology, but you’ll also discover where programming is heading. One of our main goals with LINQ in Action was to help you fully comprehend the new approaches associated with LINQ.
Fabrice Marguerie
Cross-posted from http://linqinaction.net
In the official LINQ forum, someone asked whether it's better to use query syntax (query expression) or method syntax (dot notation).
My answer is that it's mostly a matter of tastes and it depends on the query.
If
I'm writing a query that uses many query operators that aren't
supported by the query syntax, then I use the method syntax. Mixing the
two syntaxes in one single query can quickly make it hard to read, with
all the parentheses.
If I'm writing a query that consists of only one operation, then I use the method syntax as well.
In
other cases, the query syntax has advantages, like the ability to use
"range" variables. The ones defined in from clauses. If you use the
method syntax, then you have to redeclare the variables in each lambda
expression passed as a parameter to a query operator.
Let's consider the following example:
from person in persons
where person.Age > 12
orderby person.LastName
select person.LastName;
Here, person is declared once and used in the where, orderby, and select clauses.
If you write the same query using the method syntax, you have to "redeclare" person each time in the lambda expressions:
persons
.Where(person => person.Age > 12)
.OrderBy(person => person.LastName)
.Select(person => person.LastName);
Another advantage of the query syntax is the ability to use let
clauses. This is really useful in complex queries or simply to avoid
performing the same operation several times in a query, by storing
temporary results in a variable.
Here is a sample query expression with a let clause:
from person in persons
let name = person.FirstName+person.LastName
select new { Name = name, Phones = person.Phones.Count() }
To reproduce the same using the method syntax, you have to write the following:
persons
.Select(person => new { person = person, name = person.FirstName+person.LastName })
.Select(x => new { Name = x.name, Phones = x.person.Phones.Count() });
Not so easy to read, don't you think? This is what the compiler
generates when it encounters the above query expression, by the way.
There are other advantages to each syntax, but the ones listed above
are already enough to decide which one to use in most cases.
Cross-posted from http://linqinaction.net
Book sent to the printer! Yeah!
Cross-posted from http://linqinaction.net
From February 11 to 13 will take place the Microsoft TechDays France 2008. It will be the main Microsoft event of the year in France, with no less than 280 sessions.
LINQ will be one of the major subjects covered this year: seven sessions will be related to LINQ. I'll be presenting two of them. The first one will be an introduction to LINQ. The second one will cover the ADO.NET Entity Framework and LINQ.
Du 11 au 13 février 2008 ont lieu à Paris les Microsoft TechDays France 2008. Il s'agit du principal événement Microsoft de l'année en France, avec pas moins de 280 sessions.
Cette année, un des sujets majeur sera LINQ : sept sessions parleront de LINQ. C'est un sujet que je commence à connaitre, après avoir passé près de deux ans à travailler dessus pour écrire LINQ in Action !
J'animerai deux sessions en duos le lundi 11 février :
- Tout d'abord, rendez-vous de 11h00 à 12h00 avec Philippe Mougin pour une introduction à LINQ.
LINQ apporte une petite révolution dans les développements d'applications .NET. Venez découvrir et comprendre, dans cette session à but pédagogique, les mécanismes de bases d'une technologie principalement basée sur les évolutions des langages de programmation. Nous vous montrerons progressivement comment passer de C# 2.0 et VB 8.0 à C# 3.0 et VB 9.0 pour tirer parti de LINQ et des nouvelles orientations des langages.
- Ensuite, on se retrouve l'après-midi de 14h30 à 15h30 avec Sébastien Ros pour vous présenter ADO.NET Entity Framework et LINQ.
Il s'agit de la troisième session du parcours "Symposium DNG 2008". Nous vous montrerons Entity Framework et ses fonctionnalités en pratique. Nous verrons ensuite comment LINQ peut être utilisé avec Entity Framework pour en profiter au maximum. Nous discuterons ensuite de ce qu'Entity Framework apporte par rapport aux autres outils de mapping objet-relationnel.
Pensez à réserver votre journée et à vous inscrire. C'est gratuit.
This isn't my first post in 2008, but I'll still dedicate this post to wishing you a Happy New Year. May it be successful for your business, work, and family plans.
2007 was certainly a busy year for me - especially due to the book that will be published at the end of this month - but I have no doubts that 2008 will keep me equally busy, if not more.
One of the first things on which I'll focus this year is the Microsoft TechDays France 2008 event. More about this in my next post.
Another big project for this year is the business development of Proagora.com. The site started well, even if it's true mostly for its French part, but we have more plans for it this year. Stay tuned, and don't forget to create your profile!
2008 will also see the release of long due new versions of SharpToolbox.com and JavaToolbox.com. Again, several new features are in the works. I'll keep the surprises for now, but you can expect to see them come to life soon. Of course, the additions of tools and components will continue. I still have a long list of submissions to process...
Let the new year begin and success continue!
Yesterday, a developer asked in the LINQ in Action forum and in Microsoft's official LINQ forum how to write a LINQ to SQL query that would return random records from the database.
It's not something built-in. There is no Random query operator provided by Microsoft. In addition, it can't be done simply by using the System.Random class, because everything in a LINQ to SQL query must be translatable to SQL.
Jim replied with several options:
- Use a pass-through query to get the results
- Use a view to return the ID of the record from tblImages from your subselect and map to that view. Then use a LINQ query to join the tblProperties through the Randomize view and then to the tblImages
- Use a scalar TSQL Function to get a random picture and include that in your LINQ query.
- Use a stored procedure to return the results.
As Jim points out, we discuss consuming pass-through queries, functions and stored procedures in chapter 8 of LINQ in Action.
Let's detail the solution that uses a SQL user-defined function. The most common way to sort records randomly is to use the NEWID SQL Server function. This is what this solution uses.
First, create the following view:
CREATE VIEW RandomView
AS
SELECT NEWID() As ID
Then create the following function that uses the view:
CREATE FUNCTION GetNewId
(
)
RETURNS uniqueidentifier
AS
BEGIN
RETURN (SELECT ID FROM RandomView)
END
The view is required because it's not possible to directly use NEWID in a scalar function.
You can then map the GetNewId user-defined function using LINQ to SQL's Function attribute. Again, see chapter 8 for the details.
That's it! You can now write LINQ queries as usual. Here is an example to pick a random object:
var tool = db.Tools.OrderBy(t => db.GetNewId()).First()
Here is another example that uses GetNewId to sort results randomly:
var tools =
from tool in db.Tools
orderby db.GetNewId()
select tool.Name;
Update: a similar solution that doesn't require a view and a custom SQL function has been suggested in the comments.
Cross-posted from http://linqinaction.net
Did you know that depending on the way you rethrow exceptions you may lose important information? There are already several blog posts that explain and demonstrate the difference between throw and throw ex. I'm realizing only now that none of the two solutions yields the complete call stack trace information!
Let's see what the problem is and I'll show you the real solution.
I'll use the following method to generate an exception:
private static void BadWork()
{
int i = 0;
int j = 12 / i; // Line 10: DivideByZeroException
int k = j + 1;
}
Let's consider what happens if we call BadWork and rethrow the exception with throw ex as follows:
try
{
BadWork();
}
catch (Exception ex)
{
// do something
// ...
throw ex; // Line 24
}
Here is the call stack trace that we get in this case:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.WithThrowEx() in Program.cs:line 24
at Program.Main(String[] args) in Program.cs:line 88
Line 24 is where throw ex is, not where the exception was thrown.
Let's now replace throw ex by throw:
try
{
BadWork();
}
catch
{
// do something
// ...
throw; // Line 38
}
This time, here is the call stack trace:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.BadWork() in Program.cs:line 10
at Program.WithThrow() in Program.cs:line 38
at Program.Main(String[] args) in Program.cs:line 89
As you can see, we get one additional stack frame this time. Line 10
is where the exception was thrown, which is important information
because this is the only information that identifies where the
exception actually happened.
This shows that it's better to use throw rather than throw ex if you want the full stack trace information to be preserved. However, there are cases where throw is not enough. In the following example, throw does not preserve the full stack trace:
try
{
int i = 0;
int j = 12 / i; // Line 47
int k = j + 1;
}
catch
{
// do something
// ...
throw; // Line 54
}
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.WithThrowIncomplete() in Program.cs:line 54
at Program.Main(String[] args) in Program.cs:line 106
This time, you can see that information is lost again. Line 54 is where throw is, not where the exception was thrown.
To preserve the full call stack information, you need to use the following method:
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
This method can be used as follows:
try
{
int i = 0;
int j = 12 / i; // Line 78
int k = j + 1;
}
catch (Exception ex)
{
// do something
// ...
PreserveStackTrace(ex);
throw; // Line 86
}
Here is the new call stack information you get with the above code:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.WithThrowAndStackTracePreservation() in Program.cs:line 78
at Program.WithThrowAndStackTracePreservation() in Program.cs:line 86
at Program.Main(String[] args) in Program.cs:line 110
Here is the call stack information you get with throw ex and a call to PreserveStackTrace:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.BadWork() in Program.cs:line 10
at Program.WithThrowExAndStackTracePreservation() in Program.cs:line 62
at Program.WithThrowExAndStackTracePreservation() in Program.cs:line 69
at Program.Main(String[] args) in Program.cs:line 109
Here we get the full call stack information. Lines 78 and 10 are where the exceptions were thrown. To my knowledge, this is the only way to get complete call stack information in your logs. Without it, it may be difficult to hunt down some bugs.
It's worth noting that if you call
PreserveStackTrace, then you can use
throw or
throw ex and you'll equally get the full stack trace information.
I found this useful trick on Chris Taylor's blog. If you want to use this with .NET 1, you should refer to Chris' post because it seems that the InternalPreserveStackTrace method didn't exist before .NET 2.0.
The complete source code is attached to this post.
More Posts