In this post I will explain how to seed database users roles dotnet core 2.0 ef. For this we use the UserManager and RoleManager of the AspNetCore Identity framework. In that way, your application already has a default user and role for in example logging into the application. You can use it for test data but also for new installations of your application. In my case I will create a default Administrator user with the Administrator role attached to it for new installations of the application.

Seeding a database in dotnet core 2.0 is different than earlier versions. I followed the basics of the new documentation of Microsoft to get to a good solution. So I first created a new project with the authentication set to Individual Accounts.

This is almost the same code as the documentation but I also injected a RoleManager and UserManager so we can create the default user and role for the application. When the instances are created the Initialize method of the DbInitializer is called. This can be used to seed your database.

Because I want to know more information about my users than just their email and username, I extended the ApplicationUser object that is used to create a user in the database with the UserManaer.

I like constructors for new objects so I will use the long constructor to create my default user.

DbInitializer

The DbInitializer is the class that is used to seed the database. It is created by the program class. It has a static method Initialize that will be used to pass the external dependencies. The Initialize method will be used to orchestrate all the actions.

First a new Administrator role is created. In my application this is the highest role a user can have. When the role is created, a new default user is created with the earlier provided constructor. After the user is created, the user needs a password to sign into the application. So a password is set. The last step is to connect the user to the Administrator role so he has all the permissions that he needs.

For logging, I use the default logging extension framework provided by dotnet core. I connected Serilog to the logging extension for better control.

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.

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.

Is it possible to connect SoapUI to WCF Service certificate authentication, the answer is yes! If you search on the internet, there is little information about this topic but it is really possible!

Adding security to your WCF service is a best practice. Not only when your creating services connected by the internet but also inside your company.

One way for securing your WCF service is adding certificates for authentication. But also signing your message is good way to preserve the integrity of your message. So to use a secure service we can enable transport and message security. See a list of common security scenarios with WCF for a good reference. In that way we can use SSL in IIS.

Service configuration

Add a service to your application with a WsHttpBinding. See for an example the following config:

Configuration SoapUI

If you want to connect to this service with SoapUI it is more difficult. I’m not a Java developer so I use SoapUI for an easier understanding of connecting to our WCF Service in a different language. For this example I use the curret latest version 5.3. See for an overview of WS-Security the following help page.

Follow the steps below for adding a new project to SoapUI with the right configuration.

Project configuration

First of all create a new project and add the url to the wsdl. A new project is generated with a sample request for your service.

Now double click the project or use right click of the mouse to open the “Project view”.

Navigate to the “WS-Security Configurations” tab

Select the “Keystores” tab and add the certificate with private key so we can sign the request.

Go to the “Outgoing WS-Security Configurations” and add a new configuration with the name that you like.

Add in the newly created configuration a “Signature”.

Configure the keystore that you’ve added.

Use “Binary Security Token” as Key Identifier Type.

Set the right Algorithms that you have configured in the service. I change the configuration to a higher security because the default uses SHA1 and that is not a best practice anymore. I changed the configuration in my WCF service to algorithmSuite=”Basic256Sha256Rsa15″ in the message element of the binding. See this page for more information. Then it uses RSA-SHA256 for signature algorithm, XML-EXC-C14n# for Signature Canonicalization and XMLENC#SHA256 for the Digest Algorithm.

Check the “Use single certificate” checkbox.

By default SoapUI signs the whole request but that isn’t the default by WCF so we have to set the parts that we want to sign. So add as Name “To”, Namespace “http://www.w3.org/2005/08/addressing” (this is my namespace but check yours) and set Encode to “Element”.

Add a timestamp and set it to 300. Use milisecond precision.

Check the order on the left. So first signature and then timestamp!

Request configuration

Adjust the sample request body so it is a valid request.

Go back to your request.

Under the request open the “Auth” panel. Add Basic security. Leave everything blank except the “Outgoing WSS” configuration. Select the configuration that you have created.

Go to the WS-A panel and check the “Enable WS-A addressing” checkbox.

Finally the last thing that you have to do is check the checkbox “Add default wsa:To”. This in combination with the signature parts “To” configuration passes the right header values to the server. If you don’t do this you will get the following exception “The message received over Transport security has unsigned ‘To’ header”. See this StackOverflow post for simulair issue.

Hopefully this helped somebody. I spend to much time to this issue with SoapUI. Just to show that SoapUI works with a WCF soap service and high security configuration. The conclusion is that it works! It’s just soap… why wouldn’t…

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

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.

Create a new class library and call it “Extensions”.

In the Extensions project, add a reference to “Microsoft.VisualStudio.QualityTools.WebTestFramework”. This project is for creating custom extension for Visual Studio webtests.

Add again a new project. Choose a “Web Performance and Load test Project” project. I called mine “WebApiTest”.

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.

Rename the webtest to ValuesTest because we are going to test the ValuesController of the Web Api project.

Right click your ValuesTest and add a “Web Service Request”. Change the url to “http://localhost:26159/api/values” (your portnumber can be different).

Change the method from POST to GET.

Run your test and you will get a 401 unauthorized request back.

Remove the Authorize attribute on the ValuesController

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.

Right click your web request and select “Add Validation Rule”.

A window appears. Select the “Find text” validation rule.

Enter in the “Find text” property the value “value3”.

Run your test and your test will fail on the validation rule.

Change the “Find text” property to “value2”.

Run the test again and now your test will be valid.

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.

In the BaseRule class we have to identify how the rules are named and where they could be found. To do this change the code in the BaseRule class.

BaseRule

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

usingMicrosoft.FxCop.Sdk;

namespaceCustomCodeAnalysisRules

{

publicabstractclassBaseRule:BaseIntrospectionRule

{

protectedBaseRule(stringname)

:base(

// The name of the rule (must match exactly to an entry

// in the manifest XML)

name,

// The name of the manifest XML file, qualified with the

// namespace and missing the extension

typeof(BaseRule).Assembly.GetName().Name+".Rules",

// The assembly to find the manifest XML in

typeof(BaseRule).Assembly)

{

}

}

}

Now we have the framework for our new custom code analysis rules. In this example we are creating a custom rule that says that fields are not allowed. We are creating this rule because our team doesn’t want any fields in Data Transfer Objects (DTO).

We name the custom rule ‘NoFieldsAllowed’, so create a class with the name ‘NoFieldsAllowed’. The rule is inherit from our BaseRule so we can give the name of the rule to the base class.

Basic setup custom rule

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

usingMicrosoft.FxCop.Sdk;

namespaceCustomCodeAnalysisRules

{

internalsealedclassNoFieldsAllowed:BaseRule

{

publicNoFieldsAllowed()

:base("NoFieldsAllowed")

{

}

}

}

Next we have to say for which type of access modifiers the rule is made for. We can do this be overriding the ‘TargetVisibility’ property. We want to make this rule for all access modifiers so we have to use ‘TargetVisibilities.All’.

The setup for the rule is complete so we can write the implementation. Override the ‘Check’ method for a ‘Member’. Cast the member that you get as parameter to a ‘Field’. Check if the Field is ‘null’. If so, the check is not for this member.

Check if member is field

C#

1

2

3

4

5

6

7

8

9

10

publicoverrideProblemCollection Check(Member member)

{

Field field=member asField;

if(field==null)

{

// This rule only applies to fields.

// Return a null ProblemCollection so no violations are reported for this member.

returnnull;

}

}

If this member is a field we have to create a ‘Problem’ and a ‘Resolution’. To create a resolution you must create a ‘Rules.xml’ file in your project.

<Resolution>Field {0} is not allowed. Field must be removed from this class.</Resolution>

<MessageLevel Certainty="100">Warning</MessageLevel>

<FixCategories>NonBreaking</FixCategories>

<Url />

<Owner />

<Email />

</Rule>

</Rules>

You can add the following information to the ‘Resolution’:

Display name of the rule.

Rule description.

One or more rule resolutions.

The MessageLevel (severity) of the rule. This can be set to one of the following:

CriticalError

Error

CriticalWarning

Warning

Information

The certainty of the violation. This field represents the accuracy percentage of the rule. In other words this field describes the rule author’s confidence in how accurate this rule is.

The FixCategory of this rule. This field describes if fixing this rule would require a breaking change, ie a change that could break other assemblies referencing the one being analyzed.

The help url for this rule.

The name of the owner of this rule.

The support email to contact about this rule.

Now we have the information to show as a Resolution. We only have to show it to the user in Visual Studio. So expand the ‘Check’ method by creating a ‘Resolution’ and add it to the ‘Problems’ list of the base class.

Complete Check

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

publicoverrideProblemCollection Check(Member member)

{

Field field=member asField;

if(field==null)

{

// This rule only applies to fields.

// Return a null ProblemCollection so no violations are reported for this member.

returnnull;

}

Resolution resolution=GetResolution(

field// Field {0} is not allowed. Field must be removed from this class.

);

Problem problem=newProblem(resolution);

Problems.Add(problem);

// By default the Problems collection is empty so no violations will be reported

// unless CheckFieldName found and added a problem.

returnProblems;

}

Test your Custom code analysis rule

To test your custom rule we can add some fields to your custom rule class. So add under the ‘Check’ method the following fields.

Test fields

C#

1

2

3

4

5

6

privatestringtestField1="This should give an error!!!";

privateconststringtestFieldconst1="This should give an error!!!";

protectedstringtestField2="This should give an error!!!";

internalstringtestField3="This should give an error!!!";

publicstringtestField4="This should give an error!!!";

publicconststringtestFieldconst4="This should give an error!!!";

To test this we are going to change the “Start Action” of your class library. Open the properties of your class library and navigate to the ‘Debug’ tab.

Use as working directory your debug folder in the bin folder of this class library.

Now run your application with Debug. You will see a command prompt showing up. This will check your fields with your rules. The outcome of the test will be written in your debug folder. There you will find a ‘results.xml’ file. If you open it in ‘Internet Explorer’ you will see the information. Of course you can open it in every xml tool.

If your test is what you’ve expected, you can use your custom code analysis dll in your ruleset for your application. See here the outcome an application that uses the custom dll.

The list of tools beneath are tools that I use every day! Some are extensions for Team Foundation Server but also extensions for Visual Studio, awesome Nuget packages or general tools.
It are the best Visual Studio extension and applications that I could find.

Visual Studio Extensions

EnterpriseLibrary.Config
This is a handy tool for your Enterprise Library packages. With this tool you can edit your config with an interface.

GhostDoc
I use the free version of this but you also have a payed version of this. With this tool you can generate your summaries above your code. It will also generate documentation for parameters, properties, field, methods etc.

This is not the first time that I write about mvc localization validation. The last time that I wrote about this was back in 2012 when I wrote the blog “Localization validation in MVC“. This blog post helped a lot of people with this question on StackOverflow.

In this blog post I create a website with localization for English and Dutch. I will use a DateTime as an example property to display and edit this property for validating the localization. This because the Dutch localization is dd-MM-yyyy and in English we have MM\dd\yyyy.

Technology used

Now I want to write a new post that uses all the latest technology in the MVC world at this moment. At this moment the latest version of Visual Studio is Visual Studio 2013 Update 3. The latest version of MVC is: 5.2.2. This is also the version that we use in combination with .NET Framework 4.5.1.

Setup MVC localization validation

New project

Create a new MVC 5 ASP.NET Web Application in Visual Studio with the use of the .NET Framework 4.5.1. When it is created, update all your Nuget packages about MVC.

Web.config

Some people say that you have to alter the web.config to use localization. This is true when you create a website for a particular localization. In this tutorial I want to create a website that is compatible with multiple cultures from all over the world. Of course you can create a website in English but some people prefer their own language. In this tutorial I will create a website in English and Dutch (I’m from the Netherlands).

So we don’t edit the web.config. We don’t set any culture or UI culture in the web.config. In that way, the default culture is the culture of the pc or (if set) the culture of the browser.

Culture selector

The user should be able to overwrite the default culture from his browser or pc. Maybe the user wants to use another culture than his default culture for your website. So we create some code to create a list with the cultures that you have setup to support in your website.

Code for creating the list of cultures and select a culture different to your browser culture. Add this code in your “_Layout” page in example your menu or footer:

Create a folder in the root of your project called “Localizations”. Add a Resource file called “Labels.resx” in that folder. This is your English resource file so the default language is the English language. Set the Access Modifier to Public. Copy the Labels resource file for the other languages. For Dutch is this: Labels.nl-NL.resx. So when the user switches from culture or the browser has another culture set, the right resource file is automatically chosen.

DateTime Example

Now we have the right culture of the user, we need an example so we can prove it actually works. So we create an object with a DateTime property. In that way we can display and edit that property in the different cultures. Remember that the Dutch language has a different date format than the English language.

Because all the browser are displaying date textboxes different, we create our own until the HTML 5 specification is finally done. Also, the older browsers don’t support HTML 5 so we must create our own textbox with jQuery UI datepicker.

To do this, we create a new EditorTemplate. If you never done this before, don’t worry it is very easy. Create a new folder called “EditorTemplates” in your “Shared” folder in the “Views” folder. In the EditorTemplates folder, create a new view called “Date”.

Now when a Date field is used for editing, the editortemplate is automatically used. Paste the following code in the Date editortemplate.

Initialize the Datepicker

Now we have created an editor for editing, the jQuery datepicker should be created. Because we also create the datepicker for a specific culture, the right language file of the jQuery datepicker should be selected as well. You can find the url of the language file in the documentation/source code from the jQuery datepicker documentation page.

Add the following code in the _Layout page just after setting up jQuery and jQuery UI.

C#

1

2

3

4

5

6

7

8

9

10

@if(!string.IsNullOrWhiteSpace(UICulture))

{

stringshortCulture=UICulture.Substring(0,2);

if(shortCulture!="en")

{

// Only set culture script if it isn't en because en is the default

stringurl=string.Format("/Scripts/datepicker-{0}.js",shortCulture);

<script src="@url"></script>

}

}

This code finds the right language file and add it to the page for the current (selected) culture.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

<script type="text/javascript">

$(document).ready(function(){

$('.date').datepicker({

showOtherMonths:true,

selectOtherMonths:true,

changeMonth:true,

changeYear:true,

numberOfMonths:1,

showButtonPanel:true

});

});

</script>

This code creates the datepicker in the right culture.

Test the editor

To test the editor, create an object with a DateTime property. See the following example for the class “Member”:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

publicclassMember

{

[Key]

publicintId{get;set;}

[Display(Name="Voornaam")]

[Required]

[StringLength(50)]

publicstringFirstName{get;set;}

[Display(Name="Achternaam")]

[Required]

[StringLength(50)]

publicstringLastName{get;set;}

[Display(Name="Geboortedatum")]

[Required]

[DataType(DataType.Date)]

publicDateTimeBirthDay{get;set;}

}

The EditorTemplate is selected because we have used the “DataType” attribute with the “DataType.Date” value. You could also use the “UIHint” attribute.

If you generate (scaffold) a new Edit or Create view, change the code for the Birthday property to:

Now run your project and try to edit or create a member object. You now should see a textbox with a jQuery UI datepicker inside. When you select a date from the datepicker, the format of the date should be the format of the culture you requested. Also the validation should be right for the Culture you have selected.

Conclusion

Now you have a culture independent website with a jQuery datepicker in the culture that the user wants. You can upload this website to every server you want. You don’t have to set any culture on the server because this solution is culture independent. This is easy for me in the Netherlands because now I can create a Dutch website that I can upload to Microsoft Azure (in azure you have en-US culture) without any problems.

We want to trigger a CI build after a gated checkin because we have two builds in our company. One with a gated checkin for fast building and very important test. The other build is for code analysis and long running tests. Because we don’t want to wait very long on our CI build we have created that QM build. The problem is that the QM isn’t triggered anymore after changing the CI build to a Gated checkin build.

I found a blogpost for TFS 2010. Because TFS 2013 is slightly different, I thought I would give it an update.

This is how to fix it for TFS 2013

Create an argument called “NoCIOption” of the type boolean with default True.

Set the metadata information so you understand the argument in your build definition.

Use the argument in the TFS 2013 build template. You can find the property under “Run on agent” and then “Get sources from Team Foundation Version Control”. Go to the properties window and change the hard coded “True” in the NoCIOption property to the argument you just created.

Now checkin your changes of the teamplate and use (if you don’t already have) the template in your CI build (the one with the gated checkin). Change the new argument to “false”.

In the welcome page I have a section of the architecture of the application. I wanted to add an image of the architecture schema. The problem was that I didn’t found anywhere how to do this. The problem was that I didn’t use the id of the image but the name of the image. The solution was just to just use the id.

Updated 2017-01-17: Updated the blogpost to the new outlook.com experience (on the office 365 platform).

Edit outlook.com contacts in android is a real pain. But in this post I will explain to you have to fix this.

Because Google and Microsoft are in some kind of war in what the best way is to edit contacts, you could be having troubling with editing your Outlook.com contacts in Android. Follow these steps to edit your Outlook.com contacts again.

Setup the new Outlook application and disable contact sync. Contacts do get synced to your device very nice but you can’t edit them. So they are useless to use. We disable the sync so we can sync them another way. If you leave this enabled you will end up with dupplicates on your phone.

On your phone, go to Settings -> Accounts & Sync

Add an Exchange ActiveSync account. Do not use the outlook.com account. some phones will display an outlook.com sync possibility but that is an old obsolete one. If you can’t find an Exchange account, try to use the default email application on your phone. It should have one build in.