Archive

Archive for the ‘Visual Studio’ Category

XAML Formatting in Visual Studio

May 7, 2010 1 comment

A question came up last night at RVNUG about manually editing XAML, something I avoid as much as reasonably possible.  When I have to edit XAML though, I almost always jump over to Visual Studio, so I was asked why I prefer to edit XAML in Visual Studio over the Blend editor.  Besides the fact that I’ve always just done it that way because originally we did not have Intellisense in Blend, I have two other reasons.

The first reason is that I use Blend to write XAML and Visual Studio to code XAML.  It sounds like splitting hairs, but let me explain.  Blend is the best darn XAML Editor ever written, primarily because it allows me to write and edit XAML without actually typing the XAML.  It magically translates the design I have on the screen into it’s XAML representation: that’s what makes it so awesome.  When I find a situation where I actually need to code the XAML and make textual changes to it myself, then I use Visual Studio, because it is the best darn Code Editor ever written.  To sum up: Design = Blend, Code = Visual Studio.

The second reason is far less highbrow: I dislike the default XAML formatting that Blend produces.  Don’t get me wrong, the XAML code itself is wonderful, almost pristine, but it compresses it to as few lines as possible.  That means lots of properties on a single line, which becomes an issue when you have a bunch of properties full of Binding references and more complicated structures.  So my preference is to see one property per line in the XAML.  This makes it much more palatable on those rare moments when I must code the XAML manually.

Setting up Visual Studio

I saw the question today on the Expression Blend forums about how to get Blend or Visual Studio to do exactly that, so I thought I would put up a quick post for the archives.

While Blend cannot format the XAML in this fashion, Visual Studio can:

  1. In VS2008 or VS2010 go to Tools –> Options
  2. Expand Text Editor -> XAML -> Formatting –> Spacing
  3. Under "Attribute Spacing" check "Position each attribute on separate line".
  4. If you prefer, you can also put the first attribute on the same line as the tag by checking the box.  I use this setting because it isn’t offensive and still saves a little space.

Now, whenever you edit XAML in Visual Studio, press "Ctrl+K+D" and Visual Studio will reformat the XAML as desired. 

Enjoy!

Categories: Blend, Visual Studio, XAML

Setting Conditional Breakpoints in VS2008

June 17, 2008 Comments off

I subscribe to Sara Ford’s excellent Blog Visual Studio 2008 Tip of the Day.  I have to admit though, that I rarely use the tips.  They tend to be a little too deep in the mud for my tastes, although I will forever be grateful for her showing us how to change colors for things like Matching Braces.

Today, however, she has a great tip that you should probably read: how to set conditional breakpoints.

Categories: Visual Studio

First Foray into Unit Testing with Visual Studio 2008

June 12, 2008 12 comments

I’ve read about Unit Testing and Test Driven Development (TDD) but have never attempted to use it or even really understand it. I recently became intrigued by it watching Rob Conery’s excellent video series. Today I began putting the final touches on the Authorize.Net code I am going to release, so I thought this would be a good opportunity to try some testing.

I have never done any Unit Testing, and even though I wasn’t sure where to start, I figured it out pretty quickly. First things first, I added a Test Project to my solution. This created all the necessary framework code as one might expect. I deleted the default TestMethod and began adding TestMethods of my own, intuitively marked with the [TestMethod] attribute. A little Google hopping and I quickly learned about Assert.xxx() methods.

When it came time to actually run the tests, I was a little stumped. I read where you could right click the method name and execute “Run Tests”, but it seems to only run one at a time. In the test results window, there is a button for “Run All test”, but it too only ran the last executed test. Finally, I changed the Test project to my Solution Start Project, and pressing F5 to execute will run all the tests.

Here is the code from my first stab at it:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DevelopingForDotNet.AuthorizeNet;

namespace TestAuthorizeNet
{
    ///
    /// Summary description for UnitTest1
    ///
    [TestClass]
    public class UnitTest1
    {
        public UnitTest1()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void TestCreditCardNumberWithCharactersConvertedToJustNumbers()
        {
            TransactionRequestInfo req = new TransactionRequestInfo();
            string testValue = "1234-5678-9012-3456";
            req.CardNumber = testValue;
            Assert.AreEqual("1234567890123456", req.CardNumber);
        }

        [TestMethod]
        public void TestZipCodeNotNumericThrowsArgumentException()
        {
            TransactionRequestInfo req = new TransactionRequestInfo();
            string testValue = "034JB";
            try
            {
                req.Zip = testValue;
                Assert.Fail("Exception not thrown.");
            }
            catch (ArgumentException aex)
            {
                Assert.IsTrue(true, "Exception Thrown Properly");
            }
        }

        [TestMethod]
        public void TestZipCodeNumericButGreaterThan99999()
        {
            TransactionRequestInfo req = new TransactionRequestInfo();
            string testValue = "58634789";
            try
            {
                req.Zip = testValue;
                Assert.Fail("Exception not thrown.");
            }
            catch (ArgumentException aex)
            {
                Assert.IsTrue(true, "Exception Thrown Properly");
            }
        }

        [TestMethod]
        public void TestZipCodeValidReturnsLeadingZeros()
        {
            TransactionRequestInfo req = new TransactionRequestInfo();
            string testValue = "586";
            req.Zip = testValue;
            Assert.AreEqual("00586", req.Zip);
        }
    }
}

A few notes worth mentioning:

  1. I found a bunch of sites that talked about Testing in Visual Studio, about half and half claiming it was a good thing. What I did not find so readily was a good tutorial. I did finally come across a good post at http://www.geekzone.co.nz/vs2008/4819, a blog I had never visited before.
  2. What I have done so far would certainly not qualify as TDD, I’m just experimenting at this phase. I did, however, try to write tests that failed before correcting them to pass, but they were all on pre-existing methods.
  3. I tried to follow the “use long, descriptive test method names” rule.
  4. I need to understand mocking. Right now, I am creating full fledged class instances.
  5. It seems a tad slow. I can’t imagine what this would be like with hundreds of tests to run. I’m sure there are ways to handle this issue.

My plan is to include the test Project along with the entire Authorize.Net Solution. Whether it will be helpful or not, I don’t really know.

Visual Studio 2008 Setup Project Frustrations

March 4, 2008 28 comments

I have not needed to create a Setup project since installing VS2008, but this afternoon I needed to share a utility program with a coworker friend of mine (who is not technical), so I opened the solution and added a Setup and Deployment project. Everything seemed to be fine. I added the primary output of my application’s project and adjusted the company name and product name properties, as well as some other settings, just like I used to do in VS2005.

The problem occurred when I wanted to create Start Menu and Desktop shortcuts for the application. In VS2005, double clicking the Application Folder would show you the list of DLLs, EXEs, and other files that would be installed. You could right-click the main project output file and create a shortcut to the program, which could then be copied to the User’s Desktop and User’s Program Menu directories. And you could also add icons and assign them to the shortcuts.

This was what I wanted to do in VS2008, but double clicking on the folders in File System does nothing. As a result, you cannot select the output file as instructed in the MSDN documentation. This is very frustrating: the Setup and Deployment project has always worked well for me (these are internal distribution installers), but now with VS2008 it no longer appears to function properly. The resulting MSI did work and did install the software, but without an icon and without shortcuts in the desired locations.

If you know the solution for this, please leave a comment. If I find a solution to this, I’ll be sure to share it. For now, all I can do is share the pain.

Event Handling made even easier

November 29, 2007 1 comment

Event Handling Made Easy is my favorite post I’ve written. Mostly, because I’m lazy and I have a bad memory. I love events, but I find it difficult to remember all the bits and pieces in my head, so I wrote the post to give me some documentation.

NOTE: the following feature is NOT new: it has been available since .NET 2.0, but I learned about it while examining the new features in 2008.

I recently came across the EventHandler<T> generic delegate. In this case, T represents any EventArgs object, so when you create your custom EventArgs class just make sure that you inherit from EventArgs. Now, when you register the Event Handler with the object, you reference EventHandler<T> instead of your custom event name:

// registering EventHandler<T>
person.MaritalStatusChangedEvent +=new EventHandler<MaritalStatusChangedEventArgs<(person_MaritalStatusChangedEvent);

This approach buys us a couple of things. First, it means you no longer need to declare a public delegate to define the EventHandler signature. Instead, in your class, you simply declare a public EventHandler<CustomEventArgs> CustomEventName. I don’t know about you, but anytime I can avoid using “delegate” I get a smile on my face! Also, it means that event registration code is a little more standardized, and is syntactically a little nicer.

So here is the whole process, revisited and updated:

Step 1: Create our custom EventArgs class. Be sure it inherits from EventArgs.

class MaritalStatusChangedEventArgs : EventArgs
{
    public readonly string Message;
    public MaritalStatusChangedEventArgs(string message)
    {
        Message = message;
    }
}

Step 2: Define the EventHandler<T> in the firing class.

// Generic EventHandle<T> delegate definition
public event EventHandler<MaritalStatusChangedEventArgs> MaritalStatusChangedEvent;

Step 3: Fire the Event.

// No change here
if (MaritalStatusChangedEvent != null)
{
    MaritalStatusChangedEvent(this, new MaritalStatusChangedEventArgs("Marital Status is now " + _maritalStatus));
}

Step 4: Register the EventHandler<T> listener.

// Use the EventHandler<T> format when registering
person.MaritalStatusChangedEvent +=new EventHandler<MaritalStatusChangedEventArgs>(person_MaritalStatusChangedEvent);

When you register the Event listener, Visual Studio will help out by offering to stub out the listening method. Just hit tab when prompted and it will insert the method stub for you and place your cursor inside the method. Naturally, it throws our old friend NotImplementedException. This is a nice little addition that means less coding for you!

Categories: .NET 2.0, C# 2.0, Visual Studio

Visual Studio 2008 Class Diagram

November 29, 2007 12 comments

I’ll be returning to my series on “Upgrading your C# skills” next week. For now, though, I wanted to share with you a cool new option in VS2008: Class Diagrams.

Class Diagrams

A Class Diagram is a new file type that allows you to visually create, edit, and manage Classes, Structs, Enums, Interfaces, Delegates, and more. It is a quick and easy way to add Property and Method stubs to existing Classes or to create entire class shells. You can even manage Events and Fields. The interface is immediately familiar and intuitive. Diagrams can even be exported to Images.

To begin, open a project in Visual Studio and follow these steps:

  • In the Solution Explorer window, right click the project and select “Add -> New Item”.
  • From the Add New Item dialog box, highlight “Class Diagram” and give it a name.
  • Press the Add button. The Class Diagram file will be added to your project and the designer will open.

You will now have a Blank Diagram to work with in the designer. To add an existing class to the diagram, simply drag and drop it from the Solution Explorer window onto the design surface. To create a new Class (or Struct, Enum, etc.), right click in the designer and expand the “Add ->” menu item. Select the appropriate type and follow the instructions. Easy as pie.

Once you have an item in the designer, it will look something like this (Click on Screen Shot for Full Size):

Class Diagram Screenshot

I moved the Class Details window to the right, but the default will have it on the bottom. Just like working with a Control in a Form, you will need to select the class in the designer window in order for its details to show in the Class Detail window. And you can have multiple classes in a diagram.

When you create a new item, you will be prompted to either create a new file or append to an existing file. As you can see, the Class Detail window allows you to easily add Methods, Properties, Fields, and Events to a class. You can edit the Name of an element, the Type, the Access Modifier, and the Summary. The Summary column is the XML Comments description: if you leave it blank, then there will be no XML comments at all. If you supply a Summary, it will be added to the source code. You can also elect to “Hide” an element, which only means that it will be not listed in the Class Diagram itself.

So let’s talk about what code the IDE generates from this designer. Consider the Person class listed above: this class already existed and was dropped into the Class Diagram designer. I then added the DOB, MaritalStatus, and IsMilitaryVeteran properties using the Class Detail window. Now the code looks like this:

class Person
{
    public Person()
    {

    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    /// 
    /// Date Of Birth
    /// 
    public string DOB
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Marital Status Code
    /// 
    public char MaritalStatus
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Exposes whether or not this Person ever served in the Armed Forces
    /// 
    public bool IsMilitaryVeteran
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }
}

The properties were created, but not as I would have expected. I would have expected these to be default Automatic Property stubs. Instead, they are classic property stubs, and the getter throws a NotImplementedException. The good news is that this will compile as is. The bad news is that it is surely not the behavior you want, so you will have to do some work to implement the details. And you cannot simply remove the NotImplementedException because the getter must have a return path. Of course, a simple copy and paste can quickly convert these to Automatic Properties, but it is unfortunate that this isn’t the default behavior.

Which brings up another good point: the Property is created, but with no corresponding variable, and yet it still compiles. This tells me that the Automatic Property mechanism is still in play here, but it causes a problem when you go to implement the details: there is no variable to return, so you must create one. A pretty minor point, but worth noting none-the-less. And again, I think this issue could have been avoided if the standard Automatic Property stub had been implemented (or at least optional).

So let’s make this a little more robust and add some other goodies. First, since I have to implement the details anyway, I’m going to add fields to support my new properties. Next, I’m going to add a GetFullName method, and I’m going to override the ToString method. Finally, I’m going to add a MaritalStatusChangedEvent Event Handler. Now let’s look at the results:

class Person
{
    private string _dob;
    private bool _isMilitaryVeteran;
    private char _maritalStatus;

    public event EventHandler MaritalStatusChangedEvent;

    public Person()
    {

    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    /// 
    /// Date Of Birth
    /// 
    public string DOB
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Marital Status Code
    /// 
    public char MaritalStatus
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Exposes whether or not this Person ever served in the Armed Forces
    /// 
    public bool IsMilitaryVeteran
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Retrieves the Full Name of the Person formatted as "Last, First".
    /// 
    public string GetFullName()
    {
        throw new System.NotImplementedException();
    }

    public string ToString()
    {
        throw new System.NotImplementedException();
    }
}

Much as expected, the fields are simple fields, the Event is declared, and the methods are stubbed but all throw a NotImplementedException. This all compiles right out of the box, but if you want to really override ToString(), you’ll need to add the keyword yourself. Again, it would be nice if the tool detected that for you and prompted you to select the desired behavior, but it is not that big of a deal.

Finally, the Class Diagram tool has some options. When you open one, VS2008 will include a new Menu and a new Toolbar. Explore these options a little and you’ll find some other helpful items. In this last screen shot, representing the completed class above, I have elected to show full signature detail in the Designer. (Click on Screen Shot for Full Size).

Class Diagram Screenshot

So I encourage you to explore this feature. For rapid stubbing, I think you’ll find this a very handy and useful tool.

Categories: Visual Studio

Changing Visual Studio Shortcuts

November 29, 2007 7 comments

OK, so I’ve been playing with VS2008 for a few days now, and I had a minor annoyance. At first, I was inclined to blame the designers, but it turns out it was my own fault, or rather, my own lack of knowledge.

My complaint was that in VS2005, “F6″ is the Shortcut Key for “Build Solution”, but in VS2008 it had been returned to “Ctrl+Shift+B” (like VS2003). At first, I was upset by this, but I did a little digging and was chagrined to find that my VS2005 Keyboard Settings had been changed from “Default” to “Visual C# 2005″. I checked in VS2008, and sure enough when I changed the Mapping Scheme to “Visual C# 2005″, my beloved F6 had been restored. There are several options here (none of which is C# 2008).

In the process, I also found that you can set these Shortcuts yourself. If you do not want to switch, but instead wish to customize the Default settings (which can always be restored later), follow these steps:

  1. Go to Tools -> Options -> Keyboard.
  2. In “Show Commands Containing”, type “Window.NextSplitPane” (this is what F6 points to now – I found this out by first by skipping all the other steps and going directly to #8 below).
  3. The Current Shortcut “F6″ for “Window.NextSplitPane” will be shown in the “Shortcuts for Selected Command Box”.
  4. Press the “Remove” button.
  5. Go back to the “Show Commands Containing” and type “Build Solution”.
  6. The Current Shortcut “Ctrl+Shift+B” for “Build.BuildSolution” will be shown in the “Shortcuts for Selected Command Box”.
  7. You do NOT need to Remove this, but you can if you wish. To do so, press the “Remove” button again.
  8. Put your cursor in the “Press shortcutkeys” textbox and press the “F6″ function key.
  9. Press the “Assign” button.
  10. Press the “OK” button to save your changes.

Changes to the Keyboard Mapping Scheme should show immediately in the IDE. You can have multiple shortcuts for a given function, but naturally a shortcut can only be assigned once.

Now, obviously, I had changed the Keyboard Mapping Scheme in VS2005, I just don’t remember doing it. Visual Studio is just such an incredible tool with so many options: I’ll bet that most of us don’t know the half of it. And something like this you may do once, to tweak your setup, and then never think about again. At any rate, I hope this helps someone out there.

Categories: Visual Studio
Follow

Get every new post delivered to your Inbox.