Archive for the ‘.*’ Category

1
Sep

Kindle 3rd edition (3G, WiFi) – first sight review

Last (almost) day I was playing with new Kindle 3rd generation and I’ll share my initial thoughts. I’ll came with more detailed observations later (i.e. battery life).

Let’s start with pictures. Kindle 3rd generation compared to Kindle 2nd generation.

The new Kindle is smaller and lighter (you can’t get that from the picture :) ). Exact dimensions at Amazon page. Important is you feel it’s smaller and it looks good. Partially also because it’s graphite and the old one was white. What I was worried about is the smaller space on left and right side of display, where I place my thumb while reading. Now it’s just to place it there and not press the button(s). The back is not some metal alloy but it’s plastic (good for weight) and covered with some antiskid layer. And it really works, at least from what I can judge from one day using.

Talking about buttons etc. you may notice the numbers are gone, you have to use “SYM” key to type numbers, (to make the device even smaller) and keyboard contains home, back, menu buttons and 5-way key. On previous Kindle I typed only couple of characters I don’t think I’ll notice at all. Previous page as well as next page buttons are on both sides and are smaller. When I first time saw the pictures I had doubts about it (together with above mentioned smaller place for thumbs). To press the button, I, need to focus more (maybe because I’m used to old ones), partly because it’s smaller and partly because the button isn’t pressed directly down but slightly down and left/right (on left side left, on right side right). Also if you grab Kindle on sides you may accidentally press the button, as happened couple of times to me. Taking into account turning pages and holding Kindle is what I do most, this could be serious drawback. Or maybe it’s just a question of getting used to it. I’ll definitely report back after some time.

While pressing buttons you’ll notice faster responses. Speed of old one wasn’t bad, but the new one is better. Waking it up, opening book etc. every move is faster. Some more some less, but every little counts.

If you look at image above, you can see the difference between displays. The new has better contrast. (For PDFs you can set it up.) I had no problems reading on old one, no eye glare etc. But it was not black on white. New one is better. Letters are darker, close to pure black and the background, I think, is slightly lighter (If it’s not an optical illusion caused by darker letters. I did not make any exact measurements.). Less work for my eyes isn’t bad at all. :)

The new Kindle has also new browser based on WebKit. With non-restricted browsing even outside USA it’s a useful improvement. I checked only couple of pages (including homepage of my blog) and everything renders quickly, looking same as using desktop browsers (including JavaScript rendered pieces). With this browser I’ll read more articles on Kindle than previously, I feel it.

The WiFi, new feature in 3rd generation, simply works. In “Settings” you see networks available, select one a optionally provide credentials. You can connect to networks 802.11b or 802.11g standard with support for WEP, WPA and WPA2 security using password authentication.

As a second to last paragraph, I’ll mention the migration. Shortly it wasn’t bad, though I was expecting it easier. I was expecting turning it on and after a while having the new Kindle in with same content as in old one, with books at same pages. Nope. First you have to manually redownload all books from “Archived Items” and then resynchronize collections. Then when you open the book you will get the standard message about “Sync to Furthest Page Read”. As a result your new Kindle will be sooner or later as old one. Sure own content you have uploaded via USB you have to upload manually again and similarly you have to push samples to new one again as well.

Conclusion? The new Kindle is great. I’m happy spending my money on new Kindle. The improvements are worth it. If I get used to new buttons on sides without problems, I’ll not change these words.

  • Twitter
  • Facebook
  • Share/Bookmark
25
Aug

TPH mapping discriminator condition from MetadataWorkspace

The MetadataWorkspace contains a lot of useful information. Recently I was facing a challenge to get information about TPH (table per hierarchy) inheritance conditions for particular type. Sure, it’s in EDMX file and/or in MSL file. So you can parse the XML and get the info. I was on the other hand more interested getting the info from MetadataWorkspace, partially as a good “brain training” 8) side project.

Sadly the information about the mapping is very limited. Most interesting parts are not public, thus you’re forced to use reflection. So it’s a lot back and forth with, in my case, QuickWatch window. It helps a little to be familiar with MSL file structure.

static object GetNonPublicPropertyValue(this object o, string propertyName)
{
	return o.GetType()
		.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance)
		.GetValue(o, null);
}

public static IEnumerable<KeyValuePair<string, object>> GetMappingConditions<T>(this ObjectContext context)
	where T : class
{
	string typeToSearch = typeof(T).Name;

	var mapping = context.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace).First();

	return ((IEnumerable<object>)mapping.GetNonPublicPropertyValue("EntitySetMaps"))
		.SelectMany(entitySetMap => (IEnumerable<object>)entitySetMap.GetNonPublicPropertyValue("TypeMappings"))
		.Where(typeMapping =>
			((IEnumerable<dynamic>)typeMapping.GetNonPublicPropertyValue("IsOfTypes")).Any(type => type.Name == typeToSearch)
			||
			((IEnumerable<dynamic>)typeMapping.GetNonPublicPropertyValue("Types")).Any(type => type.Name == typeToSearch))
		.SelectMany(typeMapping => (IEnumerable<object>)typeMapping.GetNonPublicPropertyValue("MappingFragments"))
		.SelectMany(mappingFragment => (IEnumerable<object>)mappingFragment.GetNonPublicPropertyValue("AllProperties"))
		.Where(mappingFragment => mappingFragment.GetType().Name == "StorageConditionPropertyMapping")
		.Select(condition =>
			{
				bool? isNull = (bool?)condition.GetNonPublicPropertyValue("IsNull");
				string value = (string)condition.GetNonPublicPropertyValue("Value");
				return new KeyValuePair<string, object>((string)((dynamic)condition.GetNonPublicPropertyValue("ColumnProperty")).Name, (isNull.HasValue ? (object)isNull.Value : (object)value));
			});
}

Because the code is heavily using reflection and non public members, it’s possible it’ll not work other/future versions of Entity Framework. I tested it with current version, version 4.

It’s written in a compact way. If you want to further dig into partial results, I recommend to split it into foreach loops and do small steps. That’s in fact how I started and was incrementally discovering the information available at given level.

As all the data are not public, I’ll not describe how and why it is as it is. I did it using trial and error process. :) Maybe there’s other/simpler path. Feel free to use comments if you find one.

  • Twitter
  • Facebook
  • Share/Bookmark
24
Aug

Vyjmenovávat sloupce v SQL příkazu nebo ne???

Nedávno se na Builderu lehce rozjela diskuze, ačkoli v threadu na odlišné téma, jestli sloupce v SQL příkazech vyjmenovávat nebo ne. Nedá mi to a přispěju taky svou troškou.

Já bych “problém” rozdělil na dvě části. První je SQL kód v aplikaci. Druhou je kód v rámci pohledů, spouští, uložených procedur atp.

V prvním případě jasně a striktně sloupce vyjmenovávám. Jednak mám pocit, že to přidá na přehlednosti. Nejenom v rámci zápisu, ale i když později človek kód prochází a třeba něco přidává – vidí co do aplikace přichází a jak se to jmenuje. Případně se tak triviálně (aka Find) dají hledat závislosti. A jednak si myslím, že to ukazuje, že člověk nad výsledkem přemýšlel. Samozřejmě platí i to klasické, že při změně struktury nedochází k neočekávanému chování, kdy aplikace tahá sloupce, o kterých nemá ponětí a nedokáže je využít.

V druhém případě to již tak striktně nemám, ačkoli stále jsem daleko od volnosti. Sloupce opět vyjmenovávám, ale mám pár – v pro mě velmi opodstatněných, triviálních případech – “povolení”, kdy nevyjmenovávám. V zásadě se jedná o případy, kdy daný objekt jen k datům něco přidává resp. je překlápí. Typicky pohled, který k sadě přidává třeba RANK. Nebo trigger kopírující data 1:1 navíc do jiné tabulky. Potom si dovolím použít * (a někdy i přesto sloupce vyjmenuji). Jinak standardně vyjmenovávám.

Kdejaký nástroj vám všechny aktuální sloupce dokáže vygenerovat: Flamerobin, SQL Server Management Studio, IBExpert, Database Workbench, … Slušně si je naformátovat do zápisu je pak triviální.

Proč psát něco, čehož chování se může změnit, aniž bych se o tom ïmplicitně dozvěděl. A samozřejmě stále platí to co jsem napsal výše o přemýšlení nad tím co píšu.

  • Twitter
  • Facebook
  • Share/Bookmark
8
Aug

FbTransaction changes to support tables locking

Firebird has a feature allowing you to specify tables you want to lock (read or write and exclusive/protected/shared) when starting transaction. (Note that Firebird still uses MGA/MVCC. This is just a feature to support some scenarios.) We had constants in ADO.NET Provider for Firebird for some time, but using them resulted in wrong parameters being sent to the server and followed by exception. :)

Today I implemented support for this locking (tracker item, mailing list thread). That means sending proper sequences. The FbTransactionOptions class created earlier for timeout support was extended with new property LockTables. You can use to specify table name and lock specification. The lock specification there is in fact only subset of all options you can specify for transaction (same enumeration). You can put there whatever you want other options will be simply ignored.

Small example:

conn.BeginTransaction(new FbTransactionOptions()
	{
		TransactionBehavior = FbTransactionBehavior.ReadCommitted,  // etc.
		LockTables = new Dictionary<string, FbTransactionBehavior>
		{
			{ "TABLE_1", FbTransactionBehavior.LockWrite | FbTransactionBehavior.Shared },
			{ "TABLE_2", FbTransactionBehavior.LockWrite | FbTransactionBehavior.Exclusive }
		}
	});

Here I’m specifying that for TABLE_1 shared (huh :) ) write lock will be placed and for TABLE_2 exclusive (that sounds better, isn’t it?) write lock will be placed. Similarly you can go with LockRead.

Available right now in weekly builds and SVN.

  • Twitter
  • Facebook
  • Share/Bookmark
4
Aug

Projection (select) on a collection running in parallel with exceptions handling

Few days ago I posted an extension method to run projection on a collection in parallel. The method has one problem. It’s not dealing with exceptions. And because the ordering wasn’t (and isn’t) implicitly preserved, I did this small improvement.

Right now the method returns simple structure with original item, the result (if no exception occured, sure) and exception (if any). I didn’t went to AggregateException (although you can modify the code yourself to use it). Now you can decide while consuming what to do when exception occurred. Adding some kind of cancellation shouldn’t be difficult.

The idea behind is the same as in previous version.

#region ParallelProjection
internal struct ParallelProjectionResult<TSource, TResult>
{
	public TSource Item { get; set; }
	public TResult Result { get; set; }
	public Exception Exception { get; set; }
}

internal static IEnumerable<ParallelProjectionResult<TSource, TResult>> ParallelProjection<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> projection, int maxParallelism)
{
	BlockingCollection<ParallelProjectionResult<TSource, TResult>> results = new BlockingCollection<ParallelProjectionResult<TSource, TResult>>();

	ThreadPool.QueueUserWorkItem((o) =>
	{
		Semaphore semaphore = new Semaphore(maxParallelism, maxParallelism);
		CountdownEvent countdown = new CountdownEvent(1);
		try
		{
			foreach (var item in source)
			{
				countdown.AddCount();
				semaphore.WaitOne();
				ThreadPool.QueueUserWorkItem(
					(element) =>
					{
						TSource e = (TSource)element;
						ParallelProjectionResult<TSource, TResult> result = new ParallelProjectionResult<TSource, TResult>();
						result.Item = e;
						try
						{
							result.Result = projection(e);
						}
						catch (Exception ex)
						{
							result.Exception = ex;
						}
						results.Add(result);
						semaphore.Release();
						countdown.Signal();
					},
					item);
			}
			countdown.Signal();
			countdown.Wait();
			results.CompleteAdding();
		}
		finally
		{
			if (countdown != null)
				countdown.Dispose();
			if (semaphore != null)
				semaphore.Dispose();
		}
	}, null);

	return results.GetConsumingEnumerable();
}
#endregion
  • Twitter
  • Facebook
  • Share/Bookmark
4
Aug

Microsoft.Data.dll after crop

Last 24 hours was interesting. Almost everybody doing something with databases and .NET was talking about new Microsoft.Data.dll. And there has been recently a lot of clarification (i.e. this or this) (check your favorite search engine for more) what it is and what it is not and who’s target audience.

From what I read emerges that it’s focused on starting developers who may not even be interested in being “real” developers. Somebody who wants to just put some site together and run. Be close to PHP world style of working. Together with WebMatrix.

I’ll not think about whether it’s good for MS’s ecosystem or not. Although I see the the points as valid, I still don’t get it. If you’re a beginner, really beginner and you wanna create some site, would you spend some time on creating it or rather try to install i.e. WordPress. It’s probably the same challenge, but the result will be different. Not taking into account, that you would still need to have at least basic knowledge of (X)HTML, programming and databases and SQL when doing it on your own, isn’t it? OK, so maybe the novice just wants to create some site on his/her own. Learn something. Improve own skills. But all this stuff isn’t going to give him/her touch of how it’s really done. You’ll be learning something that useless for bigger, real-world, applications. Umm, than he or she may not be interested in expanding skills, really just create something for fun, you might think. But do you really think this case exists? Doesn’t it sooner or later fall into one of two categories above?

And the dynamic point of view? I read somewhere that the target audience is expected to use not so sophisticated editors etc. (BTW isn’t Visual Studio Express free???). But that’s not what bothers me. What bothers me, it’s the lack of compile-time checking (which is what I damn like when I develop). You’ll upload the site to web a you’ll have to check a lot of code (pages) to see whether it works. The refactoring is harder; ahh damn, that’s not what the target audience is going to be doing or will they? Don’t forget the find&replace is refactoring as well, and here the compile time checking is really useful?

On the other hand, maybe it’s a good idea, and only because we’re not novices and the “product” isn’t enterprise ready, we should understand it and try not to judge it with enterprise-ready eyes. Because we are maybe spinning in our own world not seeing outside the box. But I personally still think the idea how it’s done it’s wrong.

  • Twitter
  • Facebook
  • Share/Bookmark
3
Aug

Let’s try something new… What about Microsoft.Data.dll?

The new Microsoft.Data.dll seems to be very “interesting”. 8-)

I generally agree, that pure raw ADO.NET is more verbose than the shown example. And that’s all. On the other hand, everybody using pure raw ADO.NET have written couple of helper methods already. And directly for his/her desired approach, with non-dynamic typing. This isn’t going to make anyones life easier. As an experiment with dynamic keyword it’s nice. But a stuff used in real world deployed application? No so sure.

Wanna go easy path? Go LINQ to SQL of Entity Framework with just 1:1 model generated from database (if we’re on MS’s stack, nHibernate or LLBLGen Pro will do the work as well). Wanna go pure SQL, all under own control? ADO.NET is waiting for you. But this, this looks like kind of mixture of both, but nothing good resulted.

By the way, will there be any support for parametrized queries? I hope so. Because if not, then it’s even more funny than it already is.
UPDATE: There’s a support: http://blog.andrewnurse.net/2010/08/03/MicrosoftDataItrsquosNotAsEvilAsYouThink.aspx.

For me it’s a step back. Or am I missing something?

  • Twitter
  • Facebook
  • Share/Bookmark
2
Aug

Projection (select) on a collection running in parallel

Here’s updated version of the method.

I have here another not-general-purpose-parallel/multihtreaded-method. :) To make a long story short I needed do some transformation on collection’s elements, aka projection. Unfortunately the method I was plugging in was doing some network requests, in fact couple of requests. Sequentially, blocking processing until the response came back. I know a proper way will be to turn these requests into asynchronous, unluckily this was part of bigger architecture I could not change. Because it’s not CPU bound the AsParallel method would not help much. So I solved it abusing ThreadPool threads. Bad for scheduler and memory, as I’ll be wasting threads and resources, blocking, until reply is sent by server, but very easy for me. I told you, abusing. ;)

So I came with this method. It’s utilizing new .NET Framework 4 concurrent collections, BlockingCollection in particular as it’s great for producer-consumer scenario and I want the method to return results whenever one is done (that also implies the ordering isn’t preserved).

internal static IEnumerable<TResult> ParallelProjection<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> projection, int maxParallelism)
{
	BlockingCollection<TResult> results = new BlockingCollection<TResult>();

	ThreadPool.QueueUserWorkItem((o) =>
	{
		Semaphore semaphore = new Semaphore(maxParallelism, maxParallelism);
		CountdownEvent countdown = new CountdownEvent(1);
		try
		{
			foreach (var item in source)
			{
				countdown.AddCount();
				semaphore.WaitOne();
				ThreadPool.QueueUserWorkItem(
					(element) =>
					{
						results.Add(projection((TSource)element));
						semaphore.Release();
						countdown.Signal();
					},
					item);
			}
			countdown.Signal();
			countdown.Wait();
			results.CompleteAdding();
		}
		finally
		{
			if (countdown != null)
				countdown.Dispose();
			if (semaphore != null)
				semaphore.Dispose();
		}
	}, null);

	return results.GetConsumingEnumerable();
}

The method is straightforward, a lot of work was saved using the smart blocking collection. I’m simply reading items from the collection and applying the function to them. To not overload the system with huge number of threads I also added maxParallelism parameter. When this number of threads is processing items, I’ll stop scheduling more, using Semaphore, until some are done and again available. When there’s no item in source collection available and all item were processed I call CompleteAdding method to say I’m done and there will be no other items. Here I’m using CountdownEvent class initialized to 1 as you can’t, of course, add items if it reaches 0. Before final Wait I’m subtracting one to compensate this.

And that’s it. Again, it’s not general purpose method. Use with care, it may bring you even worse performance if wrongly used.

  • Twitter
  • Facebook
  • Share/Bookmark
31
Jul

Array of WaitHandles (ManualResetEvent, AutoResetEvent, …) when waiting for operations to complete …

Often, when you discover the beauty of multithreading and parallelism, you find a need to run some operations in parallel and wait for completion. Fairly common scenario. Although now, with .NET Framework 4, you can write it using Task Parallel Library‘s Parallel.Invoke, there are scenarios when you need to plug it in into some other methods/parameters, so you’ll do it yourself explicitly with threads or better to say ThreadPool.

The method I see from time to time looks basically like this:

void DoSomethingExample()
{
	int numberOfActions = 10;
	ManualResetEvent[] mres = new ManualResetEvent[numberOfActions];
	for (int i = 0; i < numberOfActions; i++)
	{
		mres[i] = new ManualResetEvent(false);
		ThreadPool.QueueUserWorkItem((o) =>
			{
				Thread.SpinWait(20000000);
				(o as ManualResetEvent).Set();
			},
			mres[i]);
	}
	ManualResetEvent.WaitAll(mres);
}

Though it’s not wrong, except the ManualResetEvents are not Disposed, it’s suboptimal. You’re wasting resources creating array of these objects.

But if you think about it, you can write it better. Better in a way for scaling, performance and memory consumption.

void DoSomethingBetter()
{
	int numberOfActions = 10;
	using (ManualResetEvent mre = new ManualResetEvent(false))
	{
		for (int i = 0; i < numberOfActions; i++)
		{
			ThreadPool.QueueUserWorkItem((o) =>
				{
					Thread.SpinWait(20000000);
					if (Interlocked.Decrement(ref numberOfActions) == 0)
						mre.Set();
				},
				null);
		}
		mre.WaitOne();
	}
}

I’m simply using one synchronization object (and using using statement ;) ), because I’m really interested in only when all tasks are done (one stuff), and decrementing the total number of tasks every time one finishes. Using Interlocked class I’m sure no race condition will occur and I’ll get the right results. After it reaches zero I’m signaling I’m done and the method can continue.

Fewer resources, atomic operations usage … better/faster results.

  • Twitter
  • Facebook
  • Share/Bookmark
26
Jul

Ultimate EFv4 CTP4 Code First (full mapping) example (using Firebird)

There’s a lot of content for latest CTP, CTP4, for Entity Framework “new features”. It’s mainly focused on Code First stuff, that fills the triad with Database First and Model First. I like Code First but what I also like is maintainable code. Hence I was more trying not to use convention-over-configuration, in opinion good for only small projects, and focus on specifying everything the way I want it to be, especially with my database structure (yes, I’m data consistency and storage freak).

Let’s model some kind of simple library and try to use there couple of Entity Framework’s features. And to make things worse, try to do it with ADO.NET provider for Firebird.

Good news is I succeeded. My database structure was my first and non-touchable object (to be honest the first was the idea what to create and how to represent it in database) together with the idea of objects.

Here’s the script for Firebird database (Did you noticed we’re fully Entity Framework 4 compatible?). See the quoted column names? Yes, not nice, but later in mapping in C# it looks nicer. ;) And I mixed the mapping with one for MS SQL Server (see below).

RECREATE TABLE Authors (
	"id" INT NOT NULL,
	"FirstName" VARCHAR(255) NOT NULL,
	"LastName" VARCHAR(255) NOT NULL,
CONSTRAINT PK_Authors PRIMARY KEY ("id")
);

RECREATE TABLE Books (
	"id" INT NOT NULL,
	"Discriminator" char(2) NOT NULL,
	"Title" VARCHAR(1000) NOT NULL,
	"Published" TIMESTAMP NOT NULL,
	"ID_Author" INT NOT NULL,
	"IssuesPerYear" SMALLINT,
	"Price" DECIMAL(9,0),
CONSTRAINT PK_Books PRIMARY KEY ("id")
);

RECREATE TABLE Languages (
	"id" INT NOT NULL,
	"LanguageName" VARCHAR(100) NOT NULL,
	"LanguageAbbrevation" CHAR(3),
CONSTRAINT PK_Languages PRIMARY KEY ("id")
);

RECREATE TABLE Translators (
	"id" INT NOT NULL,
CONSTRAINT PK_Translators PRIMARY KEY ("id")
);

RECREATE TABLE Translators_Languages (
	"ID_Language" INT NOT NULL,
	"ID_Translator" INT NOT NULL,
CONSTRAINT PK_Translators_Languages PRIMARY KEY ("ID_Language", "ID_Translator")
);

ALTER TABLE Books ADD CONSTRAINT FK_Book_Author FOREIGN KEY ("ID_Author")
REFERENCES Authors("id")
ON DELETE CASCADE
;

ALTER TABLE Translators_Languages ADD CONSTRAINT FK_TL_Languages FOREIGN KEY ("ID_Language")
REFERENCES Languages("id")
ON DELETE NO ACTION
;

ALTER TABLE Translators_Languages ADD CONSTRAINT FK_TL_Translators FOREIGN KEY ("ID_Translator")
REFERENCES Translators("id")
ON DELETE NO ACTION
;

ALTER TABLE Translators ADD CONSTRAINT FK_TypeConstraint FOREIGN KEY ("id")
REFERENCES Authors("id")
ON DELETE NO ACTION
;

So it’s time to create mapping right? Nope. Now I’ll switch my brain from ER thinking into OO thinking mode. Here’s the world of entities (sure I made some adjustments to fit some Entity Framework features, like Complex Types):

public abstract class Book
{
	public int ID { get; protected set; }
	public string Title { get; set; }
	public DateTime Published { get; set; }
	public Author Author { get; set; }
	public int AuthorID { get; set; }
}

public class RealBook : Book
{
	public decimal Price { get; set; }
}

public class Magazine : Book
{
	public short IssuesPerYear { get; set; }
}

public class Author
{
	public int ID { get; protected set; }
	public Name FullName { get; set; }
	public ICollection<Book> Books { get; set; }

	public Author()
	{
		this.Books = new List<Book>();
	}
}

public class Translator : Author
{
	public ICollection<Language> Languages { get; set; }

	public Translator()
	{
		this.Languages = new List<Language>();
	}
}

public class Language
{
	public int ID { get; protected set; }
	public string LanguageName { get; set; }
	public string LanguageAbbrevation { get; set; }
}

#region Complex Types
public class Name
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
}
#endregion

As you see I’m using pure POCOs.

So far we haven’t touched any Entity Framework related stuff. So it’s time to create our context and all DAL related stuff. Mine is very simple and exposes only few properties and methods, just to keep it simple and focus on the aim.

public class LibraryContext : DbContext
{
	public LibraryContext(DbConnection connection)
		: base(connection)
	{
		this.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
	}

	protected override void OnModelCreating(ModelBuilder modelBuilder)
	{
		base.OnModelCreating(modelBuilder);

		modelBuilder.Configurations.Add(new BookConfiguration());
		modelBuilder.Configurations.Add(new AuthorConfiguration());
		modelBuilder.Configurations.Add(new TranslatorConfiguration());
		modelBuilder.Configurations.Add(new LanguageConfiguration());
		modelBuilder.Configurations.Add(new NameConfiguration());
	}

	public string CreateDatabaseScript()
	{
		return this.ObjectContext.CreateDatabaseScript();
	}

	public IDbSet<Book> Books
	{
		get { return this.Set<Book>(); }
	}

	public IDbSet<Author> Authors
	{
		get { return this.Set<Author>(); }
	}
}

public class DoNothingWithMyDatabase<TContext> : IDatabaseInitializer<TContext>
	where TContext : DbContext
{
	public void InitializeDatabase(TContext context)
	{ }
}

Pretty simple, isn’t it. I’m using new stripped down objects DbContext (← ObjectContext) and IDbSet/DbSet (← IObjectSet/ObjectSet).

You may also notice, I’ve created object which implements IDatabaseInitializer. That’s because, by default, Entity Framework will try to create database for you and check whether your database matches model (CreateDatabaseOnlyIfNotExists). I‘m controlling my database. You have to add somewhere into your application before doing anything with the context call to SetInitializer:

Database.SetInitializer(new DoNothingWithMyDatabase<LibraryContext>());

And finally we’re ready to dive into the mapping. Again, you can type the mapping directly into overridden OnModelCreating, useful if you have only couple of diversions from default conventions. I created configuration classes where I specified as much as I want. And I need (almost) everything to be nailed down (remember, data consistency and storage freak ;) ) as I don’t want to be surprised when something in database or in entities changes and application will start behave weird.

class BookConfiguration : EntityConfiguration&ltBook>
{
	public BookConfiguration()
	{
		this.HasKey(x => x.ID);
		this.Property(x => x.ID).IsIdentity();
		this.Property(x => x.Title).IsRequired().IsVariableLength().HasMaxLength(1000).IsUnicode();
		this.Property(x => x.Published);
		this.HasRequired(x => x.Author).WithMany(a => a.Books).WillCascadeOnDelete().HasConstraint((b, a) => b.AuthorID == a.ID);

		this.MapHierarchy()
			.Case<Book>(x => new
			{
				id = x.ID,
				Title = x.Title,
				Published = x.Published,
				ID_Author = x.AuthorID,
			})
			.Case<RealBook>(x => new
			{
				Discriminator = "B",
				Price = x.Price,
			})
			.Case<Magazine>(x => new
			{
				Discriminator = "M",
				IssuesPerYear = x.IssuesPerYear,
			})
#if FB
			.ToTable("BOOKS");
#else
			.ToTable("Books");
#endif
	}
}

class AuthorConfiguration : EntityConfiguration<Author>
{
	public AuthorConfiguration()
	{
		this.HasKey(x => x.ID);
		this.Property(x => x.ID).IsIdentity();
		this.HasMany(x => x.Books);

		this.MapHierarchy(x => new
		{
			id = x.ID,
			FirstName = x.FullName.FirstName,
			LastName = x.FullName.LastName,
		})
#if FB
		.ToTable("AUTHORS");
#else
		.ToTable("Authors");
#endif

		this.MapHierarchy().Case<Translator>(x => new
		{
			id = x.ID,
		})
#if FB
		.ToTable("TRANSLATORS");
#else
		.ToTable("Translators");
#endif
	}
}

class TranslatorConfiguration : EntityConfiguration<Translator>
{
	public TranslatorConfiguration()
	{
		this.HasMany(x => x.Languages).WithMany()
#if FB
			.Map("TRANSLATORS_LANGUAGES",
#else
			.Map("Translators_Languages",
#endif
				(t, l) => new
				{
					ID_Translator = t.ID,
					ID_Language = l.ID,
				});
	}
}

class LanguageConfiguration : EntityConfiguration<Language>
{
	public LanguageConfiguration()
	{
		this.HasKey(x => x.ID);
		this.Property(x => x.ID).IsIdentity();
		this.Property(x => x.LanguageName).IsRequired().IsVariableLength().HasMaxLength(100).IsUnicode();
		this.Property(x => x.LanguageAbbrevation).IsFixedLength().HasMaxLength(3).IsUnicode();

		this.MapSingleType(x => new
		{
			id = x.ID,
			LanguageName = x.LanguageName,
			LanguageAbbrevation = x.LanguageAbbrevation
		})
#if FB
		.ToTable("LANGUAGES");
#else
		.ToTable("Languages");
#endif
	}
}

class NameConfiguration : ComplexTypeConfiguration<Name>
{
	public NameConfiguration()
	{
		this.Property(x => x.FirstName).IsRequired().IsVariableLength().HasMaxLength(255).IsUnicode();
		this.Property(x => x.LastName).IsRequired().IsVariableLength().HasMaxLength(255).IsUnicode();
	}
}

I don’t know whether it’s worth to describe the lines. Should be understandable if you know how the entities and database look like. Just maybe small notice. Besides Complex Types we used two most common inheritance mapping scenarions – TPH aka Table Per Hierarchy for Books and TPT aka Table Per Type for Authors (there’s also TPC (Table Per Concrete Type)). However if you have questions feel free to use comments, if I’ll know answer I’ll be happy to reply.

And finally some really simple application to test the result:
If you define #define FB it’ll use Firebird database else MS SQL Server.

Database.SetInitializer(new DoNothingWithMyDatabase<LibraryContext>());

Action<LibraryContext> doSomething = (context) =>
{
	Console.WriteLine(context.CreateDatabaseScript());
	var query = context.Books
		.Select(b => new
		{
			BookName = b.Title,
			AuthorName = b.Author.FullName.LastName + ", " + b.Author.FullName.FirstName
		})
		.OrderBy(x => x.BookName);
	Console.WriteLine((query as ObjectQuery).ToTraceString());
	var data = query.ToArray();
	foreach (var item in data)
	{
		Console.WriteLine("Book {0} written by {1}.", item.BookName, item.AuthorName);
	}
};

#if FB
using (LibraryContext context = new LibraryContext(new FbConnection(@"database=localhost:ctp4;username=sysdba;password=masterkey;pooling=true;")))
{
	doSomething(context);
}
#else
using (LibraryContext context = new LibraryContext(new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=ctp4;Integrated Security=True;Pooling=False;MultipleActiveResultSets=True")))
{
	doSomething(context);
}
#endif

I’m glad I was able to figure out how to map everything without touching database structure (although it’s pretty straightforward) or letting the default rules to kick in. Hope it will help you if you struggle with something (and hope the naming will not change much in future). It’s also nice to see the whole infrastructure fits together and changing provider, in my case for Firebird’s, doesn’t make the code to blow out.

  • Twitter
  • Facebook
  • Share/Bookmark
26
Jul

Useful Find method on DbSet

The ObjectStateManager contains a lot of information about entities currently in context. In fact it contains complete entities too. So you can try to look into it before issuing query and use it as local cache. For some simple cases, like PK match, you can create extension method in no time.

But in current feature pack for Entity Framework 4 if you’re using new DbSet object you can find Find method, which does exactly this.

You provide PK value (or values if it’s composite) and it’ll first look for that object locally and if not found it’ll try to fetch it from database.

using (testEntities ent = new testEntities())
{
	var data = ent.Masters.Select(x => x.ID).Take(1).First();

	var item1 = ent.Masters.FirstOrDefault(x => x.ID == data);
	// Find method will find it locally, no querying will be done
	var item2 = ent.Masters.Find(data);
}

using (testEntities ent = new testEntities())
{
	var data = ent.Masters.Select(x => x.ID).Take(1).First();

	//var item1 = ent.Masters.FirstOrDefault(x => x.ID == data);
	// here the Find method will not find it and will query database
	var item2 = ent.Masters.Find(data);
}

It’s nothing from what you’ll be excited couple of hours, but every little counts.

  • Twitter
  • Facebook
  • Share/Bookmark
24
Jul

Handy ModelMatchesDatabase method

The Entity Framework 4 CTP4 is out and contains nice improvements. One is especially handy. Well you was able to do the same even in v1 but it was a lot of work. The method is ModelMatchesDatabase in System.Data.Entity.Infrastructure.Database. You can get Database object easily through DbContext.Database. The method return boolean value and checks whether your database matches mapping or not.

Only not useful thing is the EdmMetadata table the whole infrastructure is using. I know it’s easier with it, but could be done without as well. I hope will be removed (or be optional) in future CTPs or final releases. Because then you’ll be able i.e. check that your mapping is valid for selected database, check that your database has expected structure from application’s point of view (i.e. after new release) or simply spin up you own custom database altering process and check results.

  • Twitter
  • Facebook
  • Share/Bookmark
23
Jul

Solved Samsung i900 Omnia’s freezing

I had problem with my Samsung i900 Omnia phone being stuck in stand by mode for no obvious reason, except I discovered applications doing this. I was living with that some time until I finally jumped into the problem.

I was, from old ages, used to install almost all applications to storage card. Only some critical ones (like today screen items) into internal memory. I did the same with Omnia, although it has another storage already build in. The symptoms were simple. I ran application, put phone into stand by mode and (sometimes) later I wasn’t able to wake it up. Pretty annoying. I spotted these “problematical” applications and get used to close these after the work.

But few days ago I was sick of this. Mainly because you have to later wait when you’re starting the application again. So I did some observations and thinking. After some false (and tedious) attempts I inferred the problem might be Omnia’s handling of storage card. And yes, it was. After I move all applications from storage card to internal storage, all problems disappeared. Well, at least the phone isn’t freezing. Sometimes it takes 2-5 seconds to wake it up (light up the display), but that’s minor for me (probably the phone is doing something with the storage).

So if you’re experiencing same problem, install/move all (or the “problematic” ones) applications from storage card to internal memory of internal storage.

Note: If you’re using internal storage as USB drive and you connect phone to the computer some applications may stuck or behave weird as during this time the storage is not accessible to phone itself.


My terminology: :)
internal memory = couple of MBs where system is
internal storage = x GBs where you can put your files
storage card = SD card you can put into your phone

  • Twitter
  • Facebook
  • Share/Bookmark
23
Jul

Is ORM just about bridging the gap or are we trying to wrongly match ER world into OO world?

Recently I’ve got to think about ER world and OO world. There’s a lot of people around there who understand ER or OO world very deeply. In fact ER world is well formalized, described and has a strong mathematical background. A lot of theoretical work is behind OO as well. But what about ORMs?

Is it about the fact we understand both worlds correctly and it’s good we’re trying to bridge them using the power of machines instead of our hands and brains all over again or the exact opposite? Trying to wrongly create something that automagically does this bridging even if the bridge itself will be bloated, slow and creating ugly results?

Have you ever seen query from Entity Framework, LLBLGen Pro, Hibernate, nHibernate, …, name yours? Don’t blame the tool. I think any of them is doing great job translating the query from some king of object oriented way of expressing what I want to i.e. SQL. The problem is, that we’re not querying database, but objects mapped to database objects. Sometimes with very clever mapping. The tool then has to reason about some general transitions from objects to tables and then creating the query. Sure a room for improvement is here. But is it worth?

What other options do we have? Object databases (or post-relational)? Relational programming (probably not)? Maybe just the ORMs idea is wrong. Maybe the bridging is good, and we just need to start from the other end and do it differently. Maybe allow lower the abstraction for those who understand both worlds. And remember these worlds proved self to be very useful doing what they were designed to do. So we just need to find a way to work in both with less friction; or did we find it?

  • Twitter
  • Facebook
  • Share/Bookmark
18
Jul

Zooming images in Kindle books

Recently I was reading book with images at the end and I more or less accidentally pressed the 5-way joystick and got cursor near the image. What a surprise (for me; it’s probably described in manual ;) ):

There’s a small magnifier icon and you can zoom in the image and see it full screen even if in book is only shown as small (of course, the book has to contain bigger image to see more details). In 16 shades of gray it’s not perfect for pictures but better than nothing.

BTW the bike on this picture is one of OCC‘s old school choppers.

  • Twitter
  • Facebook
  • Share/Bookmark
5
Jul

Kindle and international web browsing

Maybe it’s related to new firmware, but today I noticed, that my Kindle no longer limits access to web only to selected sites (wikipedia, amazon, …). I’m able to access any page I want (here in Czech Republic). ID3 renamer‘s site works, this blog as well (though it takes some time to render the page). I don’t know whether it’s written somewhere and I just missed it, but I do like it.

What about others? Feel free to use comments to report result in your country.

  • Twitter
  • Facebook
  • Share/Bookmark
4
Jul

Firebird Embedded in comparison to SQL Server Compact Edition 4

Scott Guthrie recently posted article about New Embedded Database Support with ASP.NET. This made me think about other options, Firebird in particular, and advantages and disadvantages. What I’m going to do is to very shortly introduce Firebird Embedded here and then compare it with features Scott wrote in his article.

Firebird Embedded, shortly, is Firebird database server in one DLL. No need to install etc., just load this DLL and use it. To be precise, there are some other DLLs, i.e. to support national charsets, but it’s still in under 10MB all. The database itself is built from same sources as “full” server and it’s not limited in any way.

Works with Existing Data APIs – as I said, Firebird Embedded is based on same codebase as “full” server, thus the SQL and API is same. And not only this, the ADO.NET provider for Firebird works with it and you’re programming using same thinking.

No Database Installation Required and Database Files are Stored on Disk – databases created by Firebird Embedded are stored wherever you want, with any extension. Firebird itself doesn’t have any master database, thus even the “full” server works with any (valid database) file.

Shared Web Hosting Scenarios Are Now Supported with SQL CE 4 – sure you don’t need to install anything with Firebird Embedded, that’s why it’s called Embedded. And not only this, from version 2.5, you can open database from different processes, i.e. IIS worker process and Apache workers or some console application doing something in background.

Visual Studio 2010 and Visual Web Developer 2010 Express Support – as the tool set for Firebird Embedded is exactly same as for “full” Firebird, you can use DDEX (aka Server Explorer support), Entity Framework (LINQ), …

Supports Both Development and Production – this is something I’m silently expecting. But yes, you can do the same with Firebird Embedded too.

Easy Migration to SQL Server – ahh, my favorite point. The Firebird Project has of course whopping number of tools to support migration from Embedded to “full”. The most used is … nothing. The databases are fully compatible and you can switch servers without any other tools, migration, conversion, … Just place it where you want it and connect to it, either with “full” or Embedded Firebird. And to switch your application? Again nothing. Same ADO.NET provider, just change connection string, if needed. Mostly you’ll add server IP address and maybe different path and manually switch server type, if you want. Really the migration is so simple. It is one minute task and thanks to same tool set, no matter what you version your targeting during development, your application will work with the other as well without any additional effort.

You like Firebird Embedded? I do, a lot. SQL Server Compact Edition 4 looks promising, but Firebird has something to offer as well. And recall, it’s based on same sources as “full” Firebird, very mature codebase, examined with tons of installations.

  • Twitter
  • Facebook
  • Share/Bookmark
29
Jun

Prepend method in LINQ

Yesterday I needed to put one element at beginning of the collection I already had. Some kind of Concat upside down. :) As you can use the Concat method, it looks weird when you see the code, because two items are actually swapped. So I created a simple extension method to do it for me.

I started with:

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
	yield return item;
	foreach (var x in source)
		yield return x;
}

It’s classic imperative approach, you’re expressing how you’ll do it. Then I thought: “Hey, why not to use LINQ methods already available.”. As you guess, I abused Concat method as I wrote above:

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
	return new[] { item }.Concat(source);
}

You can easily extend both methods to accept also collection as a second parameter.

If you’re more about declarative programming you’ll probably like the other one. But choose whatever fits your brain better.

  • Twitter
  • Facebook
  • Share/Bookmark
27
Jun

Shortly with iPad

Some time ago I was writing about my thoughts about Kindle vs. iPad. Information about iPad was based from different sources around internet. As my friend Petr Kaleta (Mac obsessed ;) ) recently bought one and I was able to play with it for a short I would like to share some of my initial feelings.

I was first surprised with the size. It’s pretty thick, I was expecting it to be much thinner. And then the dimensions. Again I thought it’s close to A4 paper, but it’s actually smaller and square-ish. Maybe I just got wrong impression from pictures. Last but not least is the weight. The thing is damn heavy. Really, it’s heavy. Forget about holding it with one hand only for a long time and i.e. walking with it in your house. You’ll be tired quickly. My expectation here was based entirely on Kindle. And now I really realize how light the Kindle is, though for comfortable reading in any position it’s on the edge.

Now the good sides. The display, although average in resolution, is great browsing internet. Wanna check maps or weather at home just before you leave? Exactly the spot where I see iPad as a great device. Similarly checking news or TV schedule or … Simply the handy device connected to internet you have home, using it for common tasks for which you don’t want to grab your notebook or walk to computer.

And as a reading device? I don’t know. I have doubts about the weight, at least until you lean it on your body or something like that. Another story is the display. I wasn’t watching it couple of hours in a row, but I bet the Kindle will be more comfortable no matter what. And the it has also the next/previous page buttons so you’re doing minimal move when turning pages. Sliding with the finger looks or maybe is cool, but I bet on simple buttons.

Would I buy one? For half a price, yes. Would I throw away my Kindle? No. Kindle is so focused on reading; and that’s what I like on it.

  • Twitter
  • Facebook
  • Share/Bookmark
26
Jun

New Kindle firmware (2.5) – reflections

Amazon released new firmware (2.5) for Kindle couple of days ago. And I have to say, there were some features I was quite looking forward. Namely the collections, PDF zoom and lately also the social networks integration. The rest wasn’t so much interesting for me. Let me go through these three and put out some reflection I have from usage.

Collections are great. Simple powerful. Everything I was expecting for my usage, which is to just keep some order in my books. One book can be in zero, one or more collections. Nothing more or less.

The PDF zoom is good, though I was expecting little bit more (at least in back of my head, as I know creating something with wide application would need a serious thoughts). You can simply zoom into your PDF document if the font, image, graph, whatever is too small to easily read it on screen. Using it for images, tables etc. is great. Finally you can read the complete PDF without later checking some small tables on computer. Sadly it doesn’t solve the problem with small font in PDF. Well, it does, but it’s not pleasant. The font used to create the PDF is normal for computer reading then it’s too small to read it easily on Kindle (for me at my 6”). And although you can now zoom into it the reading experience is not so great. You have to use 5-way joystick to jump left and right to read whole line. I know (and I wrote/said many times on many places), PDF is for showing and printing, it contains a lot of information about layout etc., for reading (and “just” keeping text with simple formatting) we have some other formats, but I was expecting little bit more from this feature from reading point of view. Maybe better usage of buttons? …

The so called social networks like Twitter and Facebook are now supported in a way you can highlight some part of book and post it there, using Whispernet. When I first read it, I thought: “Cool.”. But the real world implementation is slightly different from description. First the highlighted passage isn’t posted to social network. It’s posted to kindle.amazon.com and only link is posted to network. On the kindle.amazon.com you can see the highlighted part, your (my) comment, the book name, author and link into Amazon store to buy it. And as a bonus you can see most highlighted parts in books you have in your Kindle directly when reading these. Problem is, sometimes I just want to share some part of book, sentence even a word and add comment. But the message posted will contain only my comment and the link to it (to Twitter). Why? If it’s short enough to fit in why to share link? And why even share the link? What if I don’t want to show from what book it came from? What if I just want to point out some interesting wording … Sure I know. It supports the Kindle business and all around. When you’re reading the highlighted part you’re only one click from the store and there you’re one click from buying. I totally understand it. I was just expecting something different. Or at least let me decide what to do. But overall the feature is good as well. Especially the overview about the most highlighted passages. It allows you to spot interesting pieces you might miss otherwise.

Be it as it is, I like it. The main feature – collections – I was looking forward to this firmware is truly great! The other one are good as well and some issues are just my personal opinions and others might be happy with the implementation. And who knows what improvements will be there with another update (either firmware or backend services).

  • Twitter
  • Facebook
  • Share/Bookmark
Next Page »