Featured

Welcome to the Pantheon

Quality is not a choice, it’s a requirement.

— Anonymous.

This blog we have started to give our software design ideas a voice, to help developers to create a simplified and intuitive code implementations.

We are just getting this new blog going, so stay tuned for more. Subscribe below to get notified when I post new updates. Meanwhile check out my twitter handle for latest updates.

Freelancing Boot Camp

Recommended System Requirements
– 8 GB RAM,
– Intel Core i5 Processor,
– 500 GB HDD,
– 22″ Monitor

System Setup
Click the below links to download and install the softwares/tools to setup your development environment:

Visual Studio Community Edition

MS SQL Server Express

MS SQL Server Management Studio

Java SDK

Eclipse

Android Studio

Flutter

Git

Visual Studio Code

Beyond Compare

AnyDesk

Test your Development Environment
Perform the below steps to test if you have installed all the required software properly or not.

Visual Studio Community Edition
– Create an user account in GitHub. Launch Visual Studio and login with the GitHub credentials.
– Create a new C++ Console project from the Create Project wizard (or from File -> New -> New Project). Once the project is created, hit F5 to build and run the project output. If a black command prompt appears then the installation is successful.
– Again do the above steps for a C# Console project. If a black command prompt appears then the setup is right of C# projects as well.

MS SQL Server Express
– Open the MS SQL Server Management Studio.
– Click New Query.
– Enter an SQL query to create a table e.g. CREATE TABLE Student(ID int, NAME varchar(50)) and hit F5 to execute the query. If the query executed successfully then the installation is proper.

Eclipse
– After installing Java SDK. Add the path of Java\Bin folder to the PATH environment variable.
– Launch Eclipse.
– Create a new Java project.
– Add a new java file
– Write a HelloWorld program and hit CTRL + F11 to build and run.
– If the application runs properly, then your setup is correct.

C++/CLI Logger

In our previous post we learnt about C++/CLI concepts, here is an example how to implement a logger library using C++/CLI which can be used both C# and C++.

Every software product development needs a mechanism to track execution of it application or to report glitches if any. Therefore, a logger becomes an indispensable module of a software package. Moreover, it becomes more rewarding if all logs are saved in coherent and centralized manner irrespective of which language (C# or C++) it is logged from.

C++/CLI based logger therefore turns into a single useful trick to log all important events (not C# events of course) from both C# and C++. Lets see how we can implement one now.

Here is a C++/CLI based logger class which implements from a pure abstract class ILogger which is again C++/CLI based; see the usage of caret added as suffix in ILogger name. Also ref keyword is used in Logger class declaration to make this class a .NET type instead of native C++ class.

public ref class Logger : public ILogger
{
public:
Logger(ILogWriter^ logWriter);
void LogInfo(String^ MESSAGE, [CallerMemberName][Optional] String^ memberName, [CallerFilePath][Optional] String^ callerFilePath) override;
void LogWarning(String^ MESSAGE, [CallerMemberName][Optional] String^ memberName, [CallerFilePath][Optional] String^ callerFilePath) override;
void LogError(String^ MESSAGE, [CallerMemberName][Optional] String^ memberName, [CallerFilePath][Optional] String^ callerFilePath) override;
private:
ILogWriter^ myLogWriter;
};
view raw Logger.h hosted with ❤ by GitHub

Also notice that this class depends on ILogWriter which is pure C# interface and and .NET String and Caller info attributes; these attributes in C# provide a powerful method to associate metadata, or declarative information with code (we can discuss later), here they are used to get source function name (CallerMemberName) and file path (CallerFilePath) from where a particular log is created.

Next find the implementation of Logger class below. It creates the instance of a simple C# data structure class LogData using gcnew keyword. It also uses .NET DateTime struct to fetch time of log creation.

Logger::Logger(ILogWriter^ logWriter)
{
myLogWriter = logWriter;
}
void Logger::LogInfo(String^ message, String^ memberName, String^ callerFilePath)
{
String^ currentDate = DateTime::Now.ToString("g");
myLogWriter->WriteLog(gcnew LogData(currentDate, LogLevel::INFO, message, memberName, callerFilePath));
}
void Logger::LogWarning(String^ message, String^ memberName, String^ callerFilePath)
{
String^ currentDate = DateTime::Now.ToString("g");
myLogWriter->WriteLog(gcnew LogData(currentDate, LogLevel::WARNING, message, memberName, callerFilePath));
}
void Logger::LogError(String^ message, String^ memberName, String^ callerFilePath)
{
String^ currentDate = DateTime::Now.ToString("g");
myLogWriter->WriteLog(gcnew LogData(currentDate, LogLevel::ERROR, message, memberName, callerFilePath));
}
view raw Logger.cpp hosted with ❤ by GitHub

Now our logger class can be instantiated in any C# class to start logging information. Usually a provider class is implemented to provide a singleton logger instance with desired logging destination (e.g. file, event or database logging) across application.

Logger class we have seen above is of course a .NET compatible type can be used in C# directly but it cannot be used in native C++ as it is; native C++ compiler does not recognize special character caret (^) which is used to refer our managed Logger class. We need to create a wrapper written again in C++/CLI using native C++ class declaration. We can call this class as a LoggerProxy; it only delegates a logging call to our original managed Logger class.

void LoggerProxy::LogInfo(const string MESSAGE)
{
myManagedLogger->LogInfo(ConvertToManagedString(MESSAGE));
}
void LoggerProxy::LogWarning(const string MESSAGE)
{
myManagedLogger->LogWarning(ConvertToManagedString(MESSAGE));
}
void LoggerProxy::LogError(const string MESSAGE)
{
myManagedLogger->LogError(ConvertToManagedString(MESSAGE));
}
String^ LoggerProxy::ConvertToManagedString(string input)
{
return msclr::interop::marshal_as<String^>(input);
}
view raw LoggerProxy.cpp hosted with ❤ by GitHub

Here one more concept is used, Marshalling; it is a process of exchanging data between managed and unmanaged code provided by CLR. One data type in managed context can be marshalled in corresponding data type in unmanaged context or vice versa. So, in above wrapper class, a C++ string is passed to LoggerProxy functions, it is converted into .NET string using marshalling.

msclr::interop::marshal_as<String^>(input);

So, this LoggerProxy class instance can be created in C++ classes to log information. Again, we can use a provider class to get singleton instance of logger with homogeneous logging destination settings. If we use this mechanism, we are ultimately logging information from both C# and C++ software modules using a single logger library in a coherent and centralized manner.

Find complete implementation in my Github repository here.

C++/CLI programming

With .NET framework Microsoft created Common Language Infrastructure (CLI) which lays down specifications for a language to become compatible with .NET framework; to be executed under Common Language Runtime (CLR). CLR is a virtual machine which provides an software environment for programs written using CLI specification to execute. It basically provides a managed environment where memory allocation-release, optimization and interoperability between different .NET langauges, all these are taken care by the environment.

So, here we are going to describe C++/CLI programming technique, a .NET extension of native C++ programming with the help of which we create programs executing within CLR. In other words, with the help of this technique a program can access all .NET managed components in C++. And additionally, as C++/CLI programs written execute within CLR, managed code written in C# can also access C++/CLI classes and invoke its APIs.

This technique first appeared with Visual Studio 2005 as a substitute for the Managed C++ programming which became deprecated. It is usually used as a bridge between C# and C++ in the large production development setup where an application is created using both managed and unmanaged components.

Syntax for C++/CLI classes

A class written in C++/CLI is decalared with ‘ref‘ keyword.

public ref class MyClass

ref keyword here indicates that this class is of reference type and thus can accessed from .NET runtime.

To access above class in C++ Caret symbol (^) is added as a suffix to a class name, symbolizing that this class is a .NET environment class not a native C++ class.

For e.g., following snippet shows way to access .NET string class in C++/CLI class.

String^ myString;

For creating instance of managed types, gcnew keyword is used, ‘gc’ of course symbolizes ‘garbage collected’.

String^ myString = gcnew String();

Note that caret is not used on right side of assignment operator.

Next, C++ scope resolution operator (::) is used instead of dot(.) for accessing public properties/methods of a .NET class and in importing managed namespaces.

Console::ReadLine();

using namespace System::Diagnostics;

Now, that you are familiarized with differences in C++/CLI from native C++ syntax, lets brush up some C++ concepts before starting to build a C++/CLI program.

Object creation in C++

In C++, if you have a class as MyNativeClass and we declare its object like

MyNativeClass myNativeClass;

this myNativeClass is not a reference to the object (which is the usual case in C#), it is a value type object. C++ objects are referred to as static variables which means they are created in Stack unless they are created with pointer reference.

Second, when you have myNativeClass1 and myNativeClass2 and you assign one to another using assignment operator (=), you are not referencing one object to another, you are actually doing a MEMBER-WISE ASSIGNMENT.

So, after this you can appreciate caret(^) and gcnew usage above to create reference type objects in C++ context.

Now, that we have explored all aspects of C++/CLI programming, in our next post we will demonstrate its example by creating a library which can be accessed in both native C++ and C#.

Mocking in C# Unit testing

In our previous post, Unit Testing in C#, Calculator class under test does not have any dependencies. We need not create any other class instance other than Calculator’s. But this is not usually the case in production environment. Here we will see unit testing approach for the classes having one or more dependencies.

Before we start to explain mocking, remember that one of the concepts of Unit testing is isolation of class under test; this means that dependencies of the class under test should have minimum or no affect on test outcome. This becomes possible when we can mimic the dependencies in the test class with objects which we can control and dictate.

‘Mock’ is something which is not real, is an imitation of a real object. So, Mocking in Unit tests is creating replica objects of real dependencies of class under test, which we can control in test environment.

Let’s start by how we create these mock objects. We can implement mock objects by ourselves or better we should take help of mocking frameworks available such as NMock, Moq for C#, Gmock for C++, Mockito, JMock, EasyMock for Java.

Here for the demonstration, I have a Logger class which has two dependencies, IWriter and IDateTimeProvider, responsibilities for each is evident from the names of interfaces. Logger methods for e.g., LogInfo calls Write method of IWriter‘s implementation. Thus we need to verify in our unit tests whether call to the Write method is done with desired argument or not.

namespace LoggerLib
{
using System;
using System.Runtime.CompilerServices;
/// <summary>
/// Logger class.
/// </summary>
internal class Logger : ILogger
{
private IWriter writer;
private IDateTimeProvider dateTimeProvider;
private readonly string info = "Info";
private readonly string warning = "Warn";
private readonly string error = "Error";
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class.
/// </summary>
/// <param name="writer"></param>
public Logger(IWriter writer, IDateTimeProvider dateTimeProvider)
{
if (writer == null)
{
throw new ArgumentNullException("writer cannot be null!");
}
if (dateTimeProvider == null)
{
throw new ArgumentNullException("dateTimeProvider cannot be null!");
}
this.writer = writer;
this.dateTimeProvider = dateTimeProvider;
}
public void LogInfo(string infoText, [CallerMemberName] string memberName = "", [CallerFilePath] string callerFilePath = "")
{
this.writer.Write(string.Format("{0} {1}:{2} {3} {4}", LogTime, info, infoText, callerFilePath, memberName));
}
public void LogWarning(string warningText, [CallerMemberName] string memberName = "", [CallerFilePath] string callerFilePath = "")
{
this.writer.Write(string.Format("{0} {1}:{2} {3} {4}", LogTime, warning, warningText, callerFilePath, memberName));
}
public void LogError(string errorText, [CallerMemberName] string memberName = "", [CallerFilePath] string callerFilePath = "")
{
this.writer.Write(string.Format("{0} {1}:{2} {3} {4}", LogTime, error ,errorText, callerFilePath, memberName));
}
private string LogTime => this.dateTimeProvider.CurrentDateTime.ToString();
}
}
view raw Logger.cs hosted with ❤ by GitHub

Now, in unit test class for creating Logger instance, we need not to create instance of its dependencies, instead we can create mock objects.

namespace LoggerLibTests
{
using LoggerLib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Diagnostics;
[TestClass]
public class LoggerTest
{
private Mock<IWriter> mockWriter;
private Mock<IDateTimeProvider> mockDateTimeProvider;
private Logger logger;
[TestInitialize]
public void TestInit()
{
mockWriter = new Mock<IWriter>();
mockDateTimeProvider = new Mock<IDateTimeProvider>();
logger = new Logger(mockWriter.Object, mockDateTimeProvider.Object);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestConstructor_WriterNull_ArgumentNullException()
{
// Arrange
logger = new Logger(null, mockDateTimeProvider.Object);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestConstructor_DateTimeProviderNull_ArgumentNullException()
{
// Arrange
logger = new Logger(mockWriter.Object, null);
}
[TestMethod]
public void ConstructorTest()
{
// Assert
Assert.IsNotNull(logger);
}
[TestMethod]
public void Test_LogInfo()
{
// Arrange
string textToLog = "SampleTestLog";
string memberName = new StackTrace().GetFrame(0).GetMethod().Name;
string callerFilePath = new StackFrame(0, true).GetFileName();
DateTime dateTimeNow = DateTime.Now;
this.mockDateTimeProvider.Setup(m => m.CurrentDateTime).Returns(dateTimeNow);
string expectedLogText = string.Format("{0} {1}:{2} {3} {4}", dateTimeNow.ToString(), "Info", textToLog, callerFilePath, memberName);
// Act
logger.LogInfo(textToLog);
// Assert
mockWriter.Verify(m => m.Write(expectedLogText), Times.Once);
}
}
}
view raw LoggerTest.cs hosted with ❤ by GitHub

In above LoggerTest class, we have used Moq framework, which gives powerful APIs such as Setup and Verify; using Setup, we can arrange desired return value from the mocked object’s properties and methods; using Verify, we can assert whether the call to the mocked object’s method is created or not.

For creating mock objects, Moq gives Mock<T> type where T is the type for which mock object is to be created. Usually for creating mock objects, dependencies of the class are preferred to be of interface types which both results in better abstraction and loose coupling.

Moq library can be download as nuget package from nuget website. Extract the package with WinZip or 7Zip and refer Moq.dll as assembly reference in your unit test project.

Find complete project solution here.

Unit Testing in C#

Testing any product system becomes necessary to verify its usability and validate its intended purpose. If this testing procedure can be executed on every modification of the product system as a sanity check, it becomes a measure to alleviate chances of any discrepancy introduced.

Thus, Unit testing in software development plays a important role to verify intend and pacify chances of bug instigation on the very basic unit of software. Unit testing is a level of software testing where individual units of software are tested against logical flaws. In object oriented programming, the smallest unit is usually a ‘method‘.

How to start writing Unit Tests

  • Identify logical unit, usually a method or a property which needs to be tested.
  • Create setup in the unit test class to invoke that method.
  • Initiate the call/trigger to the method in focus from your test method.
  • And the last step, compare the actual results/outcome of the call to the expected result/outcome.

We can start with a simple implementation of a calculator and its unit tests.

Lets take basic methods of a calculator, Add and Subtract. I will show you how we can create multiple tests cases on these simple methods.

public class Calculator
{
public Calculator() {}
public double Add(double a, double b)
{
return a + b;
}
public double Subtract(double minuend, double subtrahend)
{
return minuend – subtrahend;
}
}
view raw Calculator.cs hosted with ❤ by GitHub

Now, we will see the unit tests corresponding to these two methods.

[TestMethod]
public void Test_Add_WholeNumbers()
{
// Arrange
var calculator = new Calculator();
// Act
double sum = calculator.Add(3, 5);
// Assert
Assert.AreEqual(8, sum);
}
[TestMethod]
public void Test_Add_FractionalNumbers()
{
// Arrange
var calculator = new Calculator();
// Act
double sum = calculator.Add(3.7, 5.3);
// Assert
Assert.AreEqual(9, sum);
}
[TestMethod]
public void Test_Add_NegativeNumbers()
{
// Arrange
var calculator = new Calculator();
// Act
double sum = calculator.Add(-5.6, 10.6);
// Assert
Assert.AreEqual(5, sum);
}
[TestMethod]
public void Test_Subtract_WholeNumbers()
{
// Arrange
var calculator = new Calculator();
// Act
double difference = calculator.Subtract(5, 3);
// Assert
Assert.AreEqual(2, difference);
}
[TestMethod]
public void Test_Subtract_FractionalNumbers()
{
// Arrange
var calculator = new Calculator();
// Act
double difference = calculator.Subtract(5.3, 2.3);
// Assert
Assert.AreEqual(3, difference);
}
[TestMethod]
public void Test_Subtract_MinuedNegative()
{
// Arrange
var calculator = new Calculator();
// Act
double difference = calculator.Subtract(-5.3, 2.3);
// Assert
Assert.AreEqual(-7.6, difference);
}
[TestMethod]
public void Test_Subtract_BothNegativeNumbers()
{
// Arrange
var calculator = new Calculator();
// Act
double difference = calculator.Subtract(-5.3, -2.3);
// Assert
Assert.AreEqual(-3.0, difference);
}
[TestMethod]
public void Test_Subtract_MinuedLessThanSubtrahend()
{
// Arrange
var calculator = new Calculator();
// Act
double difference = calculator.Subtract(5.3, 7.3);
// Assert
Assert.AreEqual(-2, difference);
}

As you can see, these test cases are logical scenario based, it is not enough to test the method with only positive scenario as our implementation usually breaks for negative and borderline scenario, so it becomes necessary for a effective unit test to verify these corner cases.

Also, as a better design practice, try not to club two or more ‘Assert‘ in one test method, one assertion in one method makes easier to identify and pin-point the failure scenario when tests fail.

Further, to increase readability few things should be kept in mind, first, unit test method name should preferably include name of method under test, scenario and expected result; second, follow AAA pattern i.e. divide your test method in Arrange-Act-Assert sections.

Arrange – creating instances, Act – invoking the method under focus and Assert – comparing expected and actual results.

Here unit tests are written using one of the most popular and intuitive unit testing framework in .NET – MsTest. NUnit is also a good option but MsTest is preferred because of its seamless integration with Visual Studio IDE.

Find complete project here.

Design a site like this with WordPress.com
Get started