Uncategorized


10
Mar 11

subversion-for-visual-studio-developers

Most Visual Studio Developers will be comfortable using Either VSS (Visual Source Safe) or TFS (Team Foundation Server) but as Subversion continues to sement its position as the most popular version control system, more and more Microsoft developers are starting to look at Subversion.

 


5
Mar 10

Single instance .NET executables

It’s not a common problem, which probably explains why there isn’t much information out there on the topic, but how do you make it so that your executable can only have a single running instance? That is, if you user tries to launch the same programme twice, the second instance silently closes down.

There aren’t many obvious practical uses for this, but they are out there and they do exist. We’ve come across the requirement a few times as consultants to enterprise organisations — for example, a utility that gathers information on a wire that must only be running a single instance — and it took us a while before we settled on the code to solve it.

We tried various methods — broadcasting on sockets, named pipes, magic ‘lock’ files (this is the simplest solution, and the one that a lot of software uses — it’s effectively a file with a non-sharable lock — if you can’t lock the file, the app is already running). We finally came across the .NET Mutex class, and that fit our needs beautifully. You define a string which becomes your identifier, and then create a Mutex for that identifier. Mutex stands for Mutually Exclusive. If somebody else has Mutex’ed that identified, you’ll get a fail. Here’s the code to add to your static main method:

static void main(string[] args)
{
  string identifier = "MyApplicationIdentifier";
  bool ok;

  Mutex mutex = new Mutex(true, identifier, out ok);

  if (!ok)
  {
    // Message box provides visual feedback for this demo
    MessageBox.Show("This application is already running");
    return;
  }
  else
  {
    // This becomes your application's entry point
  }

  // Don't allow the mutex to be garbage collected when it falls out of scope.
  GC.KeepAlive(mutex);
}

25
Feb 10

Built-in .NET Utility Classes for encoding/decoding strings

Every now and again, you’ll will come across a string that has been encoded (or possibly you need to encode a string) and you’ll wonder whether there is a class in .NET that can help. The answer is probably yes, but they are tucked away and difficult to find. In this article I’ll show you how to easily encode/decode your strings for the three most common forms of encoding.

HTML encoding

This is also used in XML data, to quote ampersands and other characters. For example, the string “Ben & Jerry’s” will be encoded as “Ben & Jerry's”.

To escape and unescape these strings, use System.Web.HttpUtility.HtmlEncode() and System.Web.HttpUtility.HtmlDecode().

URL Encoding

URL encoded characters are the %-number elements you occasionally see in URLs. For example, “Ben & Jerry’s” this time will become “Ben+%26+Jerry’s”. Note that spaces can be represented as “+” or as “%20″. The encode method will always use +, but the Decode method handles both.

To escape and unescape these strings, use System.Web.HttpUtility.URLEncode() and System.Web.HttpUtility.URLDecode().

Note that both of the above examples require your project to have a reference to System.Web.

Escaped Strings

These characters are the \r\n and \t’s that you use to specify special characters in strings. Though it’s rare, sometimes you’ll come across these characters in plain text and need to convert them to the actual character codes (or vice versa).

To handle these strings correctly, use the frustratingly obscure Regex.Escape and Regex.Unescape methods. Escape will turn control characters in to their plain-text escaped representation (e.g., a new line will become \r\n) and Unescape will turn them back again.


12
Jan 10

An adaptation of seed-fu, to make seeds.rb a bit nicer

The db:seed rake task in Rails is a nice addition and we use it a lot. The trouble is, you end up writing a lot of redundant code to check if records exist and stuff like that. Not very DRY, not very Rails.

Seed-Fu is a nice plugin that works very well, but it replaces the new db:seed rake task, and this solution is far more light-weight. You add another file to your db folder, seeds-helper.rb, and just require it at the top of seeds.rb.

Here’s the contents of seeds-helper.rb:

class SeedsHelper
  def self.seed(model_class, *keys, &block)
    s = SeedsHelper.new(model_class)
    s.parse_keys(*keys)
    yield s
    s.plant
  end

  def initialize(model_class)
    @model_class = model_class
    @keys = []
    @data = {}
  end

  def parse_keys(*keys)
    keys = [:id] if keys.empty?
    keys.each do |key|
      raise "'#{key}' is not defined in #{@model_class}" unless @model_class.column_names.include?(key.to_s)
      @keys << key.to_sym
    end
  end

  def plant
    r = find_record
    @data.each do |key, value|
      r.send("#{key}=", value)
    end
    raise "Error Seeding: #{r.inspect}" unless r.save(false)
    puts r.inspect
    return r
  end

  def find_record
    results = @model_class.find(:all, :conditions => conditions_hash)
    if results.any?
      return results.first
    else
      return @model_class.new
    end
  end

  def conditions_hash
    @keys.inject({}) {|a, c| a[c] = @data[c]; a }
  end

  def method_missing(method_name, *args)
    if args.size == 1 and (match = method_name.to_s.match(/(.*)=$/))
      @data[match[1].to_sym] = args[0]
    else
      super
    end
  end
end

class ActiveRecord::Base
  def self.seed(*keys, &block)
    SeedsHelper.seed(self, *keys, &block)
  end
end

You can now use the seed-fu magic in seeds.rb:

require 'db/seeds_helper.rb'

Account.seed(:username) do |t|
  t.username = "adrian.oconnor"
  t.name = "Adrian O'Connor"
end

The active record model object is extended with a seed method. This takes a list of symbols that act as the key — if the values passed in match the keys in an existing record, it’ll replace it, otherwise it’ll create a new record. Pretty clever stuff.

If you like this, you should definitely check the full seed-fu plugin. You can find it here: http://github.com/mbleigh/seed-fu. I just like having a single additional file that is only used by seeds.rb.


28
Sep 09

Tidy up your Java logging

The logging libraries provided with Java 5 and above are pretty good, except they produce output that is almost unreadable. For example, consider the simplest example:

Logger logger = Logger.getLogger("PushServer");

logger.log(Level.SEVERE, "This is a sample message");

That produces the following log entry, on your screen and/or in a file:

Sep 28, 2009 9:30:48 PM javaloggersample.Main main
SEVERE: This is a sample message

Individually, that’s OK, but 20 messages? Messy. 1000 messages? Pretty nasty. 100 threads each generating a stream of FINE messages? Yikes.

We recently wrote a Java server application that was massively threaded, and because of the nature of the systems we were communicating with, we needed solid logging output that we could easily scan to get an idea of the health of the software. The default logging format was not it.

While you can get some degree of flexibility by changing configuration options, we found that the best solution, for us, was writing a new Formatter that the logger client could use to generate output. Here’s the above sample, using our formatter:

28/09/2009 21:41:44 SEVERE: This is a sample message

That is vastly more readable when the log file starts filling up, because each message is on a single line and each component of the message is formatted in columns. Here’s our logger class — you should add this class to your own project:

public class SingleLineFormatter extends Formatter
{
    public SingleLineFormatter()
    {
    }

    private SimpleDateFormat dateFormat;

    static final String lineSep = System.getProperty("line.separator");

    public String format(LogRecord record)
    {
        StringBuilder buf = new StringBuilder(180);

        if (dateFormat == null)
            dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

        buf.append(dateFormat.format(new Date(record.getMillis())));
        buf.append(' ');
        buf.append(record.getLevel());
        buf.append(": ");
        buf.append(formatMessage(record));
        buf.append(lineSep);

        Throwable throwable = record.getThrown();

        if (throwable != null) {
            StringWriter sink = new StringWriter();
            throwable.printStackTrace(new PrintWriter(sink, true));
            buf.append(sink.toString());
        }

        return buf.toString();
    }
}

When you create your logger, you need to tell it not to use the default formatter, and to use this formatter instead. Since the original Apache Log4j, loggers have been hierarchical — you can set parent/child relationships between logger objects and the child will do as its parent does, plus any configuration of its own. Therefore, to disable the default logger we set UseParentHandler to false. Then, we create a handler and initialize it with our formatter:

Logger logger = Logger.getLogger("PushServer");

logger.setUseParentHandlers(false);

ConsoleHandler h = new ConsoleHandler();
h.setFormatter(new SingleLineFormatter());
h.setLevel(Level.ALL);
logger.addHandler(h);

logger.log(Level.SEVERE, "This is a sample message");

Hopefully this will be useful to somebody. We’re trying out something different here — posting coding tips to the CodeSpaces blog (rather than our company blog — Component Workshop). Also, we don’t often post Java tips, so on both of these points your feedback is most welcomed! Also, let us know if there are any topics you’d like us to cover — I think the next post might be about Middleware-Oriented-Messaging in .NET. — Adrian

This advice and any code samples are provided as-is, and without any warranty. You are free to use them as you wish. If you require professional services, or support on your own projects, get in touch with us and we’ll see if we can help. Note that we are UK based.