Tag Archive for Visual Studio

Attaching on Startup

Here’s a neat trick I stumbled onto that can make life a lot easier – in our development workstations, certainly, and even in a pinch on staging and testing machines:

How many times have you wished you could attach to a process immediately when it launchs? If we’re running a simple EXE, we can launch it from the debugger directly, but if we’re trying to debug a Windows Service, a scheduled task or a sub-process that is launched automatically, it isn’t that simple. We can try to press CTRL-ALT-P as quickly as possible, but that will almost always miss the very beginning. We can add a call to System.Diagnostics.Debugger.Launch() to our Application_Startup() function (or equivalent), but that’s polluting production code with debugging statements, and it isn’t really something we can send over to a staging or QA machine.

I was all set to write a tool to monitor new processes being launched and latch onto them when I discovered that there’s no need, and Windows provides me with this facility automatically!

All we need to do is create a new registry key under HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Image File ExecutionOptions and name it after the EXE we want to attach to.

Under this key, we create two values: A DWORD named PauseOnStartup with a value of 1, and a string named Debugger, with a value of vsjitdebugger.exe. Here’s a sample .REG file

Code Snippet
  1. Windows Registry Editor Version 5.00
  2. [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\MyApplication.exe]
  3. “PauseOnStartup”=dword:00000001
  4. “Debugger”=”vsjitdebugger.exe”

 

Now, when MyApplication.exe launches, it will automatically launch the familiar “Choose the debugger to use” dialog, and we can point it to our solution of choice.

Surviving the Enterprise Application

Many of us have worked on this sort of application: “The Monster”, “The Big One”, “The Behemoth”, or simply “The Enterprise Application”. You know the kind I mean: it’s a mess of dozens of projects and solutions. It requires setting up three console applications and two databases just so you can debug something (god forbid you could just launch it from within Visual Studio), and after making changes to some code, getting the updates DLLs to the right place can be a headache. The sheer amount of time wasted on getting around the architecture can be daunting, and changing this behavior, especially when the app has years of crud and not enough tests, is not something you want to take on yourself.

This is where tools come in. Good tools make the difference when navigating such a codebase between “horrendous chore” and merely “momentous undertaking”. Some are commercial tools and add-ins, like Resharper, which are indispensable for making heads or tails of a giant project. But there are many tools that are built into Visual Studio or even Windows that can make our lives easier. Here are a few of them:

 

Macros Are Your Friends

I’m saddened, heartbroken, devastated that Microsoft has removed support for Macros in Visual Studio 2012. They’re a feature I’ve used for many years for automating common tasks, especially the ones that accompany a huge project. In many projects, one needs to launch the application manually, then attach via the Attach to Process command. That, in itself, is not an overly complex process. But repeat that fifty times a day, and you’re starting to lose serious minutes. And if you’ve got specific parameters involved – such as attaching to one process with .NET Debugging only, and to another with Managed Debugging as well, and you have endless frustration. That’s where macros come in. You can add a short macro (recorded automatically, then customized) to attach to a specific process, add that macro to your toolbar or map it to a keyboard shortcut, and watch productivity soar (well, jump a bit, maybe). Here’s an example of such a macro. Do not fear the Visual Basic. The Visual Basic is your friend.

Code Snippet
  1. Dim dbg2 As EnvDTE80.Debugger2 = DTE.Debugger
  2. Dim trans As EnvDTE80.Transport = dbg2.Transports.Item("Default")
  3. Dim dbgeng(1) As EnvDTE80.Engine
  4. dbgeng(0) = trans.Engines.Item("Managed (v4.0)")
  5. Dim proc2 As EnvDTE80.Process2 = dbg2.GetProcesses(trans, "MYCOMPUTERNAME").Item("MyExternalProcess.exe")
  6. proc2.Attach2(dbgeng)

That’s all there is to it, barring some error handling code if the process isn’t found – in which case you can even add code to launch it automatically. Assuming, of course, it’s a simple case of launching an EXE. If it isn’t, we have some more tricks up our sleeve:

Back To Basics With Batch Files

Yes, yes. It ain’t pretty, and It’s not as powerful as bash or PowerShell scripts. But many times you need a simple script without the learning curve, .BAT files can give you what you’re after. In my current project, launching the basic application environment involves launching a server app in a console window, waiting for it to load, then launching a second service, giving that one enough time, and only then launching the client. This can be easily implemented with a lesser-known utility called TIMEOUT.EXE, originally a part of the Windows Resource Kit, but starting with Vista, a standard part of every Windows installation. This lets us space our startup logic appropriately:

LaunchApp.bat
  1. pushd D:\EnterpriseApp
  2. start /min ConfigService.exe
  3. timeout 5
  4. start /min ServerService.exe
  5. timeout 15
  6. start ClientApplication.exe

(Yes, that’s fifteen seconds to wait every time. That’s one heck of an Enterprise Application).

But spacing out application launches isn’t always enough. Sometimes we need a batch file to kill all processes at once, so we can update data and restart them. Here we have, again, a built-in Windows utility named TASKKILL.EXE that can receive either a process ID or, better for us, an executable name and kills the process dead. However, in this case, I would recommend skipping the built-in tool and using PsKill, part of SysInternals indispensable PsTools package, which has a host of useful tools.

SendTo? Really?

I remember, when Windows 95 rolled into town, I was enchanted with the possibilities that Windows Explorer offered. One of these was the Send To menu, and specifically, how easy it was to add a new option to that menu. Now I could send any file to any app, easily! Of course, after 10 minutes of wonder, I discovered that I never use it for anything except attaching a file to an Outlook message, and (rarely) creating a desktop shortcut. But now, with the Enterprise Application, it came back to me!

In my current project, we have several solutions, each compiling outputs to a different build folder. Of course, if you’re building the Shared Enterprise Apps solution, you have to remember to copy the new files to the Enterprise Application Client folder, or you’ll be constantly surprised and frustrated by your old code running again. Of course, this entails keeping lots of Explorer windows open, closing them, reopening them, copying the new files, and so on, and so forth. This is where my teenage fascination with Send To came back to me – I can actually use it! For real!

In Windows 7, the Send To menu resides in the application data folder, under %AppData%\Microsoft\Windows\SendTo. All we have to do is add a shortcut to our Enterprise Client folder, and be able to quickly send any file to it from anywhere:

image

 

Seconds Count

All these tips I’ve collected here may seem a bit trivial. The problems they come to solve only cost us a handful of seconds each. But when we sit in front of our projects for hours every day, repeating endless cycles of code-test-fix, these seconds add up. They add up in productivity, and they add up in frustration. A smooth development and operations process keeps us focused on what counts – fixing the real bugs, solving the real problems, and going home. If you have your own productivity tips, I’d love to hear them.

Remote Debugging through fire, snow or fog

Remote Debugging in Visual Studio is a wonderful feature, especially during the later stages of testing and deployment, and even (if all else fails) when in production, but getting it to work is rarely smooth. Everything is fine if both the computer running VS and the one running the application are in the same domain, but when they aren’t, things start to break, fast. I

So for those stuck debugging remote applications in different domains, here’s a quick guide to east the pain.

  1. On the the remote machine, install the Visual Studio Remote Debugging package, which comes with the version of Visual Studio you’re using.
  2. On the remote machine, create a new local user account. Give it the exact same name and password that you use on your development machine.
    If you’re developing when logged into MYCORPDOMAIN\MyUserName, with password MYPASS123, you wil have to create a local user REMOTEMACHINE\MyUserName with the same password. It doesn’t matter that the domains are different and there’s no trust relationship and so forth. Just have them be the same username and password.
  3. Give REMOTEMACHINE\MyUserName permissions. Administrator permissions is the safest, though you should be able to get it to work with a more restricted group, but I haven’t checked it yet.
  4. Run the application you want to debug using the MyUserName credentials. In Windows 7, this means using Shift-Rightclick and choosing Run As Different User. For Vista, there’s a shell extension to enable it.
  5. Run the Remote Debugging program, again under MyUserName credentials, same as above. The Remote Debugger will start with a new session named MyUserName@REMOTEMACHINE.
  6. Copy the remote debugging session name from the remote machine (you can copy it via the Tools –> Options menu).
  7. In your development machine, open Visual Studio, and go to Debug –> Attach to Process.
  8. In the Attack to Process screen, paste the remote debugging session name into the Qualifier textbox (the second one from the top).
  9. Voila! You are now debugging remotely!

Remote Debugging through fire, snow or fog

Remote Debugging in Visual Studio is a wonderful feature, especially during the later stages of testing and deployment, and even (if all else fails) when in production, but getting it to work is rarely smooth. Everything is fine if both the computer running VS and the one running the application are in the same domain, but when they aren’t, things start to break, fast. I

So for those stuck debugging remote applications in different domains, here’s a quick guide to east the pain.

  1. On the the remote machine, install the Visual Studio Remote Debugging package, which comes with the version of Visual Studio you’re using.
  2. On the remote machine, create a new local user account. Give it the exact same name and password that you use on your development machine.
    If you’re developing when logged into MYCORPDOMAINMyUserName, with password MYPASS123, you wil have to create a local user REMOTEMACHINEMyUserName with the same password. It doesn’t matter that the domains are different and there’s no trust relationship and so forth. Just have them be the same username and password.
  3. Give REMOTEMACHINEMyUserName permissions. Administrator permissions is the safest, though you should be able to get it to work with a more restricted group, but I haven’t checked it yet.
  4. Run the application you want to debug using the MyUserName credentials. In Windows 7, this means using Shift-Rightclick and choosing Run As Different User. For Vista, there’s a shell extension to enable it.
  5. Run the Remote Debugging program, again under MyUserName credentials, same as above. The Remote Debugger will start with a new session named MyUserName@REMOTEMACHINE.
  6. Copy the remote debugging session name from the remote machine (you can copy it via the Tools –> Options menu).
  7. In your development machine, open Visual Studio, and go to Debug –> Attach to Process.
  8. In the Attack to Process screen, paste the remote debugging session name into the Qualifier textbox (the second one from the top).
  9. Voila! You are now debugging remotely!

Upgrading all projects to .NET 3.5

A simple macro to change the Target Framework for a project from .NET 2.0 to .NET 3.5, hacked together in a few minutes. This will fail for C++/CLI projects, and possibly VB.NET projects (haven’t checked). Works fine for regular C# projects, as well as web projects:

 

For Each proj As Project In DTE.Solution.Projects
   Try
       proj.Properties.Item("TargetFramework").Value = 196613
       Debug.Print("Upgraded {0} to 3.5", proj.Name)
   Catch ex As Exception
       Debug.Print("Failed to upgrade {0} to 3.5", proj.Name)
   End Try

Next proj

Why 196613, you ask? Well, when I see such a number my first instinct is to feed it into calc.exe and switch it to hexadecimal. And I was right: 196613 in decimal converts to 0x00030005 – You can see the framework version hiding in there. Major version in the high word, minor in the low word. The previous TargetFramework number was 131072 – 0x00020000, or 2.0.

 

(Nitpickers might point out that I could simply set it to &30005 rather than messing with the obscure decimal number. They would be correct – but I got to this number through the debugger, so that’s how it will stay)

Another minor C#/C++ difference – adding existing files

Another minor detail that bit me for a few minutes today. I’m posting this so I’ll see it and remember, and possibly lodge it in other people’s consciousness.

Using Visual Studio 2005, adding an existing .cs file to a C# project will cause a copy of that file to be created in the project directory. If I want to link to the original file, I need to explicitly choose Add As Link from the dropdown on the Add button.

C++ projects, however, have the opposite behavior. Adding an existing item in a different folder will add a link to the original file in the original location. To create a copy, manually copy it to the project dir.

That is all.

Sharepoint Extensions for Visual Studio – released!

Finally, we have a full, RTM version of the Visual Studio extensions!
The download page says March 15th, but I haven’t seen anyone mention it around yet – could it be just me that missed the boat?
I got it from Mark Bower’s blog, but haven’t seen it mentioned anywhere else.

On one hand, this is great – the last version was from November ’06, and crashed often. Deployment seemed to work only for empty web-part projects and the Solution Generator crashed when trying to dump a whole site.

On the other hand, there are still many basic scenarios not covered by the tools – we can’t export a Publishing site into a site definition, or any list with a Lookup field. This is a huge drawback.  I hope they release a newer version soon, or perhaps a set of MOSS extensions (rather than WSS) that supports these scenarios.

Regardless, congrats to the team for releasing it for us, and keep up the good work.

Get it here:

http://www.microsoft.com/downloads/details.aspx?FamilyID=19f21e5e-b715-4f0c-b959-8c6dcbdc1057&DisplayLang=en

 

UPDATE: As sral and others reminded me, the main drawback of these extensions is that most of the functionality can only be used when running Visual Studio on the Sharepoint server itself. The most noticeable is the Deployment scenario, which is a pain to do manually.

This forces developers to either forego most of the benefits of the tools or start running Server2k3 on their dev machines, which is a hassle.

The alternative is of course to run a virtual machine for all development work, but this isn’t feasible in all situations. I only recently got my development machine upgraded to the point it can run a VM decently, and even now it could do better (2GB RAM, 1.5 of which go to the VM). What did I do earlier? Installed Win2k3 (sometimes on a dual boot) and cursed the slowness.

The current message, which is “You have to buy all your developers a fast machine and a copy of Win2k3” even if you only want to develop for the (freely available) WSS 3.0 is a bit off-putting.

I call for a WSSExpress edition, similiar to the other offerings from Microsoft. It can run on Vista only, I suppose, that wouldn’t be too bad. It’s time to get up off my lazy ass and upgrade. :)

Visual Studio obstructing DebugView

I’ve mentioned it before, but SysInternal‘s DebugView is a great utility. It allows you to get the Debug.WriteLine() strings from your application even when you’re not attached with a debugger, as long as it was compiled in Debug mode. Very convenient.


Unfortunately, it’s a bit hard to use when I’m also actually doing work with Visual Studio. It seems that some bits of VS are also logging calls with the OutputDebugString API call. I can live with the occasional message like this:



[3448] DllCanUnloadNow called for VSA7.dll
[3448] DllCanUnloadNow returned S_FALSE


but getting these:



[3448] Left. Enter HWND 90ea6


whenever I do anything in Visual Studio is annoying, and quickly hides any pertinent debug messages I want to see.


Running  Microsoft Visual Studio 2005 Team Edition for Software Developers
Version 8.0.50727.51  (QFE.050727-5100)
Microsoft .NET Framework
Version 2.0.50727

I pity the fool who messes with CTRL-SHIFT-T.

The Visual Studio IDE, among its myriad options and combinations and features and so forth, has a trio of rather odd key combinations:

CTRL-T – Interchanges the current letter and the one after it.
CTRL-SHIFT-T – Same thing, only for the current word.
ALT-SHIFT-T – Same thing, only for the current line.

These keybindings have been there at the very least since Visual Studio 4, where I first came across them.

And I wonder – what are they good for? Is there anyone that uses them regularly, or at all? What are they good for?