LINQPad – Cool Utility For LINQ

Maybe you know about this, but I saw it first few days a go. I feel in love.linqpadlogo

LINQPad is a cool little utility that was mainly created to allow you to test LINQ expressions and see them produce a  result and output the results in a nice easy to visualize format. It’s great for running LINQ Queries without having to fire up Visual Studio.

LINQPad is also a great way to learn LINQ: it comes preloaded with 200 examples from the book,"C# 3.0 in a Nutshell" written by Joseph Albahari, the author of LINQPad.  There’s no better way to experience the coolness of LINQ and functional programming.

LINQPad is more than just a LINQ query tool: it’s a code snippet IDE. Instantly execute any C# 3 or VB 9 expression or statement block! LINQPad does a great job at LINQ execution and visualization, but it has a lot more uses than just a LINQ query tool. It’s basically a snippet editor that allows you to save snippets and more importantly, execute just about any code that you can write as an expression or single function block.

For example, LINQ to SQL results:

linqpad1

Output can be displayed both as a result table view, the raw SQL (from .ToString()) and a useful code conversion from the LINQ Expression syntax to LINQ command syntax using command chaining of the various LINQ extensions methods.

Other example (from the preloaded examples):

linqpad2

There’s no installation – it’s a single self contained EXE you can copy anywhere assuming you have .NET 3.5 installed.

Download it here.

 

Share this post :

Visual Studio 2008 and .NET Framework 3.5 Training Kit

Microsoft released a nice training kit (~126MB) (it’s a real treasure!) for the latest technologies.

This package covers a bunch of technologies and includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies vs2008 training kitincluding:

  • Visual Studio Tools for Office
  • Visual Studio Team System
  • Application Lifecycle Management
  • C# 3.0
  • VB 9.0
  • LINQ
  • WPF
  • WCF
  • WF
  • Silverlight
  • ASP.NET
  • AJAX
  • CardSpace
  • Mobile

Download here.

Query types using LINQ

It’s great. It’s so beautiful. I really like it.

Reflecting types using LINQ.

How can we do it?

We can use Reflection of course, but with LINQ it shortest and simplest.

Declare “Type” object , assign the class you want to query and query with LINQ.

Example 1:

To get all methods of a class:

   1:  Type tPerson = typeof(Person);
   2:  var methods = from method in tPerson.GetMethods()
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods:");
   6:  foreach (var m in methods)
   7:  {
   8:      Console.WriteLine(m.Name);
   9:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Example 2:

To get all methods that returns “int”, use the “where’ clause:

   1:  var ints = from method in tPerson.GetMethods()
   2:                where method.ReturnType == typeof(int)
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods that returns int:");
   6:  foreach (var intType in ints)
   7:  {
   8:      Console.WriteLine(intType.Name);
   9:  }

C# 3.0 Extension Methods

Posted also at: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/27/c-3-0-extension-methods.aspx

How many times have you written wrapper methods for objects that in reality you wished were part of the object itself?For example, we have the following method which returns the first and last char of a given string in upper case:

   1:  namespace MaorDavidsBlogExamples
   2:  {
   3:      public static class Extensions
   4:      {
   5:          public static string UpperFirstAndLast(string str)
   6:          {
   7:              string ret = "{0}{1}{2}";
   8:              ret = String.Format(ret,
   9:                  str.Substring(0, 1).ToUpper(),
  10:                  str.Substring(1, str.Length - 2),
  11:                  str.Substring(str.Length-1).ToUpper());
  12:              return ret;
  13:          }
  14:      }
  15:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 
We called this method:

   1:  static void Main(string[] args)
   2:  {
   3:      string str = "maordavid";
   4:      Console.WriteLine(Extensions.UpperFirstAndLast(str));
   5:      Console.ReadLine();
   6:  }

…when really, what you want is something more readable like this:

   1:  Console.WriteLine(str.UpperFirstAndLast());

That is exactly what Extension methods let you do.

Extension methods new feature of C# 3.0. They are static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods. Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.

 

Now we want to add this new UpperFirstAndLast() method to the existing string type. Some of us can think that we can create our own class that inherits System.String and add that method there, but it’s impossible – System.String is a seald class. What can we do? use Extension Methods!

Declaring Extension methods

Extension methods are declared by specifying the keyword this as a modifier on the first parameter of the methods. Extension methods can only be declared in static classes.

Let’s rewrite the UpperFirstAndLast:

   1:  namespace MaorDavidsBlogExtensionExamples
   2:  {
   3:      public static class Extensions
   4:      {
   5:          public static string UpperFirstAndLast(this string str)
   6:          {
   7:              string ret = "{0}{1}{2}";
   8:              ret = String.Format(ret,
   9:                  str.Substring(0, 1).ToUpper(),
  10:                  str.Substring(1, str.Length - 2),
  11:                  str.Substring(str.Length-1).ToUpper());
  12:              return ret;
  13:          }
  14:      }
  15:  }

 

The static method above has a “this” keyword before the first parameter argument of type string.  This tells the compiler that this particular Extension Method should be added to objects of type “string”. 

To add this specific Extension Method implementation to string instances within my code, I simply use a standard “using” statement to import the namespace containing the extension method implementation. (Line 6 below)

The compiler will then correctly resolve the UpperFirstAndLast() method on any string.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:   
   6:  using MaorDavidsBlogExtensionExamples;
   7:   
   8:  namespace MaorDavidsBlogExamples
   9:  {
  10:      class Program
  11:      {
  12:          static void Main(string[] args)
  13:          {
  14:              string str = "maordavid";
  15:              Console.WriteLine(str.UpperFirstAndLast());
  16:              Console.ReadLine();
  17:          }
  18:      }
  19:  }

 

The intellisense will help you to find the extension method: new icon indicates an “extension method.

 

 

Another posts about C# 3.0:

C# Automatic Properties

First posted at: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/26/c-automatic-properties.aspx

Visual Studio 2008 and .NET 3.5 introduces us new feature: Automatic Properties.

You probably write classes with properties like this:

   1:  public class Student
   2:  {
   3:      private string _firstName;
   4:   
   5:      public string FirstName
   6:      {
   7:          get { return _firstName; }
   8:          set { _firstName = value; }
   9:      }
  10:   
  11:      private string _lastName;
  12:   
  13:      public string LastName
  14:      {
  15:          get { return _lastName; }
  16:          set { _lastName = value; }
  17:      }
  18:   
  19:      private string faculty;
  20:   
  21:      public string Faculty
  22:      {
  23:          get { return faculty; }
  24:          set { faculty = value; }
  25:      }
  26:   
  27:  }

 

Usually, you aren’t actually adding any logic in the getters/setters of your properties – instead you just get/set the value directly to a field.

Basically, automatic properties allow you to replace this common pattern with this one:

   1:  public class Student
   2:  {
   3:      public string FirstName
   4:      {
   5:          get; set;
   6:      }
   7:   
   8:   
   9:      public string LastName
  10:      {
  11:          get; set;
  12:      }
  13:   
  14:   
  15:      public string Faculty
  16:      {
  17:          get; set;
  18:      }
  19:  }

No fields, only properties and declarations of get/set. The compiler can automate creating the private field and the default get/set operations for you.

This is certainly much more compact and requires fewer steps. When the compiler sees this class, (according to Reflector) it translates it to:

public class Student
{
// Fields
[CompilerGenerated]
private string <Faculty>k__BackingField;
[CompilerGenerated]
private string <FirstName>k__BackingField;
[CompilerGenerated]
private string <LastName>k__BackingField;

// Methods
public Student();

// Properties
public string Faculty { [CompilerGenerated] get; [CompilerGenerated] set; }
public string FirstName { [CompilerGenerated] get; [CompilerGenerated] set; }
public string LastName { [CompilerGenerated] get; [CompilerGenerated] set; }
}

There are a few things to look out for when using this syntax. The compiler forces you to declare properties with both a get and a set. You also don’t get any kind of “safety” features, such as ensuring that you don’t allow a null value to be assigned to a string property. If you want these more “advanced” features, you’ll still need to define your property with the “old way”.

Getting started with LINQ – Maor David's Blog

Getting started with LINQ – Maor David’s Blog

Getting started with LINQ

New post about Linq in my blog:

Getting started with LINQ

C# 3.0 var keyword

C# 3.0 has many-a-new features. This post will explain the ‘var’ keywork and the concept of Implicitly Typed Variables.

The var keyword is not a late-bound or un-typed variable reference. The var keyword always generates a strongly typed variable reference. The main idea is that the developer is not required to define the type of the variable at the time of declaration, but it is the task of the compiler to decide what type of the object the variable is. The compiler infer the type of the variable from the expression used to initialize the variable when it is first declared.

Important points about var keyword:

  • The type of the variable is defined by the value declared and decided at the compile time. (Size depends on the type of the value initialised)
  • Type casting is simple and handled by CLR.
  • Explicit functions for parsing to specific type.
  • Can be used to reference any type in C#.
  • The CLR actually never knows that the var keyword is being used.

What rules shuold you force to use the var keyword?

When you declare variable with the var keyword, you must to always do an initial value assignment.  This is because the var keyword produces a strongly-typed variable declaration. Hence, the compiler needs to be able to infer the type to declare based on its usage.   If you don’t, the compiler will produce a compiler error.

   1: var vAge = 32; 
   2: var vHeight = 175.2; 
   3: var vName = “Maor David“;  

 

The compiler will infer the type of the “age”, “height” and “name” variables based on the type of their initial assignment value. This means it will generate IL that is absolutely identical to the code below:

   1: int age = 32;
   2: double height = 175.2;
   3: string name = "Maor David";

You can also use it to other data types:

   1: foreach (var vTable in ds.Tables) 
   2: {
   3:     foreach (var vRow in ((DataTable) vTable).Rows) 
   4:     {
   5:  
   6:     }
   7: }

This is equal to:

   1: foreach (DataTable table in ds.Tables)
   2: {
   3:     foreach (DataRow vRow in table.Rows)
   4:     {
   5:     }
   6: }

Technorati Tags: , ,

You can read this post also at Maor David’s Blog: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/15/C_2300_-3.0-var-keyword.aspx

Lambda expressions introduction

NET 2.0 introduced Anonymous Methods. The idea behind anonymous methods it to write methods inline to the code. They are mainly used for small methods that don’t require any need for reuse. For example, we have this code:

   1: bool isGreaterThan5(int n)
   2: {
   3:     return n > 5;
   4: }
   5:  
   6: ...
   7:  
   8: int GetGreatersThanFives(List<int> numbers)
   9: {
  10:     return numbers.Find(isGreaterThan5);
  11: }

We can code it with anonymous method:

   1: int GetGreaterThanFives(List<int> numbers)
   2: {
   3:   return numbers.Find(
   4:         delegate(int n) { return n > 5; }
   5:     );
   6: }

c# 3.0 represent cool thing: Lambda expressions.
Lambda Expressions make things easier by allowing you to avoid the anonymous method and that annoying statement block.

Instead

   1: delegate(int n){ return n > 5; }

We can write:

   1: n =>  n > 5

The form of Lambda expressions is:

argument-list => expression

Parameters to Lambda Expressions

The parameters of a lambda expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:

   1: (int x) => x + 100         // explicitly typed parameter
   2:  
   3: (x,y) => return x * y;    // implicitly typed parameter

Lambda Expressions with Multiple Parameters

   1: (x, y) =>  return x * y

Lambda Expressions without Parameters

   1: () => Console.WriteLine("Hello world!")      // No parameters

I think that’s enough intro to Lambda Expressions.
I will follow up with a part 2 to show more about this cool fteature: Expression Trees, how LINQ uses it to pass code as parameters and more.

SqlMetal for Linq

SqlMetal builds a data access layer in seconds. The output is not just a first generation data access; SqlMetal’s output includes all defined relationships (based foreign keys) between your tables. SqlMetal will produce a class for each table and, optionally, classes for all views, stored procedures and user-defined functions.

SqlMetal can generate strongly typed interfaces for stored procedures and user-defined functions. From the developer point of view, it is now a complete breeze to call either a stored proc and/or a user-defined function.

SqlMetal can generate a DataContext for your entire database with a single command.

This is very useful if you have a large number of tables in your system, as dragging and dropping them onto the designer would have got boring very quickly. You can find SqlMetal at [C:]Program FilesMicrosoft SDKsWindowsv6.0Abin.

Lets create Northwind datacontext:

C:Program FilesMicrosoft SDKsWindowsv6.0Abin>sqlmetal /server:.sqlexpress
/database:northwind  /code:”c:tempnorthwind.cs”

We can then include the class within our project and use it as if the designer had created it. We can also get SqlMetal to include all of our views, functions and stored procedures. (use /sprocs /views /functions to extract these objects).

SQLMetal can also output the dbml (/dbml:file.dbml) or mapping (/map:file.xml) file for the database.

C:Program FilesMicrosoft SDKsWindowsv6.0Abin>sqlmetal /server:.sqlexpress
/database:northwind /dbml:”c:tempnorthwind.dbml”

SqlMetal has also generated an external XML Mapping File that maps the classes generated to the database tables, which is much more complete than what I had done my self…

C:Program FilesMicrosoft SDKsWindowsv6.0Abin>sqlmetal /server:.sqlexpress
/database:northwind /map:”c:tempnorthwind.map”

Conclusion:

The SqlMetal tool is useful to generate C# or VB.NET objects mapped on SQL Server database. It provides classes with members and properties mapped on table and view columns. It reflects the relationships between tables. It provides also a class derived from base class DataContext which maps, on request, functions and stored procedures, making difference between table functions and scalar functions and between stored procedures which returns a rowset and those who perform only operations such as insert, update and delete.

From my point of view: great and useful tool.

 

Technorati Tags:

 

del.icio.us Tags:
%d bloggers like this: