Microsoft Accounts for business

Have you ever asked, why do I have to choose between work- and personal-account when logging into Microsoft sites? Or maybe even sometimes you are asked and sometimes you are not asked if it is a personal- or a work-account?

Lets start with the work accounts. They are created through a company and are owned by the company. Our company has the domain “co-IT.eu” and it is registered with Microsoft. A new login is created by an admin of the company. Those can be created in the PartnerCenter. All those accounts are in an ActiveDirectory from Microsoft, which is only for business software. So as example:

  • Azure Company Subscriptions
  • Office 365
  • PartnerCenter
  • Skype for Business
  • OneDrive for Business

 

The other ActiveDirectory is the personal one. These are not owned by a company, they are owned by you! So the big difference is: a personal account can be delete by the person owning it and a company account can be deleted by the company owning it. Personal accounts can be created by everyone here. Your email address is not allowed to end with a company domain. In my case I cannot create a personal account for our domain. But be aware, it was possible in the past! So personal accounts with company emails exists, but cannot be created anymore. With the personal account you can login here:

In the case you are an Microsoft Certified Professional, you have the privilege of helping your company with the Microsoft Partner Network. You must link your personal-account to the company in the PartnerCenter.

IF you are one of the guys like me, who have both accounts on a company email, than you can’t link them in the PartnerCenter. They are working on it or they recommend to move the MCP-ID to a “real” personal account.

 

 

ASP.NET Core 2.1. MVC Testingframework

Today I had the opportunity to use the new MVC testing framework for integration tests. In a previous post, I wrote about CodedUI and now I want to show a different approach.

When using CodedUI I stumbled over some problems, which could become a bit of burden over the time:

  • Test setup: it is only possible to write the tests for the UI against a running application
  • running Tests: When running the tests on the local machine, CodedUI takes over the controls and it is not possible to work.
  • Continuous Integration: CodedUI will not run out of the box, because it needs controls over the mouse and access to a browser

The Testingframework lets you setup a testserver in your code. Instantiate the testserver in your SetUp method and for the generic type use your startup.cs.

[TestFixture]
public class BasicTests
{
private WebApplicationFactory<Startup> _factory;

[SetUp]
public void Setup()
{
_factory = new WebApplicationFactory<Startup>();
}

}

The next step is to create a client in your test and send a request. In my case I just want to test, that the root page works:

[Test]
public async Task Get_EndpointsReturnSuccessAndCorrectContentType()
{
// Arrange
var client = _factory.CreateClient();

// Act
var response = await client.GetAsync(“/”);

// Assert
response.EnsureSuccessStatusCode(); // Status Code 200-299
Assert.AreEqual(“text/html; charset=utf-8”,
response.Content.Headers.ContentType.ToString());
}

The good part here is, that the Tests will run without an UI and just return the response from the web server.

When it is required to customize our setup from our web server, we can inherit from WebApplicationFactory and override the ConfigureWebHost function. The following configuration will setup an in memory database for the EntityFrameworkCore, seed the database and disable the “Authorize” filter. It is not required to test the ASP.NET Authentication(this is already done by microsoft), I would like to test my own code:

public class NoAuthenticationWebApplicationFactory<TStartup>
: WebApplicationFactory<Startup>
{
protected override void Dispose(bool disposing)
{

base.Dispose(disposing);
}

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// Create a new service provider.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();

// Add a database context (ApplicationDbContext) using an in-memory
// database for testing.
services.AddDbContext<WorkshopContext>(options =>
{
options.UseInMemoryDatabase(“InMemoryDbForTesting”);
options.UseInternalServiceProvider(serviceProvider);
});

services.AddMvc(opts => { opts.Filters.Add(new AllowAnonymousFilter()); });
// Build the service provider.
var sp = services.BuildServiceProvider();

// Create a scope to obtain a reference to the database
// context (ApplicationDbContext).
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<WorkshopContext>();
var logger = scopedServices
.GetRequiredService<ILogger<NoAuthenticationWebApplicationFactory<TStartup>>>();

// Ensure the database is created.
db.Database.EnsureCreated();

try
{
// Seed the database with test data.
Utilities.InitializeDbForTests(db);
}
catch (Exception ex)
{
logger.LogError(ex, $”An error occurred seeding the ” +
“database with test messages. Error: {ex.Message}”);
}
}
});
}
}

With that it is possible to customize your web server and run tests against it. Just use the new WebApplicationFactory in your tests. With that setup we can:

  • Customize our web server for each test
  • can run the tests at all time without having to stop working.

In my next post I’ll write about how you can parse the webpages and navigate through them! Feel free to share your ideas about integration testing!

Exception Handling for Posts in ASP.NET Core

Visual Studio comes with a nice feature called scaffolding. If you use that, Visual Studio will generate code for your controllers. A Post-method looks like that:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
// TODO: Add insert logic here

return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}

Here we have some problems:

  • Violation of Single-Response-Principle (SRP). Error handling and logic is in the “Create”-function
  • Don’t Repat Yourself (DRY).  Every method will have the error handling.
  • Validation from constructors will not return the error message

For that, it is practical to write an ActionFilterAttribute. Here is the code:

public class PostExceptionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
if (context.HttpContext.Request.Method.Equals(“POST”))
{
if (context.Exception is ArgumentException exception)
{
context.ModelState.AddModelError(exception.ParamName, exception.Message);
context.ExceptionHandled = true;
context.Result = new ViewResult();
}
else if (context.Exception is Exception exception1)
{
context.ModelState.AddModelError(“”, exception1.Message);
context.ExceptionHandled = true;
context.Result = new ViewResult();
}
}

base.OnActionExecuted(context);
}
}

Next the filter must be added to MVC, so that it is used all the time. Change the fallowing in the ‘Startup.cs’:

services.AddMvc(options => { options.Filters.Add<PostExceptionFilterAttribute>(); })

Happy coding and feel free to leave a comment!

UI-Tests with CodedUi

Today I wrote some UI-tests for my ASP.NET Core application. UI-Testframeworks let you record the steps you take with some final assertions. The recording tool creates a “UI-Map”, which stores the mapping between the C# Objects and the DOM (Document Object Model). I hit a wall really fast with the straight forward approach. I’ll show you what I went through.

In the example I have an index page with a list, where I can create items on a second page. In the first try the result looks mostly like this:

var browser = BrowserWindow.Launch(new Uri(“http://localhost:63238/&#8221;));
browser.FindElement(By.Id(“create”)).Click();
var div = browser.FindElement(By.Id(“errors”));
div.TryFind().Should().BeFalse();

The question is: What happens when I change an element? I could nest it or need to make an other click on a modal window. Whatever the reason, I need to change ALL tests which contain the part of the code. This violates the SRP (Single Response Principle). The used example has only 2 pages and 2 elements to use. Just imagine this code in a real world application.

Next point is the readablility of the Tests. It is really time consuming to read and understand. Just try to figure out what the code does or read the next test, which does the same.

var browser = BrowserWindow.Launch(new Uri(“http://localhost:63238/&#8221;));
var index= new HomePage(browser);
index.NavigateToCreateNewContact().HasError().Should().BeFalse();

The last test is called a DAMP (Descriptive And Meaningful Phrases) test. To accomplish that, write the navigation Code for each page in one class. If you like to use the testrecorder, use a “Coded UI Test Map” for each page you have in your application. Start with the general layout, which contains all actions which are present all the time.

Next write the steps, what you can do on each page in a partial class. The return value of the actions should always be a new page. This is also known as FluentAPI. Here is my homepage:

public class HomePage : SharedActionsAndElements
{
public HomePage(BrowserWindow browserWindow) : base(browserWindow)
{
}

public CreateContactPage CreateNewContact()
{
BrowserWindow.FindElement(By.Id(“create”)).Click();
return new CreateItemPage(BrowserWindow);
}

}

With that your UI-Tests can adhere to the SRP and your code is maintainable. Feel free to write a comment or ask some questions if some things are unclear.

SSL and NameServers with Azure

Recently I wanted to add an Azure test website to “azure.co-IT.eu”, just to test how I have to set up SSL for our applications. There are 2 vital things which are required:

  1. access to the nameserver for your domain
  2. the SSL-certificate

First setup the nameserver for your domain so that it has a CNAME pointing to your Azure website. CNAME is only used for subdomains or wildcard domains. If the root domain must point to Azure, an “A record” should be used, as written here.

The CNAME should point to something like “yourAppName.azurewebsites.net”. This way your DNS knows when somebody calls “azure.co-IT.eu”, it should be the content of “yourAppName.azurewebsites.net”. You can check if this works correctly with digwebinterface.com.

In Azure go to “web app”->”Custom domains”. There the hostname “azure.co-IT.eu” must be validated and added. With this done, the url should show the correct website from Azure. Be aware that most browser will show you that this site cannot be trusted, because SSL is missing. The certificate as it is, is from *.azurewebsites.net.

You can fix this warning by going to “web app”->”SSL Certificates”. Upload the private certificate with password and add an SSL binding to the correct hostname. After that just enable “HTTPS only” under “Custom domains” and it is all set. https://azure.co-IT.eu will show a nice SSL symbol in your browser.

Feel free to leave comments or ask questions!

 

Web hosting for ASP.NET

Currently we are hosting our legacy applications on a php-server. But we plan                 n building our new fancy web apps with ASP.NET. The problem with our current hoster DomainFactory.eu is that it does not support this technology. So I was searching for a hoster who is able to host ASP.NET. A database was not really a requirement, because we only want to host the services, but I checked for it just in case we might need it one day.

Here are my findings:

I decided to choose Azure, because it has a lot of features, like Azure Functions or Cognitive Services. Furthermore it integrates well with Visual Studio and our developers can use their private Azure accounts for testing. MSDN Enterprise subscribers get 150€ per month to spend on their whim. One thing the others did not have was something like the Azure Active Directory or an IoT-Hub. The scaling options are also a powerful tool to scale applications on demand. This could definitely be helpful for some of our customers. We decided to pay a bit more to build up some knowledge, that we can pass on to our customers in the form of consultings in the future.

For companies who do not need to scale their services and only need simple hosting, I would recommend smarterasp.net. They seem to have a good number of services for a low price.

Feel free to leave a comment with some other ideas or questions

 

 

Obtaining Silver Competence from Microsoft

 

When I started at co-IT.eu GmbH, my first task was to get the Silver Competency from Microsoft. The main benefit for us is the logo for advertisement and the licenses.

Here are all the licenses a company will get for a silver or gold competency. What really stands out are 25 Office 365 licenses and 5 Visual Studio Enterprise licenses. One “Enterprise” license costs 2.999 USD/year. Even the normal “Professional” licenses cost 539$/year.

A Silver Competency has 4 requirements:

  1. have 2 Microsoft Certified Professionals (MCP) in your company
  2. Provide customer evidence
  3. Complete your company profile
  4. Pay money, I think it is something around 1756$

The only “difficult” part is in my eyes to get 2 MCP’s. I explained in my previous post how I got my ASP.NET MCP. The price for a certificate is 165$ for the C# exam. So compared to even the “Professional” license it is really cheap.

Feel free to leave some comments or feedback!

 

Obtaining Microsoft Certificate 70-486 for ASP.NET MVC

The past weeks I studied for the ASP.Net certificate from Microsoft. I’ll share some of my experience here.

My starting knowledge which helped me a bit was from developing the competition software for figure skating:

  • Katana/Owin
  • SignalR
  • C#

Pretty long list. So my brain was like a blank sheet. One of the first things I checked out was my Pluralsight account. They have a Path for MVC 5. This is a good starting point. Some videos have references to videos with needed knowledge for the current video. This is sometimes like a chain with recommendations for other videos. For my exam I only watched the beginner and intermediate level videos. The advanced are usefull if you have special needs in ASP.Net.

After a bit of searching I stumbled over the post from Mike Woodring. This is a really long list if you want to watch all of it. Unfortunately some videos are old. The Azure platform for example has changed a bit in the last years.

Here are some video resources I found useful and good:

After I watched these I did not know what to focus my studies on. So I took the test exams on measureup and studied for the questions. It worked for me like they wrote on the site. If you pass 2 Test Exams in a row over 90% you’ll pass the real exam. I tried and succeeded.

If you have any questions feel free to leave a comment