Wednesday, November 15, 2017

Code sample for .Net Core Web Api Controller Integration Tests

Integration testing ensures the different parts of an application work correctly together. Unlike unit testing, integration tests frequently involve application dependencies such as database.

To get set up integration tests in .Net Core, you'll need a test project, add reference to your .Net Core Api project and a test runner. Magic is in the test host which comes with ASP.NET Core that can be added to integration test project and can be used to host .Net Core Apps, serving http requests with out the need for a real web host.

Following sample uses xUnit, FluentAssertions and TestHost to compose a simple integration test.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Xunit;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using FluentAssertions;
using Microsoft.AspNetCore;


namespace VisualStudio99.Tests.IntegrationTests
{
    public class LookupApiControllerIntegrationTests 
    {
        private readonly HttpClient _client;
        private readonly TestServer _server;
        
       
        public LookupApiControllerIntegrationTests()
        {
            //_server = new TestServer(WebHost.CreateDefaultBuilder().UseUrls("http://localhost:5000").Configure(_ => { }));
            _server = new TestServer(new WebHostBuilder().UseStartup<Startup>().UseUrls("http://localhost:5000"));
            _client = _server.CreateClient();

            _client.BaseAddress = new Uri("http://localhost:5000");
            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
        [Fact]
        public async Task Lookup_Get_All_EmployeeTypes()
        {
                var response = await _client.GetAsync($"/api/lookup/employeetypes");
                // Assert
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                var responseString = await response.Content.ReadAsStringAsync();
                var employeeTypes = JsonConvert.DeserializeObject<IEnumerable<EmployeeTypeDto>>(responseString);
                employeeTypes.Count().Should().Equals(5);
                employeeTypes.Should().OnlyHaveUniqueItems();
                employeeTypes.Should().OnlyContain(x => !string.IsNullOrEmpty(x.EmployeeTypeCode));
        }
    }

.Net Application Architecture patterns for modern applications (docker, azure, mobile and cross platform)


Microsoft has posted some great content on .Net Application Architecture. This is similar to now stopped Microsoft Patterns and Practices guidance on architecting enterprise application using .Net stack or in general best practices guides to design solutions.

.Net Application Architecture is reincarnation of Microsoft Patterns and Practices where you can find some guides on building modern solutions using new patterns, frameworks, techniques and workflows like

  1.  Building Docker Applications, 
  2.  Azure Cloud ready applications
  3.  Modernizing Full .Net Framework apps to cross platform .Net Core apps
  4.  Xamarin Mobile Apps

These new design guides are extensive. You can download these guides along with a sample app to test new patterns

Go to: https://www.microsoft.com/net/learn/architecture

Enjoy!

Nicely curated keyboard shortcut cheat sheet for Visual Studio 2017



  • Useful key board shortcuts cheatsheet for visual studio 2017 published by Microsoft. 
  • Neatly captures most heavily used productivity improving keyboard shortcuts.
  • Provides side by side keyboard shortcuts for Resharper, Visual Studio 2017 and Visual Studio 2015
  • Click here to download pdf cheat sheet

Sunday, April 9, 2017

C# code snippet for setting up a FileSystemWatcher on a directory or file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.IO;

 FileSystemWatcher watcher = new FileSystemWatcher();
 watcher.Path = @"C:\filedumps";
        /* Watch for changes in LastWrite times, and the renaming of files  */
        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
        // watch text files
        watcher.Filter = "*.txt";
        // Add event handlers
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // raise events
        watcher.EnableRaisingEvents = true;

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
          Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
          Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }

C# code snippet for creating a self hosted WCF service

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 ServiceHost employeeServiceHost = null;
            try
            {
                //Base Address for EmployeeService
                Uri httpBaseAddress = new Uri("http://localhost:8080/EmployeeService");
                
                //Instantiate ServiceHost
                employeeServiceHost = new ServiceHost(typeof(Employee.EmployeeService),httpBaseAddress); 
 
               //Add Endpoint to Host
                employeeServiceHost.AddServiceEndpoint(typeof(EmployeeService.IEmployeeService),new WSHttpBinding(), "");            
 
               //Metadata Exchange
                ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
                serviceBehavior.HttpGetEnabled = true;
                employeeServiceHost.Description.Behaviors.Add(serviceBehavior);
 
                //Open
                employeeServiceHost.Open();
                Console.WriteLine("Employee Service is listening at : {0}", httpBaseAddress);
                Console.ReadKey();                
            }
            catch (Exception ex)
            {
                employeeServiceHost = null;
                Console.WriteLine(" An error occurred with EmployeeService" + ex.Message);
            }