What to Read this Week?

Integrating Cosmos DB with OData (Part 1)

Azure Cosmos DB is great, but what if you need expose it as OData standard, including the query in URI convention? Well, you integrate it with OData. Hassan covers the basic of Cosmos DB, what is it and how to set it up, and how to integrate it with OData.

40 Visual Studio Code Plugins I Have

One can never has enough Visual Studio Code plugins. Here’s another 40 for you.

Open Neural Network Exchange (ONNX)

Machine learning is on the rise and everyone develops their own standard. ONNX (read `onix`) is an open standard model for machine learning. This explains what is it in more details as well as where to get the pre-build ONNX models (model zoo).

Introduction to Big O Notation and Time Complexity (Data Structures & Algorithms #7)

CSDojo explains Big O Notation in a simple, easy to understand way and how time and space complexity are calculated. There are some maths involved, but they are pretty basic.

C# Data Structures

And along with Big O Notation, these articles go over the data structures that are available in C#. Learning and knowing when to use these data structures are important in building the fast algorithm.
Advertisements

What I’m Reading This Week.

“Maybe” monad through async/await in C# (No Tasks!)

https://habr.com/en/post/458692/

Dmitry Tikhonov outlines how to create `Maybe` object in C# that carries 2 states (think about success and failure object) in a monad way. The implementation includes code sample and usage in async / await.

 

Functional Programming In Object-Oriented Programming In C#

https://www.codeproject.com/Articles/5162828/Functional-Programming-in-Object-Oriented-Programm

Emulate functional programming in an object oriented programming world. Yes it is possible. I do feel a basic understanding of functional programming is needed.

 

2019 State of Testing Report

https://www.infoq.com/articles/2019-state-testing-report/

Worth your time to read if you are involved a lot in testing. At least, read the “Key Takeaways”. This report covers what’s going on around global testing community as it surveys 1000 participants from around 80 countries.

 

Clancey’s HotUI

https://github.com/Clancey/HotUI

A MVU (Model View Update) way of building UI. Platform supported includes: iOS, Android, UWP, WPF, Mac OS, Xamarin.Forms, Blazor. And it support hot reload! It’s still proof of concept though, definitely don’t use it in production.

 

Jason Livesay’s NoScriptWeb

https://github.com/runvnc/noscriptweb

I thought this is a very cool concept. The idea is to build all pages in a website from markdown. 100% JavaScript free. That means, no ads, secure, fast browsing. Still work in progress, but promising.

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

Autofac Keyed Service Example

Note: Tested on Autofac 4.9.2.

Autofac Keyed Services provide convenience way to register multiple types of same interface with key identifier, see the documentation here.

It’s very useful feature when we want to choose between different implementations of same interface. See below for example:

`WebApiConfig.cs`
This is where we register our type in Autofac container.

var builder = new ContainerBuilder();

builder.RegisterType<CorporateService>()
    .As<IService>()
    .Keyed<IService>("Corporate");
builder.RegisterType<SchoolService>()
    .As<IService>()
    .Keyed<IService>("School");

GlobalContainer.Container = builder.Build();

`GlobalContainer.cs`
This is global object to store our container for resolving type later in application lifecycle.

using Autofac;

namespace QC
{
    public class GlobalContainer
    {
        public static IContainer Container { get; set; }
    }
}

`IService.cs`
This is sample service interface – don’t copy, make your own.

namespace QC.Service
{
    public interface IService
    {
        double GetRate();
    }
}

`CorporateService.cs`
This is sample service interface implementation – don’t copy, make your own.

namespace QC.Service
{
    public class CorporateService : IService
    {
        public double GetRate()
        {
            return 15;
        }
    }
}

`SchoolService.cs`
This is sample service interface implementation – don’t copy, make your own.

namespace QC.Service
{
    public class SchoolService : IService
    {
        public double GetRate()
        {
            return 10;
        }
    }
}

There are 2 options to resolve `IService` to type we desired (ie: Corporate or School).

1. Resolving Explicitly.
Documentation.

`CustomerController.cs`
Sample controller that choose which service to initiate.

using Autofac;
using QC.Service;
using System.Web.Http;

namespace QC.Controllers
{
    public class CustomerController : ApiController
    {
        [HttpGet]
        public IHttpActionResult GetRate()
        {
            // In real-world, we would have business logic to determine which service to initiate
            var service = GlobalContainer.Container.ResolveKeyed<IService>("Corporate");

            var rate = service.GetRate();
            return this.Ok(rate); // Return 15
        }
    }
}

2. Resolving with an Index (recommended).
Documentation.

`CustomerController.cs`

using Autofac.Features.Indexed;
using QC.Service;
using System.Web.Http;

namespace QC.Controllers
{
    public class CustomerController : ApiController
    {
        private readonly IIndex<string, IService> serviceIndexes;
        private readonly IService service;

        public CustomerController(IIndex<string, IService> serviceIndexes)
        {
            this.serviceIndexes = serviceIndexes;

            // In real-world, we would have business logic to determine which service to initiate
            this.service = this.serviceIndexes["Corporate"];
        }

        [HttpGet]
        public IHttpActionResult GetRate()
        {
            var rate = this.service.GetRate();
            return this.Ok(rate); // Return 15
        }
    }
}