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
)).
Posts Tagged .NET
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.
EdmGen2 with EFv4
Feb 14
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.
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?
Knetlik – konference o .NET
Jan 21
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).
Directory.GetFiles moral
Jan 9
Oh yes. I have here another moral. And it’s not good for me, because it’s (again) described in documentation (but who reads it when there’s nice IntelliSense?). In my program ID3 renamer I have couple of custom IO operations. One of fundamental methods is for enumerating directory(ies) for all MP3 files. It’s based on Directory.GetFiles and few functions inside ID3 renamer need exact order of files. One of these functions is FreeDB search. When I was renaming files on my network share, it wasn’t finding anything. But when moving the directory to local drive everything was fine.
After some debugging I found, that the ordering of files from network share is different than from local drive. If you look to documentation you see:
The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.
Ahh, there’s your problem.
Sadly enough, the ordering from local drive looks stable and it’s based on filename as expected. Thus in a lot of cases you’ll not smell that something may go wrong. But on non local drives (for me my NAS) you’ll hit this immediately.
Never mind, could be worse (my first shot was some bug in my “MP3File” class and that will be really bad, as it could break users’ files). This can be fixed easily.
Nová verze Entity Frameworku už pomalu klepe na dveře a proto není od věci podívat se, co nového nabídne. V rámci přednášky na MS Festu projdu největší změny a vylepšení. Rozhodně je na co se těšit – pokud již EF používáte, tak na ulehčení života a pokud ještě ne, tak na ještě větší lákadla jej použít. A vzhledem k plánované večerní akci bude prostor i pro kuloární diskuze, nejen o EF.
Next Firebird conference is coming. This year in München, Germany. I’ve never been in München though it’s pretty close to Czech Rep. thus I’m looking forward.
You can find info about conference at firebird-conference.com. I’ll be speaking there too, hence if you’re interested in Firebird and .NET you should definitely come. Every day I have one session. I’ll be covering new (2.5+) protocol implementation in .NET client for Firebird 2.1, Entity Framework support (also new in 2.5) and finally you’ll see how to create Windows phone (formely PocketPC, …) application and accessing Firebird database.
And the conference will be also great place to meet people you know from list etc. and talk face to face about your Firebird related problems, challenges and solutions. If you have any specific need to show (related to my three sessions) feel free to drop line in comments.
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.
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í.
Enum.HasFlag is in .NET 4
Oct 22
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.
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.
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í.
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í.
Most of the time you’re using properties in objects that are also in database. But sometimes you may need to create property in object that’s not in database – it’s used only in this application or it’s there custom logic. Then, if you wanna use it in queries, you’re out. You can use only those properties declared in table, obviously.
But there’s a solution. First, the property has to be created from some other properties, so you’re able to do the same in database. And of course, functions used there needs to be translatable to store language too. This may limit you, but there’s nothing you can do about it, except evaluating query on client side.
Let’s have a table like this:
create table Foo ( ID int primary key, IsAccepted bit, IsPayed bit not null, IsPacked bit not null, );
And you wanna have property IsReadyToShip, in application. So you create:
public bool IsReadyToShip
{
get { return this.IsAccepted.HasValue && this.IsAccepted && this.IsPayed && this.IsPacked; }
}
But with this property you’re not able to query for all Foos ready to ship. Luckily the solution is pretty easy. First you’ll create expression for this:
public static Expression<Func<Foo, bool>> IsReadyToShipExpression = f => f.IsAccepted.HasValue && f.IsAccepted && f.IsPayed && f.IsPacked;
Then you’l prepare static compiled version of this expression, just for performance reasons, you can compile it in getter everytime too:
protected static Func<Foo, bool> IsReadyToShipFunc = IsReadyToShipExpression.Compile();
And finally the property:
public bool IsReadyToShip
{
get { return IsReadyToShipFunc(this); }
}
Right now we have the same result as before – working property. But because we also have the expressions of the property (and incidentally it’s translatable to store language
), so we can use it for querying. You can use it in an easy way (this is in this case ObjectContext used in Entity Framework):
public IQueryable<Foo> FoosReadyToShip
{
get { return this.Foos.Where(Foo.IsReadyToShipExpression); }
}
Not the shortest way to do it. But if you don’t wanna to write the condition again and again (and lower the maintainability) this is a way to do it.
Singleton shortcut
Aug 26
Probably every developer sometimes heard about the singleton pattern. I’ll be not far from truth that you’re probably writing it like this:
class Foo1
{
private static Foo1 _instance;
public static Foo1 Instance
{
get
{
if (_instance == null)
_instance = new Foo1();
return _instance;
}
}
}
I do it same way. But today I seen little bit different way. It’s using the C# coalesing operator and some C-like magic syntax.
class Foo2
{
private static Foo2 _instance;
public static Foo2 Instance
{
get
{
return _instance ?? (_instance = new Foo2());
}
}
}
Looks cool, isn’t it? On the other hand I’ll probably use the first one, as it’s more readable, at least for me.
There’re two kinds of people. 1) people doing almost everything in code; 2) people doing everything on database side. I’m in neither of these buckets.
I like doing a lot of stuff on database side, because sometimes expressing something in set operations (these are good for RDBMS) is really challenging. On the other way, when it’s easy and fast to do it in code, why bother…
From this few sentences you can guess that I like writing stored procedures. Because of this in project I’m currently working on I created some stored procedures for difficult and expensive searching and I’m mapping results back to entities in Entity Framework. The problem is that this particular entity has a lot of associations. Thus it’s more than likely somebody will need the related entities too. Sadly there’s no Include (stored procedures are not composable by default, so you cannot create left join to fetch the related data). But that was a problem, because loading – using Load method – x related entries for even small with i.e. 20 items results in 20×x calls to database. Although these queries are in most cases cheap, it’s not good for performance.
So I started creating extension methods to get this solved in a little bit better way. My goal was to have one query for one related end for all items in result. Hence there will be only x additional queries. The result is here:
Disclaimer: The code is not general purpose and contains some assumptions based on my conditions and rules.
public static IEnumerable<T> LoadRelated<T>(this ObjectResult<T> result, MergeOption mergeOption, params Func<T, IRelatedEnd>[] relatedEnds)
where T : EntityObject
{
return LoadRelatedStarter(result, mergeOption, relatedEnds);
}
public static IEnumerable<T> LoadRelated<T>(this ObjectResult<T> result, params Func<T, IRelatedEnd>[] relatedEnds)
where T : EntityObject
{
return LoadRelatedStarter(result, MergeOption.AppendOnly, relatedEnds);
}
private static IEnumerable<TEntity> LoadRelatedStarter<TEntity>(ObjectResult<TEntity> result, MergeOption mergeOption, params Func<TEntity, IRelatedEnd>[] relatedEnds)
where TEntity : EntityObject
{
result.EnsureNotNull();
TEntity[] tmp = result.ToArray();
relatedEnds.EnsureNotNull();
relatedEnds.EnsureEachNotNull();
if (tmp.Any())
{
for (int i = 0; i < relatedEnds.Length; i++)
{
ObjectQuery query = relatedEnds[i](tmp[0]).CreateSourceQuery() as ObjectQuery;
Type related = query.GetType().GetGenericArguments()[0];
typeof(Extensions)
.GetMethod("LoadRelatedHelper", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)
.MakeGenericMethod(typeof(TEntity), related)
.Invoke(null, new object[] { tmp, query, mergeOption });
if (i == relatedEnds.Length - 1)
{
FixAssociations(query.Context, tmp);
}
}
}
foreach (TEntity item in tmp)
{
yield return item;
}
}
private static void FixAssociations<TEntity>(ObjectContext context, IEnumerable<TEntity> entities)
{
// this is a workaround to make associations wire up properly
context.Refresh(RefreshMode.ClientWins, entities);
}
private static void LoadRelatedHelper<TEntity, TRelated>(ICollection<TEntity> entities, ObjectQuery<TRelated> query, MergeOption mergeOption)
where TEntity : EntityObject
where TRelated : EntityObject
{
string separator = string.Format("{0}) union ({0}", Environment.NewLine);
// In general this may produce wrong results
string queryTemplate = query.CommandText.Replace(query.Parameters.First().Name, "{0}");
StringBuilder newQuery = new StringBuilder();
newQuery.AppendLine("(");
for (int i = 0; i < entities.Count; i++)
{
if (i > 0)
newQuery.Append(separator);
newQuery.Append(string.Format(queryTemplate, string.Format("p{0}", i)));
}
newQuery.AppendLine();
newQuery.Append(")");
// I know (from my design rules) that there's only one (key) param
ObjectParameter[] parameters = entities.Select((x, i) => new ObjectParameter(string.Format("p{0}", i), x.EntityKey.EntityKeyValues[0].Value)).ToArray();
query.Context.CreateQuery<TRelated>(newQuery.ToString(), parameters).Execute(mergeOption).ToArray();
}
The idea is pretty simple. For each related end, grab the query and instead of using one parameter, add there all the value for all items in result – the primary key columns. I’m actually parsing the Entity SQL query returned to me, although with MetadataWorkspace one should be able to create it yourself (you can do it as a homework
). Then I modify the query, fill the parameters and execute it. Again, the parsing isn’t perfect, as well as the work with keys for parameters – there’s a simplification based on my conditions and rules.
With the automatic association wiring (used also in this trick) this should work nicely. It works like a charm for ObjectQuery, but not for ObjectResult (in EFv1). I don’t know, maybe it’s a problem on my side – anyway it’s reported in EF forum, so far without reply. If you read the second post there from me, you’ll find the workaround I found. This idea is captured in FixAssociations method (and may result in a huge or clause for big results).
These methods are taking array/params of related ends to get all in one method. And finally you get the result back and you can start processing it. The result is, for me, acceptable, I ended up with x+1 queries (with i.e. EFExtensions, I think, one can be able to do this with even lower number of queries).
Anyway, hope this helps and hope I find why the associations are not wired up properly. Maybe some considerations to improve this scenario are worth to discuss for post-EF4, as as far as I know, there’s no improvement on this in EF4.
Note: EnsureXxx are my runtime validation extension methods, similar to Code Contracts.
Today I was writing some code, where I needed create initially empty array. I wondered if the array[0] vs. array[] { } is the same. Alike with the string concatenation.
Without writing further text. Lines:
private static void Test1()
{
string[] s1 = new string[0];
Console.WriteLine(s1);
}
private static void Test2()
{
string[] s2 = new string[] { };
Console.WriteLine(s2);
}
resulted in this IL:
.method private hidebysig static void Test1() cil managed
{
// Code size 14 (0xe)
.maxstack 1
.locals init ([0] string[] s1)
IL_0000: ldc.i4.0
IL_0001: newarr [mscorlib]System.String
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call void [mscorlib]System.Console::WriteLine(object)
IL_000d: ret
} // end of method Program::Test1
.method private hidebysig static void Test2() cil managed
{
// Code size 14 (0xe)
.maxstack 1
.locals init ([0] string[] s2)
IL_0000: ldc.i4.0
IL_0001: newarr [mscorlib]System.String
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call void [mscorlib]System.Console::WriteLine(object)
IL_000d: ret
} // end of method Program::Test2
As you (and I) can see, the code is the same (I was kind of expecting that – but what’s better proof than IL?). So you don’t need to worry using the first or the other syntax.
.NET Framework 4 comes with (among others) with two new interfaces. IStructuralEquatable and IStructuralComparable. These are implemented (right now in Beta 1) by Array and Tuple(s).
With this new implementations and StructuralComparisons you can check arrays and tuples for structural equality (or compare these).
object[] o1 = new object[] { 1, "2" };
object[] o2 = new object[] { 1, "2" };
Console.WriteLine(o1.Equals(o2));
Console.WriteLine(o1.Equals(o2, StructuralComparisons.StructuralEqualityComparer));
The code above writes first false and then true. The first one is classic “old-school” Equals. Following line is using new structural comparison, thus the true as result. Neat, isn’t it?
By the way, F# is now using these interfaces too.

