Author: Sabarinathan A

About Sabarinathan A

I, Sabarinathan Arthanari have over 20 years of experience in Computer science and specialise in Microsoft architecture for enterprise applications.

Xunit test standards and Nsubstitute approaches

Naming conventions


Parameterized unit test

xUnit uses the [Fact] attribute to denote a parameterless unit test, which tests invariants in your code.

In contrast, the [Theory] attribute denotes a parameterised test that is true for a subset of data. That data can be supplied in a number of ways, but the most common is with an [InlineData] attribute.

[InlineData(1, 2, 3)]
[InlineData(-4, -6, -10)]
[InlineData(int.MinValue, -1, int.MaxValue)]
public void CanAddTheory(int value1, int value2, int expected)


If the values you need to pass to your [Theory] test aren’t constants, then you can use an alternative attribute, [ClassData], to provide the parameters. This attribute takes a Type which xUnit will use to obtain the data:

public void CanAddTheoryClassData(int value1, int value2, int expected)
public class CalculatorTestData : IEnumerable<object[]>
    public IEnumerator<object[]> GetEnumerator()
        yield return new object[] { 1, 2, 3 };
        yield return new object[] { -4, -6, -10 };
        yield return new object[] { -2, 2, 0 };
        yield return new object[] { int.MinValue, -1, int.MaxValue };

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();


The [MemberData] attribute can be used to fetch data for a [Theory] from a static property or method of a type. This attribute has quite a lot options, 

The [MemberData] attribute can load data from an IEnnumerable<object[]> property on the test class. 

    public void CanAddTheoryMemberDataProperty(int value1, int value2, int expected)

    public static IEnumerable<object[]> Data =>
        new List<object[]>
            new object[] { 1, 2, 3 },
            new object[] { -4, -6, -10 },
            new object[] { -2, 2, 0 },
            new object[] { int.MinValue, -1, int.MaxValue },
    public static IEnumerable<object[]> GetData(int numTests)
        var allData = new List<object[]>
            new object[] { 1, 2, 3 },
            new object[] { -4, -6, -10 },
            new object[] { -2, 2, 0 },
            new object[] { int.MinValue, -1, int.MaxValue },

        return allData.Take(numTests);

Throw exceptions

Callbacks can be used to throw exceptions when a member is called.

//For non-voids:
calculator.Add(-1, -1).Returns(x => { throw new Exception(); });
//For voids and non-voids:
    .When(x => x.Add(-2, -2))
    .Do(x => { throw new Exception(); });



Assert received method calls, properties, indexer, event subscriptions, event invocation

var command = Substitute.For<ICommand>();
//Check received with second arg of 2 and any first arg:
calculator.Received().Add(Arg.Any<int>(), 2);
//Check did not receive a call where second arg is >= 500 and any first arg:
.Add(Arg.Any<int>(), Arg.Is<int>(x => x >= 500));
//Number of times
command.Received(3).Execute(); // << This will fail if 2 or 4 calls were received
//ignore arguments

Can’t mock an LogError extension method. What you should mock, is the ILogger.Log method, which LogError calls into. It makes the verification code a bit clunky, but it should work

public static class MockExtensions
/// <summary>
/// Checks the given logger received a message which contains given ‘ExpectedLogMessage’
/// Throws exception in case given log message is not received
//If LogInformation() has not been received NSubstitute will throw a ReceivedCallsException
//and let you know what call was expected and with which arguments, as well as
//listing actual calls to that method and which the arguments differed.
//Log<Object>(Information, 0, *Xml File or XML folder Path is not Specified in command line arguments or configuration file.*, <null>, Func<Object, Exception, String>)
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”logger”></param>
/// <param name=”ExpectedLogLevel”></param>
/// <param name=”LogExpected”></param>
/// <param name=”args”></param>
public static void AssertLog<T>(this ILogger<T> logger,
LogLevel ExpectedLogLevel, string ExpectedLogMessage, params object[] args)
logger.Received().Log(logLevel: ExpectedLogLevel, eventId: Arg.Any<EventId>()
, state: Arg.Is<FormattedLogValues>(data =>
data.ToString().Contains( string.Format(ExpectedLogMessage, args) ))
, exception: Arg.Any<Exception>(), formatter: Arg.Any<Func<Object, Exception, String>>());



HTTP / API mocking

  • I find the unit testing approach as broadly practiced to be way too granular and it’s not obvious that the strategy of mocking and faking and tickling every method and property singly yields higher coverage for the code you care about.
  • What we in our team generally aim for internally is not to wedge ourselves into parts of the framework our team doesn’t own (we don’t use the source code of HttpWebRequest, we use what you use) but rather create an environment in the small that can give us the answers we’re looking for to achieve maximum coverage during build-verification testing.
  • That means that if we need one, we’ll have a mock HTTP service that can run on every developer box (self-hosted in the same process, even) and spews out the right set of errors and we run that as we execute the unit tests.

Database mocking

  • If tests have a dependency on a database we’ll have a little local one that’s just capable enough and prepopulated for predictable results in order to exercise the scenario.


Token Authentication and .NET

  • ASP.NET Core Identity automatically supports cookie authentication.
  • It is also straightforward to support authentication by external providersusing the GoogleFacebook, or Twitter ASP.NET Core authentication packages.

  • The customer has a local server with business information which will need to be accessed and updated periodically by client devices.
  • Rather than store user names and hashed passwords locally, the customer prefers to use a common authentication micro-service which is hosted in Remote network (Azure) and used in many scenarios beyond just this specific one.
  • This particular scenario is interesting, though, because the connection between the customer’s location (where the server and clients reside) and the internet is not reliable.
  • Therefore, they would like a user to be able to authenticate at some point in the morning when the connection is up and have a token that will be valid throughout that user’s work shift.
  • The local server, therefore, needs to be able to validate the token without access to the Azure authentication service.
  • This local validation is easily accomplished with JWT tokens. A JWT token typically contains a body with information about
    1. the authenticated user (subject identifier, claims, etc.),
    2. the issuer of the token,
    3. the audience (recipient) the token is intended for, and
    4. an expiration time (after which the token is invalid).
    5. The token also contains a cryptographic signature as detailed in RFC 7518.
  • This signature is generated by a private key known only to the authentication server, but can be validated by anyone in possession of the corresponding public key.
  • One JWT validation work flow (used by AD and some identity providers) involves requesting the public key from the issuing server and using it to validate the token’s signature.
  • In our offline scenario, though, the local server can be prepared with the necessary public key ahead of time.
  • The challenge with this architecture is that the local server will need to be given an updated public key anytime the private key used by the cloud service changes, but this inconvenience means that no internet connection is needed at the time the JWT tokens are validated.

authentication server

  • IdentityServer4 is a flexible OpenID Connect framework for ASP.NET Core.
  • Another good option is OpenIddict. Like IdentityServer4, OpenIddict offers OpenID Connect server functionality for ASP.NET Core.
  • Both OpenIddict and IdentityServer4 work well with ASP.NET Identity 3.
  • Please note that both IdentityServer4 and OpenIddict are pre-release packages currently.

Adding Roles

  • ASP.NET Identity 3 includes the concept of roles.
  • To take advantage of this, we need to create some roles which users can be assigned to.
  • In a real application, this would likely be done by managing roles through a web interface.



Copy large files via Internet

Recently, while copying large files to SharePoint document library via Internet I ran into the issue “The semaphore timeout period has expired”. You find more details about this issue in the link.

One possible solution is to compress the files and split them up to the size as per the limitation of the network bandwidth. We can easily achieve this via the 7Zip tool.

Follow below steps and utilities to copy the large files over Internet.

  • Install 7 zip utility
  • Copy your files to a folder and move to the folder using the CD command
  • Use below command to compress the files individually using ultra compression method and split the files upto 50 MB in length
    FOR %i IN (*.*) DO “C:\Program Files\7-Zip\7z.exe” a “%~ni.7z” “%i” -m0=lzma2 -mx=9 -aoa -v50m
  • Following portion of the command takes all files in the current directory and compresses them individually
    FOR %i IN (*.*) DO “C:\Program Files\7-Zip\7z.exe” a “%~ni.7z” “%i”
  • Following portion of the command uses ultra compression level and lzma2 method (-m0=lzma2 -mx=9 -aoa )
  • Following portion of the command splits the file to 50 MB chunks. (-v50m)
  • RoboCopy is the tool to copy files between different drives with a lot of failover options. You can find more details in link. You can download the GUI tool from here.
  • You can map the Sharepoint folder to your local drive. Please find more details in this link.
  • Use RoboCopy to copy the files from


Raspberry Pi 1 : Hardware Setup

This series of article is for the software engineers who are also interested in electronics/robotics.

Raspberry Pi is the credit card size computer. We may compare it with P3 , 512 MB desktop PC system box. Few people use it as a standalone server or computer. You may find some of the uses in the following link. I connected my external hard disk to it and I’m using it as a file server for my laptop and other PCs.

As a software engineer, my plan is to use Raspberry Pi to code high level language to learn, create and control the basic electronic/digital/robotic circuits via GPIO interface in the shortest period of time.

In order to get started with the Raspberry Pi, please purchase Raspberry Pi Model B. People from Tamilnadu, India can order from Simple Labs (and for me they delivered within 24 hours even to the remote location in Tamilnadu).

Price of Raspberry Pi in India as of 19th September 2013 is:

  • RASPBERRY PI – MODEL B – 512MB – Rs.3,465.00 (with free GPIO cable)
  • Low Cost Case for Raspberry Pi – Rs.262.50

As I have a laptop, I planned to use it as headless device (means using it with remote desktop, without separate monitor, keyboard, mouse). Even for that, you may need to purchase additional components, wires and connectors.

  1. SDHC memory card or Micro SD card with adapter (4 GB min/32 GB Max). Please ensure that card is of Class 10 type. As memory card will be used as permanent storage, Class 10 is essential to achieve high disk I/O performance. Cheap Class 4 type card will degrade the disk I/O performance.

  2. 5 V 2 Amp DC adapter (1 Amp is also OK)
    • All recent model mobile phones comes with micro USB male adapter. Please check the Ampere rating, it should be at least 1 Amp(otherwise in peak power consumption, Raspberry Pi may restart)

    • You may connect the board to normal PC/laptop via USB to micro USB cable also. But your PC/laptop should support power ratings as mentioned earlier.

  3. RJ 45 network cable to connect with Laptop/PC/Hub/Switch:

  4. (optional) Normal mobile earphone to listen to audio from raspberry:

Connecting the wires/components is a straight forward process. If you need detailed description, please check the following references:

  1. RPi Hardware Basic Setup
  2. FAQs

Assembling the Case



Raspberry Pi Ports

Assembled Raspberry Pi

The next part in this series will be installing the OS. Meanwhile, please check the video of Hello World output from Raspberry Pi GPIO using C Language.

PlantUML – N Tier architecture Diagram

1 Introduction

  • PlantUML is an open source tool that can create a variety of diagrams, including
    sequence diagrams.
  • Each diagram is created from a set of instructions contained in a text file.
  • Anyeditor that does not introduce formatting characters (e.g., notepad, wordpad) may be used to create or edit the files.
  • .NET programmers can use VS Code with PlantUML plugin.
  • PlantUML can be downloaded at

2. Quick reference

  • All frequently used symbols are documented in the page
  • PlantUML file contains processing instructions starting with @startuml on the first line and @enduml on the last line.
  • You can create a common theme file and include in your code files. !include Theme.txt
  • Indentations, white spaces, line continuation
    • PlantUML ignores blank lines and whitespace at the beginning of a line. Liberal use of whitespace to offset logical blocks in the text file can enhance readability.
    • Place backslash at the end of the line “\”. Preprocessor will concatenate subsequent line to the current line
  • Comments
    • Comments can be included in the file by starting the line with a single quote (‘).
    • To put a comment on several lines you can start with /’ and end the quote with ‘/
      • 'This is a short comment
        /' This is how you can
        span multiple lines
        of comments
  • Declarations
    • Although PlantUML does not require you to define elements / interfaces / participants (i.e., entities), it is recommended best practice to define all participants together and before they are used.
    • If the element name is long or needs spaces, declare the participant using a short name and the display name. The short name can be used in diagram specific processing instructions.
    • To control the layout of the diagram, you can add spaces in the display name to better
      position the participants.
    • participant POS as " POS "
      participant OPT as " OPT "
      participant LH as "Loyalty Host"
  • Notes
    • Text for notes can be split over multiple lines by inserting new lines (\n) into the note text. Alternatively, the keyword note may be used, followed by the note text on one or more lines, followed by keyword end note.
    • note right of OPT: right of OPT\non two lines
    • note over POS
      over POS
      on two lines
      end note
  • Splitting Diagrams
    • When a diagram is too long to fit on a page without losing readability, split it into one or more graphic files using the keyword newpage.
    • Each additional graphic file generated will have 00x appended (e.g., example.png, example_001.png, example_002.png).
    • Place a divider at the bottom of the first page and at the top of the second page to make it clear that the diagram is split.

3. N Tier architecture Diagram

  • I created as typical N Tier architecture using PlantUML’s diagram. Please find the code below.

@startuml MultiTierArchiteture

‘ Include section with id mail of PlantUMLTheme.pu
!include PlantUMLTheme.pu!theme

&lt;u&gt;Generic Multi Tier Architeture&lt;/u&gt;
end title

caption Prepared by Sabarinathan A.

‘When a line ends with a backslash, the preprocessor will merge the two lines.
Try to keep 2 items together, so they are at the same level in the diagram.

Cloud "External Consumers &amp;lt;&amp;amp;people&amp;gt;" {
actor Clients
[Identity Providers] &amp;lt;&amp;gt; as IdentityProvider
[Single Sign On Services] &amp;lt;&amp;gt; as SSOServer

Cloud "Third Parties &amp;lt;&amp;amp;people&amp;gt;" {
[Third party application] &amp;lt;&amp;gt; as ThirdPartyApp

Folder N-TierArchitecture {
node "UI Tier in DMZ" {
[Front End Controllers] &amp;lt;&amp;gt; as UILayer
node "Application Tier" {
queue Messaging
[Core Business Logic] &amp;lt;&amp;gt; as BusinessServices
[UOW with Generic Repository] &amp;lt;&amp;gt; as DataAccessLayer

node "Data Tier" {
‘[Cache] &amp;lt;&amp;gt; as CacheServer
Database CacheServer
Database OLTPDatabase

[Mail server] &amp;lt;&amp;gt; as Mail
[Remote Services] &amp;lt;&amp;gt; as ThirdPartyServices

note as ArchitectureNote
**N-Tier architecture**
*A layer is a reusable portion of code that performs a specific function.
*Each layer has specific function and interacts with only the layer directly below.
end note

note as BLLNote
**Patterns in Services and Business Layer**
* Facade – single point of entry – unified interface to a set of interfaces in a subsystem
*Factory: Define an interface for creating an object,
but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.
* Dependency Injection DI – allows removing hard-coded dependencies
making it possible to change them, whether at run-time or compile-time.
* Strategy: Allow algorithm selection at runtime.
Encapsulate related algorithms and let the algorithm vary and evolve from the class using it.
Separate the implementation from the delivery of its results.
end note

note as DALNote
**Patterns in Data Access Layer**
* Unit Of Work (UoW) with Generic Repository
* CRUD Methods for domain objects Used in Data layer
* Alternative storage implementations may be easily interchanged.
end note

Clients –&amp;gt; IdentityProvider
Clients –&amp;gt; SSOServer
Clients —&amp;gt; UILayer : HTTP

IdentityProvider –&amp;gt; UILayer
SSOServer –&amp;gt; UILayer

ThirdPartyApp —&amp;gt; UILayer : HTTP

UILayer –&amp;gt; Messaging : HTTP
Messaging -&amp;gt; BusinessServices

BusinessServices –&amp;gt; DataAccessLayer

DataAccessLayer &amp;lt;– CacheServer
CacheServer &amp;lt;– OLTPDatabase ‘ ‘\n \l \r for left and right alignments DataAccessLayer —&amp;gt; OLTPDatabase

BusinessServices —-&amp;gt; Mail
BusinessServices —-&amp;gt; ThirdPartyServices

ArchitectureNote . UILayer
BLLNote . BusinessServices
DALNote . DataAccessLayer


3. UML Diagram Output

Application launcher : Freeware

Application launcher is a light-weight tool created in C# .NET. This serves following four important uses.

  1. With this tool users can load multiple applications, documents and utilities (executables) with a simple mouse click.
  2. Users can move the applications (low priority) from auto startup of Windows to this application. So that users can load them manually only when necessary. It will help Windows to load quickly.
  3. This application runs silently in background and displays just notification icon in Windows tray area. As Windows 8 doesn’t have Start menu, it will be helpful for Windows 8 users to quickly load the necessary applications and documents.

  4. Users can save their list of preferred files as as session so that they can be launched whenever required. It will also help users to switch between the sessions easily. This tool will be useful for the users who are using same machine(laptop/PC) for multiple purposes. For example, for the users who are using a same laptop to develop different types of applications (.NET, Java, Android etc) or for the users who are using a machine for both official and personal uses.


You can download Application Launcher tool from the following link


  • Please install this application other than the programs files folder to avoid folder security permissions issue.
  • This application is portable. The files can be copied to any other machine having .NET 2.0 and can be used.

Implement important design patterns in a single solution


Recently I had been provided with the interesting problem “Cube list to be implemented with the double linked list”.

I began with solving the problem with the straightforward algorithm. But started refactoring the same with OOP principles and design patterns.

The solution is implemented with C# Core 2.0. You can find the source code at Google Drive.

Phase 1: Use most important design patterns

The most important design principles and patterns, I applied in the first phase of refactoring are as below.

  1. Dependency Inversion principle is implemented with necessary interfaces.
  2. Factory pattern
  3. Service Locator pattern is implemented using inbuilt .NET core dependency injection framework.
  4. Iterator pattern is implemented using IEnumerable and yield.

Basic Idea

  1. Cube is implemented with both singly linked list and doubly linked list.
  2. Both the list classes implement common interface ICubeNode. The Cube list class is not aware of (doesn’t care) what type of list is used. (Dependency Inversion principle)
  3. The type of list to be used to build the cube can be selected by the user at run-time.
  4. The selection is passed as a parameter to the Factory class. (dependency injection)
  5. The Factory will generate the required node objects (service locator pattern)
  6. Each and every element of the cube can be extracted using Iterator pattern.


Note: Thanks to Armen Shimoon for sharing the idea to invoke the factory pattern within the .NET Core dependency injection container.

Software Maintenance and Support


This article is a collection of notes and references from other web sites for the self study of Single Page Applications and Angular. The list of source web sites referred are mentioned in the “References” section of this article.


“Begin with the end in mind”

  • Maintenance and support will continue for the life of your software system. A significant portion of the system’s life-cycle budget will be consumed by these tasks. In fact, experts estimate that Maintenance can eventually account for 40 to 80% of the total project cost. 
  • Software does not “wear out” but it will become less useful as it gets older, plus there WILL always be issues within the software itself.
  • Software maintenance cost is derived from the changes made to software after it has been delivered to the end user.


What is Maintenance?


This phase of the software lifecycle consists of the tasks required to keep your system operational after it is delivered into Production.


The different types of maintenance tasks are described as:

  1. Corrective – Updates that are required to correct or fix problems. (generally 20% of software maintenance costs)
  2. Perfective – Modifications that enhance or improve the functionality or performance of the software. This includes new user requirements. – costs due to improving or enhancing a software solution to improve overall performance (generally 5% of software maintenance costs)
  3. Adaptive – Software modifications that are required due to environmental changes (eg. upgrade to operating system) – costs due to modifying a software solution to allow it to remain effective in a changing business environment (25% of software maintenance costs)
  4. Preventative – This corrects potential flaws or problems in the software before they become effective.
  5. Enhancements – costs due to continuing innovations (generally 50% or more of software maintenance costs) Same as Perfective ?

What is Support?

Support refers to the assistance given to users to address their problems and queries after system implementation.

Effort Estimation

Key parameters considered while estimating the efforts required are as below

  • The industry and application type
  • Size of the application
  • Platform Types.
  • Programming language used
  • Effort spent on different maintenance activities
  • Effort spent on different support activities
  • The number and types of defects found during the maintenance period
  • Average time is taken to repair defects
  • Calls to Help Desk
  • Team size

Approaches to take over projects in production

Requirement Elicitation

  • The term elicitation is used in books and research to raise the fact that good requirements cannot just be collected from the customer, as would be indicated by the name requirements gathering. Requirements elicitation is non-trivial because you can never be sure you get all requirements from the user and customer by just asking them what the system should do OR NOT do (for Safety and Reliability). Requirements elicitation practices include interviews, questionnaires, user observation, workshops, brainstorminguse cases, role playing and prototyping

Detect patterns and the general structure of an application at a high level

  • Reverse analysis the source code

    The architecture tools and Static Code Analysis in Visual Studio Ultimate help us to visualize the organization, relationships, design patterns and behavior of existing applications

  • Generate sequence diagrams from the existing code and get required interfaces for each component
  • Sequence diagrams help to asses the impact of changes

Improve productivity and quality through Automation

  • Automated Live Unit Testing with VS
  • Automatically runs the impacted unit tests in the background as you type and provides real-time feedback

Use Agile or Iterative Waterfall SDLC

  • Produces working software early during the lifecycle
  • The focus is on delivering a sprint of work
  • Deliver series of valuable/shippable features/projects
  • Lowrisk
    • Low risks factors as the risks can be identified and resolved during each iteration.
    • if one project goes wrong, it would not impact another project
  • Flexible
    • More flexible as scope and requirement changes can be implemented at low cost
Questions / Metrics to be clarified

  1. Size of each application or module
Application Number of Modules Number of



Number of  Scheduled Batches Number of  Integrations to External applications

The number and types of defects found in a year

Classification Priority No of issues found
Standard Critical (P1)
High (P2)
Medium (P3)
Low (P4)

List of different .NET languages, Databases used with the applications.

Technology / Languages Number of applications
SQL Server

List of different .NET frameworks used with the applications.

Technology / Languages Number of applications
ASP.NET – Web Forms
Entity Framework
Any other technologies

Third-party applications or packages integrated with the applications

Third Party integrations Number of applications
CRM (Siebel, Vantive, Remedy, SharePoint, Documentum etc.)
BI / OLAP / DW Tools

(ETL, Data Stage, Sagent, Informatica,

SAS, Ab Initio)

ERP Skills (Peoplesoft, SAP,

Oracle Applications etc.)

Software development life cycle models used

SDLC Number of applications Number of releases in a year
Iterative Waterfall
Any other SDLC methods

Type of Integration and deployment methods used (to estimate the efforts to deliver the build to different environments

Integration and Deployment Number of applications
Automated deployments only
Manual Integration and deployment

Availability of the documents in English

  • Architecture documents, HLD, LLD, User guides, deployment documents etc


  5. SDLC Models
  6. Visual Studio Architecture Tooling Guide Scenarios