Archive for category .*

Running queries in parallel with Entity Framework (and not only with it)

From time to time I have to run two or more queries that I know will always be two or more – like some first/skip records and also total count. If you write it as two queries and execute, that means two round trips to database. Although it may not matter if the network latency is very small, why not to challenge myself and try to find some workarounds.

Sure you can create some stored procedures and get the data back from these, but I was thinking about more LINQ to Entitiesish way. I recalled a way I one time used inside one project. Although it was done in pure SQL, it, as it turned out, works, kind of, for LINQ to Entities as well.

The idea is using “one row table” and put the queries as columns. Let me demonstrate:

select
  (select foo, bar from table1 where ...),
  (select baz, foo from table2 where ...)
from OneRowTable;

Where the OneRowTable can be specially created table or i.e. for Firebird RDB$DATABASE or for Oracle Database dual. It isn’t the nicest SQL (and also challenges optimizer), but works. In columns as queries you can put anything you want as long as it is syntactically correct.

OK, what about the Entity Framework or LINQ to Entities respectively. I created the “one row table” first:

create table OneRowTable(x bit primary key);
insert into OneRowTable values (0);

The table needs to have the primary key to be able to import it into entity model, the datatype doesn’t matter (I was using MS SQL, hence the bit).

What about the queries? Similar approach:

var allinone = context.OneRowTable.Select(_ => new
{
	AData = context.a.Where(a => a.x.HasValue && a.x.Value > 10).Select(a => new { A1 = a.id, A2 = a.id * 2 }),
	BData = context.b.Where(b => b.id < 999).Select(b => new { B1 = b.id, B2 = b.y }),
});
string query = (allinone as ObjectQuery).ToTraceString();
var data = allinone.First();
var adata = data.AData;
var bdata = data.BData;

The a and b are my testing tables. You can check there’s only one query executed. Encapsulating this into some method is only piece of cake.

And how the query looks like? Well for my MS SQL test:

SELECT
[UnionAll1].[x] AS [C1],
[UnionAll1].[C2] AS [C2],
[UnionAll1].[C1] AS [C3],
[UnionAll1].[id] AS [C4],
[UnionAll1].[id1] AS [C5],
[UnionAll1].[C3] AS [C6],
[UnionAll1].[C4] AS [C7],
[UnionAll1].[C5] AS [C8],
[UnionAll1].[C6] AS [C9]
FROM  (SELECT
	[Project1].[C2] AS [C1],
	[Extent1].[x] AS [x],
	1 AS [C2],
	[Project1].[id] AS [id],
	[Project1].[id] AS [id1],
	[Project1].[C1] AS [C3],
	CAST(NULL AS int) AS [C4],
	CAST(NULL AS int) AS [C5],
	CAST(NULL AS varchar(1)) AS [C6]
	FROM  [dbo].[OneRowTable] AS [Extent1]
	LEFT OUTER JOIN  (SELECT
		[Extent2].[id] AS [id],
		[Extent2].[id] * 2 AS [C1],
		1 AS [C2]
		FROM [dbo].[a] AS [Extent2]
		WHERE ([Extent2].[x] IS NOT NULL) AND ([Extent2].[x] > 10) ) AS [Project1] ON 1 = 1
UNION ALL
	SELECT
	2 AS [C1],
	[Extent3].[x] AS [x],
	[Extent4].[id] AS [id],
	CAST(NULL AS int) AS [C2],
	CAST(NULL AS int) AS [C3],
	CAST(NULL AS int) AS [C4],
	[Extent4].[id] AS [id1],
	[Extent4].[id] AS [id2],
	[Extent4].[y] AS [y]
	FROM  [dbo].[OneRowTable] AS [Extent3]
	CROSS JOIN [dbo].[b] AS [Extent4]
	WHERE [Extent4].[id] < 999) AS [UnionAll1]
ORDER BY [UnionAll1].[x] ASC, [UnionAll1].[C1] ASC

Not exactly the original shape. The translator took another way creating two one row results and using union all to get it into one query. Except this, the query is in general the same (the explicit joins are as result same as the subselects, though little bit more confusing in this case).

Again, this isn’t general purpose way of doing it and may result in worse performance than running queries separately and I would recommend using it only after careful testing and on controlled limited set of queries.

Tags: , , , , , ,

Missing notes for new IEnumerable<string> methods

I noticed is that the documentation for some of new IEnumerable<string> methods in System.IO I wrote before is missing important parts. For example, the old method has notes about unstable sorting and about the different behavior for patterns where the extension is exactly three characters long. But the new one is missing these notes and these are quite important, in my opinion. I hope this is just because we’re in RC stage and in RTM all will be ready. Else it could cause confusion when using new methods (until you find the string[] version (or this post ;) )).

Tags: , ,

IEnumerable<string> result for some methods in System.IO

The .NET Framework 4 includes some nice new methods in System.IO namespace. There’s a lot of methods on Directory class etc. returning string[]. That’s OK until you try to enumerate directory with thousands of files (for example). Then you’re waiting for complete result even is you just need couple of first item. The new EnumerateXxx methods are solving this as these are returning IEnumerable<string> (i.e. EnumerateFiles).

I’m looking forward to use these in ID3 renamer when .NET Framework 4 will be released.

Tags: ,

Second feelings about the new SSD

Let’s call it a day. I’m now running my new Intel X25-M SSD for a little bit more than a day, but more importantly one working day. Shortly, I’m pleased.

I don’t know, maybe my expectations yesterday were too high or maybe I wasn’t just observing (or had no time) the useful stuff. And as correctly this morning my friend Petr Kaleta pointed, I’m not only comparing the disk itself, but also the rest of the system (Dell Latitude D620), whether it’s able to keep up with the disk.

Anyway new observation from today is seeking. Simply forgot about it. First you not hear it – no moving heads, no sound. So somewhere in background you feel something is different. And other fact is that the “seeking” is so fast, you’ll waste other time checking email etc. My Opera, right now with 30 tabs, starts with same speed as empty Chromium was doing on old disk. And it’s not only about the start, when you see the application it’s ready to work with. The post-start processes are already done. Same with Outlook. It behaves really instantly when switching folders, searching, checking calendar etc.

Other piece I noticed is working with virtual machines. You know, I run all my development environment in VMs, hence I stress it a lot. The start up is roughly two times faster as I wrote yesterday. The suspend is even faster. But when you suspend one and start another it’s significant. Normally I was waiting a long time, the disk was overloaded. Now, it doesn’t matter. Same speed.

Another chapter is working inside the VM. The applications there are working faster, thanks to the good seeking behavior. The Visual Studio 2010 RC there starts in under 10 seconds (loading solution with one DAL and BL library and one console application). The first compilation is about four times faster, subsequent ones are not such a big improvement as good piece of work is CPU bound. I like this improvement a lot.

The battery life seems to be about 50% better. It depends very on what you’re doing (and in what shape your battery is), and I even don’t remember exactly how quickly was my battery discharging before. So it’s based on my estimate how many tasks I was able to solve before need to recharge. :) Bear with me.

Last stuff I was carefully observing was installation of Opera 10.50, which came out today. After 15-20 seconds the installation was done. The progress bar flew couple times from left to right. I put this down again to great seeking times (the installation pack is around 10MB, no huge data).

The rest of work is more pleasant. It’s not lightning fast (as I expected for the first time – I know it’s not RAM, beat me :) ), but your not waiting for the disk too much. And maybe it’s just me, but I feel more relaxed when the machine waits for me not vice versa. :D

If you have any questions or you want me to test something, let me know, I’ll try my best. Oh, for true geeks, I’m running SSDSA2M160G2GC (model code) or SSDSA2MH160G2XX (product code) Intel X25-M 34nm SATA SSD.

Tags: , , ,

New SSD (Intel X25-M) – first feelings

It is couple of hours I’m using my new SSD – Intel X25-M. I ordered it to improve and speedup by working environment.

I’ll start with the migration steps I performed. My initial idea was to use “Complete PC Backup and Restore” function that’s available in Windows 7 (since Windows Vista, I think). As the hardware, except the disk, will be the same it should work smoothly. Research on some blogs and also some friends confirmed this idea (especially Michal Altair Valášek). You create a backup, swap disks, boot from DVD and start restore. Simple and also nice, that such a tool is available directly in Windows.

That was the original idea, and I did the backup just in case and also another two (you know, it’s my data). But my disk came with something called Apricorn Notebook Hard Drive Upgrade Kit. Basically it’s a USB bay for disks and bootable (not only) CD with some rebranded version of Acronis True Image (as I’ve found in some discussions). This tool, among other, can do the disk-to-disk copy. After the first boot and doing nothing just looking what it can do I decided to use it. If you’re asking why, it’s probably because it looked as simpler and more straightforward way. After some time the operation was done.

After boot the system found the drive, installed drives and asked me for reboot. Nothing bad (so far) happened.

Now about the performance. I state beforehand, that I’m using the drive only a while and I don’t have any numbers and I’m going to do any tests.

The first think that literally made me confused was the noise. Well the lack of any noise. Really, the drive is completely silent. And for a guy used to hear the disks from various notebooks, computers with and without cases, NASes for many years it’s really weird. I was so confused I don’t hear the heads seeking a turned off the stereo and looked for some problem. :) On the other hand it’s nice to have completely silent notebook (except times the fan is on).

The boot of Windows 7 was little faster, but nothing killing speed. Same after logging in. When you start application you can definitely feel it’s faster, especially application doing a lot of I/O, like Opera, Outlook or VMWare Workstation when starting VM. Roughly two times faster. But to be honest it’s not a high order of magnitude I was expecting (maybe I expected it to be close to RAM).

Anyway it’s just couple of hours. I’m pleased with the result so far. The drive is completely silent. It’s perceivable faster. And the battery life should be better too. I’ll give it hard times later while doing real work and report back.

Tags: , ,

Sherweb’s Hosted Exchange – what a great service

Generally, I’m not commending services I’m using here. But experience from today is just too great not to share it. I’m using Hosted Exchange from Sherweb.

Last week I ordered something from one e-shop and I didn’t received the email neither the next one after phone urgency what is with my order. Today morning I jumped into support chat with Sherweb and we found that emails has been blocked because of the sending mailserver was on two blacklists. Yep, I thought it’ll something like that. But the people from Sherweb were able not only to found the reason, but also find the emails and manually redeliver(!!!) these after a week(!!!).

Wow. I can’t be more pleased with the attitude (and steps they’re able to do – in most setups I’ve seen, the rejected email is after bouncing the mail (if used) deleted) of Sherweb. The Hosted Exchange service provided is simply great, great service!

Tags: ,

Complex types and stored procedures – 2nd edition

Some time ago I was writing about not supported scenario when you have entity with complex type and you want to map result of stored procedure to this entity. I couldn’t believe that this, from my point of view fairly common, scenario will not be supported in designer in RTM.

Right now I’m running RC of Visual Studio 2010 (the development probably in feature freeze mode) and the limitation is still there. :( Jeff Derstadt was not lying. Although Zeeshan Hirani in forum said, he was able to do it manually, it’s uncomfortable. Same as complex types in EFv1.

Looks like complex types, sadly, are still not first class citizens for designer.

Tags: ,

Spatial data and Entity Framework – from real world usage

Julie Lerman created a post about spatial data usage in Entity Framework. Her conclusions are correct. But because from last three projects I did on Entity Framework two of them are working with spatial data (every customer wants a Google Maps or Bing Maps on website, it’s like cup holders in cars) I would like share my solution as well some ideas behind why I used this approach.

First and foremost Entity Framework doesn’t support spatial data now. So you have to create some workaround. The idea getting the data through blob is exactly what I created. In my tables where I need to save some coordinates (it’s mainly a point) I create simple column with this data type – I consider this clean initial work better, because maybe sometimes/somewhere/somebody will work with this structures so to have it clean. Then for the workaround I add XXX_bin column where I’ll store the binary representation of spatial data and use it for Entity Framework. Something like this:

[Location] geography Default geography::STGeomFromText('POINT EMPTY', 4326) NOT NULL,
[Location_bin] Varbinary(max) NOT NULL,

Because I’m working only through Entity Framework I need to update the Location automatically as there might be (and are) indices or other stuff working with it. To make it transparent I’m using insert or update trigger:

if (update(Location_bin))
begin
  update %tablename% set
    Location = geography::STGeomFromWKB(Location_bin, 4326)
  where
     ID in (select ID from inserted);
end

If you expect somebody updating the Location column directly too, you need to create another trigger and make sure you’ll not end up in infinite loop.

To support the – in my case – points for UI developers I create in every entity computed property turning Location_bin into my LatLong struct. This struct is using Microsoft.SqlServer.Types namespace.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Types;

namespace FooBar
{
    public struct LatLong
    {
        public double Lat { get; set; }
        public double Long { get; set; }

      public static LatLong FromSqlBytes(byte[] bytes)
      {
        SqlGeography g = SqlGeography.STGeomFromWKB(new SqlBytes(bytes), 4326);
        return new LatLong { Lat = g.Lat.Value, Long = g.Long.Value };
      }

      public byte[] ToSqlBytes()
      {
        return SqlGeography.Point(this.Lat, this.Long, 4326).STAsBinary().Buffer;
      }
    }
}
public LatLong Location
{
  get
  {
    return LatLong.FromSqlBytes(this.Location_bin);
  }
  set
  {
    this.Location_bin = value.ToSqlBytes();
  }
}

This creates almost seamless support for other developers when using spatial data in Entity Framework – inserting, updating, deleting all works without notice from others (if you’re not looking into internal implementation).

There are only two problems, both solvable.

First one is that developer cannot filter/sort/… using Location property. This isn’t probably a big problem. As (s)he doesn’t have spatial methods (like i.e. Distance) available, so the queries will not make sense. Which brings me to the other problem and that’s the querying. With EFv1 I created stored procedures for these queries and returned data through these. Same works for EFv4. If you have strict set of results you need, this is probably easiest solution. The other one, working in EFv4 is LINQ function imports via EdmFunction attribute. For computations I’m going to use I create function in T-SQL doing the work and I import it into my solution thru above noted attribute. The simple Distance method may look like:

create function Distance
(
  @Location_bin1 varbinary(max),
  @Location_bin2 varbinary(max)
)
returns int
as
begin
  return geography::STGeomFromWKB(@Location_bin1, 4326).STDistance(geography::STGeomFromWKB(@Location_bin2, 4326));
end

And

[EdmFunction("model.Store", "Distance")]
internal static int Distance(this byte[] location1, byte[] location2)
{
  throw new NotSupportedException();
}

Sure, when calling this function for a big resultsets it may be a performance bottleneck (I recommend doing there as much work as possible, even at the price of more functions doing similar stuff, to not create a deep function calls.), but with additional filters it works well.

protected IQueryable<Something> SomethingInDistance(LatLong point, int distance)
{
  byte[] spatialData = point.ToSqlBytes();
  return this.Somethings.Where(o => o.Location_bin.Distance(spatialData) < distance);
}

Another way could be to create a view (if you know the parameters in advance) and do explicit join (table/entityset <> view/entityset) in EF. Or do the filtering on client (if reasonably small). And I’m sure I’ll find other ways how to get the data you want back, simply choose what fits your needs best.

Although it may look like a lot of work, it isn’t. In fact you’re pretty fast (there’s a high level of reusability) if you know what to do (and after one implementation you will).

Tags: , , , , ,

Managing TortoiseSVN commit and update from command line and creating PowerShell alias

I started to using PowerShell in my development environment simply to learn it a little bit more (though I’m still using the old command from cmd or UNIX) and also to get out of the stone aged cmd. And because I’m using the console a lot – yep, I get used to it on UNIX/Linux machines with terminal access) I was not happy to open explorer just to issue commit or update to/from SVN (these are most common commands I’m using, together with diff in commit window).

And happily TortoiseSVN has a utility to manage most of the basic tasks. It’s called TortoiseProc. To do commit or update in current directory, you’ll simply execute:

tortoiseproc /command:commit /path:.

or

tortoiseproc /command:update /path:.

For a while I was happy with it. But typing it everytime or looking into history (I wish cmd/PS had Ctrl+R as bash has) was not perfect for me. So I started looking for a way to create alias in PowerShell. Some kind of alias. PowerShell, sure, has something like this, I thought. And it has – Set-Alias. Though, limited. If you try to create alias to command with hardcoded parameters, …

set-alias commit "tortoiseproc /command:commit /path:."

… as I was trying, you’ll not succeed. After some searching and trying I found and an idea from Andrew Watt using a function (yes, I’m a PowerShell newbie). It’s easy and convenient to wrap the command into it.

So finally I create PowerShell aliases for TortoiseSVN to nicely support my work from command line:

set-alias update fn_update
set-alias commit fn_commit
function fn_update {tortoiseproc /command:update /path:.}
function fn_commit {tortoiseproc /command:commit /path:.}

Tags: , , ,

SQL command when inserting M:N association with identity columns in the underlying table

Today I uncovered a magic command from Entity Framework v4 when you create M:N association and the underlying table is defined with both columns as identity (you insert there). I don’t what’s it good for, as this table in fact only stores the two IDs to connect other tables. But somebody may build some logic on identity there, sure.

When I first saw the command, I was completely stunned. I had no idea what’s going on there and whether I see there one or more commands. You can have fun too:

declare @generated_keys table([ID_A] int, [ID_B] int)
insert [dbo].[A_B]
output inserted.[ID_A], inserted.[ID_B] into @generated_keys
default values
select t.[ID_A], t.[ID_B]
from @generated_keys as g join [dbo].[A_B] as t on g.[ID_A] = t.[ID_A] and g.[ID_B] = t.[ID_B]
where @@ROWCOUNT > 0

As an old school guy I was first looking for semicolons and then later tried to decode it by “parsing” the content.

Isn’t it nice… :)

Tags: , ,

EdmGen2 with EFv4

EdmGen2 is a nice tool. Especially if you know EdmGen you may find it useful. I.e. you may speed up the start of you application by pregenerating views directly from EDMX file.

Unfortunately if you try to use it with EFv4 it will crash. But we have sources, why not to fix the problem? And that’s what I did.

First problem was with new namespaces the EFv4 EDMX file has. The new ones are:

static string csdlNamespace = "http://schemas.microsoft.com/ado/2008/09/edm";
static string ssdlNamespace = "http://schemas.microsoft.com/ado/2009/02/edm/ssdl";
static string mslNamespace = "http://schemas.microsoft.com/ado/2008/09/mapping/cs";

The next step is to switch the project to target .NET Framework 4, you can do it in project options. And finally check whether the references, especially System.Data.Entity.Design, where the interesting objects are, are pointing to “4.0.0.0 versions” and correct if needed.

Done. Build and use. And if you don’t wanna to have it without work, grab this file with all changes already done.

Tags: ,

New Windows Mobile 7 – why people see so much “problems”?

There’s a lot of rumors about the new Windows Mobile 7, especially in last days before MWC. A lot of unconfirmed information is flying around and lot of comments. What I would like to focus on is backward compatibility, Marketplace, Compact Framework and new look and feel of homescreen.

A lot of folks is not happy about dropping backward compatibility. I, on the other hand, am pleased with this step. The world has changed, especially the mobile world. What was ok in 2001, is not in 2010. I like new trends in control, give me that on WM too.

Marketplace should be only way to get application into device. For me as a developer this is little scary, because even for simple free utility you’ll need to buy certificate for developer. But if the applications will be thoroughly tested, I’m ok with it. And may increase the quality of apps as well.

Backward compatibility for Compact Framework is interesting too. The idea of writing application in current century’s tool like C# and .NET with GC and nice libraries I like. But JITing on not so much powerful devices? I don’t know. Here I like the speed and responsiveness of app. What MonoTouch is doing is IMO the way. And if MS would provide such a tool … neat!

I don’t know whether the screenshots and descriptions I saw/read are close to the reality or not (we’ll see in couple of days), but it looks like, there’s no classic home screen as I use it now (with Spb Diary) (and how some screens show the new iPhone OS will have it) – tasks, appointments for next couple of days/weeks. This means a lot of people will be pissed off, because the device is also work and productivity tool. Will it degrade it to into “just” device for fun, while iPhone will be slowly trying to get the attention of people using the phone for work half of the day too?

Tags:

iPad vs. Kindle

There’s a lot of blogposts about iPad and why somebody (not) loves it. What I wanna to do is think about is as Kindle competitor, because that’s also one target for iPad (at least from what I’ve heard).

Let’s start with my opinion. If you like reading and you’re reading a lot Kindle beats iPad easily. Let me tell you why.

First it’s the battery life. iPad is declared to last for 10 hours. That’s funny. My Kindle with wireless turned off survives a month. 10 hours isn’t simply enough if you’re traveling or you’re on vacation.

Next is the display. I don’t think iPad will have bad display, the big multi-touch screen is sure a nice piece of hardware. But for a reading, the back-light is problem. I’m a developer and I read a lot from LCDs, but the eInk in Kindle is definitely another level when reading text. You’ll not believe me, until you try it yourself. Your eyes are completely untired after reading.

Finally some of my absolutely personal “arguments”. The size (from point of reading). I know sometimes, I’m saying that I wish Kindle (normal) had a bigger display, especially when reading PDFs (http://twitter.com/cincura_net/statuses/8600418870). But when reading pure ebook, it’s ok. And the size is, in my opinion, just good to take your Kindle everywhere with you. Not so sure about iPad.

Tags: ,

Complex types and stored procedures

I like the idea of complex type. Sadly the designer didn’t supported complex types in EFv1/VS2008, although you could use it manually editing the model (it’s just a XML file). The designer in EFv2/VS2010 supports complex types (and you can use it also with EFv1, see this) hence it’s time to start really using these.

Unfortunately nothing is perfect. As far as you don’t wanna map some stored procedure result to collection of entities, then the designer will tell you, that it’s not supported. :( And Jeff Derstadt pointed in forum that this limitation will not be solved in RTM.

I’m using EFv4 in my current project and thanks to ability to map functions directly to LINQ functions via EdmFunction attribute I was able to to a lot of work via functions and queries created by EF itself. But I always feel a little bug in my head saying “What if you’ll need it later?”. Sure I can redo all back into direct properties, but if it’s close to the end of the project it’s pretty expensive to do it.

What a pity, I see complex types as a good concept, but I’m too careful to close myself the path with SPs.

Tags: ,

Connecting from iPhone to Firebird

During the Friday I realized, that I did a long time nothing with my iPhone & MonoTouch development environment and I should try something more challenging. As I’m still fighting with some good idea for real world test application and my UIs are looking weird, I decided to turn my attention not to iPhone app directly, but to MonoTouch capabilities.

As a true geek I decided to try to connect to Firebird from iPhone. Although, thinking about it, I’m trying to connect to Firebird (or make it work with) with various technologies (Astoria offline, Silverlight, etc.). Because .NET provider for Firebird is pure C# and we have Mono compatible build, I deduced that it should work with iPhone too.

Sure, it’s a nice challenge to whole MonoTouch stack, because the .NET provider is more about the code than about the application itself. And we’re using there a lot of different things that can go wrong or may not be available or compilable to native code. And I have to say, the guys behind MonoTouch did a great work (I still can’t believe it).

With couple of minor tweaks I was able to create application that connects from iPhone (simulator) through internet to Firebird server. Pure C#, no hacking or major problems.


Application connecting to Firebird server and showing the server version.

First I’m impressed how mature the MonoTouch is. Second I’m still trying think thru all the possibilities you have with this. With some work on UI you can deliver the same database oriented application to Windows Mobile and iPhone using the same business layer (sure some webservice approach would be better, but …).

Looks like it’s time to stop playing and get some serious test app done.

I’m wondering whether we should start providing build of .NET provider for Firebird for MonoTouch/iPhone, as we have for Compact Framework?

Tags: , , , , , ,

Interface Builder crash

I think the whole iPhone SDK knows I’m from the other side of the barricade. :D What else would explain the error I faced today after less than a minute when working in Interface Builder.

On the other hand I was brave enough to send the error report (as I was able to reproduce it quite easily), so maybe it’ll be fixed in next version. Good turn? Anyway sooner or later I’ll convince the machine that I’m not a bad guy.

Tags: ,

Be careful with “not” conditions and nulls in LINQ when querying databases

Today I seen a code with good chance of hard to find mysterious bugs. Let’s start with database table structure we’re going to use for demonstration.

create table NullTest(id int primary key, b bit);

insert into NullTest values (0, 1);
insert into NullTest values (1, 0);
insert into NullTest values (2, null);

If you now try to query this table via LINQ (i.e. LINQ to Entities) you may get surprising results.

foreach (var item in ent.NullTests.Where(x => x.b != true))
{
	Console.WriteLine(string.Format("ID: {0} \t B: {1}", item.id, item.b));
}
Console.WriteLine("===");
foreach (var item in ent.NullTests.AsEnumerable().Where(x => x.b != true))
{
	Console.WriteLine(string.Format("ID: {0} \t B: {1}", item.id, item.b));
}

If you run this code, you’ll get different results.

ID: 1    B: False
===
ID: 1    B: False
ID: 2    B:

What happened? Is the database engine doing something wrong? Or is there a bug in LINQ? Neither of those. In fact both results are correct. The second one (evaluated in .NET on client) is obvious why it’s as is. But what happened in processing of first one (evaluated on database side)? The devil is in NULL logic. Every operation with NULL results in NULL or false if it’s a boolean operation. And this exactly explains the inconsistent result. In .NET null != true is true but in databases it’s false (because of the NULL rules described above).

Thus if you’re writing LINQ query for database, although the impedance mismatch should be hidden from you when using LINQ, you need to take into account different NULL handling in database engines and in .NET (or any common programming language).

Remember the DBNull.Value? That was explicit solution for this “problem”.

Tags: , ,

Knetlik – konference o .NET

13. února 2010 (sobota) se koná zajímavá konference okolo .NETích témat s podtitulem “Bringing Good Software Architecture”. Registrace je dostupná na známém místě. Program pak naleznete na knetlik.cz.

A proč je to konference zajímavá. Kromě přirozeně kvalitních témat ;) je to jejich délka. Pouze neobvyklých 10 minut (+5 minut pro otázky). Předpoklad je, že posluchači udrží takto lépe pozornost a vstřebají více informací. A ty budou ještě vlastně hodně kondenzované, aby člověk něco smysluplného řekl a přitom se vešel do časového limitu. Těším se, až uvidím, jak to funguje (nebo taky ne).

Tags: , ,

Školení Firebird (3.)

Společně s Databázovým světem tu máme další Firebird školení. Více informací, včetně možnosti přihlášení na: http://www.dbsvet.cz/view.php?cisloclanku=2010012101.

Tags: ,

Extending IQueryable with superset method and StackOverflowException

Yesterday I was creating extension method for Skip for IQueryable. I needed to accept the nullable integer and if null just skip any processing. Something like this:

static IQueryable<T> Skip<T>(this IQueryable<T> resource, int? count)
{
	return (count.HasValue ? resource.Skip(count.Value) : resource);
}

I thought it will pick the int version from framework, because I’m calling it with int and not int?. And I was wrong, what my colleague uncovered moments later. How to solve it? I was not happy with method rename and I felt there’s a way.

Actually the solution is pretty easy. The original Skip is just extension method, right? So it’s in static class as static method. So I can call it with class definition as non-extension method and this this there will be no ambiguity. Voilà.

static IQueryable<T> Skip<T>(this IQueryable<T> resource, int? count)
{
	return (count.HasValue ? Queryable.Skip(resource, count.Value) : resource);
}