Archive for software development

Easy .Net Transaction Management with Transaction Scope

// April 3rd, 2009 // No Comments » // .net, SQL Server, ado.net, software development

Transactions are a common technique to ensure consistency of the data when using database applicationsfor example with Sql Server. The System.Transactions namespace in the .Net framework simplifies Transaction Managements considerably.

This time we are going to talk about TransactionScope, which is part of the System.Transactions assembly. Using TransactionScope to manage transactions is fairly simple, yet powerful. Let’s look at an simple example using ADO:

TransactionScope tranScope = new TransactionScope();

SqlConnection connection = new SqlConnection(connectionSettigs);
SqlCommand cmd = new SqlCommand(query, connection);

connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

transScope.Complete();

In the example we first initialized the TransactionScope object, then we initialized the connection (very important point, we will talk about it later), execute the command, etc. And then at the end we called the method Complete for the transaction scope object.

When the transaction scope object is initialized, the transaction is effectively created and all commands after that will be protected by the transaction. After the commands are executed, then we decide to either commit the transaction or rollback. Now, for the transaction scope, the method Complete effectively commits the transaction to the database, when Dispose executes the rollback.

For some developers, is quite confusing since most developers are used to:

// Handling the transactions explicitly.
SqlConnection connection = new SqlConnection(connectionSettigs);
SqlTransaction trans = connection.BeginTransaction();

SqlCommand cmd = new SqlCommand(query, connection);
cmd.Transaction = trans;

connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

connection.Commit();

Not only is the TransactionScope idiom different but also the Commit and Rollback method names are also different. The reason why the names are also different is because 1) The TransactionScope object is not a transaction per se, it is more of a transaction handler and 2) Because TransactionScope follows the Dispose pattern (just like SqlConnection). Following the Dispose pattern to implement the TransactionScope makes it easy to do this:

// Handling the transactions implicitly.
using(TransactionScope tranScope = new TransactionScope()) {

	SqlConnection connection = new SqlConnection(connectionSettigs);
	SqlCommand cmd = new SqlCommand(query, connection);

	connection.Open();
	int id = cmd.ExecuteScalar();
	connection.Close();

	// If success commit
	if(id > 0) {
		transScope.Complete();
	}
}

The example displayed above shows how to handle implicit transactions using the ‘using‘ keyword. When applying the ‘using‘ idiom on an object which implements the Dispose pattern, the ‘Dispose‘ method of such object will be called when the using block ends.

What the transaction scope is doing is registering the transaction in the connection contained in the transaction scope block. Making it easy to handle transactions in .Net code.

In the case of the example, if the transaction scope is not committed before the block ends, it is effectively rolled back automatically, since the using idiom calls the Dispose method of the selected object. This makes the use of Transactions extremely easy to read and maintain.

Now what happens if there is an exception inside of the TransactionScope block ? Well, the object’s Dispose method is called, which automatically rolls back the transaction.

Now it is very important, while using TransactionScope, that the connection is opened inside of the transaction scope block, otherwise the transaction won’t be registered in the connection.

SqlConnection connection = new SqlConnection(connectionSettigs);

// This will not work. The transaction will not be registered in the connection,
// and it will deadlock your application.
connection.Open();

// Handling the transactions implicitly.
using(TransactionScope tranScope = new TransactionScope()) {

	SqlCommand cmd = new SqlCommand(query, connection);

	int id = cmd.ExecuteScalar();

	// If success commit
	if(id > 0) {
		transScope.Complete();
	}
}

connection.Close();

The above example will not work. What happens is that when the Connection is opened inside the TransactionScope block, the transaction is registered in the connection which means that any command for that connection will be in the transaction until the connection is closed.

Be very careful to initialize the connection inside the transaction scope block, otherwise the transaction won’t register itself in the connection, and your data won’t be protected by the transaction. In some cases, any command inside of the transaction scope block, for which the connection is opened before the transaction block will result in a dead lock. The code above serves as an example of this case.

More information:
MSDN:Transaction Scope Class.

MSDN:Implementing an Implicit Transaction using Transaction Scope

Post to Twitter Tweet This Post

Fowler on Oslo

// November 10th, 2008 // No Comments » // Architecture, Tools, microsoft, software development

I just found this document written by Martin Fowler on his thoughts on Oslo.

Some comments made by Folwer:

  • Talking about Oslo in general:

“A couple of weeks ago I got an early peek behind the curtain as I, and my language-geek colleague Rebecca Parsons, went through a preview of the PDC coming-out talks with Don Box, Gio Della-Libera and Vijaye Raji. It was a very interesting presentation, enough to convince me that Oslo is a technology to watch.”

  • Talking about M:

“I think I like this. When I first came across it, I rather liked the MPS notion of: “it looks like text, but really it’s a structured editor”. But recently I’ve begun to think that we lose a lot that way, so the Oslo way of working is appealing.”

  • Talking about comparison of Oslo with other tools:

“One particularly interesting point in this comparison is comparing Oslo with Microsoft’s DSL tools. They are different tools with a lot of overlap, which makes you wonder if there’s a place for both them. I’ve heard vague “they fit together” phrases, but am yet to be convinced. It could be one of those situations (common in big companies) where multiple semi-competing projects are developed. Eventually this could lead to one being shelved. But it’s hard to speculate about this as much depends on corporate politics and it’s thus almost impossible to get a straight answer out of anyone (and even if you do, it’s even harder to tell if it is a straight answer).”

“It was only a couple of hours, so I can’t make any far-reaching judgements about Oslo. I can, however, say it looks like some very interesting technology. What I like about it is that it seems to provide a good pathway to using language workbenches. Having Microsoft behind it would be a big deal although we do need to remember that all sorts of things were promised about Longhorn that never came to pass. But all in all I think this is an interesting addition to the Language Workbench scene and a tool that could make DSLs much more prevalent.”

The article is very good. I liked a lot, I think everyone should read it in full.

Post to Twitter Tweet This Post

OpenGL 3.0 Spec Released Today

// August 11th, 2008 // 2 Comments » // OpenGL, directx, linux, software development

I am completely disappointed and utterly depressed. It is sad to see that a very important framework (at least for me) is going to hell. I’m sorry to say that the big problem in the world is not really proprietary software. Something I obviously learned way before, and that is why I left Linux. They all tend to disappoint. Gnome is a perfect example. It sucks, big time. And all of you open source zealots can say whatever you want, but proprietary software is not the problem.

Today, the OpenGL v3.0 spec was released, and it was a complete disappointment (worse than version 2.0). Not even one feature that was promised nearly two years ago is in the spec for version 3.0. The Khronos Group has failed to provide a worthy competitor to DirectX. And, you were right Mr.Stallman, Gates is not the problem, but it isn’t Microsoft or proprietary software. That I’m sure of. DirectX is a really great API, impressively clean and well designed, where OpenGL has been failing since version 2.0 to compete with even a shed of proof of a modern GL API. OpenGL is still poorly organized and it looks a lot more like a bunch stuff thrown under the bed.

While reading through the forums, which I have followed relentlessly, I can only find disappointment spreading through the community. The situation is so serious that people are even thinking on migrating to Vista just to get to work with the latest DirectX version.

I am sorry to say, that while assessing the situation, I am also going to leave OpenGL completly in favor of DirectX. I left Linux a while back because of the same feelings of disappointment, and I guess history repeats itself.

I hope, that with the recent changes in the Emacs maintenance team, the application keeps growing and moving towards the future. I would really feel helplessly depressed if Emacs turned out to be just like Gnome and OpenGL.

Today I mark the death of OpenGL for me, and any hopes of writing Games for Linux. I guess Linux was never meant for me, everything about it keeps disappointing me. (And yes I did see OpenGL as a bridge for me to work in Linux again, I wonder if there are enough bridges for me to keep Linux from drifting farther away from me).

This is indeed a sad, sad day.

Post to Twitter Tweet This Post

New Structum Site!!

// July 24th, 2008 // 2 Comments » // .net, c++, software development, windows

I have finished the first phase of the Structum site, which is the place where all of my projects will end up. I have some projects which have collaborators, but the work is mostly going to be done by myself.

Structum used to be my company when I lived in Mexico, and I left it to get a position in another company. I sold all of my products of the time to the company I moved to.

Now, I have been working on a set of projects which I plan to release through the Structum site and using (again!) the Structum brand.

The first project displayed is the RegEx Compiler. This project was displayed in my blog first, but I have moved it to the Structum Site and released a beta of the new upcoming release. The new features include an improved UI and Regular Expressions testing modules. It is not finished yet, so I don’t recommend it for production environments.

There will be more to come. Stay tuned.

UPDATE: The new site is here: http://www.structum.net

Post to Twitter Tweet This Post

RegEx Pre-Compiler

// February 28th, 2008 // No Comments » // .net, c++, software development

I have silently added a Software tab in this site, which will contain all the applications that I want to release for free to the public. I am still deciding if I’m going to include the source code. I’ll probably will, but for now only binaries will be there.

The first application is the RegexCompiler. This is a powerful tool that makes it easy to build common regular expression into .Net assemblies. Such assemblies can be used to organize and distribute commonly used regular expressions; in some cases, it even improves performance of execution of regular expressions.

This application was built for a very regex intensive application, and I wanted to have such expressions interchangeable using DLLs for my application. In some cases, if the expression is to big, it improves the performance of the regular expression, but this is not always the case.

This is an example of the final usage of the Compiled Expressions:

SelectPattern pattern = new SelectPattern();
bool isMatch = pattern.IsMatch(""select * from table1"");

Patterns are stored in an xml file with extension *.recproj. The application provides an example which is:

< ?xml version="1.0" encoding="utf-8"?>
<recproject name="Structum.Patterns.Data">
  <assemblyfilename>Structum.Patterns.Data</assemblyfilename>
  <namespace>Structum.Patterns.Data</namespace>
  <regex name="SelectPattern">(?ism)"[ t]?.*selectb(?-ism)</regex>
  <regex name="InsertPattern">(?ism)"[ t]?.*insertb(?-ism)</regex>
  <regex name="DeletePattern">(?ism)"[ t]?.*deleteb(?-ism)</regex>
  <regex name="UpdatePattern">(?ism)"[ t]?.*updateb(?-ism)</regex>
</recproject>

The whole file represents an assembly and it is identified by the ‘assemblyfilename’.
Each ‘regex’ tag contains the name of the Class and the actual Regular Expression. In the case of the Select Pattern:

  <regex name="SelectPattern">(?ism)"[ t]?.*selectb(?-ism)</regex>

Which is looking for expressions of the form: “select * from table”. It was used to identify select statements in code.

Also, this is my first application with C++/CLI. I’m a hardcore C++ fan, and I wanted to try the CLI version. While building the application, I was trying to have a more .Net mindset than C++, so that I could really learn the language. I have to say it was a really cool experience. It has been extremely useful for me, I hope it is also helpful for everybody else.

You can download RegEx Compiler in here.

A sample project can be found here.

Post to Twitter Tweet This Post