Tuesday, February 18, 2014

What’s new in Visual Studio 2013: IDE Features

This time the entry is again in English, as this is already part 2 and there is more to come!
You find the PDF version: here
The sample project: here

Introduction

The new IDE features in Visual Studio 2013 are quite nice and make our beloved IDE again better. Below you will find examples how you configure and use these new features in a day to day (developer) business.


Requirements

To follow the samples below, you need a working installation of Visual Studio 2013 on your machine (any edition will do).

Setup

Setup a sample project or download the final sample from: here
Create a new Console Application
  • Name: NewIDEFeatures
  • Location: C:\VS2013New
  • Click: OK
clip_image002
Add a new class to the project
· Name: Calcs
· Add the code below to the class (yes, the missing colon and the wrong return type is intentional)

namespace VSEnhancements
{
    public class Calcs
    {
        public static int AddNumbers(int number1, int number2)
        {
 
            return number1 - number2
        }
        public static long AddNumbers(long number1, long number2)
        {
            return number1 - number2;
        }
    }
}

Add the code below to the Main method (missing colon and wrong method calls are intentional).
namespace VSEnhancements
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = Calcs.AddNumbers(5, 7)
            Console.ReadKey(true);
            Console.WriteLine(result);
        }
    }
}

Auto complete brackets

As you might have figured out during the sample project setup, if you type some kind of bracket in Visual Studio 2013, you will see that the editor now auto closes these brackets. This feature is available in all code or markup editors.

Switch color schemes

Select the color scheme of your choice for your Visual Studio 2013 IDE.
· Goto: Tools -> Options -> Environment -> General and select the theme of your choice
clip_image004

Quick Launch Box

Visual Studio offers many configuration options and no one can really remember where to find which option, but you might remember the search term, so for example ‘color’ to change the Visual Studio theme, or ‚line numbers‘ to enable the line numbers in code files. This is where the quick launch box comes in handy. Quick Launch search results appear in four categories: Most Recently Used, Menus, Options, and Open Documents, along with the number of items in the category. Let’s try it.

· Press CTRL+Q
· Enter: Color (shows color scheme)
=> click on the result, this will bring you directly to the options to configure the color
·
clip_image005
· Enter: Line numbers
=> click on the result, this will bring you directly to the options to enable line numbers in the code editor
· Enter: blank line
=> click on the result, this will bring you directly to the options to configure the “blank line” feature (which stops you from copying a blank line to the clipboard – which happens some times to me when I am too fast with my fingers).

Search Improvements

Visual studio 2013 tries to support developers much more as before, when it comes to searching and filtering items. You will find new search boxes on several new places. Let’s have a closer look at them.

Searchable error list

· Build the sample app
· You will see three errors filter the errors
· Type a ; in the search box
=> the result is filtered to the two errors clip_image007

Regular Expression Search

· Open the search dialog (type CTRL+F)
· Type C[ao] into the search box
· Enable the regular expression search
=> All script elements starting with Ca or Co are selected.
clip_image009

Solution explorer search

clip_image010

Solution Explorer Enhancements

The solution explorer was always the one window which is always visible on my screen (or my second screen). Very nice enhancements can be found here.

1. Collapse all
  clip_image011
2. Pending Changes and Open Files Filter
  clip_image012
3. Preview selected items
   clip_image013
4. Move somewhere else in sol. Explorer, move again to the .cs file
5. Pin it using the pin
6. Scope to this
clip_image015
7. Open Is Called by on AddNumbers
clip_image017

Navigating Back and Forward

Sometimes I close a code window too early, so it might be great if I could bring it back.
· Open Calcs.cs
· Close Calc.cs
· Press CTRL-
Yes, this is again a nice feature.

Pin Tabs
In every project there are a few very important classes. Man, it would be so cool if I could ‘pin’ them so they are not moving away in the open screen tab list.

· Open Calc.cs and Program.cs
· Search for pinned tabsclip_image018
· Pin one of the two code files
clip_image020

Code Editor Features

Code editing is important for a developer. Again, some small, but important enhancements can be found in this category.

1. Use ALT+CursorUp to switch the wrong lines
clip_image021
2. Uncomment lines
3. See the red line and the yellow ones for changes
4. Click on the red line
5. Fix the error (red line disappears)
6. Save the changes
7. Select for example a method and CTRL M H (hide selected code) and CTRL M U (unhide)
8. Show that TAB key hops out of brace
9. Press CTRL +,
clip_image023
10. Search for Console and have a look at the orange lines
11. Open the Scroll Bar options page (Tools, Options, Text Editor, All Languages or a specific language, or type scroll bar in the Quick Launch window) and switch mode
clip_image024
12. Now click ALT+F12 on AddNumbers
clip_image026
13. Correct the logical coding mistake (minus).

Debugger Enhancements

Remember the time, when you were able to change the code during debugging? When 64 bit apps arrived this feature was gone. Now, it’s back!

1. Check that it is a 64-bit executable
2. Set a breakpoint on var result = Calcs.AddNumbers(5,7);
3. Run the app
4. Make some change and explain that this is allowed now.
5. Step over the method call
   clip_image028
6. In the Autos window, note that the return value is displayed and include the return value icon. (To open the Autos window, choose Debug, Windows, Autos, or press Ctrl + Alt + V, A)
7. Type: $ReturnValue in the Immediate window or a watch window (Debug, Windows, Watch) after you have stepped over or out of the method call. To open the Immediate window, choose Debug, Windows, Immediate (keyboard: Ctrl + Alt + I).
8. ReturnValue does not work in phone apps
9. Try the Code Map
clip_image030

Unit testing

A friend of mine said once to me: „Everyone is talking about unit tests, but no one is actually doing them“. Well, maybe that’s true, but you might take a closer look into it, you might start using it. If you already used it and miss the right-mouse-button-click “Generate Unit Test” popup menu, I have good news for you (thank you goes to the ALM team) – you are free to bring it back.
Also, VS 2013 is now open to other unit test frameworks, that’s why I used xUnit in my sample below. If you like the built in unit test framework more, go ahead with it, it works the same way.

1. Bring back clip_image031 on RMB on a method declaration.
2. Install from Tools -> Extensions and Updates
3. clip_image033
4. Install xUnit the same way
clip_image035
5. Press RMB Create Unit test on AddNumbers
clip_image037
6. Implement the unit test
clip_image038
7. Run the unit test in the standard manner by right- clicking on them in the code
editor or from the much improved Test Explorer window (Main menu Test ->
Windows ->Test Explorer).

Fakes Framework

In Test Driven Development isolating dependencies, mocking objects and faking objects is the daily business. There are also great 3rd party frameworks out there, which allow us to isolate dependencies without having to use any hand written mocks or fakes, but we also have everything we need built into the IDE waiting for you and me to simply use it.
The Microsoft Fakes framework was introduced in Visual Studio 2012 Ultimate, but I would like to give you a quick run-down on how to use Fakes, Shims and Stubs to build a robust test harness for your own applications. To get started we need a new class, which is not so easy to test with a simple unit test.

Add customers class:
namespace VSEnhancements
{
    public interface ICustomerRepository
    {
        Customer GetById(int id);
        bool Exists(string email);
        void Delete();
    }
 
    public class Customer
    {
        public string Firstname { getset; }
        public string Lastname { getset; }
    }
 
    public class CustomerService
    {
        private readonly ICustomerRepository _repository;
 
        public CustomerService(ICustomerRepository repository)
        {
            _repository = repository;
        }
 
        public bool DoesCustomerExist(string email)
        {
            return _repository.Exists(email);
        }
    }
}

· Click RMB on DoesCustomerExist and Generate Unit Test 

Implement stubs

Stubs, ok wht is it? Let Martin Fowler explain it in his own words:

“Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.”

The built in Fakes framework has the ability to generate stubs. You might see this more as your own implementation of some kind of virtual type. You might use it to fake virtual types such as interfaces, abstract classes or virtual methods. I will use my own implementation for the ICustomerRepository interface during the unit test. As another example I will return some value from my own implementation of the Exists method. I think you will get the idea and might start thinking on how to use it in your own test environment. Let me show you the code:
//Stubs test
[Fact()]
public void DoesCustomerExistTest()
{
    var stub = new StubICustomerRepository
    {
        ExistsString = (email) => { return true; }
    };
    var service = new CustomerService(stub);
    Assert.True(service.DoesCustomerExist("test@test.com"));
}

[Fact()]
public void ClosureShouldSetValueToExpected()
{
    //this will get set inside our stub 
    string closureToTest = "";
    var stub = new StubICustomerRepository
    {
        ExistsString = (email) =>
        {
            closureToTest = "test"//in reality set to some variable you want to test 
            return true;
        }
    };
    var doesntMatter = stub.ExistsString("ignore@ignore.com");
    const string expected = "test";
    Assert.True(closureToTest == expected);
}

Implement Shims

Enabling Fakes is about creating a fake assembly that allows you to use (fake) types that replace .NET types with delegates. This is done by right clicking on the assembly and adding the fake assembly. In this sample case it is the System.dll, which wraps the mscorlib.dll that contains the DateTime object, which I would like to change to return always the 1st January of the year 2012.
After that I add a shim for the AddNumbers method to return another result (a multiplication).

· Add Fakes Assembly on System.dll in test-project
clip_image039
· Implement shim for DateTime
//Shims
[Fact()]
 
public void Should_Override_DateTime_Now()
{
    using (ShimsContext.Create())
    {
        ShimDateTime.NowGet = () => new DateTime(2012, 1, 1, 12, 00, 00); 
        Assert.True(DateTime.Now == new DateTime(2012, 1, 1, 12, 00, 00));
    }
}
· Implement shim for AddNumbers
· Open CalcsTests.cs
    [Fact()]
    public void AddNumbersTest()
    {
        const int expected = -2;
        int actual = Calcs.AddNumbers(5,7);
        Assert.Equal(expected, actual);
    }
 
    [Fact()]
    public void Should_OverrideAddNumbers()
    {
        using (ShimsContext.Create())
        {
            ShimCalcs.AddNumbersInt32Int32 = (x, y) => x*y;
 
            const int expected = -2;
            int actual = Calcs.AddNumbers(5, 7);
            Assert.Equal(35, actual);
 
        }
    }
 
}
· Run unit tests
· Just for fun check the CodeLens feature on the AddNumbers method
clip_image041 clip_image043

More Info

· Keyboard shortcuts:
http://kbmode.com/windows/microsoft-visual-studio-2013-keyboard-shortcuts/

Conclusion

The Visual Studio 2013 development team brought great new features to our beloved IDE. Keep up the good work so we can continue to produce amazing code and fascinating products with this IDE for the Microsoft platform and mobile devices!































































































































































No comments:

CSharpCodeFormatter