Install and configure Git for windows

Download Git from here;

https://git-scm.com/download/win

Visual Studio 2019 Settings

Tools -> Get Tools and Features -> Individual components

Search “git”. Select “Git for Windows” from menu;

Visual studio will take some time to reconfigure.

Visual Studio 2017 Settings

Open Visual Studio, Check the Git for Windows in the Tools – Get Tools and Features…), go to “Individual Item” tab,  check “Git for Windows”, and click “Modify”. Then it will ask you to update Visual Studio to the latest version, for example 15.9.36.

Click ok to install and close.

Reflection – What are the benefits

Generally, when people talk about reflection, the main concern is the performance. Because it runs on runtime, so theoretically, it is a little bit slower than the normal application. But it is flexible for many scenarios, especially if you develop the framework. If it is acceptable to spend a few seconds (or only hundreds of milliseconds) to load assemblies, then feel free to use it.

Let’s walk through an example; We are going to use an interface called “ISpeaker”.

internal interface ISpeaker
{
    string SayHello();
}

Create three implementation classes:

English Speakers

internal class EnglishSpeaker : ISpeaker
{
    public string Name => this.GetType().ToString();
    public string SayHello()
    {
        return "Hello!";
    }
}

Urdu Speakers

internal class UrduSpeaker : ISpeaker
{
    public string Name => this.GetType().ToString();
    public string SayHello()
    {
        return "as-salaam-alaikum";
    }
}

Chinese Speakers

internal class ChineseSpeaker : ISpeaker
{
    public string Name => this.GetType().ToString();
    public string SayHello()
    {
        return "Nihao";
    }
}

Now we can use reflection to find all the implementations of ISpeaker interface and call their methods or properties.

internal class ReflectionHelper
{
    public static List<Type> GetAvailableSpeakers()
    {
        // You can also use AppDomain.CurrentDomain.GetAssemblies() to load all assemblies in the current domain.
        // Get the specified assembly.
        var assembly =
                Assembly.LoadFrom(Path.Combine(Directory.GetCurrentDirectory(), "ReflectionDemo.dll"));
        // Find all the types in the assembly.
        var types = assembly.GetTypes();
        // Apply the filter to find the implementations of ISayHello interface.
        var result = types.Where(x => x.IsClass && typeof(ISpeaker).IsAssignableFrom(x)).ToList();
        // Or you can use types.Where(x => x.IsClass && x.GetInterfaces().Contains(typeof(ISpeaker))).ToList();
        return result;
    }
}

In this class, we load the specified dll file that contains types we need. Then we can apply the LINQ query to find all the implementations of ISpeaker interface using Reflection.

Test the program output. we can output the name and call SayHello method of each speaker:

using ReflectionDemo;
using System.Reflection;

Console.WriteLine("Hello, World!");

Console.WriteLine("Here is the Reflection sample:");
// Find all the speakers in the current domain
var availableSpeakers = ReflectionHelper.GetAvailableSpeakers();
foreach (var availableSpeaker in availableSpeakers)
{
    // Create the instance of the type
    var speaker = Activator.CreateInstance(availableSpeaker);
    // Get the property info of the given property name
    PropertyInfo namePropertyInfo = availableSpeaker.GetProperty("Name");
    // Then you can get the value of the property
    var name = namePropertyInfo?.GetValue(speaker)?.ToString();
    Console.WriteLine($"I am {name}");
    // Invoke the method of the instance
    Console.WriteLine(availableSpeaker.InvokeMember("SayHello", BindingFlags.InvokeMethod, null, speaker, null));
}
Console.WriteLine();
Console.ReadKey();

Run the program, you will see the below output:

If we need to add other speakers in other languages, just add the implementation classes in the same project. .NET reflection can automatically find out all the required classes and call the methods correctly.

It is extremely useful when we create the plugin-type applications. First we make the interfaces and call the methods from the client by reflection. Then we can create plugins following the interface for the client, which can be loaded as the *.dll files dynamically and executed.

Another scenario is for the framework development. As a framework developer, you will not be able to know what implementations the users will create, so you can only use reflection to create these instances. One example is in some MVVM frameworks, if you create the classes following the conventions, eg. xxxViewModel, the framework can find all the ViewModels and load them automatically using reflection.

The main namespaces we need to use for reflection are System.Reflection and System.Type. You may also need to know the below terms:

Resources

Reflection in .NET

Viewing Type Information

Dynamically Loading and Using Types

https://levelup.gitconnected.com/four-ways-to-generate-code-in-c-including-source-generators-in-net-5-9e6817db425

https://docs.microsoft.com/en-us/dotnet/core/tutorials/creating-app-with-plugin-support

Rest API HATEOAS (Hypermedia as the Engine of Application State)

REST architecture allows us to generate hypermedia links in our responses dynamically and thus make navigation much easier. To put this into perspective, think about a website that uses hyperlinks to help you navigate to different parts of it. You can achieve the same effect with HATEOAS in your REST API.

The advantage of the above approach is that hypermedia links returned from the server drive the application’s state and not the other way around.

REST client hits an initial API URI and uses the server-provided links to access the resources it needs and discover available actions dynamically.

The client need not have prior knowledge of the service or the different steps involved in a workflow. Additionally, the clients no longer have to hardcode the URI structures for various resources. HATEOAS allows the server to make URI changes as the API evolves without breaking the clients.

Let’s say we need to define an API that guides a client through a signature process. In this process after getting a Resource, the resource will include a Link indicating the following elements that are necessary. The plan is to add a signature link in this example:

{
    "documentID": 10,
    "documentType": "Contract",
    "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    "links": [
        {
            "href": "10/signatures",
            "rel": "approval",
            "type" : "POST"
        }
    ]
}

The recommendation is to add a link to xsd/schema document which will define the structure of model attributes. e.g.

"links": [
    {
        "href": "10/signatures",
        "rel": "approval",
        "type" : "POST",
        "schema" : "/schemas/signature.xsd"
    }
]

Now the client can read the XSD document to find out about the model. This approach wouldn’t process the request but return the model XSD/schema document to the client. In this way, when client want to POST on 10/signatures, it may get the request schema by GET 10/signatures.xsd.

Resources

https://thereisnorightway.blogspot.com/2012/05/api-example-using-rest.html

https://medium.com/@andreasreiser94/why-hateoas-is-useless-and-what-that-means-for-rest-a65194471bc8

https://stackoverflow.com/questions/1775782/does-anyone-know-of-an-example-of-a-restful-client-that-follows-the-hateoas-prin

https://netflix.github.io/genie/docs/3.0.0/rest/#_introduction

Project post-build event command to copy files to a local folder or network share in VS

I wanted to copy DLL files to a network share. I am dynamically loading assemblies in different applications and can not risk changing file paths.

I don’t want to mess up Visual Studio default binary locations. The work around is to do XCOPY in visual studio post build event;

XCOPY "$(TargetDir)*" "\\Netowrk Path\FolderName\" /S /Y

It’s that simple.

Resources

https://stackoverflow.com/questions/834270/visual-studio-post-build-event-copy-to-relative-directory-location

https://social.msdn.microsoft.com/Forums/vstudio/en-US/7dc8f75f-596e-427a-9f6e-bd1a2408b9e6/post-build-command-to-copy-files?forum=visualstudiogeneral

Return multiple values to a method caller

This is a code sample for returning multiple values from a c# method. For example, imagine a method that accepts multiple parameters and return two parameters;

So far the best method that I have found is this;

public Tuple<int, int> GetMultipleValue()
{
     return Tuple.Create(1,2);
}

This works in .NET 4 and up. Tuples with two values have Item1 and Item2 as properties.

Here is a list of different methods;

1. ref / out parameters

using ref:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add = 0;
    int multiply = 0;
    Add_Multiply(a, b, ref add, ref multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
    add = a + b;
    multiply = a * b;
}

using out:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add;
    int multiply;
    Add_Multiply(a, b, out add, out multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
    add = a + b;
    multiply = a * b;
}

2. struct / class

struct Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

using class:

class Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

3. Tuple

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.Item1);
    Console.WriteLine(result.Item2);
}

private static Tuple<int, int> Add_Multiply(int a, int b)
{
    var tuple = new Tuple<int, int>(a + b, a * b);
    return tuple;
}

C# 7 Tuples

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    (int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
    Console.WriteLine(a_plus_b);
    Console.WriteLine(a_mult_b);
}

private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
{
    return(a + b, a * b);
}

C# 7 Tuples More..

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

which could then be used like this:

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

You can also provide names to your elements (so they are not “Item1”, “Item2” etc). You can do it by adding a name to the signature or the return methods:

(string first, string middle, string last) LookupName(long id) // tuple elements have names

or

return (first: first, middle: middle, last: last); // named tuple elements in a literal

They can also be deconstructed, which is a pretty nice new feature:

(string first, string middle, string last) = LookupName(id1); // deconstructing declaration

Resource

https://stackoverflow.com/questions/748062/return-multiple-values-to-a-method-caller