Dynamic Menu Commands in Visual Studio Packages - Part 2

March 22nd, 2008 DBML Fixup, VSX, Visual Studio 2008

In this post I’ll be building on the principles of my last post with dynamic menu development in Visual Studio, so if you haven’t read that post please go back and check it out!

If you remember from last time, we were able to create a dynamic menu command without any lines of procedural code (other than those generated by the wizard). The result was a menu command that showed itself only when no solution was loaded in Visual Studio. Immediately a solution was loaded, the menu command disappeared. The limitations of this approach are that you’re reliant on built-in UI contexts, such as UICONTEXT_NoSolution. However, what I needed for my DBML Fixup project was a way to add menu commands when right clicking on .dbml files (LINQ to SQL Classes) in the Solution Explorer. The built-in UI contexts that we reviewed in the previous post are not enough to give us this functionality. In this tutorial, I take you through step-by-step on how to add this feature to your VS packages. We have to do a bit of digging though, so let’s get started!

Read the rest of this entry »

LINQ Design Guidelines

March 18th, 2008 Application Design

As a follow-up to the first Framework Design Guidelines, there’s been a new post on Mircea Trofin’s blog on the LINQ Framework Design Guidelines. They are a great read, and you will probably find something that you didn’t consider before in designing applications with LINQ.

Please leave your feedback!

Dynamic Menu Commands in Visual Studio Packages - Part 1

March 14th, 2008 DBML Fixup, VSX, Visual Studio 2008

As I get further into my DBML Fixup project, I’m learning more and more about Visual Studio Extensibility (VSX). Along the way, I have found multiple blogs which have helped me to learn a lot more than I would than just stepping through the documentation. (Those blogs are now listed on the sidebar.) The one I find especially helpful for beginners like me is DiveDeeper, whose LearnVSXNow tutorials are great stepping stones in learning the basics of VSX Packages. He currently has 14 tutorials, the first of which is located here. Although his blog is very helpful for learning about how to work with menu commands, he hasn’t (yet?) delved into making them dynamic. I needed to do this for my project, so I had to "dive deeper," as it were.

In this series of posts I’m going to focus on three ways to make menu commands dynamic—that is, how to make menu commands invisible or disabled in certain contexts, but visible and enabled in others. Two of these ways I found through some experimentation. Consequently, I’m not sure whether these represent VSX best practices, so if anyone has any more input, it would be greatly appreciated. With that said, let’s get started.

Read the rest of this entry »

PostSharp RC2 Released (And Code Analysis…)

February 24th, 2008 Code Analysis, MSBuild, PostSharp, Visual Studio Team Suite

Gael Fraiteur has released another release candidate of PostSharp, an Aspect-Oriented Programming solution for .NET. In my previous post on PostSharp, I discussed a way to work around some pesky Code Analysis errors that PostSharp incurs as a result of its post-compilation processing.

Unfortunately, I don’t believe adding the CompilerGeneratedAttribute (CGA), which was done before RC2’s release, to PostSharp-specific code fixed all of the Code Analysis warnings that our team received. After upgrading to RC2, Code Analysis warned us specifically about initializing our static fields inline in many of our classes and removing the explicit static constructors, as well as the cyclomatic complexity of some of our methods. It was the fact that we did initialize our static fields inline that tipped us off about the same problems that caused me to write my first PostSharp and Code Analysis post. The problem is that adding the CGA is not comprehensive enough to suppress all code analysis violations. For example, PostSharp effectively injects code at certain points in a program execution (join points in a method). You wouldn’t want the CompilerGeneratedAttribute applied to that code, because it could suppress other rule violations that come from your code, not PostSharp’s code. Fortunately PostSharp does not apply the CGA in those circumstances, but there needs to be a middle ground such that PostSharp code is totally ignored by code analysis.

Read the rest of this entry »

The LINQ to SQL Metamodel

February 16th, 2008 DBML Fixup, LINQ to SQL, ORM

For my DBML Fixup project, I’ve really had to drill into the structure of LINQ to SQL—including how the data is stored in the .dbml file, how various changes in the designer affect the serialized XML (which is the format of the .dbml file), and what the various elements and attributes in the DBML file actually mean. (Honestly, what does the IsForeignKey attribute on the Association element imply as its meaning? I thought all “associations” represented foreign keys!)

At first I tried to dissect LINQ to SQL by keeping track of the various elements and attributes and their representations in the XML and the designer in big Excel tables. They quickly became unwieldy, and I decided to cut my losses and model the LINQ to SQL schema (DBMLSchema.xsd). Needless to say this was a very challenging exercise, but I gleaned a significant amount of knowledge about LINQ to SQL after finishing it.

The purpose of this post is to post the various pages of the LINQ to SQL model; I want this post to clarify the infrastructure of LINQ to SQL to others, so I would appreciate if you can comment on any inconsistencies or missing constraints you can see. I used Object-Role Modeling (ORM) for the model, so if you are not familiar with that, you may want to check out the following resources:

  1. Object Role Modeling: An Overview, http://msdn2.microsoft.com/en-us/library/aa290383(VS.71).aspx
  2. Halpin, T. 2001. Information Modeling and Relational Databases: From Conceptual Analysis to Logical Design.San Francisco: Morgan Kaufmann Publishers

The model starts like this…here’s the database page. The derivation rules aren’t on the diagram explicitly, as they are stored as part of the properties of the fact type. Other advantages of having the .orm file are that I’ve put definitions on all of the fact types to clarify their meaning, in the case that the predicate text is still not clear enough. If anyone wants the .orm file, feel free to contact me at david.dewinter AT (@) rev-net DOT (.) com. (You can open .orm files with Visual Studio after installing Project NORMA.) I will also put up a contact form soon…

Read the rest of this entry »

LINQ to SQL and Database Schema Sync

February 16th, 2008 DBML Fixup, LINQ to SQL, Requirements Analysis

Since the new year I’ve been working on a project that attempts to solve the following problem:

How do I keep my generated entity classes in sync with the current database schema using LINQ to SQL?

For some people, this question is moot. It’s easy enough to utilize the current “resync” mechanism in LINQ to SQL by deleting all the entity classes and functions (the LINQ to SQL term for sprocs and UDFs) on the designer surface and then redragging and dropping the tables and functions of interest, thus updating the entity classes by regenerating from scratch. However, for others, this solution is not good enough for a few reasons:

Read the rest of this entry »

Profiling the Visual Studio Web Server

February 12th, 2008 Profiling, Visual Studio 2008

With JetBrains’ dotTrace and Red Gate Software’s ANTS Profiler, developers can find bottlenecks in their code as well as profile memory usage. Both tools also support tracing the Visual Studio (2005) Web Server out-of-the-box. However, tracing with Visual Studio 2008 Web Server is a little different.

Read the rest of this entry »

PostSharp + Code Analysis = Abomination

January 15th, 2008 Code Analysis, MSBuild, PostSharp, Visual Studio Team Suite

(If you just want the targets files, click here.)

Are you using PostSharp for your .NET development? Do you get frustrated when code analysis within VSTS reports warnings like these:

Code Analysis Warnings

Now PostSharp is a superb AOP tool for .NET, but it is annoying to see these issues in code analysis again and again; what would be great is if we can edit the build process to make Code Analysis (CA) run before PostSharp processes the assembly. That way, code analysis errors on PostSharp-generated code is ignored, and everyone is happy. :)

Read the rest of this entry »

CA2104: DoNotDeclareReadOnlyMutableReferenceTypes

January 5th, 2008 Code Analysis, Visual Studio Team Suite

If you’re not familiar with the code analysis rule mentioned in the title of this post, I recommend you check out David Kean’s FAQ post here for some background.

In summary, a violation of this rule may be fired even if you declare a read-only variable of a type that’s immutable, because the code analysis engine won’t know that that type is immutable. To get around this, you can follow David’s suggestion of putting an ImmutableTypes.txt file in the same directory as your FxCop project file.

But if you’re using Visual Studio Team System to execute your Code Analysis, it’s a different story because you don’t have an FxCop project file. Fortunately, this ImmutableTypes.txt file can be placed in the C:\Program Files\Microsoft Visual Studio 9\Team Tools\Static Analysis Tools\FxCop\ImmutableTypes.txt location to be picked up.

What would be great is if there was an MSBuild task that allowed developers on a project to make an ImmutableTypes.txt file directly in a VS project and have that merged with the existing ImmutableTypes.txt at the target location. That way, individual projects can build their ImmutableTypes without worrying about CA2104 violations. In fact…I may just build that task. ;) Right now I have a centralized project for gathering Immutable Types and I do this as part of my build:

<Copy SourceFiles=ImmutableTypes.txt DestinationFolder=$(VS90COMNTOOLS)..\..\Team Tools\Static Analysis Tools\FxCop\ />

That will copy the ImmutableTypes.txt file from my project to the C:\Program Files\Microsoft Visual Studio 9\Team Tools\Static Analysis Tools\FxCop\ImmutableTypes.txt location. Problem (tentatively) solved. :)

The ExceptionMessageBox

December 1st, 2007 C# .NET

Ever seen this in your application?

TargetInvocationException

Yes? Then this article is for you. If not, you might know what this entry’s going to cover, but perhaps you’ll learn something new.

In tools I’ve been building, I’ve always been dissatisfied with this sort of “error reporting” (outside of logging, of course), but none of us have had the time to build something really spectacular to handle exceptions. And I have to say–thank goodness we didn’t! Yesterday I read about the ExceptionMessageBox class, and this is the sort of thing I’ve been waiting for! (Except it’s been out for well over a year…but that’s another story).

Since pictures speak better than words, the same exception from the first image is thrown again and is handled with the ExceptionMessageBox under default settings:

New and Improved

Much cleaner, huh? Not only does it give you the original exception, but it gives you all of the inner exception detail as well. When you click on the “Show Technical Details” icon in the toolbar (the button on the right) you’ll see a much appreciated stack trace for each of the exceptions in your chain.

Details

All of this is accomplished with two lines of code:

/// <summary>

/// Handles and logs the specified <see cref=”Exception”/>.

/// </summary>

/// <param name=”exception”>The <see cref=”Exception”/> to handle.</param>

private static void HandleException(Exception exception)

{

    ExceptionMessageBox mbox = new ExceptionMessageBox(exception);

    mbox.Show(null);

}

Very simple, indeed. The ExceptionMessageBox class is in the Microsoft.SqlServer.MessageBox namespace in the Microsoft.ExceptionMessageBox assembly. That assembly is available for download on this page. (Search for “Exception Message Box.”)

In addition, the ExceptionMessageBox supports a fair number of properties that should be touched on. We’ll cover the highlights here:

Properties

  • Beep (Boolean) - Specifies whether the ExceptionMessageBox beeps when it is launched (similar to a normal MessageBox).
  • Buttons (ExceptionMessageBoxButtons) - Specifies the type of buttons used by the ExceptionMessageBox. You can also use Custom buttons, a nice touch on top of the original MessageBoxButtons enumeration.
  • Caption (String) - The caption/title of the ExceptionMessageBox form.
  • CustomDialogResult (ExceptionMessageBoxDialogResult) - Specifies the button that was clicked when using custom buttons.
  • CustomSymbol (Bitmap) - Specifies a custom image to display instead of the normal Asterisk, Error, Warning, Information, etc.
  • DefaultDialogResult (DialogResult) - Specifies the result of user action on the dialog when not using custom buttons.
  • IsCheckBoxChecked (Boolean) - Specifies whether a check box for “Do not show this dialog again” was checked.
  • Message (Exception) - The original exception passed into the ExceptionMessageBox constructor.
  • MessageLevelDefault (Int32) - Specifies the maximum number of exceptions shown in the dialog. For example, if an exception is thrown that has two inner exceptions, and the MessageLevelDefault property is set to 2, then only the top-level exception and the first inner exception will be shown in the dialog.
  • Options (ExceptionMessageBoxOptions) - Enables various options like right-to-left reading or right alignment.
  • ShowCheckBox (Boolean) - Specifies whether to show the checkbox which enables developers to hook into users’ preferences on whether they want to show the dialog again.
  • ShowToolBar (Boolean) - Specifies whether to show the toolbar (which allows copying text from the message and showing technical details).
  • Symbol (ExceptionMessageBoxSymbol) - The symbol to show in the message box, like Asterisk, Error, Warning, and so on.
  • Text (String) - If the message box is being used for custom text instead of an exception, then this property will be populated with that text.
  • UseOwnerFont (String) - If you want to keep a consistent look across your application, you can tell the ExceptionMessageBox to use its owner window’s font instead of the default.

Methods

  • SetButtonText - There are a couple of overloads for this method. It’s used to set the text of one to five buttons on the dialog. This only applies if the Buttons property is ExceptionMessageBoxButtons.Custom.
  • Show - Where the magic happens. The basic version of this method requires an IWin32Window as an owner window. The nice thing is that you can pass in null. This would be appropriate if the executing code is inside of an event handler for AppDomain.UnhandledException, for example.

Event

  • OnCopyToClipboard -This is a pretty interesting event. It’s raised when the user clicks on the copy to clipboard button in the toolbar or presses Ctrl+C. The event supplies a CopyToClipboardEventArgs instance that has two properties: ClipboardText and EventHandled. When the event is raised, the text hasn’t been copied to the clipboard yet. Instead, you get the chance to handle the event separately. If you want to do your own custom processing and not copy the text to the clipboard, then set the EventHandled property to true on the event arguments and the clipboard data will not be changed. I thought this would be useful for doing something extra, like emailing developers with exception information. However, there’s no easy way to change the text on the toolbar button…

So that’s a brief look at the ExceptionMessageBox. One thing I didn’t cover was how to use the multifarious CheckBox-related properties to stop showing the message box to end users. Here are some links that can help you further:

How To: Program The ExceptionMessageBox

The ExceptionMessageBox Class

Download Page For ExceptionMessageBox (Search for “Exception Message Box”)