Archives for January, 2012
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?
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.
I recently started thinking about backing up also “less” [1] important data to Amazon S3 from my Synology NAS, which is my primary backup location. The problem was, that the amount was about 150GB. Far more than I can upload through my home connection in reasonable time. It would take weeks. When I first started using S3 backup on my NAS, I checked, what’s exactly being copied to the bucket, in case disaster happens and I’ll be force to restore without any Synology box around (or at least restore critical data sooner than I’ll have it available).
Luckily it’s almost the same structure as on disk. There’s a @tmp folder added and whole backup is in particularly named folder, but the name is same for all backups from the NAS. If you checked also Enable metadata backup, there’s one file per folder, with metadata in it (guessing, I haven’t tried to reverse it), but I’m not using this option.
I wanted to upload the initial data from my office, where the connection is better and, because the data isn’t changed too often, just backup the differences directly from box. With the above knowledge I was pretty confident, the off-site upload is going to work.
And it did. After I uploaded the data, I triggered the backup on box and after a while it was done. Like a glove.
And remember, backup is one part. Restore is the key other!
[1] No matter what you think, every data is important. You’ll find out, when you will loose the least important data (you thought it’s least important). But everybody needs to learn that the hard way, before really believing.
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.
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.
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.
A question came to me last week. It was simple. Given the column I’d like to query all tables in database for this column (with some condition) and get values back. It was on Firebird so I jumped into system tables and generated query on the fly in execute block (aka anonymous stored procedure).
The idea is simple. First get all table names (views and system tables excluded, but you can also exclude i.e. temporary tables) with this column (to be able to later run the query successfully), then concatenate some strings to build the query (with condition for the column) and finally use execute statement to run the query. The into clause will fill the variable and suspend will send the result (row) to client.
execute block
returns (table_name varchar(100), column_value varchar(100))
as
declare variable column_name varchar(100);
begin
column_name = upper('id'); /* put here your column name */
for select rdb$relation_name from rdb$relations r
where rdb$system_flag = 0 /* no system tables */ and
rdb$view_blr is null /* no views */ and
exists(select 1 from rdb$relation_fields rf where rf.rdb$relation_name = r.rdb$relation_name and rf.rdb$field_name = :column_name)
into :table_name do
begin
execute statement 'select cast(' || column_name || ' as varchar(100)) from ' || table_name || ' where /* put your condition here */' into :column_value;
suspend;
end
end
As a modification you can also instead of running n queries create one big string with union all-ing all queries and run just this one. You should compare execution plans and speed to see which one performs better. Then you would use for execute statement ... do do process results.
Visual Studio‘s Navigate To window (Ctrl+,) is a very fast way to navigate in your files, classes etc. Few days ago I accidentally found a “feature”. I always started typing with first letter in upper case and after few characters I messed it up by typing letter in wrong case and missing object I was looking for. I was trying to find a way to make it do the search case insensitively.
And it’s actually pretty easy. As long as you type using lower case, it’s case insensitive. Using upper case once, turns it to case sensitive mode. No settings needed. Easy. I like it.
The Kindle 4 Touch has, as expected, new (improved) browser experience. It’s pretty good in fact, for quick look and read on some pages or for reading articles in your Instapaper.
If you’re a site owner, you may want to know accesses from Kindle to your site (i.e. to provide simplified version). The User-Agent for Kindle 4 Touch with latest firmware (in time of writing this post – Kindle 5.0.0 (1370280073)) is:
Mozilla/5.0 (X11; U; Linux armv7l like Android; en-us) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/533.2+ Kindle/3.0+
Probably the interesting piece is Kindle/3.0+, so you can distinguish previous Kindle 3.
When I first saw the news about new Kindle coming and being with touch support, I was calm. I didn’t seen why would somebody need touching it. You know, I’m reading on my Kindle. And I’m reading a lot (in fact, I’m reading, except technical books and papers, as you’d expect also various different genres I wouldn’t thought I’d ever read). Next page, sometimes previous page button. That’s 99% of my “hardware” interaction with my Kindle. When it first came out, again nothing. Why should I buy new one, I thought. I don’t know what happened after few weeks, but I found myself checking the new Kindle. Probably the most interesting piece for me was a missing keyboard. I’m typing probably only hundred or so characters in a month aka nothing.
Boring story for the beginning.
Now about the Kindle 4 Touch itself.

Although you can check the dimensions compared to Kindle 3 Keyboard, something different is feeling. Yes, it feels smaller, but also – to me – little bit heavier and also thicker. The thickness is actually good. The previous Kindle was to thin for my hands. The new one is more comfortable to hold.
There are no buttons, except one, that brings you to home screen, every time. You’re turning pages by touching right (approximately) two thirds of screen of one third on left side. Flipping also works. Touching about two centimeters on top shows you the menu (when reading a book). The touch layer is infrared layer above the screen. It has advantage of being able to register touches not only by finger, but also using i.e. pen. On the other hand, the display is little bit deeper in device (so if the light goes from side, there’s a small shadow, that I find sometimes disturbing). Multitouch is also supported, so you can i.e. change the size of letters using pinch-to-zoom gesture. I’d like to see the display after few months of usage. More cleaning will be probably necessary.
After few weeks of using, I don’t see any problem using touch to turn pages. And because there are no buttons on sides, I can rest my thumbs on these margins without turning page accidentally from time to time as with Kindle 3.
The UI inside is similar to previous version, but improved to flow nicely with touches. I have to say, that was the part I was scared of a little when ordering. But no, the UI and touch goes hand in hand, frictionless.
But there’s one downside, I hope will be solved in next firmware version. Rotation. Right now there’s no way (or I don’t know it 8-)) to rotate the screen. Although a lot of non-Amazon publishers are now offering more and more books not only in PDF, but also in MOBI/EPUB formats, occasionally I use PDFs. In landscape mode, it’s easier to read it, especially if the PDF was (probably was) meant for printing and font size is “regular”.
The rest of Kindle properties are still there. Great display, easy to read. Simple books buying and delivery. Wireless delivery of documents. Decent speed. Long (I mean long) battery life. Etc. etc. etc.
Obbligato question at the end. Would I buy it again? Yes, I would. Do I regret it? No, I don’t.
If you have any question or something to try, feel free to ask in comments. I try to answer to my best.