Posts Tagged ‘.NET’

24
Jan

Try catch return bool

I was recently writing a lot of method that talked to 3rd party API. And after small refactoring a lot of methods was like try to call some method, if it throws exception return false, if not return true. And I was wondering, what’s the best (in terms of code being generated, speed, efficiency but also readability) way to write it.

I found basically three ways to write it (sure there are other ways):

try
{
	FooBar();
	return true;
}
catch (SomeException ex)
{
	LogException(ex);
	return false;
}
try
{
	FooBar();
	return true;
}
catch (SomeException ex)
{
	LogException(ex);
}
return false;
bool result = false;
try
{
	FooBar();
	result = true;
}
catch (SomeException ex)
{
	LogException(ex);
}
return result;

No magic. The third way is probably something you might recognize, if you were programming couple of years in Delphi/(Object)Pascal. Anyway, back to basics. My friend ildasm is going to help us with initial review, what we have actually done.
Everything compiled with full optimization turned on.

.method private hidebysig static bool  Test1() cil managed
{
  // Code size       28 (0x1c)
  .maxstack  1
  .locals init (class TryCatchTest.SomeException V_0,
           bool V_1)
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  call       void TryCatchTest.Program::FooBar()
    IL_0007:  nop
    IL_0008:  ldc.i4.1
    IL_0009:  stloc.1
    IL_000a:  leave.s    IL_0019
  }  // end .try
  catch TryCatchTest.SomeException
  {
    IL_000c:  stloc.0
    IL_000d:  nop
    IL_000e:  ldloc.0
    IL_000f:  call       void TryCatchTest.Program::LogException(class [mscorlib]System.Exception)
    IL_0014:  nop
    IL_0015:  ldc.i4.0
    IL_0016:  stloc.1
    IL_0017:  leave.s    IL_0019
  }  // end handler
  IL_0019:  nop
  IL_001a:  ldloc.1
  IL_001b:  ret
} // end of method Program::Test1
.method private hidebysig static bool  Test2() cil managed
{
  // Code size       32 (0x20)
  .maxstack  1
  .locals init (class TryCatchTest.SomeException V_0,
           bool V_1)
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  call       void TryCatchTest.Program::FooBar()
    IL_0007:  nop
    IL_0008:  ldc.i4.1
    IL_0009:  stloc.1
    IL_000a:  leave.s    IL_001d
  }  // end .try
  catch TryCatchTest.SomeException
  {
    IL_000c:  stloc.0
    IL_000d:  nop
    IL_000e:  ldloc.0
    IL_000f:  call       void TryCatchTest.Program::LogException(class [mscorlib]System.Exception)
    IL_0014:  nop
    IL_0015:  nop
    IL_0016:  leave.s    IL_0018
  }  // end handler
  IL_0018:  nop
  IL_0019:  ldc.i4.0
  IL_001a:  stloc.1
  IL_001b:  br.s       IL_001d
  IL_001d:  nop
  IL_001e:  ldloc.1
  IL_001f:  ret
} // end of method Program::Test2
.method private hidebysig static bool  Test3() cil managed
{
  // Code size       34 (0x22)
  .maxstack  1
  .locals init (bool V_0,
           class TryCatchTest.SomeException V_1,
           bool V_2)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  .try
  {
    IL_0003:  nop
    IL_0004:  call       void TryCatchTest.Program::FooBar()
    IL_0009:  nop
    IL_000a:  ldc.i4.1
    IL_000b:  stloc.0
    IL_000c:  nop
    IL_000d:  leave.s    IL_001b
  }  // end .try
  catch TryCatchTest.SomeException
  {
    IL_000f:  stloc.1
    IL_0010:  nop
    IL_0011:  ldloc.1
    IL_0012:  call       void TryCatchTest.Program::LogException(class [mscorlib]System.Exception)
    IL_0017:  nop
    IL_0018:  nop
    IL_0019:  leave.s    IL_001b
  }  // end handler
  IL_001b:  nop
  IL_001c:  ldloc.0
  IL_001d:  stloc.2
  IL_001e:  br.s       IL_0020
  IL_0020:  ldloc.2
  IL_0021:  ret
} // end of method Program::Test3

The third way is longest and I think also least readable (taking into account it’s C#). Also you can easily break the code. The first and second are really close in terms of code. The first one I’m using if I like to state, that after the exception is processed, nothing is going on further – “do, return or catch, return, done”. Nor in catch block, nor after it. The second one I’m using if my code is like “do something and return something” and then “else recover based on error and return fallback result”.

And what’s your preference?

24
Jan

InfoQ interview with me

I was recently interviewed for InfoQ article – Q&A with Jiri Cincura of the Firebird Database Project. We touched Firebird, ADO.NET, O/RMs, Entity Framework etc. If you have any questions, feel free to ask.

15
Jan

Entity Framework 5.0!

Yesterday I wrote a post about a possible confusion that might be introduced with new version being version 5.0. Diego Vega wrote a follow up post describing the rationale behind it (and it was also noted in comments in previous post). Simply the team is now sticking to semantic versioning no matter what. Hope that will last a while. Let me recap.

The first version was, hey, version 1. The second version was version 4, because the numbering being unified with .NET Framework. Then there was a bunch of CTP, vNext, Preview, Alpha/Beta versions something being just update with version 4 core, something with new core. Hard to track what was what. Decision to use semantic versioning was made and the numbering was cleared a little, simply to 4.x and whatever version comes next. Still on track? Because of the semantic versioning rules, the next version is going to be 5. I thought the previous versioning decision would take precedence (though I think the .NET Framework version could be 5.0 as well) and it will be 4.5 as well.

I was wrong. The semantic versioning is now the way Entity Framework is going no matter what. Good. Hope the third version will be still using this scheme and will be version 6.

So. Next version is going to be version 5(.0.0) and will be delivered with .NET Framework 4.5.

13
Jan

Entity Framework 5.0???

There’s a follow up post.

I’m a little bit perplexed. Entity Framework 4.3 Beta 1 was just released. And there’s a sentence in the document that’s very interesting:

As soon as the next preview of the .NET Framework 4.5 is available we will be shipping EF 5.0 Beta 1, which will include all these new features.

Does it mean that the version that will ship with .NET Framework 4.5 (the next version in time of writing this post) is going to be 5.0? I still clearly recall the mess the second version with version number 4.0 created – a lot of people, on my trainings, talks, …, confused. What happened to clear versioning strategy?

I hope it’s just a small miss/typo and the version will be Entity Framework 4.5 and the following (additive) updates will be 4.5+n.

13
Jan

CultureInfo equality

I have a small morale from today. I was writing some code that was handling searching for items base also on CultureInfo. Because it’s a pretty straightforward object, in core of .NET Framework (it’s in mscorlib) I was expecting to handle equality using == based on culture itself not the object. And of course, I was wrong. :)

The code below should explain it clearly (CurrentUICulture might be different based on your system).

// false
System.Threading.Thread.CurrentThread.CurrentUICulture == System.Globalization.CultureInfo.GetCultureInfo("en-US");
// true
System.Threading.Thread.CurrentThread.CurrentUICulture.Equals(System.Globalization.CultureInfo.GetCultureInfo("en-US"));

Yep. Learning something every day.

24
Dec

Composing functions the LINQ way

Few days ago I was writing a class, that was simply wrapped for a collection of other classes (with same interface), aggregate class. The class also had few methods, where the logic was simple. Let’s say one method M. Other classes having same method as well. This method was simple transformation of data with same output as input. The aggregate class was simply calling M method of first, second, … of other classes.

I started with something like this:

function T M<T>(T data)
{
	T tmp = data;
	foreach (var c in classes)
	{
		tmp = c.M(tmp);
	}
	return tmp;
}

But then I had some weird wave in my brain and started thinking. I could create collection of functions, like IEnumerable<Func<T, T>> and call methods from this collection. Wait a minute… I can create from this collection of function one aggregate function and call just this one. Crazy? ;) Probably. But it’s a nice way to keep my brain running.

It turned out, it’s pretty easy with LINQ:

public static Func<T, T> Compose<T>(this IEnumerable<Func<T, T>> source)
{
	return source.Aggregate((agg, fn) => (d => fn(agg(d))));
}

I don’t think it’s any more (less) useful than the foreach with direct method calls, but it’s more succinct, more functional and more fun. 8-)

19
Dec

Improved command logging in ADO.NET provider for Firebird – part 2

Previous version of ADO.NET provider for Firebird brought us a support for command tracing. Although it was good, it could be done better. Few interesting scenarios came back to as a valuable feedback and with the old implementation it was hard to do it.

The new one builds on top of TraceSource class allowing you to handle different sources from trace messages easily and independently. The what’s logged is same, but now every message is traced through FirebirdSql.Data.FirebirdClient source, hence you can easily i.e. turn it of (and just these messages, without affecting other messages) or send it to i.e. console window. Just a few lines in app.config and you’re done.

<system.diagnostics>
	<sources>
		<source name="FirebirdSql.Data.FirebirdClient">
			<listeners>
				<clear />
				<add name="console" type="System.Diagnostics.ConsoleTraceListener"/>
			</listeners>
		</source>
	</sources>
</system.diagnostics>

The code above sends all messages (commands) from provider to (only) console window. You can use your own listener, of course or turn it off completely, using just the <clear />.

19
Dec

ADO.NET provider for Firebird 2.7 released

I’m happy to bring you early Christmas gift packed as ADO.NET provider for Firebird version 2.7. This version brings important bug fixes (tracker.firebirdsql.org) and logging improvements.

This release wouldn’t be possible without support of people/companies using provider actively. Big thanks to them.

You can download it at www.firebirdsql.org or use NuGet package.

Enjoy!

29
Aug

Collection type result – speed comparison of IList.Add and IEnumerable.Concat

From time to time I’m working on some method that returns some collection. Mainly processing some data from input. Often it’s really just couple of conditions, get something from there and here and return it. Because I’m composing these methods too, if I return IEnumerable<T> and later in other method I need to add something (if you’re lost, you’ll see what I mean in example below), I need to use some variable, like array or list and append (or prepend). Boring.

For a while I was wondering, how slow it will be, if I’ll be simply creating new IEnumerable sequences and concatenating these. I was expecting it to be slower, but is it only couple of percents or order of magnitude? Today, when I came to my office, I simply decided to test it.

The first version looks like

static IEnumerable Test1(int[] part1, int[] part2, int[] part3)
{
	IEnumerable<int> result = Enumerable.Empty<int>();
	result = result.Concat(part1);
	result = result.Concat(part2);
	result = result.Concat(part3);
	return result;
}

And the other one

static IEnumerable<int> Test2(int[] part1, int[] part2, int[] part3)
{
	IList<int> result = new List<int>();
	foreach (var item in part1)
		result.Add(item);
	foreach (var item in part2)
		result.Add(item);
	foreach (var item in part3)
		result.Add(item);
	return result;
}

Although it, especially the other one, can be written in different way(s), as a measure I think it’s OK. And it’s close to how I often process the data.

I did couple of runs to eliminate some errors, with “Release” build, without attached debugger. The part1 and part3 parameters were always the same in size. The part2 I was playing with, because the size affects the speed too.

If the part2 size was roughly under 10k items, the speed difference was on the edge error of measurement. From 10k+ to 1M items it’s about 25% the Concat approach being slower. Some absolute numbers (averages from 20 runs, “Release” build, without attached debugger) from my laptop:

Size: 1         Time1: 0        Time2: 0        %: 0
Size: 2         Time1: 0        Time2: 0        %: 0
Size: 3         Time1: 0        Time2: 0        %: 0
Size: 4         Time1: 0        Time2: 0        %: 0
Size: 5         Time1: 0        Time2: 0        %: 0
Size: 6         Time1: 0        Time2: 0        %: 0
Size: 10        Time1: 0        Time2: 0        %: 0
Size: 100       Time1: 0        Time2: 0        %: 0
Size: 1000      Time1: 0        Time2: 0        %: 0
Size: 6000      Time1: 0,2      Time2: 0        %: 0
Size: 20000     Time1: 2,05     Time2: 0,5      %: 24,390243902439
Size: 60000     Time1: 6,55     Time2: 1,6      %: 23,3576642335766
Size: 100000    Time1: 11,8     Time2: 3,15     %: 24,7899159663866
Size: 1000000   Time1: 124,85   Time2: 33,2     %: 26,9609775325187

Conclusion? If the data is relatively small, the path you choose doesn’t really matter. For “bigger” collections the imperative approach provides better performance.

13
Aug

FirebirdClient on NuGet

Yep, it’s done. Now you can download FirebirdClient from NuGet. From nuget.org/List/Packages/FirebirdSql.Data.FirebirdClient to be precise.

It took me a while to find some time to create the package and publish it. But recently I started using NuGet quite often, so assigned this task higher priority.

The build there is same as the default one (targets .NET 4 CLR) you can download from site. Later I’d like to incorporate into package other versions (different CLRs, Mono builds, …) too. Maybe the other pieces like WebProviders, DDEX (?) and unstable builds could be there too. I’ll think about it more.

Hope you’re excited as I’m and you’ll enjoy it. :)

9
Jul

Coalescing object and accessing it

I was reading Twitter yesterday and spotted a tweet from Shawn Wildermuth about his pain about using coalesce operator (??) in C# and doing immediately something with result.

I had same problem maybe a year back, when I was dealing heavily with XML and LINQ to XML (but it doesn’t matter). I created for myself a little extension method to help me solve writing lines like:

Something x = (a == null ? "FooBar" : a.FooBar);

The method:

public static TResult ObjectCoalesce<T, TResult>(this T o, Func<T, TResult> operation, TResult @default)
	where T : class
{
	if (o == null)
		return @default;
	else
		return operation(o);
}

And simple usage:

Something x = a.ObjectCoalesce(y => y.FooBar, "FooBar");

When it’s nested in some calls, it really helped me to make my code shorter. You can also play (I did) with idea of having the default parameter as delegate so it will be evaluated only if needed. In some cases it could make a huge difference (i.e. side-effects).

3
Jun

ADO.NET provider for Firebird version 2.6.5 released

I’m proud to announce new version of ADO.NET provider for Firebird – 2.6.5. It’s half maintenance release, half new features.

You can find all bug fixes in tracker.

The new features include and improvements:
* Support for Trace API in Firebird 2.5.
* Improvements in SQL generation for Entity Framework.
* Support for commands logging .
* Slightly faster command execution of big queries.
* And a lot of small code improvement making it more stable…

You can download it at http://sourceforge.net/projects/firebird/files/firebird-net-provider/2.6.5/ or http://www.firebirdsql.org/en/net-provider/.

Hope you’ll enjoy the release.

19
May

Improved command logging in ADO.NET provider for Firebird

I recently improved the command logging in ADO.NET provider for Firebird. Let me start with little bit of history and then you’ll see the motivation and current improvements.

Before I added simple Debug.WriteLine to the FbCommand class. This was mainly driven with need to easily see commands I was generating for Entity Framework. Then the Visual Studio 2010 came with the IntelliTrace (only Ultimate version) and while working with MS SQL Server I was happy to see commands without any additional effort. I wanted the same for Firebird too. Sadly the IntelliTrace right now isn’t publicly pluggable. I was still using the debugging code, but often when doing development on customer’s applications using released version of provider I lost this ability. No debug outputs, no IntelliTrace.

Because I believe it’s important to have easy way to see (and not only for Entity Framework’s generated) the command, to spot performance problems early, I added simple logging facility. This logging is enabled for all builds (not only debug) and uses Trace class from .NET Framework. Everytime you Prepare (the Prepare method is called also automatically before execute if not called manually) command you’ll see the command text and current parameter names and values (if any). If you’re inside Visual Studio you see by default the output in Output window. You can also configure it to log i.e. to file, probably usable in staging and/or production.

Hope you find this useful as I do.

16
May

Easy indentation control for Debug/Trace/…

I was setting up simple command logging, but keeping in my mind where I increased the indentation to later decrease it back was causing me headache. Also formatting the string I’d like to put out wasn’t smooth.

So I created simple wrapper class implementing IDisposable, where the disposing will actually decrease the indentation automatically. Only thing you (I) have to use is simple using block. The precooked WriteLine helper method is there just to save me some typing.

class IndentHolder : IDisposable
{
	public void Dispose()
	{
		Trace.Unindent();
	}
}

public static void WriteLine(string format, string category, params object[] args)
{
#if (TRACE)
	Trace.WriteLine(string.Format(format, args), category);
#endif
}

public static IDisposable Indent()
{
#if (TRACE)
	Trace.Indent();
	return new IndentHolder();
#endif
}
15
Mar

Are you Lazy<T>?

Yesterday I was chatting with Aleš Roubíček after lunch and he told me he likes the Lazy<T> I put into project we’re working right now and that could be worth to write about it.

Well, here it is. The Lazy<T> class is new in .NET Framework 4. Using this class is easy. If you don’t wnat to create instance of some object until it’s really needed this class will help you. And it can deal with multithreading as well.

So the well known code:

Foo _foo;
public Foo Foo
{
	get
	{
		if (_foo == null)
			_foo = new Foo();
		return _foo;
	}
}

can be replaced with:

Lazy<Foo> _foo = new Lazy<Foo>(() => new Foo());
public Foo Foo
{
	get
	{
		return _foo.Value;
	}
}

Nothing special, but when the multithreading comes into play, it’s more fun. This class has a constructor taking LazyThreadSafetyMode and you can specify what kind of thread safety you want.

By the way if you don’t provide the function, the default constructor will be invoked.

Handy isn’t it.

Let’s play with it:

class Program
{
	static void Main(string[] args)
	{
		Test(LazyThreadSafetyMode.PublicationOnly); // 2x ctor, True
		Console.WriteLine("===");
		Test(LazyThreadSafetyMode.ExecutionAndPublication); // 1x ctor, True
	}

	static void Test(LazyThreadSafetyMode mode)
	{
		Lazy<Foo> _foo1 = new Lazy<Foo>(() => new Foo(), mode);
		Foo f1 = null;
		Foo f2 = null;

		Parallel.Invoke(() => { f1 = _foo1.Value; }, () => { f2 = _foo1.Value; });
		Console.WriteLine("Same: {0}", object.ReferenceEquals(f1, f2));
	}
}

class Foo
{
	public Foo()
	{
		Console.WriteLine("Running Foo's ctor.");
		Thread.Sleep(2000);
		Console.WriteLine("About to finish ctor.");
	}
}
28
Feb

Casting Expression<Func<TEntity, TProperty>> to Expression<Func<TEntity, object>>

From time to time I’m dealing with API that’s using Expression<Func<TEntity, object>> as parameter, mainly to show property you want to deal with. And that’s fine, if you need just the expression itself. But I often create my custom extensions, where I’m somehow working with the property itself or the result. And that’s a problem, because I don’t know any info about the type, it’s just object.

If you try to directly cast the expression, it will not work, of course. First I though, it’s going to be a lot of juggle with pieces of expression and reconstructing the final one. But it’s pretty easy, see yourself:

void FooBar<TEntity, TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> property)
{
	Expression<Func<TEntity, object>> result;
	if (typeof(TProperty).IsValueType)
		result =  Expression.Lambda<Func<TEntity, object>>(Expression.Convert(property.Body, typeof(object)), property.Parameters);
	else
		result = Expression.Lambda<Func<TEntity, object>>(property.Body, property.Parameters);
	// do something with result ...
}

I’m simply creating new expression based on the original ones’ body and parameters. If the TProperty‘s type was value type I only do boxing in addition.

Nothing difficult, right?

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.

Next Page »