Saturday, June 30, 2018

Visual C# Technical Guru - May 2018

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

image
Visual C# Technical Guru - May 2018
Happy Coding.

Regards,
Jaliya

Thursday, June 21, 2018

ASP.NET Core: FromServices Attribute

In this post let’s have a look at what FromServices attribute in ASP.NET Core brings in to the table.

Imagine I have the following interface and its implementation.
public interface IMyService
{
    string SayHello(string name);
}
 
public class MyService : IMyService
{
    public string SayHello(string name)
    {
        return $"Hello {name}";
    }
}
And I have IMyService registered with ASP.NET Core Services.
services.AddTransient<IMyService, MyService>();
Now imagine, I want to use IMyService.SayHello() method and in one of my controllers, but it’s going to be used in one single action.

Usually what we would be doing is, use constructor injection.
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IMyService myService;
 
    public ValuesController(IMyService myService)
    {
        this.myService = myService;
    }
 
    [HttpGet("{name}")]
    public ActionResult<string> Get(string name)
    {
        return myService.SayHello(name);
    }
}
This looks fine, but if myService is going to be used only in Get(string name) action, having a separator field for IMyService and complicating constructor is really unnecessary.

In these type of situations, FromServices attribute is really handy.
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet("{name}")]
    public ActionResult<string> Get([FromServices] IMyService myService, string name)
    {
        return myService.SayHello(name);
    }
}
So when we decorate the parameter with FromServices attribute, the framework will look up the services container and inject the matching implementation. No need to do constructor injection at all. After all parameter injection is one of the ways we can do DI.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Friday, June 15, 2018

Session: ASP.NET Core 2.1: ActionResult<T> and HttpClientFactory at Sri Lanka Developer Forum

Delivered an hour-long session at Sri Lanka Developer Forum titled ASP.NET Core 2.1: ActionResult<T> and HttpClientFactory. Actually, this was a cover-up session, the original speaker couldn’t make it to deliver the session. And this is the very first session that I did using someone else's laptop as my laptop had trouble connecting to the projector.

There was no time to prepare the slides, it was purely a hands-on session. There I demoed the use of ActionResult<T> and HttpClientFactory which was released with ASP.NET Core 2.1. And there were a lot of questions in overall .NET Core and ASP.NET Core.

Glad the session went well.

More information,

Happy Coding.

Regards,
Jaliya

Friday, June 8, 2018

C#: Getting Power Set of Given Set of Numbers

This is a quick post on how you can calculate the Power Set of given numbers.

Let’s consider the following array.
int[] numbers = new int[] { 1, 2, 3 };
The Power Set of above would be as follows.
{}
{1}
{2}
{1,2}
{3}
{1,3}
{2,3}
{1,2,3}
Count of Power Set is 1 << CountOfNumbers (or 2 ^ CountOfNumbers).

Here is a simple method to get the Power Set of given integer array.
static IEnumerable<IEnumerable<int>> GetPowerSet(int[] numbers)
{
    List<List<int>> outerList = new List<List<int>>();
 
    int permutationsCount = 1 << numbers.Length;
    int[] permutationNumbers = Enumerable.Range(0, permutationsCount).ToArray();
 
    for (int i = 0; i < permutationsCount; i++)
    {
        List<int> innerList = new List<int>();
 
        for (int j = 0; j < numbers.Length; j++)
        {
            if ((permutationNumbers[i] & (1 << j)) != 0)
            {
                innerList.Add(numbers[j]);
            }
        }
 
        outerList.Add(innerList);
    }
 
    return outerList;
}
We can refactor the code to use LINQ and eliminate some line of codes.
static IEnumerable<IEnumerable<int>> GetPowerSet(int[] numbers)
{
    IEnumerable<IEnumerable<int>> permutations = from permutation in Enumerable.Range(0, 1 << numbers.Length)
                                                 select
                                                     from index in Enumerable.Range(0, numbers.Length)
                                                     where (permutation & (1 << index)) != 0
                                                     select numbers[index];
    return permutations;
}

Happy Coding.

Regards,
Jaliya

Thursday, June 7, 2018

ASP.NET Core 2.1: HttpClientFactory

One of the features that got released with ASP.NET Core 2.1 is HttpClientFactory. In this post let’s see how we can use HttpClientFactory in an ASP.NET Core 2.1 application.

There are basically three ways.
  1. HttpClientFactory directly
  2. Named Clients
  3. Typed Clients
Let’s have a look at them with sample use.

1. HttpClientFactory directly

Registration
services
    .AddHttpClient();
Use
public class ValuesController : ControllerBase
{
    private readonly IHttpClientFactory httpClientFactory;
 
    public ValuesController(IHttpClientFactory httpClientFactory)
    {
        this.httpClientFactory = httpClientFactory;
    }
 
    [HttpGet]
    public async Task<ActionResult> Get()
    {
        var client = httpClientFactory.CreateClient();
        client.BaseAddress = new Uri("http://myblog.blogspot.com");
        // TODO: Client configuration
 
        string result = await client.GetStringAsync("/");
 
        return Ok(result);
    }
}

2. Named Clients

Registration
services
    .AddHttpClient()
    .AddHttpClient("BlogClient", client =>
    {
        client.BaseAddress = new Uri("http://myblog.blogspot.com");
        // TODO: Client configuration
    });
Use
public class ValuesController : ControllerBase
{
    private readonly IHttpClientFactory httpClientFactory;
 
    public ValuesController(IHttpClientFactory httpClientFactory)
    {
        this.httpClientFactory = httpClientFactory;
    }
 
    [HttpGet]
    public async Task<ActionResult> Get()
    {
        var client = httpClientFactory.CreateClient("BlogClient");
 
        string result = await client.GetStringAsync("/");
 
        return Ok(result);
    }
}
The only change is, instead of CreateClient(), I am calling CreateClient(clientName) which I have registered in ConfigureServices method.

3. Typed Clients

Consider the following implementation.
public class BlogClient
{
    public HttpClient Client { get; set; }
 
    public BlogClient(HttpClient client)
    {
        client.BaseAddress = new Uri("http://myblog.blogspot.com");
        // TODO: Client configuration
 
        this.Client = client;
    }
}
Registration
services
    .AddHttpClient()
    .AddHttpClient("BlogClient", client =>
    {
        client.BaseAddress = new Uri("http://myblog.blogspot.com");
        // TODO: Client configuration
    })
    .AddTypedClient<BlogClient>();
Use
public class ValuesController : ControllerBase
{
    private readonly BlogClient blogClient;
 
    public ValuesController(BlogClient blogClient)
    {
        this.blogClient = blogClient;
    }
 
    [HttpGet]
    public async Task<ActionResult> Get()
    {
        string result = await this.blogClient.Client.GetStringAsync("/");
 
        return Ok(result);
    }
}
Alternatively, you can define a contract.
public interface IBlogClient
{
    HttpClient Client { get; set; }
}
 
public class BlogClient : IBlogClient
{
    public HttpClient Client { get; set; }
 
    public BlogClient(HttpClient client)
    {
        client.BaseAddress = new Uri("http://myblog.blogspot.com");
        // TODO: Client configuration
 
        this.Client = client;
    }
}
Registration
services
    .AddHttpClient()
    .AddHttpClient("BlogClient", client =>
    {
        client.BaseAddress = new Uri("http://myblog.blogspot.com");
        // TODO: Client configuration
    })
    .AddTypedClient<BlogClient>()
    .AddTypedClient<IBlogClient, BlogClient>();
Use
public class ValuesController : ControllerBase
{
    private readonly IBlogClient blogClient;
 
    public ValuesController(IBlogClient blogClient)
    {
        this.blogClient = blogClient;
    }
 
    [HttpGet]
    public async Task<ActionResult> Get()
    {
        string result = await this.blogClient.Client.GetStringAsync("/");
 
        return Ok(result);
    }
}
Happy Coding.

Regards.
Jaliya