Visual Studio Tips 4

OK, so this is another round of tips on using Visual Studio! See first collection here, second here and third here.

  1. Create shortcuts: you can create shortcuts to frequently used code. Just click <Ctrl>KH on any line, and you will add a shortcut to it:

    image
    After that, you can jump to any of your bookmarks from the Task view:
    image
    To remove it, click <Ctrl>KH again in the same line. Note that this is not the same as the bookmarks featured introduced in the third set of tips!
  2. Code Maps: this requires Visual Studio Enterprise. Open the Architecture menu and select Generate Code Map for Solution.

    image
    You will get a nice diagram showing all dependencies between assemblies in your project:
    image
  3. Code Metrics: get a static analysis report of your project, only in Enterprise edition. In the Solution Explorer, right click on your project, Analyze, and select Calculate Code Metrics.

    You get an analysis including metrics Maintainability Index, Cyclomatic Complexity, Depth of Inheritance, Class Coupling and Lines of Code, which you can even export to Excel:
    image
  4. Format document on save & remove unused and sort using statements on save: Visual Studio can take care of formatting your documents and removing any unnecessary using declarations for you, when you save your documents; you just need to install the Productivity Power Tools extension and enable these options in ToolsProductivity Power ToolsPowerCommands:
    image
  5. Thread Deadlocks: Visual Studio can show you thread deadlocks while debugging. When debugging a multithreaded app, break it and open DebugWindowsTasks:
    image
    From here, you can flag your code so that it is more clearly visible.
  6. Executing code in Immediate Window: the Immediate Window can be used to run .NET code. While debugging your app, pause it, and select DebugWindowsImmediate:

    image
    You can enter any .NET expressions and variables or even complex expressions and see them evaluated at once.
  7. Pin and export Data Tips: while debugging, break and hover any variable or field in your code. Click the pin icon on the right of the tooltip window. This will create a Data Tip.
    image
    You can have multiple Data Tips, add comments to them:
    image
    Also save Data Tips to files so that they can be loaded in another Visual Studio session, and, of course, load a collection of Data Tips:
    image
  8. Place reusable code in Toolbox: you can add code that you use frequently to the Toolbox. Pin your Toolbox window, highlight your code and drag it to the Toolbox. Even if you are not working in a visual app, the code snippet can be dragged from the Toolbox into your code:
    image
  9. Change C# language version: Visual Studio can use any of the C# versions. For example you may or may not want to use the latest (and greatest, by the way!) features of C# 6. All you have to do is right click on a project, Properties, Build and Advanced. In the Advanced Build Settings window, Language Version, select the one you want to support:
    image
  10. Find tips: some tips related to the Find functionality. First, you have two results windows, 1 and 2, and you can have your search results appear in any of them:
    image
    With this, you can also append to current results or show only the file names that match the search pattern.

Unit Testing .NET Core

Introduction

With the recent arrival of .NET Core, some things that we were used to having are no longer available. This includes unit tests – plus Visual Studio integration – and mocking frameworks. Fortunately, they are now becoming available, even if, in some cases, in pre-release form.

In this post, I will cover:

  • Unit testing frameworks
  • Mocking libraries
  • Validation libraries

I won’t explore everything that exists, just present a simple setup that works well for .NET Core.

Unit Testing

So, you want to do unit testing? There are a couple of frameworks for that purpose that work with .NET Core, which include:

MS Test is Microsoft’s own unit testing library, I’d say a much hated one because of its historical tie to Visual Studio. This was the last one that was announced for .NET Core and it’s still not in release form.

They more or less work the same way, so let’s see how to use xUnit, my favorite one So, you need to add two Nuget packages:

  • xunit: this is the actual library that you will be using
  • dotnet-test-xunit: this is the runner and integration with Visual Studio

I sometimes have a base class for tests, which takes care of loading configuration and initializing stuff, but let’s leave that aside. A unit test class for xUnit looks like this:

using Xunit;

public class MyTests
{
[Fact]
public void Test()
{
}
}

Now, you need to configure the runner so that you can run tests in Visual Studio. Using project.json, it goes like this:

{
"version": "1.0.0-*",
"testRunner": "xunit",
"buildOptions": {
"emitEntryPoint": false,
"copyToOutput": ["appsettings.json"]
},

"dependencies": {
"dotnet-test-xunit": "2.2.0-preview2-build1029",
"Microsoft.Extensions.Configuration": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.PlatformAbstractions": "1.0.0",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
},
"xunit": "2.2.0-beta2-build3300"
},

"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}

Notice that I am copying to the output folder the appsettings.json file, I am not going to talk about it, but let’s just say that it has some configuration that my tests will use, and it needs to be on the same file as the unit tests assembly.

With the Visual Studio integration working, we get this:

image

So we can run and debug our tests directly from here. Nice to have coherent behavior for all unit test frameworks!

Mocking

As for mocking, there are also some mocking frameworks that work with .NET Core:

I’ll pick Moq for this exercise. Just add the Moq package to your project. Here’s how to do simple mocking of an interface:

using Xunit;
using Moq;

[Fact]
public void Test()
{
var mock = new Mock<IService>();
mock
.Setup(x => x.Get())
.Returns("Hi there!");

var svc = mock.Object;

var result = svc.Get();

Assert.NotNull(result);

Assert.Equal("Hi there!", result);
}

Exactly the same as you’d do in a classic .NET unit test using mocking.

Validation

As for validations, I know of two libraries that work with .NET Core:

I’ll pick FluentAssertions. Here’s a simple example, for the same test:

using FluentAssertions;
using Moq;
using Xunit;

[Fact]
public void Test()
{
var mock = new Mock<IService>();
mock
.Setup(x => x.Get())
.Returns("Hi there!");

var svc = mock.Object;

var result = svc.Get();

result
.Should()
.BeOfType<string>()
.And
.Be("Hi there!");
}

Again, this should be familiar to everyone.

Conclusion

So, it’s no longer unit tests holding us back from .NET Core! Most of what is done today in classic .NET can be done in Core by now. There are still some more complex libraries, for interception, mapping, serialization, etc, that are not quite there yet, but I expect these to come with time.

Visual Studio Tips 3

Next round of Visual Studio tips! 10 more for you! Here you can find the first and the second posts.

  1. Change solution version: you can change the Visual Studio solution version by opening the .SLN file and changing its header:


    Microsoft Visual Studio Solution File, Format Version 12.00
    VisualStudioVersion = 12.0.30110.0

    =Visual Studio 2013

    Microsoft Visual Studio Solution File, Format Version 12.00
    VisualStudioVersion = 14.0.23107.0

    =Visual Studio 2015

  2. Even if you didn’t declare a variable for the exception in a catch block, you can still see it by adding the special keyword $exception to the watch window:

    image
  3. Scroll bar options: the vertical scroll bar can show hints for a number of different things, or even display a map of the lines in its window. You can choose what it should be used for by right clicking on the scroll bar and clicking on either bar mode or map mode and selecting changes, marks, errors, etc:

    image
  4. Show line numbers: besides having version numbers on the status bar, you can also have them on the left; go to ToolsOptionsText Editor All Languages and select Line Numbers:
    image
  5. Move lines up or down: you can move an entire line up or down; just click on it and press <Alt>-<Up> or <Alt>-<Down>; you can also duplicate it with <Ctrl><C> + <Ctrl><V>, no need to actually select it all;
  6. Add search box to the toolbar: on the standard toolbar, click the button with the triangle pointing down, then select Add or Remove Buttons:

    imageand then choose Find; you will get a search box for your source code:
    image
  7. Open multiple browsers at once: you can open your page in different browsers at the same time, automatically, upon starting (<F5>) or debugging (<Ctrl><F5>); just select the down arrow next to the browser selection
    Browse WithThen select Browse With:
    Default Selected Browser

    And select several at once:
    Multiple Default Browser
  8. Change CodeLens options: right clicking on CodeLens will bring the options dialog:
    imagefrom which you can change what to display:
    image
  9. Change variable value from the debugger: if you have a variable, settable property, field or parameter in the watch window, you can change its value by clicking on the right column and entering an appropriate expression:

    image
  10. Add bookmarks: you can easily add bookmarks to lines of code by clicking <Ctrl>+<K>; to remove a bookmark, click <Ctrl>+<K> on the bookmarked line of code; <Ctrl>+<K> followed by <Ctrl>+<N> will navigate to the next bookmark and <Ctrl>+<K> followed by <Ctrl>+<P> to the previous one; adding the <Shift> key to <P> or <N> will do the same, but inside a solution folder.

And that’s all for now. Stay tuned for more!

SharePoint Pitfalls: Creating a Visual Studio Project Without SharePoint Locally Installed

This is the first on a (huge) collection of posts on SharePoint pitfalls. Hope you enjoy, and, please, do send me your feedback!

If you do not have SharePoint locally installed, Visual Studio will not let you create a SharePoint project:

sp-not-installed

Fortunately, it is easy to go around this in two simple steps:

  1. RegistryIn the Registry, add the following key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\15.0\SharePoint

    In it, add two string values: Location=C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ and SharePoint=Installed

  2. Global Assembly CacheCopy the following assemblies from a machine where SharePoint is installed (C:\Windows\Microsoft.NET\Assembly\GAC_32) into your development machine and add them to the GAC (gacutil):
    • Microsoft.SharePoint.dll
    • Microsoft.SharePoint.Client.dll
    • Microsoft.SharePoint.Client.Publishing.dll
    • Microsoft.SharePoint.Client.Runtime.dll
    • Microsoft.SharePoint.Client.ServerRuntime.dll
    • Microsoft.SharePoint.Library.dll
    • Microsoft.SharePoint.Linq.dll
    • Microsoft.SharePoint.Portal.dll
    • Microsoft.SharePoint.Publishing.dll

    Of course, you may need others as well.

Enjoy!

Visual Studio Tips 2

Update: see the third post here.

OK, continuing with my previous post, here are some more Visual Studio tips, this time, with a lot more pictures! Winking smile

  1. Start several projects simultaneously: when it comes to starting a project in a solution, there are three options:
    1. Start a single, fixed, project;
    2. Start the project where the focus is currently on;
    3. Start multiple projects simultaneously.

    Right click on the solution – PropertiesCommon Projects Startup Project and select Multiple startup projects:

    image

  2. Break on exceptions: Visual Studio can break automatically on first-chance exceptions (ones that may be caught afterwards). This is useful, because if you have catch blocks, you might not even notice them. First-chance exception breaking can be defined on a class per class basis. First, click on DebugExceptions:image

    Then, check the ones that you are interested in:

    image

  3. Conditional breakpoints: you can enable breakpoints based on some condition on the code. First, create a breakpoint, right click in it, then click on Condition:image

    Now you can add any condition you want, either based on local or global variables and methods – watch out for any possible side effects!

    image

    Another option is to only break when the hit count – the number of times the program has processed the instruction – has reached some value. Click on Hit Count and select the right condition, break always is the default:

    image

    Yet another option is to add a filter. This is a limited condition, which can only take a couple of variables. Activate it by clicking on Filter:

    image

  4. Tracepoints: in the Ultimate edition of Visual Studio (sorry, folks that to not have it!) you can send output to the trace window without actually writing any code. How many times did you add a Trace.WriteLine call, or something similar, for this purpose? Create a breakpoint, then click When Hit:image

    Now, add an output string, which can take variables, parameters or properties, plus some special tokens:

    image

    image

  5. Showing or hiding items from Output window: while debugging your application, the Output windows tends to be cluttered with all sorts of messages. Well, you can hide some of them. Just right click on the Output window and check out those that you want to hide:image
  6. Add links: in a project, you can add physical files, which are copied to the project’s folder, or links, which are kept in their original locations. Select AddExisting Item, navigate to the folder containing the file you want to add, select it, but instead of clicking Add, select Add As Link from the drop down:image
  7. Save text files with different encoding: due to several reasons, you might need to save a text file with a particular encoding. When about to save the file, click the drop down in the Save button and select Save with Encoding:image

    Then select the encoding and line ending you want:

    image

  8. Preview Web.config transformations: ASP.NET Web.config Transformations were introduced in Visual Studio 2010 and allow us to perform transformations on the Web.config file based on the current configuration – Debug, Release, etc, upon deployment. The problem is, most of you don’t know it’s possible to view the result file without actually deploying the application, but it is! Right click on a transformation file, like Web.Release.config, and select Preview Transform:image
  9. Generate ASP.NET designer files: when your ASP.NET web forms designer files – like Default.Designer.aspx.cs – become corrupted, for whatever reason, it’s better to remove them and have them generated by Visual Studio. Right click on the markup file – .aspx, .master or .ascx – and click on Project – Convert to Web Application (weird choice of name, I know):image
  10. Debug MSBuild scripts: I left the best for last! It’s possible to debug .csproj build tasks, which are basically MSBuild tasks. I won’t cover it all here, but instead make sure you read this post by Dan Moseleyhttp://blogs.msdn.com/b/visualstudio/archive/2010/07/06/debugging-msbuild-script-with-visual-studio.aspx.

I will be back! Winking smile

Visual Studio Tips

Update: see the second post here and the third here.

Some random tips:

  1. If you need to run a web site under a different domain, so as to test multitenancy, for example, you need to run Visual Studio as an Administrator, otherwise you will get an error about an invalid hostname;
  2. If you want, you can configure Visual Studio to always start as Administrator: set the compatibility options to require additional permissions, see more here;
  3. You can have the Solution Explorer track (select automatically) the file you are editing; just select option ToolsOptionsTrack Active Item in Projects and Solutions;
  4. In case you need to find some class that you don’t know where is located, or you only know a part of its name, use the EditNavigate To option or click <Ctrl>+<comma>;
  5. Split the editor window: select WindowSplit; to close it, unselect it;
  6. You can now move a window to another monitor;
  7. Select columns across lines: click <Alt> while you make a vertical selection using the mouse or cursor keys; you can then copy the selection or paste some code into it;
  8. With <Alt>+<Up> or <Alt>+<Down>, you can switch the order of lines;
  9. Paste your JSON or XML code as classes: select EditPaste SpecialPaste JSON as Classes/Paste XML as Classes;
  10. You can see the classes that inherit from some of your project’s class: just select the file containing it in Solution Explorer, expand the selection to find the class, and then expand the class; you will find an option Derived Types.

And that’s it for now. More will follow!