Unit testing with xUnit in .NET Core

This post is about Unit testing with xUnit in .NET Core. The last few weeks I was working on a new  project in .NET Core. What I didn’t expected was that so many features weren’t documented or very bad documented. Many articles of Microsoft explained a different solution for the same result. I understand the framework is changing but the documentation should be changing as well then.

So I started unit testing with xUnit. I like the framework a lot so I hoped everything was working in the latest version of .NET Core. What I wanted to achieve was to create of course unit tests but also good integration in Visual Studio and TFS. That was not so easy as I hoped for. It took me a lot of searching and combining of solution to get everything working. Just because of the poor documentation. If you see the result to get this to work then it looks to easy.

First, which version of all the tools and Frameworks did I use:

  • Visual Studio 2017 Enterprise 15.2 (26430.12)
  • ReSharper 2017.1.2
  • dotnet version 1.0.4 (dotnet –version in command prompt)
  • Team Foundation Server 2017 Update 1

When I used the xUnit Nuget package I got with little effort the tests working in Visual Studio. But I wanted more. Because I’m CI/CD engineer, I wanted some automated builds in Team Foundation Server. So I created a new CI build for my project. I couldn’t get everything to work with the tasks that where in TFS so I used the command prompt task. I found this post from xUnit for testing in .NET Core that got me pointing in the right direction.

I installed the following Nuget packages in my project:

<ItemGroup>
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
  <PackageReference Include="xunit" Version="2.3.0-beta2-build3683" />
  <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
  <DotNetCliToolReference Include="dotnet-xunit" Version="2.3.0-beta2-build3683" />
</ItemGroup>

This gave me access to the new xunit CLI. I also installed the VS runner package so you could also run the unittests with the “Test Explorer” window in Visual Studio.

Now I could finish my CI Build definition. I removed all the tasks because in every combination that I tried I couldn’t get a part to work. I still wanted, to build the project, run the test, see the results back in Visual Studio and in TFS. As a bonus I wanted to see the Code Coverage of the tests in TFS as well.

First restore all external dependencies:

Then build the project:

Run the tests:


The trick is to use the right configuration and to export the result to an xml file. Place that file in the “$(Build.ArtifactStagingDirectory)” so we can use it in the next step. We already build the solution so add the “-nobuild” option.

Upload the test results:

The Code Coverage was not possible because that is still under development by Microsoft for the .NET Core framework. In the next version of Visual Studio will this be possible. You can already test it in the Visual Studio 2017 15.3 preview version. See this thread on Github for more information.

The result is:

Web API load testing with Visual Studio webtest

This is the first post about load testing with Visual Studio webtest. This series of posts is describing load testing on a Visual Studio Web API.

This first post is about setting up the Visual Studio webtest for the demo Web API project with Visual Studio 2015. We’re using the latest version of the .NET Framework so we can use all the latest cool stuff in our code.

Setup the project

  1. Create a new WebApi project and don’t forget to set the .NET Framework version to 4.6. Remember, I use the new Visual Studio 2015 RTM version.
  2. Create a new class library and call it “Extensions”.
  3. In the Extensions project, add a reference to “Microsoft.VisualStudio.QualityTools.WebTestFramework”. This project is for creating custom extension for Visual Studio webtests.
  4. Add again a new project. Choose a “Web Performance and Load test Project” project. I called mine “WebApiTest”.
  5. Add a reference from the test project to the Extensions project so we can use the extensions in the webtests.

So, the first thing is done. Setting up the project is the easy part. Now comes the testing part.

When you created the test project, a new empty webtest is created. We are now going to change the request so we can test it.

  1. Rename the webtest to ValuesTest because we are going to test the ValuesController of the Web Api project.
  2. Right click your ValuesTest and add a “Web Service Request”. Change the url to “http://localhost:26159/api/values” (your portnumber can be different).
  3. Change the method from POST to GET.
  4. Run your test and you will get a 401 unauthorized request back.
  5. Remove the Authorize attribute on the ValuesController
  6. Run the webtest again and now you will get a status 200 with as response “Binary Data”. This is off course your JSON response message.

Now we have to validate your response message because we don’t know if your test is sending the correct message.

  1. Right click your web request and select “Add Validation Rule”.
  2. A window appears. Select the “Find text” validation rule.
    Webstest add validation rule
  3. Enter in the “Find text” property the value “value3”.
  4. Run your test and your test will fail on the validation rule.
    Find text validation rule value3 failed
  5. Change the “Find text” property to “value2”.
  6. Run the test again and now your test will be valid.
    Find text validation rule value2 passed

Ok. The foundation is done for the testing part. We have a test project and a source project that must be validated. The extensions part isn’t used yet. This will be done in the next part. In that part we are going to create a more detailed ValidationRule that really understand JSON reponses. Then we don’t have to “find text” in the reponse but we can search for a property that we want to validate.

Custom domain url in IIS Express with Visual Studio 2013

If your creating a web application in Visual Studio 2013 (VS2013) and run it, your site is hosted in IIS express. Your url is localhost with a random portnumber.

If you want integration with Facebook, other services or just want a custom domain in your browser then you can follow these steps.

  1. Go to the properties of your (MVC) web application
  2. Go to the web tab on the left
  3. Under Servers check the Override application root URL and fill in http://YourSubDomain.YourDomain.com
  4. Hit Create Virutal Directory
  5. Change the start url above under Start Action to http://YourSubDomain.YourDomain.com
  6. Go to your IIS Express settings under C:\Users\Ralph\Documents\IISExpress\config and open the applicationhost.config file.
  7. Find your site and adjust the binding<bindings>
    <binding protocol=”http” bindingInformation=”*:80:YourSubDomain.YourDomain.com” />
    </bindings>
  8. Optionally add the binding for https (443)
  9. Go to your host file under C:\Windows\System32\drivers\etc and add 127.0.0.1 YourSubDomain.YourDomain.com
  10. Run your site

If you get an error. Try to run your Visual Studio instance as Administrator.

Use Config Transforms when Debugging your web application

Config Transforms are a great way to adjust your publish strategy. You just right click your web.config file and click “Add Config Transforms”. In that way you get the transform files of your configuration options.

In our company, we are working with a website that has multiple versions for different customers. So it is the same website only the config is changed. The config includes all kind of security settings. When we are developing we want to use the config of the specific “brand” of the website. How to accomplish this without?

SlowCheetah is a nice extension for visual studio that gives that option for WinForms projects but not (yet) for Web Applications. See the issue for this feature:
https://github.com/sayedihashimi/slow-cheetah/issues/39

 

For now I found this solution:

  1. Create your transforms as you want.
  2. Create a new config file with the name web.template.config
  3. Copy everything from your web.config file to the new web.template.config
  4. Create new config files for temp for your transforms. So if you have the transforms Debug and Release, you should create temp files for them. Call them web.dev.{Configuration}.config. So this would be web.dev.debug.config and web.dev.release.config. Place the config files in the root of your project just like your standard web.config.
  5. Copy everything from your transform files to the temp files.
  6. Add a target file to the root of your project location. Don’t do this in Visual Studio but just in Windows Explorer. Give it the following name: {Projectname}.wpp.targets
  7. Past the code beneath in the targets file.
  8. Delete your “old” web.config in Windows Explorer (not in Visual Studio)
  9. Restart Visual Studio and open your project. The solution explorer says now that you don’t have a web.config but you see the config transforms as childs. Ignore the alert that the file is missing.
  10. Rebuild your project and your done. The new web.config is generated on your drive. (if you hit refresh in the solution explorer, the alert is gone). Just change your Configuration at the top of Visual Studio and your config is changed.

Notes
Remove your web.config file from source control otherwise you will get check outs.

Screenshots
Config transforms for F5

SlowCheetah targets files

 

Contents of targets file

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <PropertyGroup>
    <PrepareForBuildDependsOn>
      $(PrepareForBuildDependsOn);
      UpdateWebConfigBeforeBuild;
    </PrepareForBuildDependsOn>
  </PropertyGroup>

  <!-- This target will run right before you run your app in Visual Studio -->
  <Target Name="UpdateWebConfigBeforeBuild">
    <Message Text="Configuration: $(Configuration): web.dev.$(Configuration).config"/>
    <TransformXml Source="web.template.config"
              Transform="web.dev.$(Configuration).config"
              Destination="web.config" />
  </Target>

  <!-- Exclude the config template files from the created package -->
  <Target Name="ExcludeCustomConfigTransformFiles" BeforeTargets="ExcludeFilesFromPackage">
    <ItemGroup>
      <ExcludeFromPackageFiles Include="web.template.config;web.dev.*.config"/>
    </ItemGroup>
    <Message Text="ExcludeFromPackageFiles: @(ExcludeFromPackageFiles)" Importance="high"/>
  </Target>
</Project>

 

Update
An optional thing that you can do is, grouping your config files beneath the template config just like that standard web.config and his transforms. The dev configs are dependent upon the template so let’s place them there. To do this is easy. Unload your project and find your dev configs. You will see something like this:

<Content Include="web.dev.{your configuration}.config" />

Change this in:

<Content Include="web.dev.{your configuration}.config">
  <DependentUpon>web.template.config</DependentUpon>
</Content>

Repeat this for all your dev transforms. After that, save the file and reload your project.
You can also use the Visual Studio extension VSCommands. right click the files that you want to group, hit group items and select your base config file.

TFS connection Value cannot be null

In our company, we are upgrading from TFS 2010 to TFS 2012. So to test everything we have a clone of the TFS server.

To test the clone I had to switch my connection to the different servers. After hitting the “Connect” button I got a “Value cannot be null.” exception. It said that also that: “Parameter name: baseUri” was the problem. After contacting a colleague of me, he said to delete the cache of the TFS server on my computer. After doing that, the connection worked as it suppose to work.

You can find the cache in the following folder: C:Users<yourusername>Local SettingsApplication DataMicrosoftTeam Foundation2.0Cache

Minification and Bundling in MVC 4 RC

Asp .NET MVC 4 Release Candidate is out. One of the features that is included is called the minification and bundling feature. This was already there in the beta but in the release candidate version it has changed.

Why should we use it

The reason why we should use the bundling and minification feature is performance. The features increases your loading performance of your website. Every time you reference a JavaScript (like jQuery or your own), or CSS file in your page, the browser makes a call to the server. This is done for each separate reference. Each referenced file has included all the comments and spacing in your file. This makes the file larger then when we should delete those spaced. The bundling and minification feature does this for us.

How does it work

In your Global.asax the CSS and JavaScript files are Bundled with BundleConfig.RegisterBundles(BundleTable.Bundles); line.

image

image

Reference the files in your page.

image

When you run the application and use Fiddler to view the calls to your server, you still see all the files called separately.

image

image

This is because the Bundling and Minification feature by default only work when your not in debug mode. This handy because then you could debug with all the whitespaces in your files and have the performance in the production environment.

See the difference in your production environment:

image

image

Force Bundling and Minification

You can use the BundleTable.EnableOptmizations override but the best way for a little test is to remove the debug=”true” attribute in your web.config.

image

Browser caching

When the feature is active, the browser will cache the files. When you add or change some JavaScript or CSS code, the files are generated again and the version number in the references are updated. In that way, the browser knows that there is a new version and your website wont brake.

image

Change Target Framework version for all the projects in the solution

Ralph Jansen BlogToday I migrated an old project from Visual Studio 2008 to Visual Studio 2010 and with that, I changed the Framework to version 4.0. This is currently the newest .NET Framework. The solution contains a lot of different projects so the challenge was to convert all the target frameworks to the 4.0 version.

 

There are a couple ways to this:

  1. Change every project by hand. (Open the properties of every project and select the target framework that you want);
  2. Edit the project files by hand in notepad;
  3. Use the macro of Scott Dorman.

The macro of Scott can be found here. Just place the macro on the right place on your pc and execute it. After you executed the macro a popup is shown with the question to which target framework you want to migrate. Choose your framework and press OK.

That’s it!!! Safes a lot of time!!

Update:
You can execute a Macro in the Tools->Macros->Macros Explorer window.

clip_image002_thumb

Default browser VS2010 Add-in

Ralph JansenLast weekend I was working on a MVC 2 application. When I started the application my default browser (Google Chrome) came up. I actually wanted to change my browser for this application to Internet Explorer because the connectivity between IE and Visual Studio 2010 is much better than with Chrome.

The problem is that you can’t choose for the option “Browse With” in a MVC Application. This is because the controller is deciding which view should start. To fix this problem, I found an add-in for VS2010 that you can switch your default browser on the fly from your toolbar. In that way, you can switch easier between your installed browsers. See the screenshot below. image

You can download the add-in by following the link below.
http://visualstudiogallery.msdn.microsoft.com/en-us/bb424812-f742-41ef-974a-cdac607df921

 

Update:
If you get a popup on the startup of your Visual Studio Instance with the text: “The bits have expired, please download an updated version from http://www.wovs.com”, you have to download the new version. To do this, follow the steps on this website: http://blog.wovs.com/2010/10/how-to-update-currently-expired.html
Search in the online extension manager for “Default browser switcher”.

Master-Detail with Silverlight RIA Services

Ralph Jansen

If you want to have a master detail view of you data in Silverlight with RIA Services you have to do two things. One thing is to tell your RIA Services meta data file that you’re including the related entities and you will have to tell your domain service as well that your including the related entities. Follow the tutorial beneath to accomplish an example for creating a master detail relation with Silverlight RIA Services.

Silverlight application

Create a new Silverlight 4 application in VS2010 and enable RIA Services. Also don’t forget to check the box to host your Silverlight application in a website.

Model

Create your Entity Framework 4.0 model so we can generate some RIA Service over it. Just use a simple example so we can practice the master detail relationships. The example that I use is shown below.

image

RIA Services

After your model is created we have to create the Domain Service that exposes your model from the server to the client. If you haven’t used RIA Services before, I suggested you should read the documentation on the http://www.silverlight.net homepage.

Select add new item on your server website. The same place as you created your Entity Framework model. Now search for the Domain Service template. After you clicked the OK button, you will get a popup that is asking you to specify which entity the domain service should expose from your Entity Framework model. Click the Brands and Product collections, select the checkbox to generate meta data files and to enable client access.

Your Domain Service would look something like this:
image

Creating the UI

Open your MainPage.xaml file that is generated by creating the Silverlight Application. Open your Data Sources window in VS2010 and drag the Brands and Products grids to your MainPage. You have to drag your Products from the inner collection of Brands.

image

Now if you run your code. Only the brands will be shown because the UI is connected to the GetBrandsQuery. Now we want to include the products to create a Master Detail relation.

Configure the Meta data

Open your meta data file that is generated by the Domain Service. Find your Brands Entity and in that entity the inner collection property of Products. Add the [Include] attribute above the inner collection of products. In that way we tell RIA Services to include the products for the brand if the products are available.

image

Make the products available

To make the products available for RIA Services you should include them in the correct query that is used in the client. In our case it is the GetBrands in the Domain Service class.

image

Add the include statement like below to the query.

image

Now you are ready to run your code and see a nice example of a master detail relationship in the client.

Note:

It is better to create a new query then change the default query. In that way the performance is better because you don’t need the products every time you use the GetBrands query. You can create a query like GetBrandsWithProducts. If you do this, don’t forget to change the query name in the client. This is still referenced to the GetBrands query!!!