Today while giving a brain-dump for a project I am no longer working on I learned something new about 2008 and targeting the 2.0 Framework. For those of you that don't know, with 2008 and .NET 3.0 Framework there is a new var keyword. Using this keyword you can still have type-inference (strongly-typed).
So if you convert a 2005 website to 2008 you can replace code like this:
public
static List<SqlParameter> CreateParameters(object input)
{
List<SqlParameter> parameters = new List<SqlParameter>();
foreach (PropertyInfo p in input.GetType().GetProperties())
parameters.Add(new SqlParameter(p.Name, p.GetValue(input, null)));
return parameters;
}
With code like this:
public
static List<SqlParameter> CreateParameters(object input)
{
var parameters = new List<SqlParameter>(); // !practical, but works
foreach (var p in input.GetType().GetProperties())
parameters.Add(new SqlParameter(p.Name, p.GetValue(input, null)));
return parameters;
}
I think it's cool. Not as long-winded. Especially if you have code like this:
Dictionary
<List<Foo>, Dictionary<Data, List<Bar>>> d = new Dictionary<List<Foo>, Dictionary<Data, List<Bar>>>();
You can now write it like this:
var
d = new Dictionary<List<Foo>, Dictionary<Data, List<Bar>>>();
There is kind of a gotcha if you decide to utilize this keyword in your 2.0 projects. If you are like me and utilize Web Application Projects then you probably have your POCO's (Plain 'Ole CLR Objects*) in an App_Code folder. The issue is that your project will compile successfully but when you F5 / CTRL + F5 you will get an error.

We found today that to rectify this problem you simply need to rename your App_Code folder to something like _code or _App_Code (what I did). You can compile your project and deploy with no problems without renaming this directory but you won't be able to test locally. The code in your App_Code directory will compile dynamically thus rendering using the cool keyword useless. If you simply reference separate class libraries for Business Logic and Data Access this should be a non-issue.
* I forgot where I originally found this term to refer to ADO.NET Generated classes but it stuck with me. I think it was when I was learning the fundamentals of NHibernate.
UPDATE
Some people like var. Other's don't. I like to use var for cases such as Andrew describes (see comments) but I know that others that don't like to type as much / lazy like to use it as a shortcut.
Tags:
C#,
Orcas
At the Scott Guthrie presentation last week he showed the SQL query that the ORM will execute at run-time with a tool called LINQ to SQL Debug Visualizer. The tool isn't included in Visual Studio 2008 due to time-constraints but the source code and binary are available on Scott's site. Here is the link.
I should've installed this sooner but I've been busy lately.
Tags:
LINQ,
Orcas,
Tools
For some reason I got an error today when I started to debug in Visual Studio 2008 Beta 2.
Unable to start debugging on the web server.
Strong name validation failed.
A quick Google search and I found the answer.
Visual Studio 2008 Beta 2 ReadMe CTRL + F -> 2.3.5.2
Tags:
Orcas,
Tools
I think I'm addicted. Aside from my first LINQ application ("Hello AccountTypeId") I haven't written one SQL-like query. From that point on everything has been done with Generics, Lambda expressions (Expression<> trees), and starting today: Reflection. In the past I tried very hard not to have any SQL or SQL-like syntax in code so why should I start now? Maybe I'll come around. Personally I think using Generics coupled with Expression<> trees and Reflection makes for much more elegant code but that is just me. :-)
I, like others I'm sure; am just waiting to see how LINQ is going to play into this whole Presentation / Business / DataAccess layer scheme. I can't find it right now but I do have a great link (2) to post discussing developer speculations on what is to become of a 3-tier architecture.
Anyway, some more code that I've been working on.
public
static void Insert<T>(T entity) where T : class
{
using (OrcasDB database = new OrcasDB())
{
database.GetTable<T>().Add(entity);
database.SubmitChanges();
}
}
public static void Delete<T>(Expression<Func<T, bool>> predicate)
where T : class
{
using (OrcasDB database = new OrcasDB())
{
T instance = (T) database.GetTable<T>().Where<T>(predicate).Single();
database.GetTable<T>().Remove(instance);
database.SubmitChanges();
}
}
How to Use
// insert
Employee will = new Employee
{
Username = "will.asrari",
EmailAddress = "me@willasrari.com",
CanCode = true
};
LinqHelper.Insert<Employee>(will);
// delete
LinqHelper.Delete(emp => emp.EmployeeId.Equals(3));
Easy. My Delete<T> method could probably be made more elegant but this code does work.
UPDATE
I found the links that I wanted to post. Pretty lengthy, but some interesting reading.
Creating a DAL with Linq to Sql Part 1
Creating a DAL with Linq to Sql Part 2
Tags:
LINQ,
Orcas
I don't know if this a bug (feature) but I am only able to add one Linq to Sql class in this project. I tried adding tables from 2 connections but no code is generated for the 2nd connection. When I look in the web.config I see that the new connection string is there but as far as generated code goes - nothing.
Anyone care to shed some light? Maybe I broke something?
UPDATE #1
Error 1 Could not load file or assembly 'System.Runtime.Serialization, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified. 0 0
Apparently I turned off the .NET 3.0 feature of Vista. I'm going to re-activate it and see if it fixes.
Update #2

Weird. I think I would remember turning off .NET 3.0. Oh well...
Tags:
LINQ,
Orcas
After I created my first LINQ Application in Orcas I started reading some blogs and articles beyond the "Hello World"-iness of most of the tutorials. I mentioned that I was interested in learning more about 3.5 Generics and that it what I spent the better part of my evening doing.
In that last (first) LINQ application I created I have a LinqHelper class. It's a little impractical as it has an Accounts class within it. Normally I would have a Helper class composed of a couple of Generic methods and Reflection to take care of all the dirty work. Again, I was just testing the waters.
More Generic Way of Doing Business
int fooId = 3;
Expression<Func<Foo, bool>> predicate = foo => foo.Id.Equals(fooId);
List<Foo> fooList = LinqHelper.Filter<Foo>(predicate);
I have updated my LinqHelper class to reflect some of what I have read about today.
static List<T> ReturnAll<T>() where T : class
{
using (SimpleSchedulerDB database = new SimpleSchedulerDB())
{
return database.GetTable<T>().ToList<T>();
}
}
public static List<T> Filter<T>(Expression<Func<T, bool>> predicate)
where T : class
{
using (SimpleSchedulerDB database = new SimpleSchedulerDB())
{
return database.GetTable<T>().Where<T>(predicate).ToList<T>();
}
}
Using the code
Expression<Func<Foo, bool>> predicate = foo => foo.Id.Equals(fooId);
List<Foo> fooList = LinqHelper.Filter<Foo>(predicate);
repeaterFooInformation.DataSource = fooList;
repeaterFooInformation.DataBind();
The Filter<T> class accepts an Expression<T, bool> predicate as a parameter. After I get my initial table I filter the IQueryable<T> sequence based on the predicate. The result is a subset of the original sequence and in this case I am only concerned about Foo's with certain Id's. That IEnumerable<T> is then converted to a List<T>. There is a lot going on in that method!
Check out Joseph Albahari's PredicateBuilder class. Good stuff! A very elegant solution for creating Expression<> trees.
LINQ, Lambda, and Generics... serious business!
Tags:
LINQ,
Orcas
Hello Orcas!
Very much testing the waters. This took me all of 10 minutes to put together. Man, I can't wait for someone to write a book on .NET 3.5 Generics. I can't wait. To think I just finished .NET 2.0 Generics!
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<title>My First LINQ Page!
</title>
</head>
<
body>
<form id="form1" runat="server">
<
p>
<a href="default.aspx?accountTypeId=1">1
</a> ~
<a href="default.aspx?accountTypeId=2">2
</a> ~
<a href="default.aspx?accountTypeId=3">3
</a> ~
<a href="default.aspx?accountTypeId=4">4
</a>
</p>
<
table border="0" cellpadding="8" cellspacing="8">
<tr>
<td><strong>AccountTypeId
</strong></td>
<td><strong>EmailAddress
</strong></td>
<td><strong>Username
</strong></td>
</tr>
<asp:Repeater ID="repeaterAccountInformation" runat="server">
<ItemTemplate>
<tr>
<td><%# Eval("AccountTypeId") %></td>
<td><%# Eval("EmailAddress") %></td>
<td><%# Eval("Username") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI;
public
partial class _Default :
Page
{
protected void Page_Load(
object sender,
EventArgs e)
{
if (!
string.IsNullOrEmpty(Request.QueryString[
"accountTypeId"]))
BindResults(
int.Parse(Request.QueryString[
"accountTypeId"]));
}
private void BindResults(
int accountTypeId)
{
repeaterAccountInformation.DataSource =
LinqHelper.
Accounts.GetAccountsByAccountType(accountTypeId);
repeaterAccountInformation.DataBind();
}
}
LinqHelper.cs
using System.Linq;
using System.Configuration;
using System.Collections.Generic;
public abstract
class LinqHelper
{
public abstract class Accounts
{
public static IEnumerable<
Account> GetAccountsByAccountType(
int accountTypeId)
{
SimpleSchedulerDB db =
new SimpleSchedulerDB();
return from account in db.Accounts where account.AccountTypeId == accountTypeId select account;
}
}
}
I won't even bother adding the code that was generated for my Linq to Sql class. I will say that I took it upon myself to refactor the hell out of it. Those that know me well enough will probably agree that I have a mild-to-moderate case of OCD when it comes to code generation. Even though the generated code is not SUPPOSED to be edited I took it upon myself to refactor. I can't continue being productive knowing that there is a generated CS class in my App_Code directory full of this.'s and un-optimized using statements. Call me crazy. You're talking to a guy that adds Tabs and Environment.NewLine's when adding composite controls to a PlaceHolder so I can still have organic-looking HTML.
Tags:
LINQ,
Orcas
Apparently I spoke too soon last night when I said the installation went well. Well, it went well meaning it installed and I was still able to use Visual Studio 2005. That's always a good thing. This morning I go to create a "Linq to Sql" class and ReSharper informs me of about 10 errors (not to mention the 60+ redundant this.'s). I thought that maybe ReSharper (EAP 3.0.2) was a little buggy so I went into my code-behind and started to write some code.
SimpleSchedulerDataContext
db = new SimpleSchedulerDataContext()
That didn't give me any problems. Then I started to type a query. Keep in mind I am doing this while watching Scott Guthrie's video on creating a Linq to Sql class and performing basic queries. I start to type my query and hit a brickwall. The var keyword isn't even available to me. I have access to the cool namespaces of 3.5 but that is about it. I can type using System.Linq with no problems! I check the 'About' and see that .NET Framework 3.5 is in fact installed. I also check my 'Programs and Features' and there it is.
I did find a blog entry where Scott Guthrie mentions that they have seen problems when trying to install the .NET Framework 3.5 on Vista machines with the KB929916 installed. I just installed this and am going to reinstall the .NET Framework 3.5 on top of what was already supposed to have been installed.
Any suggestions or references would be greatly appreciated.
UPDATE #1
No luck! Check this out though (from DataContext class).
//---------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1378
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//---------------------------------------------------------------
I checked my project properties to see that the target Framework is 3.5. I'm at a loss as for where to start trying to figure this out.
UPDATE #2
Dammit! I really want to start using this. I posted on ASP.NET forums over an hour ago and haven't gotten any replies. I have searched Google and haven't found ANYTHING related to the problems I am having. I guess I'll e-mail Scott.
UPDATE #3
I did not e-mail Scott as I received an e-mail (comment notification) from David clueing me in on some horrible, horrible news. Apparently just because R# is available for C# 3.0 doesn't mean it is working for ALL of C# 3.0 (LINQ). That really sucks. I turned off code analysis for LINQ pages and I have my LINQ keywords. Niiiiice.

UPDATE #4
I still don't have Intellisense unless I use R#. Still Niiiiiice.
UPDATE #5
I figured out why Visual Studio doesn't have Intellisense. I imported the settings from Visual Studio 2005 where I had Visual Studio Intellisense replaced by R#. DOH!
Tags:
.NET,
Orcas,
Tools
I just started installing this about 10 minutes ago. I'm not going to worry about the SQL Server Compact editions, Dotfuscator, Crystal Reports, C++, or even Visual Basic. All I am installing is the .NET Framework, C#, Visual Web Developer.
Hopefully this is smoother than my Express edition (Visual Web Developer Codename "Orcas") fiasco!
UPDATE
Successful! Side-by-side execution with VS 2005! The first 2 times I opened up Visual Studio 2008 I didn't have Intellisense but I really don't care seeing as how ReSharper's intellisense is much, much, much better. I'm currently installing the VS 9.0 version of EAP 3.0.2. I'll start jamming on it tomorrow.
Tags:
Orcas,
Tools
This afternoon I decided to download and install Visual Web Developer "Orcas" Express Edition to at least start playing with some of the new features. After the quick download I ran the setup and then restarted, resumed, finished. Great. I open Orcas and start dinking around. At this time I get an e-mail from a friend asking for some code (ASP.NET 2.0) and I respond that I will get it to him soon. I open up Visual Studio 2005 and start writing the code that I will eventually send and when I press CTRL+F5 I am greeted with:

Umm. No. This code was JUST checked out of Subversion after being checked-in working 100% so there shouldn't be any build errors. I added a new "default.aspx" to an "Examples" directory and copy-and-pasted verbatim working code from said project and slightly altered. I am using ReSharper so most errors are highlighted even before pressing F5 / CTRL+F5.
So I click "No" and look at the code one more time. I DELETE the sample code knowing full well that now I am dealing with 100% working code. Again. Same as before with the damn build errors. This time I click "Yes" and am greeted with a page displaying an "HTTP 500 Internal Server Error." WTF?
In reading the output I see the following:
Error 1 Unable to initialize the native configuration support external to the web worker process (HRESULT=0x80004002). nativerd.dll must be in %windir%\system32\inetsrv.
Oooooooook. So I navigate to my windir\system32\inetsrv and check that nativerd.dll is in fact in this location. It is. I go to my inetpub and noticed that the default program for opening all of my 2.0 files are VWDExpress9.0. Really weird.
This is when I uninstall Orcas (had to do it twice) and .NET 3.5(pre-release). After the uninstallation I get a dialog box telling me that "Visual Studio 2005 may not work correctly after uninstalling Visual Web Developer Orcas Express Edition." Easy. I'll follow the directions step-by-step and fix this. After reading in detail the first 3 "possible" problems I did what the FAQ ultimately advised which was running Visual Studio 2005 repair. After this STILL NO LUCK!
Now I started to kind of freak out. What I did was uninstall all of the Windows Updates for today, restart, and prayed for the best.
That seemed to work. This thread makes mention that this might be a bug in Windows Vista OS. I posted a quick bullet list of how I went about resolving my issues in that IIS Forums thread.
I'm going to be lurking the Express Edition Forums over the next couple of days to see if this issue pops up over there.
Side Note:
TortoiseSVN rocks!
Tags:
.NET,
Orcas,
Tools