Wednesday, April 21, 2010

How To Configure AllMargins Extension For Visual Studio 2010

UPDATE: Removed non AllMargins registry settings. Thanks David Pugh for letting me know.


UPDATE 2: Productivity Power Tools now combines most of the major features of AllMargins, due to David Pugh himself porting it over. Consider using it instead.


AllMargins is a VS 2010 extension that basically replaces Rockscroll from VS2005 and VS2008. It combines multiple extensions into one “All” inclusive extension. Here is an example of what mine looks like with a few features pointed out:

image

It looks pretty good now, but when you first install it, it is configured for a white background, rather than black. You can change the colors via the registry at \HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor, but I couldn’t find any documentation online as to what color controls what. I downloaded the code from code.msn.microsoft.com and discovered how it all worked.

AllMargin Extensions

AllMargins contains multiple extensions, but all of their configurable settings are located in the registry at \HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor. I’ve listed them by extension below along with the introduction and usage text I’ve pulled together from the readme files in the projects. Just edit the appropriate registry setting and open up a new window in VS2010, to see any changes you’ve made.

CaretMargin

This extension adds a margin to the OverviewMargin that shows the location of the caret and all words that match the word the caret is on.

You will see colored rectangles drawn that correspond to the location of the caret and all words that match the word the caret is in or adjacent to.

Registry Name Description
CaretMargin/MarginEnabled Should the CaretMargin be displayed
CaretMargin/MarginWidth Width of the CaretMargin (in pixels)
CaretMargin/CaretColor Color used to draw the location of the caret. Not used if Alpha = 0
CaretMargin/MatchColor Color used to draw the location of matching words. Not used if Alpha = 0


OverviewMarginImpl

This extension creates a margin displayed along the right edge of the editor. It, like the vertical scroll bar, logically maps to the entire file. By default, it acts as if all elided regions are expanded (though the portions of the file contained in a elided regions are highlighted). The OverviewMargin also can highlights the portions of the file that are above, contained in and below the text shown in the editor.

The OverviewMargin is a container for other margins (that all use a common mapping between a location on the screen and a position in the file). This extension includes two of these contained margins: the OverviewChangeTracking margin (which acts like the change tracking margin from the left side of the editor, but applied to the entire file) and the OverviewMark margin (which allows 3rd parties to draw colored marks to indicate positions of interest in the file).

Moving the mouse into the OverviewMargin will, after a brief delay, show a tooltip. The default tip for the OverviewMargin shows the contents of the file at the corresponding location but other margins contained in the OverviewMargin may provide more interesting tips.

Left clicking in the OverviewMargin to scroll to center the corresponding location in the editor. Left clicking in an elided region will center the(collapsed) elided region in the editor.

Double-left-clicking in the OverviewMargin will expand any elided regions that contain the corresponding location and then center that location in the editor.

Right-clicking in the OverviewMargin brings up an option menu that allow you to change:
Whether or not the OverviewMargin acts as if all elided regions are expanded (if they are not, then the OverviewMargin uses the same mapping between a location in the margin and a position in the file as the vertical scroll bar).
Whether or not the OverviewMargin will show the default tip when the mouse is inside the margin.

Registry Name Description
OverviewMargin/ChangeTrackingMarginEnabled Should the change tracking margin be displayed
OverviewMargin/MarkMarginEnabled Should the mark margin be displayed
OverviewMargin/ExpandElisionsInOverviewMargin Are elisions expended in the overview margin?
OverviewMargin/OverviewMarginPreviewSize Number of lines to show in the default tip for the overview margin. If 0, do not show any tip by default
OverviewMarginImpl/ChangeTrackingMarginWidth Width of the ChangeTrackingMargin (in pixels)
OverviewMarginImpl/MarkMarginWidth Width of the MarkMargin (in pixels)
OverviewMarginImpl/ElisionColor Color used to highlight elided text as ARGB. Not used if Alpha = 0.
OverviewMarginImpl/OffScreenColor Color used to highlight portions of the file not shown in the editor as ARGB. Not used if Alpha = 0.
OverviewMarginImpl/VisibleColor Color used to highlight portions of the file shown in the editor as ARGB. Not used if Alpha = 0.


Structure Adornment

This extension displays vertical lines in the editor to help show the block structure of the code file. Different colors are used to indicate different types of blocks.

Moving the mouse over one of the colored lines will, if the line extends off the top of the editor, create a tooltip at the top of the view that provides some context on what is out of view.

Registry Name Description
StructureAdornment/ClassColor Color used to show the scope of class definitions as ARGB
StructureAdornment/ConditionalColor Color used to show the scope of conditionally executed code as ARGB
StructureAdornment/LoopColor Color used to show the scope of loop bodies as ARGB
StructureAdornment/MethodColor Color used to show the scope of method bodies as ARGB
StructureAdornment/UnknownColor Color used to show the scope of unknown blocks as ARGB
StructureAdornment/Enabled Should the structure adornments be shown?


StructureMargin

This extension adds a margin to the OverviewMargin that shows the block structure of the code file. Different colors are used to indicate different types of blocks.

Moving the mouse over the structure margin will create a tooltip that provides some context on what is in the file at that location.

Registry Name Description
StructureMargin/ClassColor Color used to show the scope of class definitions as ARGB
StructureMargin/ConditionalColor Color used to show the scope of conditionally executed code as ARGB
StructureMargin/LoopColor Color used to show the scope of loop bodies as ARGB
StructureMargin/MethodColor Color used to show the scope of method bodies as ARGB
StructureMargin/UnknownColor Color used to show the scope of unknown blocks as ARGB
StructureMargin/MarginEnabled Should the StructureMargin be displayed
StructureMargin/MarginWidth Width of the StructureMargin (in pixels)
StructureMargin/MethodEllipseColor Color used to draw the ellipse that shows the scope of method bodies as ARGB. Not used if Alpha = 0


My Settings

Here are my setting that I use. If you want to use them, just save them as a .reg file to add/update them in the registry


Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor]
"StructureAdornment/ClassColor"="#FF5F7D7C"
"StructureAdornment/ConditionalColor"="#FF005300"
"StructureAdornment/LoopColor"="#FFFF0000"
"StructureAdornment/MethodColor"="#FF222290"
"StructureAdornment/UnknownColor"="#FF362844"
"StructureAdornment/Enabled"="True"
"OverviewMargin/ExpandElisionsInOverviewMargin"="True"
"OverviewMargin/PreviewSize"="20"
"OverviewMarginImpl/ElisionColor"="#404252FF"
"OverviewMarginImpl/OffScreenColor"="#FF000000"
"OverviewMarginImpl/VisibleColor"="#88444444"
"OverviewMargin/ChangeTrackingMarginEnabled"="True"
"OverviewMarginImpl/ChangeTrackingMarginWidth"="9"
"OverviewMargin/MarkMarginEnabled"="True"
"OverviewMarginImpl/MarkMarginWidth"="8"
"CaretMargin/Enabled"="True"
"CaretMargin/CaretColor"="#AADDFFFF"
"CaretMargin/MatchColor"="#FF6F8474"
"CaretMargin/MarginWidth"="7"
"StructureMargin/MarginEnabled"="True"
"StructureMargin/MarginWidth"="25"
"StructureMargin/MethodEllipseColor"="#20DDDDDD"
"StructureMargin/ClassColor"="#FF38E4DB"
"StructureMargin/ConditionalColor"="#FFAF22C8"
"StructureMargin/LoopColor"="#FF0AC034"
"StructureMargin/MethodColor"="#FFE86D0E"
"StructureMargin/UnknownColor"="#FFE8DE1B"

Thursday, February 4, 2010

Testing a Windows Service From Within Visual Studio

When working with Windows Services, you can’t set the windows service project as the “Startup Project” and start debugging. You get a Windows Service Start Failure dialog box telling you that you "Cannot start service from the command line or a debugger. A Windows Service must first be installed (using installutil.exe) and then started with the Server Explorer, Windows Services Administrative tool or the Net Start Command.

In order to get around this issue, a common approach I’ve seen is to add a windows form to the windows service project, and then in the project’s Program.Main() method, comment out the ServiceBase.Run() and add this code to run the windows form instead:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TestForm());

This will result in your TestForm running instead of your actual service and you can add whatever features that you want to the TestForm Form to be able to debug your service (IMHO it’s also good to add some cleanup functionality to this test form, like reprocess transaction 9999). If the Windows Service ever needs to be rebuilt, the changes to Program.cs have to be reverted. The result is a Program.cs file that get checked into source control looking like this:

static class Program

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;

// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new Service() };

ServiceBase.Run(ServicesToRun);

//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new TestForm());

}
}

and being changed to look like this:

static class Program

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;

// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new Service() };

//ServiceBase.Run(ServicesToRun);

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TestForm());

}
}

whenever it needs to be ran in Visual Studio. This can become really annoying if you’re doing this multiple times a day on different services, or your source control provider doesn’t support multiple simultaneous checkouts. It can be even worse if the build for the service takes a long time, and you forget to comment/uncomment the right lines, and there is always the risk that you check in the Windows Form version of the service.

So, because I’m a lazy programmer (If I have to do something twice, that’s one too many times) I figured out a solution utilizing the System.Diagnostics.Debugger.IsAttached property. I created a simple static class with a static constructor that accepts two parameters. One for the services that should be ran if we aren’t starting this in Visual Studio, and another for the Windows Form Type to use as the test form if debugging. It ended up looking like this:

public static class ServiceApplication

/// <summary>
/// Deteremines if the service is being ran in debug mode.
/// If it is, the testFormType is ran, if not, the service is started normally
/// </summary>
/// <param name="servicesToRun">The services to run</param>
/// <param name="testFormType">The Form type that is the test form for the service</param>
public static void Run(ServiceBase[] servicesToRun, Type testFormType)
{
if (System.Diagnostics.Debugger.IsAttached)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form testForm = (Form)Activator.CreateInstance(testFormType);
Application.Run(testForm);
}
else
{
ServiceBase.Run(servicesToRun);
}
}
}

And now my Program.cs looks like this:

static class Program

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceApplication.Run(new ServiceBase[] { new Service() }, typeof(TestForm));
}
}

No more editing the program.cs file! It just works the way I want it to!

Friday, November 20, 2009

Programming Challenge 2 - Falling

After the success of Programming Challenge 1 I finally present Programming Challenge 2. The intent of this challenge is to create a program that uses multi-threading.

Here is the Challenge:

Write a winform ASCII game that with these properties:

  • It has a game grid that is 5x5.
  • The player should be represented as a plus sign “+” located in the second row from the top.
  • The player is able to move the + from side to side.
  • A row of 4 minus signs “-” and one blank space, should be randomly generated at the bottom of the 5x5 grid, and move up (giving the perception that the user is falling down).
  • Every 1/4 of a second, the row of minuses should move up one row until it disappears off the top of the grid and another 1/4 second late, a new one will appear at the bottom.
  • Play continues until the + sign attempts to occupy the same space as a minus sign. When this happens, the minus sign should be replaced by an “X”. This can happen by either:
    • falling down on top of a minus.
    • Or moving right or left into a minus. After play ends, display a score to the player which is the number of minus rows successfully avoided.

Should look something like this when completed:

And with an end game that looks like this:



Good luck and happy falling!

* Legal Notice * These Programming Challenges

shall not be reproduced in any form without my express written consent.

Saturday, October 24, 2009

Programming Challenge 1 - Mow the Lawn - Results

There were three projects submitted.  One by a brand new .Net developer, Brandon, one by a C#/Flash developer, Kyle, and another one by myself.

This programming challenge presented some common problems that had to be over come like how store the grass, the position of the lawnmower, and what the grass should be after it has mowed.  Some solutions for these problems were extremely similar and others were surprisingly different.

Brandon’s code was the shortest and the simplest taking around 120 lines of code.  He used a two dimensional char array to store the lawn and class level variables to store the position of the lawn mower, and what the grass under the mower is.  This is his code to handle the move with the other 3 directions taken out.

private void MowerForm_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
if (MowerY < 9)
{
grassArray[MowerY, MowerX] = underMower;
MowerY++;
checkCutStatus();
}
break;
}
PrintGrass();

if (numcut == 100)
MessageBox.Show("The lawn is mowed!! Daryl's mom is lathered up and waiting to congratulate you inside!");

}


It’s very simple, first checking to be able to move in that direction and then updating the lawn under the mower, and moving the mower.  His checkCutStatus() would then update underMower, and place the mower at the new location.  Pretty simple but I would also add an else to the if, that had a return statement.  That way if you couldn’t move, you wouldn’t reprint the grass.  Whenever a piece of grass goes from medium to short, the numcut get incremented and once all 100 are cut, the congratulations message gets displayed.  I would suggest at least making it a class level constant for the 100 and the 9.  It makes it easier to update and (numcut == AllGrass) makes more sense then (numcut == 100).



Kyle’s code was the second shortest.  He also used a two dimensional array but he created a Grass class that kept track of the grass type, Label, and whether it had been marked as counted.  Below is his move function. 



protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.Right:
if (mower_location.X < lawn_width - 1)
{
mower_location.X += 1;
update_grass();
}
break;
}
return true;
}



update_grass() keeps track of the old mower position and handles cutting the grass, moving the lawn mower, and keeping track of the previous position.  One of the more unique aspects of Kyle’s program is that rather than having one label with 100 squares, he has 100 labels.  This makes it easier and quicker to update since only the text that gets changed needs to be updated.  Brandon and my solution requires the entire 100 squares to be redrawn.



My code was the longest, and with the most extra classes, but since I knew what the next programming challenge would be, I thought it would be worth it to add that additional complexity.  Instead of using a 2 dimensional array, I used an array of an array incase I wanted the yard to not be square. Below is my move function.



private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
case Keys.Left:
case Keys.Right:
if (Lawn.Move(Mower, GetDirection(e.KeyCode)))
{
lblLawn.Text = Lawn.ToString();

if (DisplayMessage && Lawn.IsMowed)
{
MessageBox.Show("Have a Lemonade, you're finished!");
DisplayMessage = false;
}
}
break;

default:
break;
}
e.Handled = true;
}



I actually pulled out the lawn logic out of my main form in an effort to make it more MVC-ish.  The Lawn.Move() returns true if the object that is attempted to be moved, was move.  Similar to Brandon’s counting of cut grass, the Lawn class keeps track of the grass left uncut, and encapsulates it with the IsMowed property.  The main work of moving the mower around is handled in Lawn.Move().



public static bool Move(LawnBase obj, Direction direction)
{
if (!obj.IsMovable) { return false; }

LawnBase nextObject = GetObjectInDirection(obj, direction);

if (nextObject == null || !nextObject.CanMoveOver) { return false; }

var mobileObject = ((MoveableLawnBase)obj);
_lawn[obj.Row][obj.Column] = mobileObject.GroundBeneath;
mobileObject.Move(direction, nextObject);
DecrementGrassCount(nextObject, mobileObject.GroundBeneath);
_lawn[obj.Row][obj.Column] = obj;

return true;
}


There are some additional checks to see if an object can be moved over, so later if we add more objects to our yard, they’ll be able to interact nicely.



Feel free to comment:

Monday, October 12, 2009

Programming Challenge 1 - Mow the Lawn

A friend of mine has just switched from developing in COBALT, to C#. As a fun way to help him learn C# and to argue over better methods of programming, we decided to make little programming challenges that were designed to be short, simple and fun. This contest is open to anyone, just feel free to e-mail me your zipped project solution and I'll post it and comment on it.

So here goes the first challenge:
Write a winform ASCII lawn mowing application with these properties:
  • It should start with a 10x10 grid of capital "X"'s.
  • The lawn mower should be represented by an "@" symbol, and start in the upper left hand corner.
  • The user should be able to use the arrow keys to move the lawnmower around the lawn.
  • The first time the lawn mower passes over an X, it gets converted to a lower case "v".
  • When the lawn mower passes over a "v", it gets converted to a ".".
  • When the entire lawn has been reduced to "."'s a message should be displayed to the user.

Good luck and happy mowing!

* Legal Notice * These Programming Challenges shall not be reproduced in any form without my express written consent.


Wednesday, July 8, 2009

Visual Studio Region Snippet

I like to format my regions, so the region name is at the bottom of the region, that way I don't have to scroll all the way to the top to see the next region. I've been doing this by hand all the time, and figured it was about time for me to create a code snippet for it.

Using this telerick blog, I was able to see the folder that all the snippets are stored ("<Visual Studio installation directory>\VC#\Snippets\1033\Visual C#") and then the rest was easy.



<?xml version="1.0" encoding="utf-8" ?>
CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<
CodeSnippet Format="1.0.0">
<
Header>
<
Title>region</Title>
<
Shortcut>region</Shortcut>
<
Description>Code snippet for region</Description>
<
Author>Daryl LaBar</Author>
<
SnippetTypes>
<
SnippetType>Expansion</SnippetType>
<
SnippetType>SurroundsWith</SnippetType>
</
SnippetTypes>
</
Header>
<
Snippet>
<
Declarations>
<
Literal>
<
ID>name</ID>
<
ToolTip>Region name</ToolTip>
<
Default>MyRegion</Default>
</
Literal>
</
Declarations>
<
Code Language="csharp"><![CDATA[#region $name$

$selected$$end$

#endregion // $name$
]]>
</
Code>
</
Snippet>
</
CodeSnippet>
CodeSnippets>


Wednesday, May 27, 2009

Yield Passes Control Through Intermediate Calls

I was wanting to be able to perform a backend database service in a batch mode, but wanted to make the actual batch processing part of it as encapsulated as possible.

I created a BO that returned an IEnumerable<List<MyBO>>, but it didn't use any yield statements, it just called a data access layer that was using the yield statements. I was concerned if this was going to work, so I decided to test it using snippet compiler.

So this is my quick and dirty test to see if it would work:

public static void RunSnippet()
{
foreach (List<string> answers in GetAnswers())
{
WL(answers.Count);
foreach (string answer in answers)
{
WL(answer);
}
}
}

public static IEnumerable<List<string>> GetAnswers()
{
return GetTheAnswers();
}

private static IEnumerable<List<string>> GetTheAnswers()
{
List<string> answers = new List<string>();
answers.Add("A");
answers.Add("B");
answers.Add("C");
answers.Add("D");
yield return answers;

answers = new List<string>();
answers.Add("D");
answers.Add("C");
answers.Add("B");
answers.Add("A");
yield return answers;

answers = new List<string>();
answers.Add("X");
answers.Add("Y");
answers.Add("Z");
yield return answers;
}






And these were the results:
4
A
B
C
D
4
D
C
B
A
3
X
Y
Z


So even though GetAnswers() gets called once, GetTheAnswers() will return control back to the enumerating foreach multiple times.