Linq To Sql – Peaking under the covers with GetChangeSet, GetCommand, Expression and ToString

In Beta 2, there are a number of ways in which linq allows you to see what it is generating under the covers.   Two new methods, GetChangeSet() and GetCommand(), which replace GetChangeText() and GetQueryText() allow you to interact with changes as objects.  Expression returns the expression tree which has been built for the query, while doing a simple ToString() on a query will return you the T-SQL query.

If we start with the Expression property.  This is a public property on a query var type which displays the expression tree built underneath.

I’ve created a simple query to return all the orders in the Northwind database.

DataClasses1DataContext db = new DataClasses1DataContext();
var query = from o in db.Orders
                  select o;

For this, query.Expression contains “Table(Order).Select(o => o)”.   For more complex queries, then this is really interesting to see what is actually being created.  Take this query:

var query = from o in db.Orders
                   join od in db.Order_Details
                   on o.OrderID equals od.OrderID
                   where od.Quantity > 100
                   select o;

This would be a lot harder to express as a expression tree.  The Expression property for this looks like:

Table(Order).Join(Table(Order_Detail), o => o.OrderID, od => od.OrderID, (o, od) => new <>f__AnonymousType0`2(o = o, od = od)).Where(<>h__TransparentIdentifier0 => (Convert(<>h__TransparentIdentifier0.od.Quantity) > 100)).Select(<>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.o)

While not easy to read, you can easily get it to a more readable state:

db.Orders.Join(db.Order_Details, o => o.OrderID, od => od.OrderID, (o, od) => new { order = o, orderDetail = od }).Where(anon => anon.orderDetail.Quantity > 100).Select((anon) => new { order = anon.order, orderDetail = anon.orderDetail });

This is really useful if you are interested in the tree being built and a good learning aid if your interested in what the equivalent tree looks like.  I;m sure there are many other uses by having access to the expression tree.

Moving onto ToString(),  query.ToString() contains the query code which will be executed against the database.  For the simple orders query, it would hold:

SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [dbo].[Orders] AS [t0]

Again, useful when learning and debugging.  However, ToString() is not a great way to get the SQL command.  A better way is to use GetCommand.

GetCommand is a method on a DataContext which takes an IQueryable parameter and returns a DbCommand object.  Once we have the DbCommand object, we can view and edit properties as required.  As this is replacing GetQueryText(), the new command would be:

db.GetCommand(query).CommandText

This returns the same value as ToString – at the moment.  Other properties include, being able to access parameters, the SqlConnection object and transaction object. 

Finally, GetChangeSet() which returns an IList read-only collection of objects which have either been added, modified, or removed since the last SubmitChanges().  The different properties are:

IList queryText = db.GetChangeSet().AddedEntities;
IList queryText = db.GetChangeSet().ModifiedEntities;
IList queryText = db.GetChangeSet().RemovedEntities;

Its a bit of a shame it returns it as object you need to cast it down if you want to do anything with it.  However, as its at the DataContext level it needs to be generic enough to hold every object.   However, it does mean that there is now no way to gain access to the ChangeText query which will be executed – via a property anyway.

Scott Guthrie has also posted how to install the query visualizer for Beta 2 – LINQ to SQL Debug Visualizer which displays the Expression tree and SQL query in its own window.  Interestingly, he has also included the code on how it was created.

Technorati Tags: ,

LinqDataSource – Visual Studio 2008 Beta 2

One of the new features within Visual Studio 2008 is the linqDataSource for ASP.net applications.

This data source allows you to attach directly to a DataContext allowing you to access Linq objects without writing any code.  Because it follows the DataSource interface, existing controls such as the GridView can connect and display data based on it.

The DataSource also handles mappings form GridView requests to the database. For example, Sorting is done server side, querying the database with ORDER BY, while paging using RowNumber feature of SQL Server 2005. 

One note, the Insert, Update and Delete only appears to work if you go via the DataContext and SELECT * on the object. Not sure if this is by design or a bug, i’ve posted a note on the forum asking.

Using the data source is very simple.  In fact, if you have used one of the existing data sources then its just the same but instead of pointing to a database, you point to the DataContext.  If you haven’t, in the Toolbox flyout, under Data you will see the LinqDataSource control.  Drag this onto your form, click the smart tag and you will be able to config the options.  If your DataContext isn’t in the list, you need to compile the application for it to be detectable. You can then drag on a GridView control and point it’s data source to the Data Source you just created.

Sample code which turns 4 columns from the Northwind.Customer table:

    AllowSorting=”True” AutoGenerateColumns=”False” DataSourceID=”LinqDataSource1″>
   
                    SortExpression=”CustomerID”>
                    ReadOnly=”True” SortExpression=”CompanyName”>
                    SortExpression=”Phone”>
                    SortExpression=”PostalCode”>
   

    ContextTypeName=”WebPOC.NorthwindDataContext”
    Select=”new (CustomerID, CompanyName, Phone, PostalCode)” TableName=”Customers”>

Simple and effective control, nice addition to the framework.

 

Technorati Tags: , , ,

Visual Studio Orcas Beta 2 Online and Available

The latest version of Orcas has just been posted online. Both the Installation disc images and VPC images can now be downloaded.

Disc available are:

Standard, Pro, Team Suite, Team Foundation Server, Test Load, MSDN Library.

VPC available are: Team Suite, Team Suite and Team Foundation.

http://msdn2.microsoft.com/en-us/vstudio/aa700831.aspx

It’s great Microsoft have listened to feedback and offering these as a single ISO, but also offering them via a ActiveX download manager to make life easier for everyone.  However on Vista, it would only let me save it on my C drive and then told me for security it was being saved in a temp folder. Great!

Visual Studio Express Editions, VB, C#, C++, Web Developer.  Both Online and Offline (414mb img) installers are available.

http://msdn2.microsoft.com/en-us/express/future/bb421473.aspx

I’m currently downloading C# Express (20 mins left) and Team Suite Installation (6hours 20mins left).   Wish I was back at Uni, would have been done by now….

Technorati tags: , ,

Notepad2 Integration

I’ve been using Notepad2 for a few weeks now and find it to be a great addition to my toolset, however I don’t like the way it doesn’t integrate into Windows and is just a standalone exe. With version 2.0.17 just released, I decided I would create a reg file which would setup the integration.  There are posts online which explain how to replace notepad.exe with notepad2.exe but I didn’t really want to do that incase I change my mind next week (more than likely).

Registry file to install Notepad2.  This will add a Edit with Notepad2 onto context menus of files, and change the default for txt files to open with Notepad2.  To have Notepad2 be the default for other file types, the registry key for the file needs to point to the value Notepad2. For example:

[HKEY_CLASSES_ROOT.txt]
@=”Notepad2″

Registry file to remove Notepad2. This will remove the context menu items, and set the file association to .txt back to the default. The only other step then is to create a start menu item shortcut, if you want – personally, I never use it.

[Sorry about the .txt extension, host doesn’t allow .reg files to be downloaded.  Remove extension to use]

Enjoy.

Technorati tags:

The results are in…

I have just received confirmation of my degree result – I was awarded a First Class Honours!

My grades for each module are:
Computer Science Project – A1
Computer Network Protocols and Architectures  – A1
Further OO Development – A1
Databases – A3
(Grade Mark A1 = 77-100 and A3 = 70-72)

Thank you to everyone who has helped over the past year. It’s been a busy year for me, with me being a MSP, entering the Imagine Cup and work on MbUnit all going on at the same time – plus job hunting and keeping up to date with what Microsoft are doing made for a busy year.  But it has all paid off 🙂

SQLBits – UK SQL Server Community Day

Hot on the deals of DDD5, information about a new community conference, SQLBits, has been announced. 

“On the 6th October 2007 we will be holding a day long conference full of SQL content. We will have 20 sessions covering everything from Maintenance plans through CLR stored procedures to Data Mining.”

If you use, or have an interest in SQL Server then this should be an great day.  I’m really looking forward to it, should be another great event.

Registration opens sometime in August, keep an eye on the RSS for updates.

More information @ http://www.sqlbits.com/

Technorati tags:

Visual Studio and moving My Documents

Tonight, I encountered a problem again and one which I think Visual Studio should really be clever enough to handle and know.

On all of my machines, I move My Documents folder onto a separate partition for management, backup and just simply because I don’t want all of my work on the main OS partition – if Windows goes down its a lot easier to recover data if its on a separate partition, of course if the drive dies I have a backup just in case.

However, Visual Studio seems to have a big problem with this.  After moving the folder, VS still tries to save and find items in the original location (C:UsersUserNameDocumentsVisual Studio 2005).  The first time I did this was when I saved a project template into F:UsersUserNameDocumentsVisual Studio 2005 , and for some strange reason VS wasn’t picking it up. Turns out, it was still looking in the old default location.  Tonight, I installed an add-in which was installed into the correct place – F:UsersUserNameDocumentsVisual Studio 2005Addins, yet Visual Studio was not setup to look in this location. There were environment variables set in the addin dialog, but nothing matching what was actually setup on my system.  I can’t believe I am the only person who moves their Documents folder and who has ran into this problem.

To make Visual Studio look in a new locations, in Tools > Options > Environment > Addins add a setting for your Addin directory in VS2005 directory, and then move all the locations in Tools > Options > Projects and Solutions to your location.  Then the only place you have to worry is making sure when you save a project, it is saved in your new location – or where ever else you want.

But really, we shouldn’t have to do this. Visual Studio should be working off the relevant path to my documents, and not a hardcoded path which it seems to be.  It’s hardly best practice…and it is still the same in 2008.

Technorati tags: , ,

Microsoft UK Hacked

You would think that Microsoft would know how to secure there own web application, however it looks like the UK Events section of the site was left open to XSS and SQL Injection attacks which caused Saudi Arabia hackers to deface the page.  A video was online over the weekend showing how it was done, however has now been taken down. Hopefully it will make a reappearance.

I found it assuming.

Saudi hackers spray digital graffiti

Reported at:

http://www.theregister.co.uk/2007/07/02/ms_uk_defacement/ and http://www.zone-h.org/content/view/14780/31/