Reading List

How Microservices Architecture Impacted the Culture of Software Development

Most people do microservice because it’s a new buzzword! But, there’s actually reason behind it and it will improve your team dynamic.


Why I love Trunk Based Development (or pushing straight to master)

Mattia made an argument why it makes sense for the whole team to push straight to `master`. The key is having the right people in the team. He has good points, most I agree, some I disagree with. What’s your take?


Async Await C#

Basic yet comprehensive article on `async` `await` in C#. Worth reading for beginners and expert alike if you want to brush up on `async` `await`.


You don’t need ordered delivery

Particular.net blog posts in general are really good, high quality. This _particular_ post, however, gives a different perspective of how messaging queues are delivered. Often time we think it needs to be ordered. Well, maybe we should think again.


Messaging Practices

I never thought there’s such things as good practices in messaging queue. After reading this, I think it makes sense to have one. When you have to deliver large number of events, good practices make big differences.


Advertisements

My Sunday Reading List

Declarative vs Imperative

https://en.wikipedia.org/wiki/Declarative_programming
https://en.wikipedia.org/wiki/Imperative_programming

This is probably your interview questions, even though not many company I came across has asked these. Declarative programming vs imperative programming, is basically, in its very simple form, like functional programming vs object-oriented programming.


6 Key Concepts in Andrew Ng’s “Machine Learning Yearning”

If you want to learn Machine Learning, Andrew Ng is the man you need to listen to. There’s so much more to cover beyond this article, but it lays out 6 basic concepts in Machine Learning.


Using the Microsoft Graph API with PowerShell

A detail walkthrough on how to query Microsoft Graph API, which is a service to manage all most aspects of Azure AD and Office 365, with Powershell. From setting up secrets, certificate, application permission to access token, all covered here.


Why our team cancelled our move to microservices

Sometime you have to know when to back out as in this story of Steven’s team backing out from implementing microservices. What’s even more awesome is, he documented the lesson-learned from his team on what to consider when implementing microservices.


How you can build a Serverless API using GraphQL .Net Core, C# and VS Code

A step-by-step walkthrough on how to build GraphQL-based API with .Net Core, C# and Azure Functions.


Programmatically Configure EF DbConfiguration

Tested on:
Entity Framework 6.2.0

There are few ways to set EF configuration, this describes using code-based DbConfiguration.

  1. Create a class inherit from DbConfiguration.
    using System.Data.Entity;
    
    namespace InfinityDataModel
    {
        public class InfinityConfiguration : DbConfiguration
        {
            public InfinityConfiguration()
            {
                // Sample configuration
                SetDefaultConnectionFactory(new LocalDbConnectionFactory("InfinityDb"));
            }
        }
    }
    

  2. The class must be in same assembly as your the Entity Framework Data Model.

  3. In the constructor, set the configuration you wanted. For all possible configurations, see here.
  4. There is no need to do anything else. EF will load your configuration class when initialized.

References:
Microsoft

C# Check if PropertyType is Null

You want to check if a property’s PropertyType is nullable. In the example below, only property `IsStudent` is nullable.

User.cs

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool? IsStudent { get; set; }
}

Checking if PropertyType is nullable is useable when adding column to `DataTable` object. If column to be added is nullable type, we need to explicitly set it.

To check if PropertyType is nullable, we can use `System.Nullable.GetUnderlyingType(Type nullableType)`, see example below and reference here.

public void GetUsers()
{
    System.Reflection.PropertyInfo[] properties = typeof(User).GetProperties();
    System.Reflection.PropertyInfo[] readableProperties = properties.Where(w => w.CanRead).ToArray();
    foreach (var property in readableProperties)
    {
        var propertyType = property.PropertyType;
        if (System.Nullable.GetUnderlyingType(propertyType) != null)
        {
            // It's a nullable type
        }
        else
        {
            // It's not a nullable type
        }
    }
}

Reference
Stackoverflow

DynamicProxyGenAssembly2

DynamicProxyGenAssembly2 is a temporary assembly built by mocking systems that use CastleProxy like Moq or NSubsitute. It is generated when the mock is needed and disposed of after the tests are finished.

Tested on:
Moq 4.10 https://github.com/moq/moq4
.Net 4.5

Following is AssemblyInfo.cs in QC.Client project.

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("QC.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QC.Client")]
[assembly: AssemblyCopyright("Copyright ©  2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]

[assembly: Guid("d62d1a60-782a-46d8-b5f5-2f6d12ad1339")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("QC.ClientTest")]

Following is class i want to test.
UserManagement.cs (In QC.Client project)

namespace QC.Client
{
    public class UserManagement
    {
        public void UpdateUser(string address)
        {
            var executer = new Executer();
            executer.Run();
        }
    }
}

Executer.cs (In QC.Client project)

namespace QC.Client
{
    public class Executer
    {
        internal virtual bool Run()
        {
            return true;
        }
    }
}

Following is my unit test.
UserManagementTest.cs (In QC.ClientTest project)

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using QC.Client;

namespace QC.ClientTest
{
    [TestClass]
    public class UserManagementTest
    {
        [TestMethod]
        public void UpdateUserShouldWork()
        {
            // Mock
            var mock = new Mock();
            mock.Setup(x => x.Run());

            // Act
            var userManagement = new UserManagement();
            userManagement.UpdateUser("Test Address");

            // Assert
            mock.Verify(x => x.Run(), Times.Once);
        }
    }
}

Problem
MS Test throwing following error when unit testing internal member of a class in different project.
When unit test in above `UserManagementTest.cs` is run, MS Test throw following error:

Message: Test method QC.ClientTest.UserManagementTest.UpdateUserShouldWork threw exception:
System.ArgumentException: Cannot set up Executer.Run because it is not accessible to the proxy generator used by Moq:
Can not create proxy for method Boolean Run() because it or its declaring type is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] attribute, because assembly QC.Client is not strong-named.

Note:
– MS Test only throw exception if the accessor of method being tested is internal. In above example it is `Executer.Run()`.
– Virtual keyword in method being tested is to allow Moq to mock the method.

Solution is to simply add following code in AssemblyInfo.cs

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Sources
Stackoverflow

Expression Func vs. Func

Func
`Func<>` is a lambda expression. A delegate. A pointer to a method. Runtime engine can not “look” inside `Func<>`, it can only execute `Func<>`.

Example usage:

Func<int> haveFunc = () => 15; // return 15

Expression Func
`Expression<Func<>>` is an expression tree. It’s a lambda expression in form of tree data structure. It only hold metadata or information and composition of the contained lambda expression. Runtime engine can look “inside” `Expression<Func<>>` and translate it to other statement you need.

Example usage:

Expression<Func<int>> notMuchFunc = () => 25;

Why is it important ?
Misuse of this could be cause compile error or in the case of EF, a performance hit.

Compile Error Example
Linq has few methods that take `Func<>` or `Expression<Func<>>` parameter, for example `Where` extension method, as seen in signature below.

System.Linq.Enumerable
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

System.Linq.Queryable
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);

Depend on parameter type we pass in, compiler know which extension method to call.

In the code below, ProcessUsers3 throw compiler error. Because we pass in `Expression<Func<>>`, compiler think we are calling `Where` extension method which accept `IQueryable<>` but `this.GetUserNames()` return `IEnumerable<>`.

The workaround is to convert `IEnumerable<>` to `IQueryable<>` using `.AsQueryable()` as can be seen on ProcessUsers4.

public IEnumerable<string> GetUserNames()
{
    return new[] { "user1", "user2" };
}

public void ProcessUsers()
{
    // Return type IEnumerable<string>
    var result = this.GetUserNames()
        .Where((item) => !string.IsNullOrEmpty(item));
}

public void ProcessUsers2()
{
    // Return type IEnumerable<string>
    Func<string, bool> predicate = (item) => !string.IsNullOrEmpty(item);
    var result = this.GetUserNames()
        .Where(predicate);
}

public void ProcessUsers3()
{
    // Compile error
    // We pass in Expression<Func<>> to Where extension method, compiler think we are calling the Where extension method for IQueryable<> - this.GetUserNames() return IEnumerable<>
    Expression<Func<string, bool>> predicate = (item) => !string.IsNullOrEmpty(item);
    var result = this.GetUserNames()
        .Where(predicate);
}

public void ProcessUsers4()
{
    Expression<Func<string, bool>> predicate = (item) => !string.IsNullOrEmpty(item);

    // Return type IQueryable<string>
    var result = this.GetUserNames()
        .AsQueryable()
        .Where(predicate);
}

Performance Hit Example
In the code below, both methods are legal, compile without error and run without error.

On GetAppConfigurations1, we query EF context by passing `Func<>`, a lambda expression. Because the context can not “look” inside the lambda expression (it can only execute it), Linq would get all AppConfiguration and run `Func<>` on each record, which increase load time.

On GetAppConfigurations2, we query EF context by passing `Expression<Func<>>`, an expression tree. It allow Linq to “look” inside the expression tree, read its metadata and composition than figure out the best and most perfomant way to query AppConfiguration with filter condition we specified.

public IEnumerable<AppConfiguration> GetAppConfigurations1()
{
    Func<AppConfiguration, bool> filter = (config) => config.Id == 1;

    using (var context = new QCEntities())
    {
        var result = context.AppConfiguration.Where(filter);
        return result;
    }
}

public IEnumerable<AppConfiguration> GetAppConfigurations2()
{
    System.Linq.Expressions.Expression<Func<AppConfiguration, bool>> filter = (config) => config.Id == 1;

    using (var context = new QCEntities())
    {
        var result = context.AppConfiguration.Where(filter);
        return result;
    }
}

References
Stackoverflow

Iterator, Enumerator and Yield Keyword

Note: The example code below is only used to demonstrate my point, by all means it’s not SOLID.

In Object Oriented Programming
Iterating is a process of repeating similar steps or functions.
Enumerating is an action of going through an entire collection of objects.

In C#
Iterator refers to set of functions to be executed on a collection.
For example:

Func<User, User> deactivate = (User u) =>
{
    u.IsActive = false;
    return u;
};

Enumerator refer to an object type that result from iterating through a collection.
For example:

IEnumerable<User> result = Users.Select(x => deactivate(x));

Complete code:

public class User
{
    public bool IsActive { get; set; }
}

public IEnumerable<User> DeactivateUsers()
{
    User[] Users = {
        new User { IsActive = true },
        new User { IsActive = true },
        new User { IsActive = true }
    };

    Func<User, User> deactivate = (User u) =>
    {
        u.IsActive = false;
        return u;
    };

    IEnumerable<User> result = Users.Select(x => deactivate(x));
    return result;
}

Yield Keyword
Yield keyword allow you to indicate that the code where it is being used is an iterator. The code must return a type of IEnumerable or IEnumerable<T>.

Continue from example above. We can write it different way, such as:

public IEnumerable<User> DeactivateUsers()
{
    User[] Users = {
        new User { IsActive = true },
        new User { IsActive = true },
        new User { IsActive = true }
    };

    List<User> result = new List<User>();

    foreach (var u in Users)
    {
        u.IsActive = false;
        result.Add(u);
    }

    return result;
}

Or another way, which utilize yield keyword to return Enumerator object for us.

public IEnumerable<User> DeactivateUsers()
{
    User[] Users = {
        new User { IsActive = true },
        new User { IsActive = true },
        new User { IsActive = true }
    };

    foreach (var u in Users)
    {
        u.IsActive = false;
        yield return u;
    }
}

References:
MSDN
Stackoverflow