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!































































































































































Sunday, February 16, 2014

What’s new in Visual Studio 2013: HTML Features


This time the entry is in English, as this will be a complete series and there will also a pdf version available of every entry!
You find the PDF version of this blog entry: here

Introduction

The new HTML features in Visual Studio 2013 make life for every web developer easier. It comes with a brand new HTML Editor. It offers great new features which are described below. I would love to get some feedback from you about this document by dropping me an email to: hamboeck@soft-dat.com
And let’s start with the first tip: You might be used to the Designer and Split View in the editor. By default now static HTML files when opened in VS 2013, do not come with them, but you are free to enable them back by right clicking any HTML file -> Open With -> HTML (Web Forms) Editor > Set as Default > OK.
Requirements
To follow the samples below, you need a working installation of Visual Studio 2013 on your machine (any edition will do).

Additional Downloads

Not an absolute requirement, but a recommendation is to download and install VSWebExtensions into Visual Studio. You find the download here: http://vswebessentials.com/
Web Essentials extends Visual Studio with a lot of new features that web developers have been missing for many years. If you ever write CSS, HTML, JavaScript, TypeScript, CoffeeScript or LESS, then you will find many useful features that make your life as a developer easier.

Setup

Setup a brand new sample project using Visual Studio 2013:
Create a new ASP.Net Empty Web Application
  • Name: NewWebFeatures
  • Location: C:\VS2013New
  • Click: OK
clip_image002
Add a new HTML page and accept the default name (HtmlPage1.html)
  • Right click on the project
  • Click on: Add
  • Click on: Html Page
  • Click: OK
clip_image004
You see now a new script window with HTML5 tags
clip_image005

Auto complete brackets

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 “everywhere”, for example here in the html code, but also in scripts, markup and so on.

HTML5 Intellisense support

Select the complete text
Type: html and press tab
-> You see a html page using the Html4 doctype tag
Type: html5 and press tab
You see (again) a html page using html5 doctype tag



clip_image006clip_image008 clip_image009
clip_image011 clip_image012
After the head element type: header and press tab
->;You see the full header Html5 tag
In the line below type: aside and press tab
->You see the full aside Html5 tag
In the line below type: audio and press tab
->You see the full audio Html5 tag




clip_image013
In the line below type: &co
–>You see the intellisense support for the html special characters
clip_image014
Add a new folder to your project and rename it to images
Add an image to your project and place it in the images folder
Drag the image and drop it below the audio tag
-> You see the full image tag and the correct path to the image
Hint: this works also with css and js files in the head section


clip_image016

CSS Intellisense Support

After the title element type: style and press tab
-> You see the full style tag
Within the style tag type: a and two curly brackets {}
Within the brackets tag type: color:#
-> You see the color selector pop up.
Hint 1: If you used a color already in your style sheet, you will see them first
Hint 2: Use the small arrow on the right to bring up the color picker.



clip_image017
Before the css style closing tag type @media and press tab
-> You see the full css media tag
Before the css style closing tag type @font-face and press tab
-> You see the full font face css tag


clip_image019
Before the css style closing tag add a style for the img tag and type transform
img {
transform
}
Press the tab key
You see the color picker pop up
-> You will see the styles for all the major browsers





clip_image020
Use the rotate function to turn the image upside down by using 180deg as parameter
clip_image021
Press the enter key
-> You see the rotation method applied to all tags


clip_image022

Intellisense for AngularJS and KnockoutJS

If you are working with AngularJS and/or KnockoutJS, now in Visual Studio 2013, there is intellisense support for these libraries built into Visual Studio. For example, if you type “ng” in an html element, you will get intellisense support specific for AngularJS.

Conclusion

Visual Studio 2013 offers fantastic new features, when it comes to HTML5/JavaScript development. In my opinion, it is the best JavaScript IDE on the market. So, if you did not already: Start coding HTML5/JavaScript with Visul Studio 2013!









Saturday, February 1, 2014

DataBinding “ohne” INotifyPropertyChanged, aber mit Fody

Einleitung

Datenbindung in WPF ohne INotifyPropertyChanged, ja geht denn das? Jein, natürlich nicht. Aber ich möchte euch ein NuGet Package vorstellen, welches euch die Arbeit erheblich erleichtern kann, wenn ihr gerade eine WPF Applikation mit Datenanbindung an die GUI, vermutlich mittels MVVM, beginnen wollt. Legen wir also gleich einmal los.

Den kompletten Beispiel-Code findet ihr hier

DataBinding ohne INotifyPropertyChanged

Zuerst fügen wir eine neue Klasse Employee zu unserem Projekt hinzu, dieser geben wir 2 Properties – FirstName und LastName.

Code:
    class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Kümmern wir uns um die GUI, diese sollte so aussehen:
image

An die beiden TextBoxen wollen wir unsere Klasse Employee mittels DataBinding anbinden.
Der XAML Code sieht so aus:
  <Grid>
        <TextBox Text="{Binding FirstName}" 
            HorizontalAlignment="Left" Height="23" Margin="62,43,0,0"  
VerticalAlignment
="Top" Width="120"/>
        <TextBox Text="{Binding LastName}" 
            HorizontalAlignment="Left" Height="23" Margin="62,104,0,0" 
VerticalAlignment
="Top" Width="120"/>
        <Label Content="FirstName" HorizontalAlignment="Left" Margin="62,10,0,0" 
VerticalAlignment
="Top"/>
        <Label Content="LastName" HorizontalAlignment="Left" Margin="62,73,0,0" 
VerticalAlignment
="Top"/>
        <Button Content="OK" HorizontalAlignment="Left" Margin="62,156,0,0" 
           VerticalAlignment="Top" Width="120" Click="Button_Click"/>
    </Grid>

Nun wollen wir noch eine neue (leere) Instanz der Klasse Employee an unser Fenster binden und im Click Event wollen wir die Werte anpassen und in einer MessageBox ausgeben. Im Idealfall sehen wir den neuen Vornamen und den neuen Nachnamen in der MessageBox UND in den TextBoxen (das wäre ja der Sinn der Datenbindung).


Code:
    public partial class MainWindow : Window
{
Employee employee;

public MainWindow()
{
InitializeComponent();

employee = new Employee();
this.DataContext = employee;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
employee.FirstName = "Berndt";
employee.LastName = "Hamboeck";

MessageBox.Show(string.Format("{0} {1}",
                employee.FirstName, employee.LastName), "Employee Info",
MessageBoxButton.OK, MessageBoxImage.Information);
}
}

Wenn wir unser Projekt laufen lassen, so können wir sehr schön erkennen, dass die Werte zwar in der Meldung ausgegeben werden, den Weg aber nicht zu den TextBoxen finden.
image
Ganz klar, werden einige von euch nun denken, kann ja nicht funktionieren, da wir ja noch INotifyPropertyChanged implementieren müssen.
Stimmt, aber genau das wollen wir uns ersparen und werden ein NuGet Package, mit dem Namen PropertyChanged.Fody zu unserem Projekt hinzufügen.

DataBinding mit PropertyChanged.Fody

Öffnen wir also das NuGet Fenster in Visual Studio 2013 und fügen dieses Package hinzu.
image
In dem neuen Fenster sucht Ihr am Besten nach Fody und wählt dann das PropertyChanged.Fody Paket zur Installation aus:
image
Alternativ könnt Ihr das Package auch über die Nuget Packet Manager Console installieren, diese findet Ihr im Menüpunkt Tools.
image
Dort gebt Ihr folgenden Befehl in der Konsole ein:
Install-Package PropertyChanged.Fody

Wie immer Ihr euch entscheidet, das Resultat sollte sein, dass Ihr die Referenz in eurem Projekt wieder findet:
image
Nun müssen wir noch die Annotation [ImplementPropertyChanged] zu unserer Klasse hinzufügen und uns den NameSpace holen.
image

Das Endresultat sieht in der Employee-Klasse dann so aus:



Code:
using PropertyChanged;

namespace FodySample
{
[ImplementPropertyChanged]
class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Jetzt lassen wir die Applikation noch einmal laufen, und wir sehen, dass die veränderten Werte nun auch in den TextBoxen zu sehen sind.
image
Wenn wir uns den kompilierten Code ansehen, dann können wir erkennen, dass Fody uns einfach nur die Arbeit abnimmt und zwar während der Kompilierung unseres Projektes. Der generierte Code sieht so aus:
Code:
namespace FodySample
{
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;

internal class Employee : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

public string FirstName
{
[CompilerGenerated]
get
{
return this.<FirstName>k__BackingField;
}
[CompilerGenerated]
set
{
if (!string.Equals(this.<FirstName>k__BackingField, value, StringComparison.Ordinal))
{
this.<FirstName>k__BackingField = value;
this.OnPropertyChanged("FirstName");
}
}
}

public string LastName
{
[CompilerGenerated]
get
{
return this.<LastName>k__BackingField;
}
[CompilerGenerated]
set
{
if (!string.Equals(this.<LastName>k__BackingField, value, StringComparison.Ordinal))
{
this.<LastName>k__BackingField = value;
this.OnPropertyChanged("LastName");
}
}
}
}
}


Zusammenfassung

WPF und Datenanbindung und MVVM ist eine tolle Art Applikationen zu entwickeln. Das funktioniert out-of-the-box schon sehr gut, aber das Fody Package kann uns doch einiges an Arbeit abnehmen. Somit bleibt mehr Zeit für die eigentlich wichtigen Dinge in einem Software-Projekt: Das Projekt muss fertig werden und die Wünsche der Anwender möglichst gut abbilden, ohne dass wir Entwickler mit der Technologie zu kämpfen haben.

CSharpCodeFormatter