When I bought my Kindle 4 Touch I was satisfied with it. But there were few pieces I was missing and previous versions have them. But with firmware 5.1.0 it’s running on full steam back again.
What I like (and I was missing) in particular is landscape mode and highlighting across pages. The new homescreen layout is nice too.
Landscape mode isn’t looking that intersting on a first sight, especially if you read ebooks only. But if you read also PDFs or ebooks with some graphs, tables or images, it’s sometimes way easier to view these in landscape than to have it “overzoomed” in portrait and constantly jump right and left.
Highlighting across pages was problem before. If you had a text, that spanned two (or more
) pages, there was no way to highlight it all in one. You either highlighted it in pieces (lame) or tried to jump between chapters to align the text on one page (lame as well). Right now, if you move your finger to the bottom right corner, the page turns and you can continue highlighting. Sweet.
And finally the new homescreen isn’t looking bad either. At least initially (you know, it’s something new). But only time will prove whether it’s better or not. Right now I have a feel it’s more easy to take in.
Good right? Sad think is, there’s currently nothing I’d like to see, so I have nothing to look forward to in next version.
NoSQL is everywhere around us. And there’s a new (well, it’s here for a while, but still in beta stages of development) kind, it’s called NuoDB. To be precise, NuoDB positions itself as NewSQL. It claims to be 100% SQL, 100% ACID and 100% elastically scalable. I was following it since early stages (original name was NimbusDB, if somebody remembers) and I’d like to show it to you quickly. In follow up posts I’ll focus on using it from (mainly) .NET and some cloud scenarios (Amazon AWS, Windows Azure).
NuoDB is based on concept of chorus (aka cluster). Chorus is set of archive and transaction nodes (more about these later). One computer can be part of many choruses. Transaction node in chorus is node processing SQL transactions. If you add more transaction nodes into chorus, you basically scale it up (you can process more transactions, in, hopefully, less time). The archive nodes are nodes used for writing data into storage (just a side note, NuoDB has support for Amazon S3 without EBS). If you add more archive nodes into chorus you’re more tolerant to storage failures. There’s also “special” process (or more), called broker that manages the chorus and through it the first interaction with database occurs (then you’re talking to transaction nodes). And all this is managed through “agent” process.
Pretty straightforward, isn’t it (sure, devil is in details)? So let’s get our hands dirty. All these examples are on Windows, but you can select from variety of platform while downloading NuoDB (and of course, you can mix platforms).
>start java.exe -jar bin\nuoagent.jar --broker --password FooBar
>start bin\nuodb.exe --chorus TestChorus --password TestPwd --dba-user admin --dba-password admin
>start bin\nuodb.exe --chorus TestChorus --password TestPwd --archive "C:\Users\Jiri\Desktop\NuoDBStorage" --initialize
The first command starts broker. Second starts transaction node in TestChorus with initial user/pwd admin/admin. And last command starts archive node, the data will be stored in C:\Users\Jiri\Desktop\NuoDBStorage directory. The --initialize switch is used only first time, to, well, initialize the storage itself. That’s it, minimal set up to start playing with NuoDB. Now we can connect to it and start playing with SQL.
>bin\nuosql.exe TestChorus@localhost --user admin --password admin
SQL> create table Contacts (ID int primary key, FirstName string, LastName string, Phone string, Street string, HouseNumber int, City string);
SQL> commit;
SQL> insert into Contacts values (1, 'Jiri', 'Cincura', '+420123456789', 'RRR Street', 6, 'RRR City');
SQL> commit;
SQL> select * from Contacts;
ID FIRSTNAME LASTNAME PHONE STREET HOUSENUMBER CITY
--- ---------- --------- ------------- ---------- ------------ --------
1 Jiri Cincura +420123456789 RRR Street 6 RRR City
SQL>
Easy, right? So get grab it and play with it. Next time we’ll try some failure scenarios and we’ll explore how to connect from .NET and some other environments. Feel free to ask if you’re interested in something.
One of my first servers I used for real world applications is now unplugged. Weird feeling. It was Linux box running Slackware 10.2.0 (yeah, old). For a while it was my main mail (Postfix, Dovecot) and antispam (SpamAssassin) server. I had Firebird there as well as Apache/httpd, PHP, Subversion and Mono. And all the standard services (SSH, cron, FTP, gcc, …). The Firebird handled quite some applications thorough years. Apache handled till very last time, among other things, download mirror for PSPad (and I learned a lot about performance tuning with limited resources available when new (non-beta) version of PSPad was released). Few scripts were written in Perl, a lot of in bash directly. And that’s just what I remember.
Upgrading, configuring, compiling all these services… What a great memories.
You served well all these years (8?).
root@<removed>:~# shutdown now
Broadcast message from root (pts/0) (Mon Apr 30 08:29:38 2012):
The system is going down to maintenance mode NOW!
Roughly two years ago I blogged about differences in NULLs handling in databases and in (some) programming languages (C# in particular). But Entity Framework 5 (in .NET 4.5) (lost?) comes with handy switch. It’s UseCSharpNullComparisonBehavior. What this basically does is ensure when you compare nullable fields to be handled like in C#, aka null == null and not like in SQL where NULL compared to anything is NULL or false when boolean value is needed.
Let’s have a look at the diffences. Simple code:
int? i = default(int);
using (testEntities c = new testEntities())
{
c.ContextOptions.UseCSharpNullComparisonBehavior = true;
Console.WriteLine((c.Details.Where(x => x.MasterID != i) as ObjectQuery).ToTraceString());
}
using (testovaciEntities c = new testovaciEntities())
{
c.ContextOptions.UseCSharpNullComparisonBehavior = false;
Console.WriteLine((c.Details.Where(x => x.MasterID != i) as ObjectQuery).ToTraceString());
}
The first query creates “magic” SQL:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[ID_MASTER] AS [ID_MASTER],
[Extent1].[BAR] AS [BAR]
FROM [dbo].[DETAIL] AS [Extent1]
WHERE NOT ((([Extent1].[ID_MASTER] = @p__linq__0) AND ( NOT ([Extent1].[ID_MASTER] IS NULL OR @p__linq__0 IS NULL))) OR (([Extent1].[ID_MASTER] IS NULL) AND (@p__linq__0 IS NULL)))
While the other expected one:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[ID_MASTER] AS [ID_MASTER],
[Extent1].[BAR] AS [BAR]
FROM [dbo].[DETAIL] AS [Extent1]
WHERE [Extent1].[ID_MASTER] <> @p__linq__0
What the first one is doing is handling the case where C# null (in parameter) can be compared to database NULL to fix-up the logic.
If you’re not familiar with NULLs in database this can be tricky to handle correctly, especially if you have negations, Alls and Anys nested inside query. Hence setting this property to true can save you hours of debugging and wondering what’s going on.
Looks like there are two groups of developers. One writing ID and one writing Id. I'm in the first one, and I'm even not 100% sure why (except because my feelings are saying me, it's "more" correct). But it looks like there's no conclusion.
More and more I see the other option being used often (DbContext or HttpApplication to name a few), especially if you take into account properties like URL and so on. It even looks this is more common inside .NET Framework, but still, i.e. DBNull or System.Web.UI is an exception. Who knows...
Anyway, I'd like to ask you. What are your habits? Have you find some good pros (or cons) for one or the other? Or articles/papers/... about this naming? Share your thoughts in comments.
Collections in System.Collections.Concurrent namespace are optimized for access from more (basically) threads. That means no stupid “one-lock-for-everything” approach. Actually these are lock free.
It’s good for performance, but also, if used foolhardily, the performance penalty can be too big. One example can be the ConcurrentStack<T> class. As with a lot of collections, this stack also has a Count property. But because it’s a lock free implementation using linked list the Count isn’t that easy. Actually it’s O(n) and this can be especially bad for big stacks. So use with care. As the remarks for this property recommends, if you need to know just whether it’s empty of not, the IsEmpty is better (though realize, that in time you check it it might be empty, but not on next line where you’re about to perform some action and vice versa).
Use the tools, but also know your tools.
I like POCOs and Code First. Simply because that way I have everything under my control. I don’t mean just the code itself, but also the formatting, ordering of static/public/private/… properties etc. Same with mapping. Everything is described by me. No magic conventions. But there was one problem. If you already had a database (even with new database the initial amount of tables is big) writing all this stuff was tedious and boring.
Apart from the option to write the tool to do it yourself, there was an “hack” to create a EDMX model and generate classes (easy) and mapping (little harder) from it. In fact there are some templates ready, so you don’t have to start from scratch. But still, too much “problems”.
Luckily now there’s a tool for that, that does all in one step. EF Power Tools (currently Beta 2). When you right-click on project, you’ll get Entity Framework menu with Reverse Engineer Code First.

This will query the database similar as when using EDMX and spit out entity classes and (complete) mapping (using Fluent API). You can even customize the template being used for generating code. It’s just T4. Only difference is, that you can’t select subset of tables. It will always create code from whole database (which can be problem for huge legacy databases). And you don’t have any progress while process is running. But it’s still beta.
On the other hand, you can run it multiple times, it will overwrite the original files, so you’ll get fresh mapping, which can be quite handy, and entities (sure you’re using VCS to merge your changes back).
I tried it even with Firebird and worked as expected, probably any EF enabled provider will work.
If you’d like to read more about features, check the blog post on ADO.NET team blog. Other are interesting too (like View Entity Data Model (Read-only)).
When you use migrate.exe from Entity Framework‘s Migrations (in time of writing 4.3.1) you might get the error saying:
Could not load file or assembly ‘<assembly>’ or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0×80131047)
That’s nice, but nothing special, right? The reason is simple and as lot of magic execution errors it is current/working directory related. To fix it, simply explicitly specify path (relative works) to your assembly using StartUpDirectory parameter. And there’s another one gotcha. This parameter work only with :. Let me explain.
migrate.exe /StartUpDirectory C:\Foo\Bar\Baz
Doesn’t work (and no error). But this one.
migrate.exe /StartUpDirectory:C:\Foo\Bar\Baz
Does.
Hope it saves you some time hunting what’s wrong.
Není tomu tak dávno, co jsem slyšel od Entity Framework týmu, že, v té době ještě pouze nad EDMX, nic jako porovnávání a změny struktury databáze oproti modelu nejsou a nebudou. A hle, o několik let později je tu máme. Pokrok nezastavíš.
Entity Framework 4.3 obsahuje velkou novinku v podobě ručních (nebo automatických) migrací struktury databáze, tak aby odpovídala tomu co předpokládá aplikace. A nejen to. Je možné tento proces provádět při startu aplikace, ručně nebo jej oskriptovat… Možnosti jsou bohaté a celý proces je navržen přímočaře.
Pokud máte zájem zjistit co (ne)můžete s migracemi provádět, úterý 17.4. přijďte do “akvárka” v Microsoftu (Praha).
Materiály ke stažení.
In last few days I’ve seen couple of pieces of code with “executing method every x seconds”. And a lot of bad. Not buggy, but superfluously expensive. I’m also here adding a simple loop to run just 10 times.
The first bad one is simply using Thread and Sleep method.
void BadOne1()
{
Thread t = new Thread(o =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("BadOne1");
Thread.Sleep(1000);
}
});
t.Start(null);
}
Problem is the Thread object is very expensive and it’s used only fraction of time. The rest is blocked. Simply wasted resources.
I’ve also seen slightly better version.
void BadOne2()
{
ThreadPool.QueueUserWorkItem(o =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("BadOne2");
Thread.Sleep(1000);
}
});
}
This is really just a little bit better. ThreadPool thread is used, but again, the thread is doing nothing a lot of time. Again wasted resources.
Better approach is to use Timer. This way you’re not wasting resources by abusing threads. The callback from Timer is executed when the interval is elapsed (on ThreadPool thread). Rest of the time it’s just sits there waiting for next tick.
void GoodOne1()
{
int i = 0;
Timer t = null;
t = new Timer(o =>
{
Console.WriteLine("GoodOne1");
if (Interlocked.Increment(ref i) == 10)
{
// could tick, still
t.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
t.Dispose(); // or somewhere else
}
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
}
Here I’d like to point to my older post about keeping the reference to Timer.
And also one question that might come. The Timer ticks every interval no matter how long executing the callback took. That might not be what you want. You may want to execute the method with xx seconds delay between (previous examples), not execute the method every xx second (this example). The solution is pretty easy. Initially just schedule one tick and then reschedule it for next interval.
void GoodOne2()
{
int i = 0;
Timer t = null;
t = new Timer(o =>
{
Console.WriteLine("GoodOne2");
if (Interlocked.Increment(ref i) == 10)
{
// could tick, still
t.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
t.Dispose(); // or somewhere else
}
else
{
t.Change(TimeSpan.FromSeconds(1), Timeout.InfiniteTimeSpan);
}
}, null, TimeSpan.Zero, Timeout.InfiniteTimeSpan);
}
All these are kinda low level. But you can use Reactive Extensions (Rx) to write it in more succinct way, but internally the core idea is same as with Timer.
void GoodOne3()
{
IDisposable obs = null;
obs = Observable
.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1))
.Take(10)
.Subscribe(_ =>
{
Console.WriteLine("GoodOne3");
}, () => obs.Dispose() /* or somewhere else */);
}
No matter what approach you’ll use, please don’t (ab)use threads (manually created or ThreadPool ones). Threads are small little nice sweet creatures that don’t deserve to be treated like this. And. Don’t forget to cleanup resources (i.e. Timer is IDisposable).
I was recently in a talk related to Firebird and I found, that people are not aware of these two constructs. Either they don’t know both or don’t know they differ. These statements are doing similar stuff, but the evil is in details.
So what’s the big deal? Both are kind of “updating” the procedure (or other object types). But the first one will first drop the procedure and then create it back again (yes, dependencies may break that). On the other hand, the another is creating the procedure if it doesn’t exist yet or altering it otherwise. Dependencies aside, what else might be “attached” to procedure? Yes, it’s i.e. access rights (grants). The former one will not keep these. You’re responsible to granting access to it again. The other one will, it’s just alter of procedure definition.
If not used carefully, you can easily break the database. Either one isn’t correct in all cases. Always use what’s appropriate for your scenario.
I letos se koná Gopas TechEd a i letos si budete moci přijít prohlédnout jednoho podivného vývojáře.
Pokud čtete můj blog alespoň více než jednou ročně, víte co mě zajímá. Takže přednášky nebudou o ničem nečekaném.
Zjednodušeně řečeno půjde o Entity Frameworku a async/await oboje o novinkách v .NET 4.5, C# 5 a Visual Studio 11. Anotace (jak já je nesnáším psát):
Entity Framework se stalé vyvíjí podobně jako např. ASP.NET. Možná ne tak virálně jako ASP.NET, nicméně novinek rozhodne není málo. Kromě “povrchu” se kterým každý vývojář pracuje se mění i jádro a rozšiřují se možnosti mapování a využití. V přednášce se podíváme jak na jádro, tj. na novou core funkcionalitu, tak i na novinky “na povrchu”, které se snaží interakci pro vývojáře zpříjemnit.
V posledních letech lze vysledovat dva trendy. Více a více vícejádrových procesorů (nebo více procesorů obecně) a přesun dat do “cloudu”. Především tyto změny staví vývojáře dneška před nové úkoly jak se vypořádat s tímto prostředím, které je pro programovaní odlišné od toho co běžně používáme. Bez ohledu na to jestli jde o desktop, web nebo serverové aplikace. C# nezůstává pozadu a snaží se vývojářům nabídnout nástroje a jazykové konstrukty, které tuto prací zjednoduší. A nejen to…
Detaily a přesný program klasicky na webu.
Yesterday I released ADO.NET provider for Firebird version 2.7.5 and there’s one feature I’d like to blog about. As you might know Firebird has a pretty old limitation on “size” of query. It’s both the string itself, but also the column datatypes and parameters used. No need to dive to details, because I’ll only talk about the first item.
When you’re using Entity Framework (or any other ORM) the query is generated by machine. And the machine (or maybe better to say algorithm) needs to be sure, that in every case the query is correct. That’s the reason why you see a lot braces even if it’s not needed in your case. A lot of table aliases, escaping, quoting and so on. It’s not a simple task. But all these extra characters are making the query bigger. Consider that the the generated query isn’t always the shortest (you could write it shorter because either you have some out-of-band knowledge about you database or simply because there’s room for improvement) and all this “character noise” and you might hit the query length limit.
In the above mentioned version I made some improvements to table aliases. Instead of using full names from Entity Framework, I’m trying to use one character names (or +1, +2, +3, … if I run out of 1, 2, 3, … character names). So instead of (example)
select Extent1.Foo, Extent1.Bar, Extent2.Baz from SomeTable as Extent1 join AnotherTable as Extent2 ...
you’ll get
select A.Foo, A.Bar, B.Baz from SomeTable as A join AnotherTable as B ...
Nothing super-cool, but because somebody suggested this in tracker, it’s there. On the other hand to be honest I’ve never hit the query length limit myself. Maybe I’m lucky, maybe I’m writing too simple queries. But still, shorter query means also less data to be transfered. Hope to help to use Entity Framework and Firebird for big stuff.
The 2.7.5 version of ADO.NET provider for Firebird is ready for download. This version contains mainly bug fixes (some pretty nasty) resulting in stability improvements.
You can check the tracker for more details about this release and of course download it from website or NuGet.
Enjoy!
Almost four years ago I wrote an article Load with filtering or limiting. You might want to do same stuff with Include method. It’s not directly supported in this method but you can do it with anonymous object easily. There’s only one catch, it’s the anonymous object. That means, if you need the entities you need to manually select these out on IEnumerable<T> (doing it on query isn’t going to work because Entity Framework will (correctly) figure out you’re not using the pieces of anonymous object and will change the generated query appropriately).
Small example:
context.EntitySet
.Select(x => new { Entity = x, Related = x.Related.OrderBy(y => y.FooBar).Take(6) })
.AsEnumerable()
.Select(x => x.Entity)
.ToArray();
Nothing fancy. But could it be wrapped inside method so you don’t have to type it over and over again. In comments of above mentioned post same question was raised. Well if I can write it manually, why it shouldn’t be possible to extract it into method, right? Don’t know whether this method has any real usage, but it was a nice exercise.
public static IEnumerable<TMain> Include2<TMain, TOther>(this IQueryable<TMain> source, Expression<Func<TMain, IEnumerable<TOther>>> path)
where TMain : class
{
TMain main = default(TMain);
var dummy = new { Main = main, Included = Enumerable.Empty<TOther>() };
Expression<Func<TMain, object>> exampleExpression = x => new
{
Main = x,
Included = Enumerable.Empty<TOther>()
};
PropertyInfo mainProperty = dummy.GetType().GetProperty("Main");
ParameterExpression accessParam = Expression.Parameter(dummy.GetType(), "x");
Delegate mainBack = Expression.Lambda(Expression.MakeMemberAccess(accessParam, mainProperty), accessParam).Compile();
NewExpression body = (exampleExpression.Body as NewExpression);
Type anonymousType = body.Type;
var parametersMap = exampleExpression.Parameters.Select((f, i) => new { f, s = path.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
Expression reboundBody = ParameterRebinder.ReplaceParameters(parametersMap, path.Body);
NewExpression newExpression = body.Update(new[] { body.Arguments[0], reboundBody });
LambdaExpression finalLambda = Expression.Lambda(newExpression, exampleExpression.Parameters);
MethodInfo miA = typeof(Queryable).GetMethods()
.Where(m => m.Name == "Select")
.Where(m => m.GetParameters()[1].ParameterType.GetGenericArguments()[0].GetGenericArguments().Count() == 2)
.First();
MethodInfo miB = typeof(Enumerable).GetMethods()
.Where(m => m.Name == "Select")
.Where(m => m.GetParameters()[1].ParameterType.GetGenericArguments().Count() == 2)
.First();
MethodInfo selectAMethod = miA.MakeGenericMethod(typeof(TMain), anonymousType);
var dataA = selectAMethod.Invoke(null, new object[] { source, finalLambda });
MethodInfo selectBMethod = miB.MakeGenericMethod(anonymousType, typeof(TMain));
var dataB = selectBMethod.Invoke(null, new object[] { dataA, mainBack });
return dataB as IEnumerable<TMain>;
}
The method is doing little bit of magic with expressions and anonymous type to do what you would normally write by hand. It returns IEnumerable<T> because the object needs to be unwrapped locally so you can’t add additional pieces into query. I’m using ParameterRebinder from Colin Meek’s post to properly rewire parameters. Same functionality can be also found in Mono.Linq.Expressions.
From input parameters types (yeah, the power of static typing [Anders Hejlsberg]) you can see how to use it:
context.EntitySet
.Include2(x => x.Related.OrderBy(y => y.FooBar).Take(6))
.ToArray();
That’s all.
More than a year ago I was blogging about how to map private/protected/… properties in Code First CTP4 for the time being. Well it a long time and a lot of changed. The code there isn’t absolutely up to date with current Entity Framework 4.3.
Although you can go raw and create the expression tree from i.e. string yourself (Mono.Linq.Expressions can be quite handy) it’s not nice and more importantly it’s not strongly typed. If you don’t want to use data annotations or couple your configuration classes into entity classes you’re still not lost. In the above linked post in comments Drew Jones came with a nice idea.
You entity classes will be partial classes and somewhere else you’ll create second part of that class with the expressions needed to express the properties. Let’s take a look at example (you can adjust access modifiers according to your needs and structure).
public partial class FooBar
{
private int ID { get; set; }
private string Something { get; set; }
}
public partial class FooBar
{
public class PropertyAccessExpressions
{
public static readonly Expression<Func<FooBar, int>> ID = x => x.ID;
public static readonly Expression<Func<FooBar, string>> Something = x => x.Something;
}
}
And now in mapping you’ll just use the expressions.
.Property(FooBar.PropertyAccessExpressions.ID);
.Property(FooBar.PropertyAccessExpressions.Something);
Nice isn’t it? It’s separated (kind of – you can’t have entity classes in one assembly and the expressions in other) and it’s strongly typed.
OK, following log4net’s versioning scheme in NuGet package wasn’t a good idea. In version 1.2.11 the new keys were used and I used this as a fresh start. I didn’t realized that thanks to semantic versioning everybody will be updated to latest version and dependencies will be broken. My fault.
If you read my previous log4net post there’s a solution with modifying package.config file, but… So to fix it package owners were forced to repack the dependencies to be =. Not good.
So today I pushed version 2.0.0, which is actually 1.2.11 with new keys, and 1.2.11 was removed. So there’s now on NuGet the new major version and dependencies need to be explicitly stated to be compatible with it (again, it’s 1.2.11 with new keys).
Fire is quenched, hopefully.
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.