Today I created my first test ASP.NET application in IIS 7 in Windows 2008. It is amazing, now in IIS manager you can configure the ASP.NET with nice panel,
I will explore more on this. A very happy 2008 ahead.
Namoskar!!!
http://csna01.libredigital.com/
Download available for Hand On Labs for
Ø LINQ
Ø LINQ to SQL
http://www.microsoft.com/downloads/details.aspx?FamilyID=e7fa5e3a-f8b2-4f77-bbcd-b5b978402dd1&DisplayLang=en
One of the biggest limitation in “var” is that it cannot be shared across the methods. So if you are doing something using that keyword then you have to stick to the local. I was reading Alex’s Blog where he explained it very nicely,
Here is my implementation,
Create an Extension method
static class MyClass
{
//Create Extension Method to covert the var
public static T CastVar<T>(this object obj, T anyType)
return (T)obj;
}
Now suppose you want to get output of type “var” from any method,
public static object GetVAR()
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
return (object)list;
Retrieve it to an object.
object o = GetVAR();
Next is the tricky part, as per Alex
“This works because when an anonymous type is used the compiler first checks that one with the same signature (i.e. all fields are the same name and type) hasn't already been used. If one has the same CLR type is used.”
You need to know the shape of the object to put it again back to “var” type.
var o1 = o.CastVar(new List<int>{1});
Now this iteration will work perfectly fine as if you are working with any other local “var”.
foreach (int i in o1)
Console.WriteLine(i);
I have tested this for LINQ to SQL where we use “var” very frequently,
static void Main(string[] args)
var query = o.CastVar(new[] {new {CID = "", Company = ""}});
foreach (var c in query)
Console.WriteLine("{0} - {1}", c.CID, c.Company);
NWDataContext db = new NWDataContext();
var q = from c in db.Customers
where c.City == "London"
select new
CID = c.CustomerID,
Company = c.CompanyName
};
return (object)q.ToArray();
Here I am going to compare the two technologies and point some missing areas.
Let us use the Northwind database and get the list of Customers from city London. The ADO.NET approach would be,
string sConn = @"ConnectionString";
using (SqlConnection conn = new SqlConnection(sConn))
using (SqlCommand comm = new SqlCommand
("SELECT CustomerId, CompanyName FROM " +
" Customers WHERE City = @City", conn))
conn.Open();
comm.Parameters.AddWithValue("@City", "London");
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
string sCID = reader[0].ToString();
string sCompanyName = reader[1].ToString();
Now this code will compile and execute perfectly. But if I change this code a bit the compiler will not throw any error but runtime errors will be there.
("SELECTBlah CustomerId, CompanyName FROM " +
comm.Parameters.AddWithValue("@City", 12.4);
string sXYZ = reader[2].ToString();
Highlighted areas will throw me runtime error.
Ø Not only the SQL keywords (SELECTBlah) but any problem there will throw error at runtime.
Ø Adding parameter with value which is not supported (float)
Ø Reading the third column value which I am actually not retrieving through my SQL query.
Ø I am converting everything to String but there might be null values and moreover this is not strongly typed.
Now with this approach people already have developed lot of projects. ADO.NET is powerful but these are the commonly faced drawbacks. To avoid all the errors we need to invest in Testing. This increases the product cost in the market.
In LINQ to SQL how this can be achieved easily,
Create mapping class for the customer Table
[Table(Name="Customers")]
class Customer
[Column]
public string CustomerId { get; set; }
public string CompanyName { get; set; }
Now directly using the DataContext I can get the output.
DataContext db = new DataContext(sConn);
var q = from c in db.GetTable<Customer>()
CustomerId = c.CustomerId,
CompanyName = c.CompanyName
foreach (var k in q)
Console.WriteLine(k.CustomerId + " : " + k.CompanyName);
Here things I cannot do,
Ø Cannot mistype any query keyword as it is native statement (not in “”)
Ø Cannot pass type to condition which is not supported
Ø Cannot project the output with any value
Ø Moreover the output is IEnumerable of some type so the output is strongly typed
There are lot of other benefits like, you will get intellisense and the statement completion. Moreover all the previous ADO.NET runtime errors will become compile time errors.
In L2S query execution can be separated in two major areas. One is to fetching the data another is manipulating the data (update, delete and insert). I use one slide during my L2S demo and here it is,
Fetching data from database
LINQ is only from fetching the data from database. LINQ does not have any query operator for delete, update or insert. When you send LINQ to your L2S layer then L2S translates that to SQL understandable query (T-SQL). This is obvious because as per one of the major design specifications we have decided to make the LINQ independent of any existing API. T-SQL is standard and works for any version of SQL Server database and will continue to work with upcoming releases. Now as usual SQL executes that query and gives the result back to our L2S layer. Then L2S gives us the result back to us in form of IEnumerable<T>.
Manipulating data
When it comes to data manipulation you can go for DML statements or Stored Procedure. If you have Stored Proc then dbml designer allows us to modify the update, delete and insert accordingly. This manipulation happens purely through object model.
For insert
You create an object and add the necessary properties. Then add to the existing collection. Once done call SubmitChanges() method.
For delete
You get the object(s) and using the method Remove(), remove it from the existing collection. Then call SubmitChanges() method.
For update
You get the object(s) to modify. Then call SubmitChanges() method.
DataContext’s Translate method converts existing IDataReader to an IEnumerable<T>. This is very useful when you may need to run raw SQL Query though System.Data.Linq. I am getting few similarities with DataContext’s ExecuteQuery.
How Translate works
+++++++++++++
Assuming I am using Northwind database.
using (NWDataContext db = new NWDataContext())
DbConnection conn = db.Connection;
DbCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT * FROM Customers";
DbDataReader reader = comm.ExecuteReader();
var q = db.Translate<Customer>(reader);
ObjectDumper.Write(q);
Now since my dbml has Customer class defined and I am running SELECT * query this can map with existing Customer class. But if I want to retrieve only the selected columns from the result set then one of the drawbacks is that I cannot project the output using Anonymous Type, rather I need to define a class in my app to project it to IEnumerable<T>. One of the reasons is that the Anonymous Type does not create any default public constructor. It would have been nice to have this anonymous type projection with the Translate.
So if you want to map it to your type then your approach would be little different.
comm.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
var q = db.Translate<CustomerSelect>(reader);
Extra things you need is that,
class CustomerSelect
public int CustID { get; set; }
Whereas in ExecuteQuery method you do things little differently,
var q = db.ExecuteQuery<Customer>("SELECT * FROM Customers", "");
What is that? Know more on http://quickstarts.asp.net/3-5-extensions/
Other related resources,
ASP.NET 3.5 Extensions Preview Download
ASP.NET 3.5 Extensions Preview Forums
People complain about the keyword “var”. Especially, when we use it with the strict programming language like C# in .NET. Developers also complain about the readability part of it. I totally agree with them, but the scenarios where there will be no options but the “var” when it comes to on the fly projection of Language INtegrated Query (LINQ). Can you initialize Anonymous Type without “var”? There are so many no-nos. Let’s appreciate it and start use. I already have explained in one of my previous blogs,
Scenario 1 (Anonymous Type)
+++++++++++++++++++
When you have no type defined but want to create that, we need “var”.
var obj = new { ID = 1, Name = "Wriju" };
You cannot assume the name created by compiler for this Anonymous Type. Please feel free to add comment to my blog if you have choice to add type in the above example while declaring the variable.
Scenario 2 (Projecting it to IEnumerable<AnonymousType>)
++++++++++++++++++++++++++++++++++++++
Suppose if you want to get the output containing only the selected column you have to project it to a type.
IEnumerable<CustomerSelect> query =
from c in db.Customers
select new CustomerSelect
CustID = c.CustomerID,
As you cannot have “,” as you are used to for any T-SQL query. Here you need everything as strongly typed. So you need to create a class, here I have created one,
So here boldly you can retrieve the result like, IEnumerable<CustomerSelect>
in case if you do not want to use var here. But if you are lazy developer like me then you might not be interested in creating class for every need. Rather you will use anonymous type and get the IEnumerable<AnounymousType> as query output. But how will be defining IEnumerable of some anonymous type (in fact no type). No wander you must appreciate the real power of “var” here.
var query =
LINQ allows us to join different collection source provided we are mapping with two properties with the same type. It is easy, it is quick and it is concise.
//Create Employee Class
class Employee
public int ID { get; set; }
public string Name { get; set; }
public string ManagerId { get; set; }
//Create Manager Class
class Manager
public string Id { get; set; }
class Program
//Create the List<Manager>
static List<Manager> GetManagers()
return new List<Manager>
new Manager(){Id = "M1", Name = "Manager 1"},
new Manager(){Id = "M2", Name = "Manager 2"}
//Create the List<Employee>
static List<Employee> GetEmployees()
return new List<Employee>
new Employee(){ID = 1, Name = "A", ManagerId = "M1"},
new Employee(){ID = 2, Name = "B", ManagerId = "M1"},
new Employee(){ID = 3, Name = "C", ManagerId = "M1"},
new Employee(){ID = 4, Name = "D", ManagerId = "M1"},
new Employee(){ID = 5, Name = "E", ManagerId = "M2"},
new Employee(){ID = 6, Name = "F", ManagerId = "M2"},
new Employee(){ID = 7, Name = "G", ManagerId = "M2"},
new Employee(){ID = 9, Name = "H", ManagerId = "M5"}
/*Doing join between two sources
*The record will be retieved only the mathched data
* Output will give values from both the collection
*/
var query = from e in GetEmployees()
join m in GetManagers() on e.ManagerId equals m.Id
EmployeeId = e.ID,
EmployeeName = e.Name,
Manager = m.Name
foreach (var o in query)
Console.WriteLine("{0}-{1} [{2}]",
o.EmployeeId,
o.EmployeeName,
o.Manager);
With this exciting release of .NET Framework 3.5 I have been exploring its magic and sharing the finding with you. Here I am compiling all of them together for indexing,
C# 3.0: Vote for the keyword “var”
C# 3.0 Features: Automatic Property
C# 3.0 Features: Automatic Property (Part 2)
C# 3.0 Features: Automatic Property (Part 3)
C# 3.0 Enhancements: Lambda Expression
C# 3.0 : Evaluation of Lambda Expression to Language INtegrated Query (LINQ)
C# 3.0 : Exploring Lambda Expression
C# 3.0 Enhancements: Expression Trees
C# 3.0 Enhancements: Object Initializers
C# 3.0 Enhancements: Collection Initializers
C# 3.0 Enhancements: Extension Methods
C# 3.0 : Anonymous Type and .NET Reflection Hand-in-Hand
C# 3.0 : Anonymous Types
C# 3.0 : Partial Methods
C# 3.0 is 100% backward compatible with C# 2.0
C# 2.0 and Partial class, in one of the amazing features to work with one class separated in multiple physical files. Not only that, it also helps us to extend designer generated code such as Typed DataSet, Designer generated code etc.
With this C# 3.0, we can now have partial method. Partial methods are the code block which reside inside a partial type and gets executed only when it has definition. This gives us the extensibility and if user wants to implement the rule, they can go ahead and define the body but if they do not want it will not. This improves the performance as you are not loading/creating unwanted methods.
Here I am going to explain what is that? People already have documented about this feature in so many places, here I am,
Let us consider this piece of code,
public partial class MyClass
//Public Constructor
public MyClass(int iInput)
//Calling Partial Method
GetMessage(iInput);
//Public Property
public string Messgae { get; set; }
//Partial Method
partial void GetMessage(int iVal);
In the partial method declaration I cannot have any body. So, where we need to define the body of our method?
Should be in another partial class (I will explain that later). But since there is no body, the method actually will have no existence in IL.
Notice no existence for the method GetMessage(int iVal)
Calling block,
MyClass obj = new MyClass(10);
Console.WriteLine(obj.Messgae);
Now if you define the body of the function in a partial class the IL will look different as well as the Console.WriteLine()will print the value.
Notice this IL, this has got the definition for GetMessage in it.
How the definition would look like,
partial void GetMessage(int iVal)
this.Messgae =
"The value entered by you is : " + iVal.ToString();
Some golden rules on Partial Methods, (these are the typical errors you will get from Visual Studio if anything is missing)
You must visit wesdyer’s blog for more detailed specification.
Ø A partial method must be declared within a partial class or partial struct
Ø A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers
Ø Partial methods must have a void return type
Ø A partial method cannot have out parameters
Ø Definition has to end with “;” No {} is allowed in this scope.
Some good resources,
http://community.bartdesmet.net/blogs/bart/archive/2007/07/28/c-3-0-partial-methods-what-why-and-how.aspx
Another Windows Presentation Foundation implementation for the popular Architecture Journal is now available for download. So know about Ray Ozzie the Chief Software Architect of Microsoft – the most prestigious position in Microsoft which was captured by Bill Gates.
Project Astoria, S+S and many more. All the 13 published journals are available in nice readable format.
So go ahead and download Just Released: Architecture Journal Reader (Beta)
Let’s check what I am reading,
Learn and for installation-free mode and get started with Visual Studio 2008.
MSDN Virtual Lab: Building Web Applications with Visual Studio 2008
MSDN Virtual Lab: What's new in C# 3.0
MSDN Virtual Lab: What's new in Visual Basic 9
Beta 3 of the ADO.NET Entity Framework, and a preview of ASP.NET 3.5 Extensions. Designed to make it even easier for developers to build data-centric applications and services regardless of the underlying data source, the ADO.NET Entity Framework is already gaining significant support from multiple database vendors and third-party providers, including Core Lab, Data Direct Technologies, Firebird, IBM, MySQL AB, Npgsql, OpenLink Software, Phoenix Software, Sybase and VistaDB.
Microsoft also announced today a preview of ASP.NET 3.5 Extensions, which leverages the Entity Framework to make it easier for developers to build rich, interactive data-centric applications on the Web. The ASP.NET 3.5 Extensions Preview includes:
Downloads
+++++++
· Entity Framework Beta 3 runtime
· Entity Framework Tools CTP 2
· ASP.NET 3.5 Extensions preview
Enjoy.
Hands on labs are available online and this is the best HOL till date for LINQ and C# 3.0.
LINQ Hands On Labs
LINQ to SQL Hands on Lab
C# 3.0 Language Enhancements Hands On Lab