Quick tip: Optimizing repeating try-catch-finally statement

Lately, I’ve started noticing a pattern in data layer of one of our projects at work. The pattern looks like this:

SqlConnection connection = null;
SqlTransacton transaction = null;
try {
    connection = new SqlConnection(connectionString);
	connection.Open();
	transaction = connection.BeginTransaction("transactionName");
	// execute database queries and do mapping and stuff
}
catch (Exception) {
	if (null != transaction) {
		transaction.Rollback();
	}
	throw;
}
finally {
	if (null != connection) {
		connection.Close();
	}
}

This repeats itself in just about every data layer method. Lines and lines of useless, repeating code for which I am also to take a lot of blame. So I thought: “There must be a better way than this.”

And there is. I created this method in data layer base class:

public T ExecuteDbCommand<T>(string connectionString, Func<SqlConnection, SqlTransaction, T> action)
{
	SqlConnection connection = null;
	SqlTransaction transaction = null;
	try
	{
		connection = new SqlConnection(connectionString); 
		connection.Open(); 
		transaction = connection.BeginTransaction("transactionName");
		return action(connection, transaction);
	}
	catch (Exception)
	{
		if (null != transaction)
		{
			transaction.Rollback();
		}
		throw;
	}
	finally
	{
		if (null != connection)
		{
			connection.Close();
		}
	}
}

This enables me to now change every data layer method to look like this:

return ExecuteDbCommand<ReturnClass>((connection, transaction) =>
{
	var command = connection.CreateCommand();
	command.Transaction = transaction;
	// do database stuff and port result to ReturnClass
	// return ported result
	// commit transaction if needed (on update or insert statement)
});

This solution has a small issue though. If you are doing insert or update, you might not want to return anything. As you cannot return void, just define returning type to be object and return null. I am prepared to live with this.

 

Web developer: Why 2017 feels exactly like 1997?

I don’t know how many of you, dear readers, remember still how it was like being a web developer in late 90s? You know, the time when not every kid knew how to do web-sites. The time of Geocities, Angelfire and Lycos. The time without Google (well, nearly). The time before cross-browser javascript frameworks and no real support for CSS2. These were the times when 5% of your work presented doing the actual web site and 95% of time was spent on tweaking HTML, CSS and JavaScript to actually work in Netscape 4 and IE 5. And in the end, you somehow always ended doing layout with tables in tables in tables… Yeah. You didn’t want to be THAT guy.

But, with web becoming “the thing” and web sites started to blossom, we got Netscape …uhm… 4 and IE6 and CSS2 support improved (yeah, right) and first semi-useful cross-browser library came to life. It was called cross-browser and surprisingly enough it still online. As funny as it looks today, this was the first library where you didn’t have to pay attention to browser specifics. It gave us at least a glimmer of hope that future is going to be better and bright…

Fast-forward 20 years. Internet Explorer and Netscape are a thing of the past. Chrome, Firefox, Edge and Safari browsers are now in. We have full CSS2 support (well, very nearly) and so many cross-browser javascript libraries that we can’t even name them. Yet, working on my side project TimeLoggerLive, I started to wonder. Is it really that different? I mean, sure, new technologies are out (HTML5, CSS3, Angluar7000 etc.), but has things actually changed for web developers?

CSS3 initial release was in 1996 and HTML5 standard was in preparation since late 2000s. Yet, all these new browsers that we switched to because of promised support for “the latest and greatest” standards still don’t support either in full. Worse even. Like back in 1990s, each and every browser implements the standard differently. You can imagine the confusion.

In case of TimeLoggerLive, my kryptonite is a property contenteditable. The property’s functionality is awesome. By setting it’s value to true, you are supposed to be able to edit content of any HTML tag, provided the property is set on that tag. Handy. Except, it does not work on all tags in IE and Edge browsers, Firefox has some strange behavior, if you use it on empty cell and Chrome, which offers the best implementation of it, for some odd reason, distorts column width.

I checked one of my favourite pages CanIUse.com and it is marked as full support across all browsers, but Opera mini. However, there is a “known issues” section, where it is explained that IE browser does not support contenteditable property in following tags: TABLE, COL, COLGROUP, TBODY, TD, TFOOT, TH, THEAD, and TR. To avoid this, one needs to implement a DIV tag into each table cell. Groovy. Except, when you implement DIV tag, suddenly all browsers start showing border around editable content, which leads to more nasty CSS hacks.

Yes. It feels exactly as 1997.

Quick tip: Setting Oracle client collation

This week one of our clients experienced an interesting problem. Data obtained from ORACLE database did not display unicode characters. They were either replaced by ‘?’ or some other character.

This happens for one of two reasons (or in worst case scneario both). Either your database has wrong collation or your ORACLE client does. The former is a bit difficult to fix, as you will need to change database collation and existing data. The later is a bit easier. Here is how you do it:

ORACLE client 8.x

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\ORACLE]
"NLS_LANG"="SLOVENIAN_SLOVENIA.EE8MSWIN1250"

ORACLE client 11.x

[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_OraClient11g_home1]
"NLS_LANG"="SLOVENIAN_SLOVENIA.EE8MSWIN1250"

I had to set Slovenian WIN1250 ecnoding and this is what sample does. More languages and options can be found in ORACLE documentation here and here.

Failed to load resources from file. Please check setup

Not so long ago an application written in .NET 1.1 started to pop this error up and about. Funniest thing though, only Windows 10 clients with Creators update installed were affected. Now, we could argue, why there is still an application written in .NET 1.1 and running, but that could be a lengthy debate in which I really don’t want to go into right now. Or ever.

Anyway. The error, as descriptive that it is, means only one thing: somewhere in your code, there is a StackOverflowException. In case you are wondering, no, event logger won’t detect a thing. After much trial and error, I have narrowed the problem down to this chunk of code:

public object GetValue(string someParam) {
    try {
        return GetValueEx(someParam).ToString();
    }
    catch (Exception ex) {
        return null;
    }
}

Method GetValueEx returns a response of type object. In this particular case, it should have been a string, but as there are no hits in the database, it returns null. So, basically, the line 3 of method GetValue should have thrown a NullReferenceException, which catch statement should have caught. Except it doesn’t.

I don’t have enough information to explain all details, but on Windows 10 Creators update line 3 throws StackOverflowException, which is for some odd reason not handled by try-catch block. And this causes “Failed to load resources from file. Please check setup” error.

Knowing this, I modified my code to:

public object GetValue(string someParam) {
    try {
        object result = GetValueEx(someParam);
        return (null == result) ? result : result.ToString();
    }
    catch (Exception ex) {
        return null;
    }
}

Needless to say, the fix works without a glitch. Being a good Samaritan, I have also posted the answer to this StackOverflow question.

TimeLoggerLive early-bird pre-order

There has been a lot said and written about how people should log time they spend on tasks. Some claim you should log only the time you actually worked on a task, some that you should log all time, including intrusions, lunch breaks etc. And from the project standpoint, I agree with later option. However, when it is you, who needs to track where your time went, you are faced up with a difficult task.

I guess you could use time logging features of your project management tool, but that is usually tedious and time consuming. Not to mention unpractical.

You could use one of the thousand apps that are out there, that require you to just press start button when you start timing the task, and stop button, when you stop doing it. But these usually come up with results in form of 2 hours and 33 minutes when you really wanted to log 2 hours and 30 minutes. This leads to editing and even more time lost. Also, all applications I have seen and tested, require you to enter tasks first, which is in my books double work. Specially when we use project management tool.

Personally, I use pen and paper. Archaic and non-environment friendly. It works, but it has a serious issue. In my line of work, I do a lot of context switching and at the end of the day, I spend some time just summing up time spent for tasks. It is not particularly time consuming, but it is tedious and error prone.

So, I have this idea of a time logging web application, that would be as simple as logging time on paper. Just start time, end time and description of your work. Description would have type-ahead of already entered descriptions, enabling easier summation of your daily time consumption. And you would be able to get nice condensed report for each day, week and month.

In future editions, integration with popular project management tools like JIRA, Trello, Trac is imminent. But for now, I aim for simple and get things done principle.

With all said and written, today, I can proudly announce TimeLoggerLive early-bird pre-order is available. As an early bird, you are entitled to:

  • minimum 30% lower subscription price for first 3 years (1st year at 80% off),
  • access to all development and future versions of the application,
  • hassle-free, any-time money back guarantee,
  • personalized and friendly support.

 

And the best part is, even if you decide to leave TimeLoggerLive, we will keep your data (unless otherwise requested) in read-only form, available to you online, if you ever need it again.

For companies, the product will also feature creation of teams and overview of their logged activities, bundling tasks into meaningful projects and user management.

TimeLoggerLive is currently in development and is expected to go live November 1st, 2017. I expect first beta to be done by August 1st, 2017 at the latest. By registering today, you will help TimeLoggerLive become awesome. And personally, I look forward to have you as a customer.

Make it pink

There is always interesting time, when new project is on the board. This time it was a mobile application and me and my coworkers were tossing ideas left and right. So a discussion got a turn to what color scheme should user interface use. Mostly out of fun (and some out of envy), I claimed: “Pink. It should be pink.”

Back then, I thought nothing of it. The statement was meant as a joke and the color was picked based on what would be most inappropriate for this project. Coworkers took it as a joke as well. As a (more and more annoying) joke I threw at them every time, the discussion turned to UI for some reason. But, as things go, the project was ready to be presented to prospective customers. Naturally and understandably, sales pushed for customer company brand color scheme for each demo. Although coworkers did a wonderful job on the project, it still took some fiddly last-minute work to sort the new color scheme and base it on a theme.

At that point, I started figuring out, that as dumb, as my “idea” was, it would be beneficial to the project, if the UI really did use pink color. Reasoning is pretty trivial. When creating a project from scratch, there is usually so much work with basic mechanics, feature implementation and testing, that UI implementation is almost an afterthought. Hence, to solve glitches as quickly as possible, we, developers, tend to use line of least possible resistance and do something stupid like specify color or font inline. I admit, I did it numerous times on other projects. I know it is wrong. Heck, I knew it back then. But I just justified it with the fact that there just wasn’t enough time.

Now, if I made one of those project pink, I am pretty sure, I would do everything in my power to not use cheap corner cutting techniques and to make darn sure that I could swap color scheme faster than you can say cookie with mouth full of, well, cookies. This applies to all other areas as well. Want to make sure that you do not have static text in your project? Use upper case text for everything. Want to write data somewhere? Store it to file on floppy instead.

Thus, the next time you are about to do something, make it pink!

 

 

Minimal Web API

For a task at work, I needed a mock WebApi for mimicking behavior of 3rd party API, that is not accessible from my machine. Sure enough I proceeded using line of least possible resistance and selected ASP.NET MVC Web Application template and WebAPI and ended up with bloated project that scared the life out of me when I just looked at it. Seriously, Microsoft, you couldn’t do a simpler template? I am pretty sure, that having all sorts MVC thingies installed helps, although, I am not completely sold on EntityFramework that sneaks in as well. But I digress.

Without further ado, I present you minimal WebAPI. A project that contains only what it needs to, to behave as WebAPI and nothing more. Below, I will lead you step by step through the process of creating one yourself, but you can also clone a repository from GitHub. Be careful though, as solution only supports .NET 4.6.x.
[Read the rest of this entry…]

Custom software – Introduction

Custom software is software that is usually done for one client, one environment and limited user base. It’s specific use case means, it won’t be sold more than once, which translates to high enough price to cover development costs. And then some.

So why do companies decide to order and pay for custom software over and over again? Custom software has one big advantage over regular off-the-shelf one. It is adaptable to whims and fancies of a customer. Hence, the name custom. Now, here is a public secret. Companies, specially wealthy ones, dig adaptable. You see, where smaller companies don’t have (many) defined processes, big companies are set on tightly defined processes, usually certified by ISO 9001 or similar standard. Off-the-shelf solution is just not an option, as changing a process would cost a lot of money, time and resources.

As a developer with a career in building custom applications, I have done and seen my share of mistakes and fallen into several pitfalls. This series is here to help you (and also future me) avoid them as best as possible.

In part I of the series, I will be blabbering about project architecture and discover last year snow in monolith vs microservices debate. We will cover how to start, how to continue and how to take care of the accumulated tech debt.

Part II will be focused entirely on how to integrate your software with third party software. There is always something to integrate with in custom software business and it is better to be prepared.

Part III will touch the topic of what happens when your custom software gets resold to another and another and another customer. Main focus will be on how to handle new requirements and hopefully not mess up existing and future deployments.

Last but not least, a disclaimer. This series is made of findings I gathered in my career of building custom software. As many things in software, it definitely does not present the only right way. In some cases you might also find it completely wrong. Good. Let me know.

API pr0n

I doubt that anyone serious about tech could avoid hearing at least a little bit about NPM “disaster” in recent weeks. Some say, it is developers ego, that caused entire ecosystem to crash down. Others blame NPM for caving in to capital instead of open source. But the problem lies elsewhere.

In recent years, a phenomena started to occur in software development cycles, that I like to call API porn. It is caused by a fact that services, such as npm, bower, nuget and such, make it as easy to add APIs to projects as it is snapping your fingers. Don’t get me wrong, I love code reuse, but this has crossed every possible edge of reason.

Let me explain why. One of most challenging and difficult things for developer to do is an API. Why? It needs to be open just enough that another developer can use it, but not in irregular way. It needs to capture every single edge case, just for the fact that a memory leak does not make you reboot your app every 15 minutes. Or, that your application does not crash, when your users are entering unicode characters. Talking from experience, this takes a lot of thinking, tweaking, debugging and testing.

In that retrospect, there are more than 500.000 APIs on NuGet alone and I am guessing NPM can beat that without a sweat. Half a million APIs.  Have developers became so much better at writing APIs or is it that we publish just about everything nowadays? As much as I would like to believe it is former, quantity wins.

Back to NPMs little problem. The package that did most “damage” was left-pad package. Let that sink in for a moment or two. Left-pad package is nothing fancy (no offense to the author). It is a simple JavaScript function that adds custom padding in front of a given string.  Yes, that is correct. We have come up so far, that people actually think, it is better to include 3rd party left padding extension than it is to write your own. Specially, when it will take about 35 minutes, inlcuding a lunch break. And this same people are now blaming developer and NPM when their projects don’t compile/deploy? Somehow reminds me of people that copy and paste first StackOverflow solution (without reading) and then complain it does not work.

This must stop. Now. I know, that package managers open entire world of possibilities, but “with great power comes great responsibility” and as it was obvious from NPM crash, most developers just cannot be trusted with it.

Windows 10 changes Slovenian locale (at last)

If you are a proud developer of software sold internationally or in Slovenia, you might pay a little attention to this. It has not been noted anywhere of importance and I discovered it by chance when one of the programs I am working on crashed.

Versions older than Windows 10 had the following Slovenian date and time format: “d.MM.yyyy”. As far as this can be understood from computing point of view, it is in conflict with Slovenian language rules.

So, in Windows 10, someone made a bold move and fixed said format to: “d. MM. yyyy”. Finally, one might say. Except, every possible application, relying on previous false date format, will now crash. This is specially true in C++ Ole objects, where calling COleDateTime::ParseDateTime with OS set language now fails, if string representation of date is in “d.MM.yyyy” format and OS primary language is Slovenian. Let me state here, that .NET handles date formatting without problems.

If you are targeting Windows 10 clients only, this is not a problem, per-se. You just need to make sure that there are spaces after each dot in date time string representation. If you are targeting multiple OS versions, you are cooked as older Windows, do not recognize new date time format.

I am still searching for least painful workaround, that would work on any Windows OS client. If anyone has an idea, you are more than welcome to share.