[:en]Author Archive[:fr]Archive Par Auteur

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.

23
Jan

Off-site initial upload for Synology Amazon S3 backup

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.

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.

11
Jan

Value of particular column from all (some) tables in database dynamically in Firebird

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.

9
Jan

Navigate To window case sensitivity and insensitivity

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.

5
Jan

Browser’s User-Agent of Kindle 4 Touch

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.

5
Jan

Kindle 4 Touch review

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.

29
Dec

PowerShell script to tabify text (i.e. in code files)

Few weeks ago I needed to tabify (change spaces to tabs) in a C# files in a solution. I tested some plug-ins to Visual Studio, but none of them did what I wanted. I left the idea, as it was not that important to have consistent tabs/spaces. But a day or two ago I had some time and yen for to create simple PowerShell script to fix that for me. It simply replaces x spaces taken from input parameter with tab(s). Text goes to stdin and result to stdout.

param([int]$spaces)

$pattern = '';
for ($i = 0; $i -lt $spaces; $i++) {
	$pattern = $pattern + ' ';
}
$pattern = '^((' + $pattern + ')*)' + $pattern;
$replace = '$1' + "`t";

$input | foreach {
	$text = $_;
	do {
		$prev = $text;
		$text = $text -replace $pattern, $replace;
	} while ($prev -ne $text)
	Write-Output $text;
}

The script, as you can see, is not interpreting the code in any way, hence some spaces i.e. in comments at the beginning might become tabs even if that’s actually wrong. But hey, you can take Roslyn and plug it in, as an exercise. :)

To, for instance, tabify all .cs files in some path, you can call this script (saved as tabify.ps1) using something like:

Get-ChildItem -Recurse ".\src" | Where-Object {$_.Extension -eq ".cs"} | foreach { Get-Content $_.FullName | .\tabify.ps1 -Spaces 2 | Set-Content -Encoding UTF8 ($_.FullName + ".tabs") }
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-)

21
Dec

log4net (back) alive on NuGet

It turned out, that the previous maintainer of log4net NuGet package @dotnetjunky was assigned mistakenly. So nobody was actually maintaining that package. After few messages with him, we decided, I’ll take over the ownership and maintain it.

I still use NLog in my projects, as I like it a little bit more. But I know, there’s big community around log4net, with my coworker Ales included. :)

Today I uploaded package with new version 1.2.11 [1], and I’ll try my best to keep the package up-to-date. Enjoy.

[1] I used the binaries signed with new key so any new dependencies will follow this recommended usage.

20
Dec

Mapping self references in Code First

From time to time I see people having problems to map self references in Code First in Entity Framework. It might be confusing what to do with HasMany/WithMany and HasOptional/WithOptional.

So let’s jump in. Define a pretty simple table:

create table SelfRefs (
  ID int primary key,
  FooBar varchar(20) not null,
  ID_Parent int
);

alter table SelfRefs add foreign key (ID_Parent) references SelfRefs(ID);

The corresponding class could be:

class SelfRef
{
	public int ID { get; set; }
	public string FooBar { get; set; }
	public SelfRef ParentItem { get; set; }
	public int? ParentItemID { get; set; }
	public ICollection<SelfRef> ChildItems { get; set; }
}

Now the mapping. The “trick” here is to realize, that we have not only child->parent association, but also parent->children. The other one is implied from the first one. Hence every child item has optional parent. If the child item has no parent, it is actually a 1st level child, aka child of (invisible) “root” (NULL parent). That also means you can map it from both directions and result will be the same. Here’s the example (it’s explicit a little more) with both mappings (you can use both declarations together without any problem):

class SelfRefConfiguration : EntityTypeConfiguration<SelfRef>
{
	public SelfRefConfiguration()
	{
		this.HasKey(x => x.ID);
		this.Property(x => x.ParentItemID).HasColumnName("ID_Parent");
		// starting from child with parent
		//this.HasOptional(x => x.ParentItem).WithMany(x => x.ChildItems).HasForeignKey(x => x.ParentItemID).WillCascadeOnDelete(false);
		// starting from parent with children
		this.HasMany(x => x.ChildItems).WithOptional(x => x.ParentItem).HasForeignKey(x => x.ParentItemID).WillCascadeOnDelete(false);

		this.Map(map =>
			{
				map.Properties(x => new { x.ID, x.FooBar, x.ParentItemID });
				map.ToTable("SelfRefs", "dbo");
			});
	}
}

Hope I made it a little bit more clear. If not, feel free to ask in comments.

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!

11
Dec

Custom logic in every Entity Framework’s query

Few days ago there was a question on Twitter in #efhelp about adding custom logic to every query in Entity Framework. It’s pretty easy and you can do it absolutely transparently so nobody using your code needs to know.

First you need to focus you Entity Set (not Entity Type) in Model Browser window.

Here set the access modifier to i.e. private or (internal/protected) and rename it to something else, so it’ll not interfere with original name of property we’re going to create. I often use X prefix (especially for properties on entities).

Now it’s pretty easy to create some logic. Here I simply added filtering to always only fetch entities younger than 10 days from now.

partial class Model1Container
{
	public IQueryable<FooBarEntity> FooBarEntitySet
	{
		get
		{
			DateTime d = DateTime.UtcNow.AddDays(-10);
			return XFooBarEntitySet.Where(fb => fb.Created > d);
		}
	}
}

And that’s it. Not a difficult task. But also note that through Entity SQL (or i.e. reflection) somebody might be still able to access original entity set and get access to the data. So it’s not rock hard security solution.

9
Dec

Sorting using blob column on Firebird

Imagine you have a blob column and you want to add sorting clause to your query based on that column. Crazy? Might be. On the other hand, why not?

Firebird allows you to use blob column for sorting. No problem. But the behavior might surprise you. I’m not going to deeply describe how the blobs are stored in Firebird database. Simply speaking, it’s stored in separate data pages and inside row only blob id is stored. If you use blob column for sorting, Firebird isn’t fetching the complete blob (though looks straightforward, it would be very slow), but rather uses blob id for sorting. You probably see the problem already – the blob id has nothing to do with content. Hence the sorting will be very likely broken.

But there’s a solution. I’m assuming that you want to mainly sort on text blobs (though you can use it on binary blobs too). Simply cast the blob to i.e. varchar(20) (choose length that fits your needs) and sort using this. Yes, it’s going to be slow, but if you need to do it often, you can precompute this column (using trigger etc.).

21
Nov

Using database initializers with EDMX

Last week at my Entity Framework training I got a question whether you can use database initializer while still using EDMX file. The answer, as it turned out, isn’t that straightforward.

Directly you can’t. Because you need DbContext to create IDatabaseInitializer<T> (or to derive from default ones respectively). Even if you try to wrap ObjectContext into DbContext you’ll fail. The default objects are derived from EntityObjects and this is something that’s a showstopper for DbContext. So that’s a bad news.

On the other hand, there’s a good news, kind of. There’s a template (from Microsoft) to generate DbContext and classes from EDMX file.

With this template you will get all you need to start using database initializers. Only problem is, that you don’t have configurations generated from EDMX. But there’s also 3rd template, that can generate configurations (I haven’t tested it exhaustively).

Final answer? Yes you can, but it’s not smooth as it could be.

19
Nov

Firebird vs SQL Server CE – MS Fest 2011

Rok se s rokem sešel a koná se další MS Fest. Tentokrát nabídnu něco alternativního. Podíváme se na databázový stroj Firebird. A protože Firebird nabízí i Embedded verzi, kterážto je velmi zajímavá, porovnáme ji i s konkurencí v podobě MS SQL Server CE.

Anotace:

Microsoft SQL Server není jedinou databází, kterou můžete používat z .NETu. Ačkoli nabízí i verzi zdarma a je plně podporován mnoha nástroji ve Visual Studiu, existují i zajímavé alternativy. Firebird může být jednou z nich. Je zdarma, výkonný, přitom nenáročný a malý. Nabízí Embedded verzi, která je (nejen) alternativou k Microsoft SQL Serveru CE. V rámci přednášky si představíme Firebird jako databázový server a ukážeme so základní práci. Nakonec se zaměříme na Embedded verzi, porovnáme možnosti s MS SQL CE 4 a vytvoříme funkční aplikaci.

Více info na ms-fest.cz.

Next Page »