Posts Tagged ‘.NET’

14
Dec

Trace API support in ADO.NET provider for Firebird (FbTrace)

When I came from Firebird Conference in Bremen I was so excited about all the people being excited about Trace and Audit API :) I decided I’ll implement this in .NET provider as soon as possible. And here it is.

Right now there’s a new class (and few supporting it) on FirebirdSql.Data.Services namespace called FbTrace, that you can use to start trace session and see what’s going on on server. I’ll not describe the Trace API itself, you can find info in documentation, I’ll rather focus on how you can use it from the provider.

Right now, as I have no sharp idea how the people will use it, I implemented it simply and later, if I find some common cases, I’ll add some “shortcuts” to help with these scenarios.

If you have ever used any FbService derived class, you’ll be able to use FbTrace in under a minute.

FbTrace trace = new FbTrace();
trace.ConnectionString = "database=localhost:rrr.fdb;user=sysdba;password=masterkey";
trace.ServiceOutput += (object sender, ServiceOutputEventArgs e) =>
	{
		Console.WriteLine(e.Message);
	};
trace.DatabasesConfigurations.Add(
	new FbDatabaseTraceConfiguration()
		{
			DatabaseName = string.Empty,
			Enabled = true,
			Events = FbDatabaseTraceEvents.Connections | FbDatabaseTraceEvents.Transactions
		});
trace.Start("test");

The important stuff is in FbDatabaseTraceConfiguration class, where you specify what should be traced, exactly the same way as in fbtrace.conf (you can find this file in Firebird‘s installation). Mainly the database name to match for trace (if you want only some), whether it’s enabled (probably useful if you want to keep the configuration somewhere, but selectively turn it off and on). And finally the events you’re interested in – FbDatabaseTraceEvents enum. In the example above I’m tracing only connections and transactions (not for example stored procedures prepares or executions). All this configuration is added into DatabasesConfigurations property. You can have for sure different configurations for different databases. For Services API tracing there’s property, because it’s only one “services instance” in Firebird server, called ServiceConfiguration. At the last line I’m starting the trace session named test using method Start.

And that’s it. When something happens in the database the ServiceOutput event handler will be invoked and you’ll get the trace message.

Of course, you can also call Suspend, Stop, Resume and List methods to do accordant actions in API.

This is the initial implementation and some methods may be added (I’m already thinking about a few). Hope you enjoy it. Feel free to play with it and comment here or in list.

18
Nov

ADO.NET provider 2.6.0 for Firebird released

Firebird .NET provider team is proud to announce next version of ADO.NET provider for Firebird – 2.6.0.

This version contains various bug fixes as well as new features and improvements. And of course support for some of new Firebird server features. Highlights:

All changes can be found at tracker.firebirdsql.org.

You can download it at http://sourceforge.net/projects/firebird/files/firebird-net-provider/2.6.0/ or http://www.firebirdsql.org/index.php?op=files&id=netprovider.

Thanks to all who helped improving and hunting issues.

8
Nov

FBCon 2010 Bremen – topics on Firebird & .NET

I almost forgot to announce the topics touching ADO.NET provider for Firebird. This year I have three sessions. You can find more info, and register, of course, at firebird-conference.com. Here’s the list.

So if you’re interested in any of these topic, come, ask, participate. Especially hearing scenarios in what you’re using the .NET provider is very valuable for me. I also like talking between sessions, I always learn something new and I’m eager to to my best to answer all questions people are asking.

2
Nov

Connecting from Android to Firebird

Remember the challenge I did some time ago with .NET provider for Firebird and MonoTouch? Well because I’ve got access to previews of MonoDroid, why not to try the same here?

Again it’s a pretty challenge for the whole MonoDroid stack, as the provider uses a lot of various pieces from .NET Framework. And taking into account, the MonoDroid is still in previews phase I wasn’t sure I’ll be able to succeed. However I did. With some tweaking, and I kind of remembered the important places from last attempt, so it was faster, I was able to make it work easily.


Application connected to Firebird server and showing server version and data from MON$DABATASE

Cool, isn’t it? Taking into account, that the Windows Phone 7 (because everything there is based on Silverlight) doesn’t contain pieces from ADO.NET, it’s nice that Mono isn’t crippling the objects available.

Still using i.e. OData is probably better idea, but who knows what somebody might wanna create.

5
Oct

LINQ and left outer join helper

Previous two functions (function 1, function 2) I presented were doing something that wasn’t core part of LINQ and it was up to you to create it. On the other hand, this function is different. It’s just a helper to simplify writing of left outer join (or right outer join, depending on what collection you consider to be on left/right side). Not because it’s hard to write it, but because it involves couple of lines and repeating it all the time is just boring. 8-)

internal static IEnumerable<TResult> LeftOuterJoin<TOuter, TLeft, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TLeft> left, Func<TOuter, TKey> outerKeySelector, Func<TLeft, TKey> leftKeySelector, Func<TOuter, TLeft, TResult> resultSelector)
{
	return
		from o in outer
		join r in left on outerKeySelector(o) equals leftKeySelector(r) into j
		from r in j.DefaultIfEmpty()
		select resultSelector(o, r);
}

Nothing tricky. You can find this in many examples, I just wrapped it into method and parametrized it a little. Enjoy.

5
Oct

Aggregating with increments

Similarly to previous method for Interleaving two IEnumerables I needed one method for doing kind of aggregate, but also to know about the intermediate steps. I could abuse the Aggregate method either directly or indirectly but I’m always more happy with clean solution.

The method is pretty simple (but before I did some rework, it was ugly ;) ). It takes, apart from the IEnumerable, two functions. One for setting up the initial value for the first item and one for getting result for next step.

internal static IEnumerable<TResult> IncrementalAggregate<TSource, TResult>(this IEnumerable<TSource> data,
	Func<TSource, TResult> init,
	Func<TSource, TResult, TResult> nextResult)
{
	bool first = true;
	TResult intermediate = default(TResult);

	foreach (var item in data)
	{
		if (first)
		{
			intermediate = init(item);
			first = false;
		}
		else
		{
			intermediate = nextResult(item, intermediate);
		}
		yield return intermediate;
	}
}

With it you can do i.e. summing the numbers and know what the intermediate sums were. Yes, sounds weird, but you might need it, one day as I did. :)

5
Oct

Interleaving two IEnumerable sources

I was recently doing some work related to custom reporting and I needed to simply interleave two streams of data (it was actually same source, but different items selected). Kind of select first item from the first stream, first from the other, second from first, second from other etc. No big deal.

To make this easily doable I created simple extension method for me.

internal static IEnumerable<T> Interleave<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
	using (IEnumerator<T>
		enumerator1 = first.GetEnumerator(),
		enumerator2 = second.GetEnumerator())
	{
		while (enumerator1.MoveNext())
		{
			yield return enumerator1.Current;
			if (enumerator2.MoveNext())
				yield return enumerator2.Current;
		}
	}
}

It keeps reading elements from the first stream and if there’s enough in the second stream then interleave. If the second one isn’t “long” enough, it’ll keep returning only items from first one. If the second one is “longer”, it’ll stop when the first one is empty. If you need handle these cases differently, you can either change the method or preprocess the streams before using this method.

4
Oct

Firebird 2.5 (final) released

Today the Firebird 2.5 is being released. You can read the press release and most importantly release notes. And sure, you can download it and use/test/deploy.

I’m not going to repeat what’s written in documents above. Instead I’m going to provide some of my information about using it and some thoughts from .NET provider view.

To be honest I’m using Firebird 2.5 in production environment since betas (I made a small mistake and wasn’t able to easily go back and was lazy to do the long process :) ). And I’m more than pleased with the stability. Even the betas were more stable than 2.1, where I, probably thanks to environment, experienced I/O problems from time to time. The language features are nice too. I don’t have any personal favorite, all are great addition to whole ecosystem. Actually I do have. It’s not a language feature, but a fixed behavior. And it’s affecting .NET provider.

In some cases the left outer join produced wrong results. Unluckily this error was exposed when discovering database structure for Entity Framework, so even you could use 2.1 in production, for development (at least for model generation) you had to use prerelease versions of 2.5 and that’s, if nothing else, little bit inconvenient. Not taking into account some internal protocol and core improvements that are now exposed in provider as well. I.e. cancellation of running command to pin point one.

I could write more and more about the .NET provider and new version. True to be told, I like every improvement I do in provider that may help other to fully unleash the power of Firebird.

Congratulation to us, the Firebird Project, especially the core team. And also to you, users, I hope you’ll enjoy and like the new Firebird 2.5 version as we (I) do.

Note: The MindTheBird campaign team will run a webinar today at 13:00 GMT in anticipation of the launch of Firebird 2.5 Final Release. See the details.

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.

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

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?

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. I didn’t want to use AsParallel method as I expected a need for more control maybe sometime later. 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.

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.

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.

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.

26
Jun

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

6
Jun

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.

5
Jun

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

15
May

T4 templates processing at runtime

The T4 templates are great tool for use. You can generate literally anything with it with comfort of using any .NET code you have available. Code generation (i.e. POCO classes in EFv4), web service proxies, simple DALs, …, all easily available.

But what if your scenario is one step further? You don’t want to use T4 template to generate i.e. code you’ll later compile into your application, but use the T4 template in runtime to generate result your application will later use (i.e. email based on template). Good news is you can do it, and it’s not hard either.

Easiest way is to start with Preprocessed Text Template file type adding to your solution. The file itself is ordinary T4 template you’re familiar with. But if you build your project the result produced isn’t output from template, but the C#/VB code that produces the result if called. Same result can be done by changing Custom Tool into TextTemplatingFilePreprocessor in Properties window of your current T4 template file.

Then you can create instance of this class (it has same name as your template file), setting up properties, if any and calling TransformText method. Pretty easy, isn’t it?

« Previous PageNext Page »