Design Pattern – Abstract Factory

Abstract Factory – Provide an interface for creating families of related or dependent objects without specifying their concrete classes. [1]

Just wrote down a few notes.

First, abstract factory is for creating families of related or dependent objects. These objects are related or dependent upon each other so that they should be created together. They probably will be used / assembled together.

Second, one concrete implementation of abstract factory could be replaced by another concrete implementation, in theory.

Third, to make it easier for me to remember, I use this as the real-life example. Imagine I am a food supplier for fast food chains such as McDonald, Burger King, Wendy’s, etc. I would have an abstract factory to create abstract burgers, fries, drinks, cups, napkins, etc. I would also have a concrete factory to create concrete specialized products for McDonald, Burger King, Wendy’s each, respectively.

References:

  1. https://sourcemaking.com/design_patterns/abstract_factory
  2. https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm
  3. https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm
  4. https://en.wikipedia.org/wiki/Abstract_factory_pattern
  5. http://www.oodesign.com/abstract-factory-pattern.html
Advertisements

A Black Screen for VM after a Successful RDP login?

Logged in remotely using RDP. To my surprise, my RDP screen was black.  Tried to disconnect and connect a few times with no luck. I remembered I used some combination of CTRL+ALT+? before. Googled and found it was CTRL+ALT+END.  This brought back the screen we would normally see when we press CTRL+ALT+DELETE in local machine. I chose Task Manager, and had my screen back.

 

Reference:

https://support.microsoft.com/en-us/help/555840

Setup Ninject in ASP.NET Web API 2

Set up Ninject in Web API 2 in Visual Studio 2015.

Use Nuget package manager to download these two packages.

  1. Ninject.Web.WebApi for API 2
  2. Ninject.Web.Common.WebHost

In the end, the two packages will bring down these packages

  1. Ninject
  2. Ninject.Web.WebApi
  3. Ninject.Web.Common
  4. Ninject.Web.Common.WebHost
  5. WebActivatorEx

Now it is very important. For some unknown reasons, NinjectWebCommon.cs was NOT created by the packages. So manually create one, and copy the following content.

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourNameSpace.APIs.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YourNameSpace.APIs.NinjectWebCommon), "Stop")]

namespace YourNameSpace.APIs.App_Start
{
 using System;
 using System.Web;

 using Microsoft.Web.Infrastructure.DynamicModuleHelper;

 using Ninject;
 using Ninject.Web.Common; 
 using System.Web.Http;
 using Ninject.Web.Common.WebHost;
 using Ninject.Web.WebApi;


 public static class NinjectWebCommon 
 {
   private static readonly Bootstrapper bootstrapper = new Bootstrapper();

 /// <summary>
 /// Starts the application
 /// </summary>
 public static void Start() 
 {
   DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
   DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
   bootstrapper.Initialize(CreateKernel);
 }
 
 /// <summary>
 /// Stops the application.
 /// </summary>
 public static void Stop()
 {
   bootstrapper.ShutDown();
 }
 
 /// <summary>
 /// Creates the kernel that will manage your application.
 /// </summary>
 /// <returns>The created kernel.</returns>
 private static IKernel CreateKernel()
 {
 var kernel = new StandardKernel();
 try
 {
   kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
   kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

   GlobalConfiguration.Configuration.DependencyResolver = 
     new NinjectDependencyResolver(kernel);
   RegisterServices(kernel);
   return kernel;
 }
 catch
 {
   kernel.Dispose();
   throw;
 }
 }

 /// <summary>
 /// Load your modules or register your services here!
 /// </summary>
 /// <param name="kernel">The kernel.</param>
 private static void RegisterServices(IKernel kernel)
 {
   kernel.Bind<IYourInterface>().To<YourImplementation>();
 } 
 }
}

 

 

In-Memory End-to-End Unit Tests of Web API

Wrote prototype in-memory end-to-end unit tests on Web API so that these tests can be run on TFS after checkin. Thanks for the articles about in-memory web server and sample tests.

[TestMethod]
public void InMemoryEndToEndWebAPITest()
{
  // Arrange
  var expectedJasonResult = "...";
  var config = new HttpConfiguration();
  YourWebAPIProject.WebApiConfig.Register(config);
  using (var server = new HttpServer(config))
  {
    var client = new HttpClient(server);
    string url = "http://localhost:60000/api/values/"; 
    var request = new HttpRequestMessage
    {
      RequestUri = new Uri(url),
      Method = HttpMethod.Get
    };
    request.Headers.Accept.Add(
      new MediaTypeWithQualityHeaderValue("application/json"));

    // Act
    using (var response = client.SendAsync(request))
    {
      // Assert
      Assert.AreEqual(HttpStatusCode.OK, response.Result.StatusCode);  
      Assert.AreEqual(expectedJasonResult,
        response.Result.Content.ReadAsStringAsync().Result);
    }
  }
}

 

References:

https://stackoverflow.com/questions/37475387/unit-testing-integration-testing-web-api-with-httpclient-in-visual-studio-2013

https://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/

TFS Build Error – Delete Sources Directory

Got this TFS build error, “Delete Sources Directory … The directory is not empty” suddenly. It was strange because there were no changes being checked in for the past few days.

Researched and found the article [1] mentioned that there are some processes such as file explorer or command prompt might have handles on file system. Followed the hint did solve the build error.

I looked back and asked so why didn’t it happen earlier? I believed it was because there were a few build agents, and it took a few rounds to reuse the same folder.

 

References:

  1. https://stackoverflow.com/questions/18696408/tfs-build-broken-the-directory-is-not-empty-on-sources-directory
  2. https://social.msdn.microsoft.com/Forums/vstudio/en-US/451e0281-94de-4b44-bfa2-90b40c3d1725/msbuild-error-the-directory-is-not-empty?forum=tfsbuild
  3. https://blogs.msdn.microsoft.com/nikita/2016/01/29/the-directory-is-not-empty-build-fails-in-the-visual-studio-online/

 

 

How to Maintain Design Intent During Development

After numerous meetings are done and a grand design is published, we must deal with another task, how to maintain Design Intent during development. I believe the following ideas will help to alleviate the issue.

  1. High-level UML diagrams
  2. Real code pre-construction prototype
  3. Well designed classes, interfaces, and APIs.
  4. Unit tests
  5. Code reviews
  6. Adopt some frameworks
  7. Agile implementation
  8. Communication, communication, and communication …

Design Pattern, Composite and Strategy

Tags

 

Composite Strategy
Type Structure Behavior
Definition The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly. [1] Defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family. [1]
Relation-ship A tree, and can be recursive abstractly Flat, a family of algorithms
Selection No, treat in individual objects and compositions uniformly Yes, select one algorithm from a family
Delegation Yes, theoretically the action can be populated down the tree simultaneously No

 

Composite is a pattern with a set of attributes and Strategy is a pattern with another set of attributes. It is interesting to see the permutation and combination of these attributes of two patterns.

As a starter, my questions are:

  1. What if we combine Composite and Strategy as one in an object, we can look at the Composite as the state of the object and Strategy as the behavior of the object.
  2. What if we apply Composite to one or all algorithms of that family
  3. What if we apply Strategy to a node or all nodes of a Composite

 

References:

  1. Gamma, Erich; Richard Helm; Ralph Johnson; John M. Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley.
  2. https://en.wikipedia.org/wiki/Strategy_pattern
  3. https://en.wikipedia.org/wiki/Composite_pattern
  4. https://sourcemaking.com/design_patterns/composite
  5. https://sourcemaking.com/design_patterns/strategy

Tests Not Discovered by Test Explorer

A few weeks back, I launched tests in Visual Studio. I was astonished to find there were no test results coming back. All tests were still there. However, the tests were not discovered by Test Explorer.

Googled and found all kinds of reasons. However, the cause in my case was one of the kind, that test projects were strong name signed by others. After removed the strong name signing, all tests were discovered by Test Explorer.

Progressive Web Apps vs Responsive Design

Tags

Heard the term ‘Progressive Web App’ from a seminar. At first, I thought it was just another buzz word for ‘Responsive Design’. However, it turns out to be a concept that contains much more.

Progressive Web Apps offer a much rich user experience, take advantage of much larger WWW eco-system and tap into modern native apps eco-system, and combine the best of both worlds, web and apps.

There are many articles about this. So I don’t say more. I list some references as the starter. One characteristic is interesting, as quoted “Because a progressive web app is a website, it should be discoverable in search engines. This is a major advantage over native applications, which still lag behind websites in search ability” [2]

According to this article [4], there are four levels of RWA.

Level 1: Responsive – Styling, Layouts, Utility Page

Level 2: Adaptive – Device optimization

Level 3: Progressive Web – Capability specific enhancements (payments, push notifications)

Level 4: Progressive App – Native enhancements (access to camera, GPS, etc)

References:

  1. https://developers.google.com/web/fundamentals/codelabs/your-first-pwapp/
  2. https://www.smashingmagazine.com/2016/08/a-beginners-guide-to-progressive-web-apps/
  3. https://en.wikipedia.org/wiki/Progressive_web_app
  4. https://www.mobify.com/insights/progressive-web-is-the-new-responsive/

C# async and await

Writing asynchronous applications can be very complicated.

Luckily, C# 5 introduced a simplified approach, async programming with async and await. It leverages asynchronous support in the .NET Framework 4.5 and higher. Developers can write codes similar to synchronous codes, make them easy to write, debug, and maintain.

The async modifier specifies that a method, lambda expression, or anonymous method is asynchronous. An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method.

The await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method. (Sidebar: according to my exercise, the thread to run the continuation after awaited task is finished could be a different thread)

In order to understand async and await a little more, I wrote a simple exercise with async programming. The source of this exercise is at the end of this blog.

Output:
Main ThreadId: 1, start

Worker #1, ThreadId: 1, begin to process tons of data here …
Worker #2, ThreadId: 1, begin to process tons of data here …
Main ThreadId: 1, control back (UI responsive).

Worker #2, ThreadId: 4, finished
Worker #1, ThreadId: 5, finished

As we can see,

  1. The main thread ID was #1
  2. The main thread kicked off the workers
  3. The worker #1 and #2 used thread ID #1 until this line ‘await Task.Delay(4000);’
  4. ‘await Task.Delay(4000);’ suspended its progress and to yield control back to main thread
  5. The main thread got control back, UI was responsive, and printed out ‘Main ThreadId: 1, control back (UI responsive).’
  6. After a while, workers finished and printed the messages to indicate it’s done
  7. The thread IDs of workers after await operations were different from the main thread ID.

Item #7, this seems to contradict the documentation [1], as quoted, “The async and await keywords don’t cause additional threads to be created. Async methods don’t require multithreading because an async method doesn’t run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.”

 

References

  1. Asynchronous programming with async and await (Excellent tutorial! Detailed explanation on what happens in an async method)
  2. Asynchronous programming
  3. async

 

Source

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main ThreadId: " 
                + Thread.CurrentThread.ManagedThreadId + ", start" + "\r\n");
            
            for (int i = 1; i <= 2; i++)
            {
                new AsyncAwait().ExecuteMethodAsync(i);
            }

            Console.WriteLine("Main ThreadId: " 
                + Thread.CurrentThread.ManagedThreadId 
                + ", control back (UI responsive)." + "\r\n");
            Console.ReadKey();
        }
    }

    public class AsyncAwait
    {             
        public async Task ExecuteMethodAsync(int workerNumber)
        {
            Console.WriteLine("Worker #" + workerNumber + ", ThreadId: " 
                + Thread.CurrentThread.ManagedThreadId
                + ", begin to process tons of data here ... ");
            await Task.Delay(4000);            
            Console.WriteLine("Worker #" + workerNumber + ", ThreadId: " 
                + Thread.CurrentThread.ManagedThreadId + ", finished");
        }
    }