Categories
.NET

Created small note taking application – introducing OP.Notes

I have spent few days to create a small note taking application as I really needed something more then just text editor (Notepad++ is a fine application) to add notes, have simple TODO lists etc. I've placed the app on Codeplex as other people might find it usefull as well: OP.Notes. Here is a screenshot of how it looks like:

OP.Notes

Categories
.NET Programming

Using System.Text.RegularExpressions.Regex to do search/replace

Note: I have transferred this blog from my old blog site: http://dcarapic.blogspot.com/ so I am reposting most of the stuff from there

Google returns ~21.000.000 results (at the time of this writing) if you do a search for 'regular expressions' so you must be asking yourself why would somebody write something about it? Well sometimes you just need to use regular expressions to do some handy text processing, such as search/replace. I wrote this post just to give you some quick&dirty info on how to use the .NET Regex class to do substitutions.

First of, the simple search and replace. We search for a word and then replace it with another word:

public static void ReplaceSimple()
{
    string example = "I am a man.";
    string replaced = Regex.Replace(example, "man", "woman");
    Console.WriteLine(replaced);
    // Output: I am a woman.
    Console.ReadKey();
}

If you are using Regex for this kind of search/replace, then do yourself a favour and take a look at String.Replace method. Regular expressions get useful when you have some limitations on how you may do search and replace. Lets say that you wish to process some HTML (I am beating a dead cat, but who cares) and you would like to replace all <div> tags with <span> tags. One of the options is to use two replacements, one which replaces <div> with <span> and the other which replaces </div> with </span> (of course we could not just replace "div" with "span" because "div" might appear as a part of a HTML body text). But, doing it that way is not so interesting (and also makes this post pretty useless), so lets do something complex:

public static void ReplaceDiv()
{
    string example = "<div>Becomes span</div>";
    string replaced = Regex.Replace(example, @"<(/{0,1})div>", @"<$1span>");
    Console.WriteLine(replaced);
    // Output: <span>Becomes span</span>
    Console.ReadKey();
}

The secret to doing some complex search/replace in .NET (and I guess in many other regular expression implementations) is to define regular expression 'capture' groups inside the search pattern and then use them inside the replacement pattern. In the code above we are saying "give me all matches that start with <, have 0 or 1 / and end with div>; also group 0 or 1 /; then replace the found matches with <, followed by the first group and then followed by span>. The parenthesis (, ) characters serve as grouping constructs which we are using to 'capture' an appearance of 0 or 1 / character.

Any time that we use the parenthesis we are creating a group 'capture' which can be used in the replacement pattern by using the dollar ($) character. Using parenthesis for capture groups is simple but may lead to regular expression search patterns which are not immediately obvious (as if any useful regular expression patterns are obvious :)). To make it easier you may use named grouping constructs:

public static void ReplaceDivNamedGroup()
{
    string example = "<div>Becomes span</div>";
    string replaced = Regex.Replace(example, @"<(?<slash>/{0,1})div>", @"<${slash}span>");
    Console.WriteLine(replaced);
    // Output: <span>Becomes span</span>
    Console.ReadKey();
}

Naming the grouping is simple, just add ?<name> after the parenthesis start. You may then use the name of that group with syntax ${name} inside the replacement pattern.

As a bizarre fact, you may use the grouping constructs inside the search pattern. Example:

public static void EhThatRegex()
{
    string example = "We are searching for Yoda speak, searching are we";
    var match = Regex.Match(example, @"(\w+)\s+(\w+)\s+.*\2\s+\1");
    Console.WriteLine(match.Success );
    // Output: true
    Console.ReadKey();
}

Here we go, I've posted a non-obvious regular expression. But it can not be helped. The grouping 'capture' can be used inside the search pattern, we just may not use the $1 or ${xxx} but rather \1 and \k<xxx>. Of the top of my head I can not think where such a pattern would be useful but you might.

Here is the explanation of the search: (\w+)\s+(\w+)\s+.*\2\s+\1 search for a sequence of characters ending with space character (\w+)\s+ (basically we are searching for a complete word) and capture it in group 1; search again for another word and capture it in group 2; skip anything until you reach a point where the second word, followed by the first word appears. I am sure that some regular expression guru could use this in some way to check if the sentence is a palindrome, but that is beyond my abilities.

Categories
Programming

Using “hole in the middle” pattern with methods to insure pre and post processing

Note: I have transferred this blog from my old blog site: http://dcarapic.blogspot.com/ so I am reposting most of the stuff from there

Sometimes it is important to do processing before and after executing a piece of code (or a function). This is usually necessary when you have unmanaged components that you wish to use. C# solves this by using the using keyword. Example of this would be the various ASP.NET connections.

var connectionString = GetConnectionString();
using (var adapter = new SqlConnection(connectionString))
{
    // do something
}

While using using is a good solution it does require the programmer to be disciplined and not to forget it. Another drawback of this solution is that requires that you have a component which implements IDisposable and you must always instantiate it in order to use it.
Another possible solution would be to use "hole in the middle pattern" to achieve the similar functionality. In short "hole in the middle" refers to having some sort of activity/processing where a part of processing is provided by an external source and this is exactly what we need.

We need to ensure that we will execute some code before and after the 'main' code gets executed. Here is how we could organize the code so that we ensure that SqlConnection gets properly disposed

public static class ContinuationTest1
{
    public static void ExecuteSql(Action methodToExecute)
    {
        var connectionString = GetConnectionString();
        using (var adapter = new SqlConnection(connectionString))
        {
            methodToExecute(adapter);
        }
    }
}

Using this new method is relatively simple

public void UseContinuationTest1()
{
    ContinuationTest1.ExecuteSql((con) =&gt;
    {
        con.CreateCommand();
        // do something
    });
}

Note that I am using new Lambda style method definitions as it makes this sort of programming style really easy to use. Here is another example of how we could achieve exception wrapping

public static void ExceptionWrap(Action methodToExecute)
{
    try
    {
        methodToExecute();
    }
    catch (Exception ex)
    {
        var exceptionHandler = GetExceptionHandler();
        exceptionHandler.Handle(ex);
    }
}

Using it is, again, simple

public void UseContinuationTest2()
{
    ContinuationTest2.ExceptionWrap(() =&gt;
    {
        // do something that might throw an exception
    });
}

Another advantage that we get from this is that we can hide the creation of parameters that we provide to our "method in the middle". This could be used as (simple) (or with) Dependency Injection mechanism where we want to ensure a consistent way to access components or services in our code. Here is a variant of the first example where we do not provide the SqlConnection but rather an interface (IDbConnection). I have also added a variant where we can ensure that everything is done inside a transaction.

public static class ContinuationTest3
{
    public static void ExecuteSql(Action methodToExecute)
    {
        var connectionString = GetConnectionString();
        using (var adapter = new SqlConnection(connectionString))
        {
            methodToExecute(adapter);
        }
    }
    public static void ExecuteSqlInTransaction(Action methodToExecute)
    {
        using (var ts = new TransactionScope())
        {
            ExecuteWithAdapter(methodToExecute);
            ts.Complete();
        }
    }
}

And using it

public void UseContinuationTest3()
{
    ContinuationTest3.ExecuteSqlInTransaction((con) =&gt;
    {
        con.CreateCommand();
        // do something, transaction will be automaticaly commited
    });
}

While this kind of programming looks great, there are some drawbacks to it if you are using the Lambda style methods to define the "middle method" that will get executed. Drawbacks with Lambdas are: Uglier stack trace - Lambda is just a nicer way to define an inline method. It is still a method and the C# compiler will give it an ugly name Method inside a method - This might be the a subjective issue to some. Wherever you are using this style you will need to have two methods, the outside method and the "middle" method.
Using Lambdas makes the "middle" method look like it is not there, but it still is. Variable in outer scope - Make sure that you understand what happens if you use an outer scope variable inside the lambda method. This is something that is good to know in general 🙂 I hope that you can see that the power that we can get from this style of programming.