Visual Studio Macros
Posted: January 5th, 2009 | Author: YuSuF | Filed under: Programming | Tags: macro, visual-studio | 2 Comments »Visual Studio Macros might make you code faster. Consider using macros for any thing that you do repeatedly;
For example, I have a static configuration class and want to add properties to this class with a macro;
Think that I have line like following in somewhere of my project;
var myValue = ConfigurationManager.AppSettings["MyValue"];
And it is much more flexible if I do it like the following. This will provide me strongly typed access to configuration values, but I need to write one property for each configuration value, and that’s the point where the power of macros helps me:
var myValue = GdmWebConfiguration.MyValue;
public static class MyConfiguration
{
public static string MyValue
{
get
{
return GetBool("MyValue");
}
}
}
here is the macro code block that I have;
Sub addPropToMyConfig()
DTE.ItemOperations.OpenFile("MyConfiguraiton.cs")
DTE.ActiveDocument.Selection.Text = " public static string " + ClipboardText
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "{"
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "get"
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "{"
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "return GetString(""" + ClipboardText + """);"
DTE.ActiveDocument.Save()
End Sub
I just double click on the string “MyValue” on the following line and make ctrl+c (copy to clipboard) and ctrl+alt+k (I have assigned this shortcut to my macro) and in MyConfiguration.cs the property I need gets created immediately.
var myValue = ConfigurationManager.AppSettings["MyValue"];
And you can manually convert this line to MyConfiguraition.MyValue or you can use another macro ;) What I do is; I select ConfigurationManager.AppSettings["MyValue"]; (without copying; just select ) part and run this macro;
Sub GdmConfAdd()
DTE.ActiveDocument.Selection.Text = "MyConfiguration." + ClipboardText
End Sub
In this blog post you will see how ClipboardText variable implemented;
http://svenmaes.blogspot.com/2007/03/access-clipboard-from-visual-studio.html




Quite inspiring,
Great information about visual stuio macros…
Thanks for writing, most people don’t bother.
Thanks a lot ;)