Archives for October, 2009

29
Oct

My Timer usage and references moral

Few minutes ago I got flash of intelligence. I’m using Timer in one of my windows service running simply 24×7. And I had a bug getting wrong data on server that I was not able to reproduce locally. Same data, same code, nothing. That was pretty weird, because after roughly four days I restarted the service and it started working correctly.

I opened a debugger, started the service locally and went for some candy. Because the data should be refreshed by default every two minutes, when I came back I realized, that the refresh procedure was not run, because there was a breakpoint, but no hit. So I started looking for some info in documentation, when suddenly the note followed by recalling the knowledge came in:

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

Yep, I was creating the instance but I was not holding a reference to it, so in under the refresh interval it was garbage collected. : Shame on me. But. We learn by mistakes.

24
Oct

Přednáška ADO.NET Entity Framework – MFF UK, Praha

Pokud jste nestihli první pražskou nebo brněnskou přednášku, máte v Praze další šanci. 3.11.2009 (úterý) od 17:20 v rámci programátorských večerů na MFF UK.

Více info zde nebo zde, registrace na http://akce.altairis.cz.

Prezentace ke stažení.

24
Oct

Kindle (International) – první zkušenosti

Kindle konečně včera dorazil, takže jej nyní mám necelých 24 hodin a ještě musíme odečíst spánek. Poznatky jsou tedy zatím povrchní.

Nejprve obrázek – porovnání Kindlu s běžnou kreditní kartou.

Kindle je jednoduchý – za dvě, tři hodiny zmáknete 99% funkcí, včetně vyzkoušení. Tlačítka jsou jasná a ovládání jednoduché, přímočaré. Žádné složité nastavování. Je třeba se připravit, že primárně je to zařízení „pro čtení“, takže vše se točí kolem toho – nečekejte nic dalšího.

Zařízení je fakticky čistě bílé, obávám se, že po čase používání dostane povrch docela zabrat. Což mě přivádí k myšlence, že obal bude asi fakt nutnost. Nejprve jsem jej neobjednal, ale pokud Kindle hodláte používat „všude“, ochrana bude rozhodně vhodná (minimálně pro vršek).

Do sítě se bez problému přihlásil. Samozřejmě jsem zkusil nakoupit hned přes Kindle Store. :) Mimochodem za procházení Kindle Storu se neplatí, i když samozřejmě data tečou. Noviny i knížky jdou bez problémů. Koupíte, 1-Click payment pořeší platbu a během chvíle je obsah v zařízení (případně lze načtení vynutit).

PDFka, HTML stránky i DOC lze do zařízení dostat přes konverzi emailem – pošlete soubory na danou adresu, a buď za poplatek přijdou přes Whispernet nebo zadarmo mailem zpět a můžete je nahrát do zařízení přes USB. Kindle je vidět jako další disková jednotka.

Jediné co jsem (zatím) objevil, že nefunguje, je brouzdání po internetu v experimentálním prohlížeči. Nicméně je to i uvedené na stránkách Amazonu, takže jsem to spíš zkoušel „co kdyby“. Text-to-Speach a přehrávání MP3 funguje bezvadně, ale o tom Kindle asi není …

Čtení je ukrutně pohodlné. A to jsem posledních osm let četl všechno z displeje notebooku – skripta, PDF knížky, články, různé papery. Začínám věřit těm oslavným hláškám o znovuobjevení čtení. Začetl jsem se a skončil až po hodině a půl, když jsem si uvědomil kolik je hodin. Regulovat jde velikost písma a počet slov na řádek (udělají se větší okraje). Obrázky vypadají rozumně. 16 odstínu šedi stačí i na screenshot Visual Studia, aby člověk poznal o co tam jde. Diakritika není problém. Zdrojáky jsou čitelné, někdy je akorát odsazování pryč, ale to se dá přežít.

Navigace je velmi pohodlná. V knihách lze skočit na začátek, na obsah, po kapitolách (nebo obecně to co tvůrce specifikoval jako dělení) a samozřejmě po stránkách. V novinách na začátek, na kategorie, po článcích a opět po stránkách. Pokud mělo vaše PDF obsah s „odkazy“, konverze je zachová a můžete se z obsahu dostat rovnou na vybranou kapitolu.

Také jsem pochopil ten tlustý okraj kolem displeje. Na první pohled to vypadá skutečně jako plýtvání místem, ale později jsem pochopil, že to místo je krásně připravené na chycení rukou, případně položení palce. Možná by mohl být menší (a možná je vynucen konstrukčním řešením displeje), nicméně maximálně tak o půl centimetru.

Jinak se Kindle nabijí přes USB (u mě asi 2,5 hodiny do plna, ale nebyl prázdný) a v balení jsem dostal i americkou zástrčku (tedy u nás úplně na nic).

Po prvním dni nelituji koupi. Pokud rádi nebo hodně čtete, Kindle je jednoznačně dobrá volba. Uvidíme, co bude dál. :)

Máte-li libovolný dotaz, využijte komentářů. V případě, že budu znát odpověď (nebo to budu moci zkusit, vyfotit, …), odpovím. A také můžete navštívit stránky Kindle.

Zobrazení kódu (původně byl barevný):

Obrázek (IE se Silverlight aplikací s tlačítky):

23
Oct

Attaching non-detached entity in Entity Framework v4 doesn’t throw exception

While slowly digging into Beta 2 of EF4 I discovered new nice “feature”. In EF1, if you had code like this.

master[] data;
using (testovaciEntities ent = new testovaciEntities())
{
	data = ent.masters.ToArray();
}
using (testovaciEntities ent = new testovaciEntities())
{
	foreach (master item in data)
	{
		ent.Attach(item);
	}
}

It threw InvalidOperationException saying An entity object cannot be referenced by multiple instances of IEntityChangeTracker.. Right but I don’t have access to my previous context anymore. This behavior caused me a lot of headache and I created couple of hacks to workaround it. But the good news is that the code above works fine in EF4.

Neat! Together with other improvements I can get rid of my hacks and sleep well again. ;)

23
Oct

Associations without foreign keys

Michal Bláha asked me, before my session when I stopped in his office, whether it’s possible to create associations in Entity Data Model without foreign keys in database, as he’s not using FKs, he’s enforcing referential integrity in application (yeah, if you’re transaction guy like I am, your brain is about to blow).

Well, it’s for sure possible. First we define some simple tables:

create table test_master(
  id int primary key,
  foo nvarchar(20) not null
);

create table test_detail(
  id int primary key,
  id_master int not null,
  bar nvarchar(20) not null
);

You see, no FK defined. Then you generate model from database, just next > next > finish style and you end up with:

Now the magic begins. :) Just kidding. First delete the id_master column from entity, it has nothing to do in conceptual model. Next create new association (right click in empty space in designer) and create it as 1-*. OK, we’re almost there. The last step, is to map the association. It’s mapped to test_detail: test_master.id to id_master and test_detail.id to id.

Now you can start querying the data across associations.

string s = context.test_master.Include("test_details").ToTraceString();

Easily done, isn’t it.

22
Oct

Superb gesture from Amazon

Few days ago I bought Amazon Kindle, the international version, as I’m not U.S.. The international version is was +$20 to the U.S. only version. And today I got email from Amazon saying that the price has been lowered to U.S. only price and that I’m getting my $20 back. 8)

Good news! Due to strong customer demand for our newest Kindle with U.S. and international wireless, we are consolidating our family of 6″ Kindles. As part of this consolidation, we are lowering the price of the Kindle you just purchased from $279 down to $259. You don’t need to do anything to get the lower price–we are automatically issuing you a $20 refund. This refund should be processed in the next few days and will appear as a credit on your next billing statement.

That’s a really nice gesture! Kudos to Amazon.

I’ll post my first experience tomorrow, when it will be finally delivered.

22
Oct

Enum.HasFlag is in .NET 4

Today I noticed, that in beta 2 of .NET Framework 4 (and Visual Studio 2010) there’s a new method for enums – HasFlag. Using bitwise operators was sometimes ugly and decreased the readability of code, hence (I think) almost everybody wrote similar method i.e.:

static bool HasFlag(this Enum e, Enum flag)
{
	return ((Convert.ToInt32(e) & Convert.ToInt32(flag)) != 0);
}

But now it’s directly in framework. Great! I like these small additions that make life easier.

21
Oct

What’s new in Entity Framework 4 Beta 2 and ADO.NET Data Services 4 Beta 2

Nice list at http://blogs.msdn.com/adonet/archive/2009/10/19/vs2010-and-net-framework-beta-2-announced.aspx.

18
Oct

Firebird(Client) with Silverlight

I had this idea on my list for a couple of months and I was always postponing it, because it’s stupid. But you know. Exploring the unexplored ways, that’s what I like to do :) .

But during (or after, I don’t remember) my presentation about Entity Framework there was a question about accessing the data provided by EF from Silverlight. Sure, doing it directly isn’t a good idea and in fact this is the reason why Astoria, eh, ADO.NET Data Services is here. But is this really stupid? Can it work?

Nope. Not at all. I tried to build FirebirdClient in a Silverlight environment and I failed. I expected to fail after some attempts with modifications and using only subset of features like i.e for Compact Framework, but this was really fast. Silverlight is only subset of .NET Framework. And one crucial part is not there, it’s System.Data stuff and without it you can drop major part of any ADO.NET provider’s code.

If you need data, use ADO.NET Data Services or any other webservices (which will also fit for DDL etc. commands). That also means, that writing Silverlight based Firebird database manager (without any support backend), which is one of few reasonable ideas, cannot be done either.

18
Oct

Memory mapped files in .NET 4

Similarly to my way to CountdownEvent class, I found MemoryMappedFiles namespace, which is new in .NET 4. It’s in System.IO.

If you’ve done some work in stone ages in C/C++ or maybe ObjectPascal (Delphi) you may remember using these files. I used these for exchanging data between two applications, but the usage is pretty much endless. And now you can benefit from it in .NET directly, without using P/Invoke.

To see what’s inside, I wrote two simple applications that are reading and writing some data (no synchronization ;) ).

The first one is doing writing and reading:

using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("TestMemoryMappedFile", 1024 * 1024))
{
	using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor())
	{
		HelperStuff.WriteData(accessor, 0);

		Console.ReadLine();

		HelperStuff.ReadData(accessor, 0);
	}
}

and the second one is just reading:

using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("TestMemoryMappedFile", 1024 * 1024))
{
	using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor())
	{
		HelperStuff.WriteData(accessor, 0);

		Console.ReadLine();

		HelperStuff.ReadData(accessor, 0);
	}
}

Nothing magical. The reading and writing methods (placed in shared library) are simply creating some dummy data. In my case struct and string, saved as array of bytes.

public static void ReadData(MemoryMappedViewAccessor accessor, int position)
{
	SomeData data1;

	accessor.Read<SomeData>(position, out data1);
	position += Marshal.SizeOf(typeof(SomeData));

	int length = accessor.ReadInt32(position);
	position += Marshal.SizeOf(typeof(int));

	byte[] data2 = new byte[length];

	accessor.ReadArray<byte>(position, data2, 0, data2.Length);

	Console.WriteLine(data1.CurrentDate);
	Console.WriteLine(Encoding.Unicode.GetString(data2));
}

public static void WriteData(MemoryMappedViewAccessor accessor, int position)
{
	SomeData data1 = new SomeData() { CurrentDate = DateTime.Today.Ticks };
	byte[] data2 = Encoding.Unicode.GetBytes(DateTime.Today.ToLongDateString());

	accessor.Write<SomeData>(position, ref data1);
	position += Marshal.SizeOf(typeof(SomeData));

	accessor.Write(position, data2.Length);
	position += Marshal.SizeOf(typeof(int));

	accessor.WriteArray<byte>(position, data2, 0, data2.Length);
}

The struct is really dummy:

public struct SomeData
{
	public long CurrentDate { get; set; }
}

The reading and writing is little bit limited, as you’re in fact dealing with just a bunch of memory, not some structured storage. But if you like working with it directly as stream (or you have some smart wrappers around streams), you can also use method CreateViewStream instead of CreateViewAccessor used in my example. These method have some overloads with option to specify also the access rights using MemoryMappedFileAccess, so you can i.e. use CopyOnWrite and any write operations will not be seen by other processes.

11
Oct

Firebird Developers’ Day 2009 :(

Možná jste si všimli, že jste si nevšimli žádné upoutávky na letošní Firebird Developers‘ Day. Není to chyba na vašem přijímači. Zatím žádné takové oznámení nebylo.

Popravdě, letos to s Firebird Developers‘ Day vypadá špatně. Ačkoli stále tvrdím, že “krize” je do jisté úrovně vyšroubovaná médii, asi zde v druhotné úrovni zasáhla. Jak jistě víte, Firebird Developers‘ Day je konference, která je zdarma, proto veškeré náklady musíme pokrýt ze sponzorských darů. Bohužel letos, jedna z hlavních úlev, kterou jsme měli – sál Věž na pražském Albertově není letos dostupný. A náklady na libovolné komerční prezentační místo jsou pro Firebird Developers‘ Day astronomické.

Zatím se nevzdáváme, je možné, že se něco podaří najít. Nicméně stále více začínáme uvažovat o přesunutí Firebird Developers‘ Day na jarní termín a výběr malého vstupného, které by pomohlo problémy s náklady vyřešit. Osobně si myslím, že konference je skvělou možností setkat se s lidmi z oboru a vyslechnout si (doufejme) zajímavá témata z různých koutů Firebirdu a proto by nemuselo být např. 200 korun dramatických pro návštěvníka a přitom by rapidně pomohlo konferenci.

Není to dobrá zpráva, ale nic není ztraceno. Tak jako tak, rád bych slyšel vaše názory na zavedení rozumného vstupného. Je to nepřekonatelný problém?

11
Oct

Multithreading with Entity Framework

From time to time I get a question about using ObjectContext from more than one thread. Because Entity Framework sits on top of ADO.NET, it’s obvious, it cannot be thread safe. So if you need to use n threads, use m (where m>=n) ObjectContexts. That’s the easy way. But what if you really need to share ObjectContext between threads?

The first fact is, that you cannot run more statements at a time, because it will sooner or later create mess in provider. So the solution is to carefully lock the usage. Not good for scaling, but you can do (almost) nothing with it.

Another basic issue is that with IQueryable (if you’re using LINQ) you don’t know, when the query gets actually executed. Until somebody calls for example ToArray, it’s just a definition/shape of the query. And when it gets executed, the code can be out of your method or out of the lock. For sure. The composition will be affected little bit. You can create a rule, that everything you’ll be exposing to UI (or any higher level) developers will be for instance List<T>. Then you will probably need to prepare significant amount of methods, for almost every data projection, selection, … they need. Good news is, that you can hide (make i.e. internal) the original methods, and nobody will screw up something.

Maybe better option is to create simple method taking complete query as parameter and returning the data i.e. as IEnumerable (simply saying, fetched from database). This is good, but everybody has to be attentive, using only this method (it will be generic, so it may look little weird using it with anonymous type, but works and you can find something about it looking for “cast by example” using your favourite search engine). As a good side-effect, you can add easily add i.e. logging of queries being sent to the database from application.

Stored procedures are executed immediately (are not composable), thus you can just create simple wrapper around it with lock. Easy.

The rest is  saving changes. The SaveChanges method is virtual in EFv4, so your own implementation with lock will be easy (and you can use T4 templates for ObjectContext to make the code with lock right from generator). In EFv1, the story is similar as with querying. Create separate method and tell everybody use only this one or swat the original over with your own using new keyword.

Last topic that’s in my head right now, is working with entities in code – changing properties (don’t forgot associations). If one entity will be edited in more than one thread, you may (or may not) confuse ObjectStateManager as the overlapping change tracking may kick in. To be on the safe side, I think avoiding this is best way – choose whatever you like for doing it (and take into account that one thread can be editing the entity and the other one refreshing it from store, for instance, so choose proper granularity of lock (or introduce some rules into your code/team ;) )).

I don’t know whether I cover all main basic stuff you can do with EF as I’m writing it from top of my head, bare with me and feel free to comment. And be it as it is right now, if there’s 1% chance of being able to use separate ObjectContexts, do it. It will prevent you lot of headaches.

11
Oct

Model Defined Function as a method on entity (or on type for store function)

Model Defined functions are new feature in EFv4. You simply define you function using EDM functions etc. in your model and then you can use it in your queries. With EdmFunction attribute you can also create stub function to use it in LINQ queries. That’s all great, and even itself makes life with Entity Framework easier.

But if you call it from LINQ (my favourite  way of querying), it’s kind of odd. You’re writing it as:

context.Persons2.Where(p => GetAge2(p) < 100);

And while I was preparing some demos for my presentation, there was a flash of idea in my head. “What if I define the function stub as extension method?”, I thought. Yes like:

[EdmFunction("testovaciModel", "GetAge2")]
static int GetAge2(this Persons2 p)
{
	throw new NotSupportedException();
}

This should work, right? It’s just sugar and the translation should work without complaining. And it really does. You can now write:

context.Persons2.Where(p => p.GetAge2() < 100)

Sweet! You can still keep these MDF method stubs in one place but use it in more natural syntax.

And by the way, it works for store functions as well (you’re just limited on types).

[EdmFunction("testovaciModel.Store", "GetAge")]
static int GetAge(this DateTime born)
{
	throw new NotSupportedException();
}
context.Persons2.Where(p => p.Born.GetAge() < 100)

I’m especially happy for store function exposed to LINQ. I’m using these in a reasonable amount in my databases and being able to filter using the function without wrapping the query into i.e. stored procedure or view is neat.

10
Oct

Přednáška ADO.NET Entity Framework – WUG, Brno

20.10.2009 (úterý) od 17:00 budu přednášet o novince (je to ještě novinka, když .NET 4 je za dveřmi?) v .NET 3.5 SP1 – Entity Framework. Tentokrát v Brně. Stejně jako v Praze se podíváme na nové vlastností, které přinese Entity Framework v4 v .NET 4, stejně tak, pokud zbyde čas, přijde na řadu rychlé info o ADO.NET Data Services (Astoria).

Registrace na http://wug.cz/Aktuality/tabid/36/ctl/Detail/mid/492/ItemId/303/language/cs-CZ/Default.aspx.

Prezentace ke stažení.

9
Oct

My Phone – folder synchronization disappointment

I just found out that My Phone was released (is it a long time or not? :) ). Although I’m synchronizing my device with Exchange server, I’m really missing (wireless) file synchronization – either with some folder on my computer or via some website. So the My Phone looked like what I was looking for.

You can synchronize certain types of files and the storage card too. Sounds great. Until you find that you cannot select folders to sync. Only file types like Music or Documents and with or without the storage card included. This might be little problem, taking into account the current space on website is 200MB and I have 2GB of data on my card. But I don’t need to sync all these, just couple of folders with important stuff.

What a pity. Hope the Live Mesh will be soon ready for Windows phones (see, new name ;) ) and will work more or less the same as on “big” computer. Or anybody knows some good similar service?

7
Oct

Moving tray icons in Windows 7

Today I found interesting thing. Tray icons in Windows 7 keep their position and you can reorder them in a way you want. What a great idea.

Because I like all tray icons to be visible, I can now place the most used closer to language bar and the other (in my case the informative) to the corner. Now as all my favorite apps have fixed place on taskbar (like it too) I can enjoy the same comfort with tray icons.

3
Oct

Generated primary key in Entity Framework model from Firebird

Firebird doesn’t have identity/autoincrement columns like i.e. MS SQL or MySQL. Firebird has concept of generators/sequences (as know i.e. in Oracle). This is more powerful concept, but comes also with drawbacks, because you can say for sure, whether the column values is generated or not. This is causing problems, if you set StoreGeneratedPattern in your model manually and then updated model from database – it’s lost. Because this can be big pain in the ass, FirebirdClient can now report the column as “Identity” if you give it little help.

If you put into comment of column #PK_GEN#, then FirebirdClient will report it as generated primary key, resulting in StoreGeneratedPattern to be set to “Identity”. Hence you don’t have to every time manually change the model and easily use automatic fetching of the value from database when saving changes. If you wanna test it, grab build from weekly builds.

3
Oct

Přednáška ADO.NET Entity Framework – Microsoft, Praha

13.10.2009 (úterý) od 17:30 budu přednášet o novince (je to ještě novinka, když .NET 4 je za dveřmi?) v .NET 3.5 SP1 – Entity Framework. A nejen to. Zabředneme také do nových vlastností, které přinese Entity Framework v4 v .NET 4. Pokud zbyde čas, na řadu přijde rychlé info o ADO.NET Data Services (Astoria).

Více info, včetně registrace na http://akce.altairis.cz/Events/298.aspx.

Prezentace ke stažení.