Archive for category C# 3.0
Design Guidelines for LINQ
Posted by Richard in .Net, C# 3.0, Design, Development, Extension Methods, LINQ, Programming, Software on March 13, 2008
Have you wondered if and when you should use the new LINQ features in .Net 3.5?
Like, where should I put a new extension method? Should I use Func<T> or a custom delegate? How do I best implement a mix-in (extension methods on an interface)?
Well, Mircea Trofin has just published a new draft of some LINQ design guidelines. You might just find your answers there.
ExtensionMethod.net – An Extension Methods Database
Posted by Richard in .Net, C# 3.0, Development on March 3, 2008
While surfing around tonight, I came across ExtensionMethod.net, a database of useful Extension Methods for C# 3.0 and VB 9. I thought it might be useful, so I added a few of my own extension methods.
There aren’t many there yet, but there are one or two on there from Scott Guthrie.
Have you got any code you could put up there? You could be one of the first if you go now.
Remove and Sort Those Ugly “using-Statements”
Posted by Richard in .Net, C# 3.0, Development, Programming, Refactoring, Visual Studio on March 3, 2008
Visual Studio 2008 has lots of goodies in it, like LINQ syntax, CSS editing, and testing tools. There’s a lesser-known feature which I really appreciate though – the “Remove and Sort Usings” command in the C# editor.
You activate the command by placing your cursor over the using statements and clicking on the right mouse-button.
Refactoring C# Series: Aggregation of IEnumerable
Posted by Richard in .Net, C# 2.0, C# 3.0, Development, Refactoring on March 2, 2008
I was recently reading Programming Ruby: The Pragmatic Programmers’ Guide, Second Edition, and came across this piece of example Ruby code:
[1,3,5,7].inject(0) {|sum, element| sum+element} -> 16
[1,3,5,7].inject(1) {|product, element| product*element} -> 105
Inject is a method which acts on an array by aggregating or accumulating the values within that array. It loops through the array, and for every item in the array, it performs a function. It then saves the result for the next iteration of the loop and eventually returns the aggregated value.
In C# 1.0 you would probably write such a method like this:
int sum = 0; int[] list = new int[] { 1, 3, 5, 7 }; foreach (int item in list) { // Perform some function, then save the result sum = sum + item; }
It’s a bit long-winded, and if you wanted to make it reusable, you’d have a hard time.
In C# 3.0, you can do it just like you can in Ruby.
The LinqDataSource and the Hidden Viewstate
Posted by Richard in .Net, ASP.Net, C# 3.0, Development, LINQ, Programming, Quaility, Software, Visual Studio on February 21, 2008
Yesterday I thought I’d learn about the LinqDataSource in ASP.Net 3.5, and got an interesting surprise.
The new LinqDataSource can also be used with a LINQ-to-SQL model to perform updates. You simply add the DataSource to your page, set the table name, and set EnableUpdate to true. Then, using a standard DataControl, you can make updates to your data entities.
The question is, how does this work? It appears to be a bit magical. Read the rest of this entry »
How to Update Data with LINQ-to-SQL
When learning LINQ-to-SQL, it’s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the DataContext and then calling SubmitChanges on the context.
var product = (from p in dataContext.Products where p.ProductID == 1 select p).Single(); product.Name = "Richard's product"; dataContext.SubmitChanges();
It’s nice to see that MSDN documentation actually addresses the obvious arising question:
Q. Can I update table data without first querying the database?
A. Although LINQ to SQL does not have set-based update commands, you can use either of the following techniques to update without first querying:
- Use ExecuteCommand to send SQL code.
- Create a new instance of the object and initialize all the current values (fields) that affect the update. Then attach the object to the DataContext by using Attach and modify the field you want to change.
Writing Custom Exception Classes the Quick Way
Posted by Richard in .Net, C#, C# 2.0, C# 3.0, Programming, Software, Visual Studio on February 15, 2008
Until recently I thought this was a well-known feature. After demonstrating it a few times, I found out it wasn’t.
A long time ago, in an cubicle far, far away, someone created the .Net Framework. To cut a long story short, they simultaneously produced guidelines for creating Exception classes, which you should always use or face having your fingernails pulled out with a staple-gun.
The guidelines state:
“Use the common constructors shown in the following code example when creating exception classes. “
[C#]
public class XxxException : ApplicationException
{
public XxxException() {… }
public XxxException(string message) {… }
public XxxException(string message, Exception inner) {… }
public XxxException(SerializationInfo info, StreamingContext context) {…}
}
How to See the SQL Generated by a LINQ to SQL Command
Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader.
If this is your code:
using System; using System.Linq; using System.Data.Linq; namespace LINQtoSQLConsole { class Program { static void Main(string[] args) { var db = new NorthwindDataContext(); // Use the console to see the SQL db.Log = Console.Out; // A query var cust = db.Customers.Single( c => c.CustomerID == "ALFKI"); // An update cust.Region = "Northwest"; db.SubmitChanges(); } } }
… then this is what you’ll see:
Pretty good, eh?
How to Use Grouping in C# LINQ Syntax
When you started using LINQ, did you think it looked like SQL? I did.
The more I learned LINQ, the more I realized it wasn’t anything like SQL. Take grouping, for example. Because LINQ has a group by statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be just like SQL. Ha ha! Wrong! As soon as I tried to use it, I discovered that the LINQ syntax is not only nothing like the SQL equivalent, but the whole grouping concept in LINQ is completely different too.
At first glance, the two syntaxes look slightly similar.
SQL:
select ReportsTo, count(LastName) as NameCount from Employees group by ReportsTo
LINQ (C#):
from employee in Employees group employee by employee.ReportsTo
Ignoring the omission of the select statement from LINQ, and the requirement of a range variable, they do look similar. But looks can be deceiving.
Let me explain why.