Monthly Archives: June 2010

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.

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.

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).

How to break your code easily a.k.a my params hell

Today I faced a behavior I have no idea exists. It’s more or less ambiguity between method with some parameters and one using params. Why more or less? Well, because it surely described in C# specification (“best match” or something similar to it). But I hadn’t know I should think about it until I was debugging weird behavior.

Let’s start with simple class:

class Test
{
	public Test(params int[] foos)
	{
		Console.WriteLine("foos");
	}

	public Test(int foo, int bar)
	{
		Console.WriteLine("foo bar");
	}
}

And now some (mind blowing ;) ) code:

new Test(1);
new Test(1, 2);
new Test(1, 2, 3);

If you see the code in the context you probably spot the problem easily. The second row will not call the params but the other constructor.

Which is “cool” until you’re doing some refactoring and you (as I did) add new constructor with params and everything starts behaving unexpectedly. Maybe this text will help somebody to realize this faster than I did. :D

Running the other method on same thread as the first one

Last week I was solving problem. The piece of code another code was plugged in was doing some crazy threading stuff inside while the code plugged in used some component that needed some methods (in my case just two) to be called in same thread. Well, that is to make the long story short.

As I couldn’t rely on the fact, that the thread calling the first method will be still available when the other one needs to be called I decided to simply steal one thread (in fact ThreadPool thread) for it a abuse it exclusively. To encapsulate this hack I created this class.

Before you dive into, I have to note, that it is really not a general purpose class and you shouldn’t blindly use it – you can easily use it badly and i.e. create unwanted shared state, screw the flow of your program or get wrong results due race conditions, …

/// <summary>
/// This is NOT a general purpose class. 
/// Use with care.
/// </summary>
sealed class ThreadMethodRunner : IDisposable
{
	AutoResetEvent _eventMethodDone;
	AutoResetEvent _eventMethodIn;
	Action _method;

	public ThreadMethodRunner()
	{
		_eventMethodDone = new AutoResetEvent(false);
		_eventMethodIn = new AutoResetEvent(false);
		ThreadPool.QueueUserWorkItem(new WaitCallback(MethodRunnerWrapper), null);
	}

	private void MethodRunnerWrapper(object o)
	{
		for (int i = 0; i < 2; i++)
		{
			Debug.WriteLine("Waiting for method");
			_eventMethodIn.WaitOne();
			Action a = Interlocked.Exchange(ref _method, null) as Action;
			a();
			Debug.WriteLine("Method done");
			_eventMethodDone.Set();
		}
		Debug.WriteLine("Thread done");
	}

	public void Do(Action method)
	{
		Interlocked.Exchange(ref _method, method);
		_eventMethodIn.Set();
		_eventMethodDone.WaitOne();
	}

	public void Dispose()
	{
		_eventMethodDone.Dispose();
		_eventMethodIn.Dispose();
	}
}

This class allows you to call the Do method with Action delegate and the method will run the code on the same thread every time (in my case just two times) called. This method blocks as you probably want to keep the behavior of you old code (at least in boundaries of method calls order, not changing some state etc. as mentioned above).

I don’t know if it’s worth any other usage than mine, but at least somebody may be inspired.

Firebird and Entity Framework 4 – stage completed

The ADO.NET provider for Firebird now fully supports all the new features in Entity Framework 4. Simple. If you’re eager to test it, grab the weekly build and enjoy.

We support the internal improvements as well as the visible changes like i.e. Model First or CreateDatabaseScript method. The template for creating SQL script is now part of sources and sure will be included in final package as well. I expect to improve it on your feedback and also the model generation from designer is pluggable so you can create custom one and use it there.

To support some new features in SQL generation I had to tweak it little bit and as with every change, there’s a change that something goes wrong. Thus I would be more than happy to get some feedback either that it works OK or any queries where it fails.

I’m so happy to cross this milestone about two months after final Visual Studio 2010, .NET Framework 4 (incl. Entity Framework 4) were released. You can expect the official release after some testing, it’s your turn :) .