Regex hints #1

I love the power of regular expressions to do highly repetitive work for me, but I don’t use them frequently enough to remember the exacting intricacies of the syntax. Time for a series of posts with examples that have worked for me.

First up, is the conversion of standard properties to notification properties.

This can be used to convert all of our vanilla DTO’s into useable Silverlight backing stores 🙂

  • find: public {(:a)+} {(:a)+} \{ get\; set\; \}{$}
  • replace: public \1 \2 {\n get { return _\2; }\n set { SetValue(ref _\2, value, "\2"); }\n}\nprivate \1 _\2;

So the Vanilla Class;

public class VanillaClass
{
public int MyInt { get; set; }

public int MySecondInt { get; set; }

public string MyString { get; set; }

public short MyShort { get; set; }

public LinkTypeEnum MyEnum { get; set; }
}

Will be converted to the Triple Chocolate Class;

public class VanillaClass
{
public int MyInt
{
get { return _MyInt; }
set { SetValue(ref _MyInt, value, "MyInt"); }
}
private int _MyInt;

public int MySecondInt
{
get { return _MySecondInt; }
set { SetValue(ref _MySecondInt, value, "MySecondInt"); }
}
private int _MySecondInt;

public string MyString
{
get { return _MyString; }
set { SetValue(ref _MyString, value, "MyString"); }
}
private string _MyString;

public short MyShort
{
get { return _MyShort; }
set { SetValue(ref _MyShort, value, "MyShort"); }
}
private short _MyShort;

public LinkTypeEnum MyEnum
{
get { return _MyEnum; }
set { SetValue(ref _MyEnum, value, "MyEnum"); }
}
private LinkTypeEnum _MyEnum;
}

Obviously the SetValue method is part of a base class from which VanillaClass will inherit, but that is irrelevent, the object of this exercise is to remove the heavy lifting involved in converting the Properties to Notification Properties. Also, post-replace, I use the Visual Studio Auto Formatting settings to correctly beautify the new properties.

Adding attributes into the mix is straightforward. For [DataMember()] handling use:

Find: \[DataMember\(\)\]\n((:b)+)public {(:a)+} {(:a)+} \{ get\; set\; \}{$}

Replace:[DataMember()]\npublic \1 \2 {\n get { return _\2; }\n set { SetValue(ref _\2, value, "\2"); }\n}\nprivate \1 _\2;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: