Category Archives: .NET

Dicas, exemplos de código, soluções e opniões sobre a plataforma de desenvolvimento da Microsoft

Mocking the HttpClient on AspNet Core

The issue?

Even if you don’t live in the microservices world, you will eventually be in need to make a REST call to some API out there, especially in the AspNet Core world, and the best way to do it is through the HttpClient class.

This class gives you pretty much everything you need, Get, Post, Put, Patch and Delete methods, which map one-to-one to the respective HTTP verbs. The problem is, if you need to Unit Test your class, you may have problems as the methods mentioned above aren’t virtual and the HttpClient class inherits from another class that is not related to these.

Well, you might have noticed (have you?) that the subtitle has a question mark. There is a reason for it. If you do the right implementation, HttpClient will not be an issue for your Unit Tests.

Everything lies on SendAsync method

If there is something beautiful in the AspNet Core world is that it is open source. YES! Every single method and property you have access to has its code open the be read at anytime on GitHub, and yes, HttpClient is part of it! I will leave the link to its source code at the bottom.

After looking close at the source code (which is well written by the way), you figure that all methods except the GET ones (Get, GetAsync, GetStringAsync, etc) make usage of the SendAsync. The SendAsync receives as a mandatory parameter a HttpRequestMessage, which is basically what you send through an HTTP call (body, headers, etc). There is an overload that gets an additional CancellationToken parameter, and that’s the one we are looking for because it is overridable. If you know what a CancellationToken is, just use it, if you don’t, just use Cancellation.None for now.

The code below is an example of a POST being done using HttpClient in a common WebApi Controller.

public class MyController : ControllerBase
{
	private readonly HttpClient client;

    	public MyController(HttpClient client)
    	{
        		this.client = client;
}

	public async Task SomePost(Criteria criteria)
	{    
	    // I am ignoring headers or anything else you might need to send 
	    // The HttpClient is injected via constructor
		var stringContent = new StringContent(JsonConvert.SerializeObject(criteria), Encoding.UTF8, "application/json");
		var result = await this.client.PostAsync($"url", stringContent, CancellationToken.None);
		return Ok(result);
	}
}

The code is fairly simple and it posts something to an endpoint. Now, the unit test that covers and mock HttpClient PostAsync method:

[Fact]
public async Task ItShouldCallSendAsyncAtLeastOnceWhenPosts()
{
	// Moq and xUnit are being used here
	var httpClient = new Mock();
	httpClient
	    .Setup(x => x.SendAsync(It.IsAny(), CancellationToken.None))
	    .ReturnsAsync(new HttpResponseMessage()
	    {
	        StatusCode = HttpStatusCode.OK,
	        Content = new StringContent("{}"),
	    }).Verifiable();

	var controller = new MyController(
	    httpClient.Object
	);

	var criteria = new Criteria() { };

	var result = await controller.SomePostPost(criteria);

	httpClient.Verify(x => x.SendAsync(It.IsAny(), Cancellation.Token), Times.Exactly(1));
}

From what I can tell, the test above passes! Note that I am not mocking PostAsync, but SendAsync as the first one is not mockable the second one is called by the first. In case you want to verify anything sent to the PostAsync, you can use CallBacks offered by Moq lib.

What about Get/GetString/GetStringAsync?

So, what about the “GETs”? Well, it’s simple, don’t use them! Here is why.

The Gets have the advantage of being simple and straightforward, but they only work well for text results and anything bad that happens will throw an exception. Fortunately, there is an alternative. The SendAsync!

Take a look at the code below and it will become more clear:

// instead of this
public async Task GetContent()
{
	var result = await this.client.GetStringAsync("https://some.api");
	return Ok(result);
}

// do this
public async Task GetContent()
{
	var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://some.api");
	var response = await this.client.SendAsync(requestMessage);

	if (response.IsSuccessStatusCode)
	{
	    var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
	    return Ok(result);
	}
	else
	{
	    return StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync().Result);
	}
}

By doing this, your return is more consistent and also gives you the chance for a better error check as the response contains everything you need, like StatusCode, etc.

Enjoy it!

HttpClient source code:

https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs

A working example of it:

https://github.com/Tomamais/dotnet_mocking_httpclient

From VSTO to Office Add Ins in Javascript – Here are my thoughts

It has been a long time since “wrote” my last article in this blog. Recently, it’s so easy to record video tutorials and post them on Youtube (including monetization)  that it’s hard to find a reason to write something. Well, after looking into the current situation of the Office Development, especially for VBA developers.

This is not a click bait article and my real intention is to promote an awareness of what is the real issue in the VBA market, from a developer perspective.

My experience with VBA started in the year 2000, 17 years ago in the Office 97 and soon, the 2000 version. So, I believe this is long enough to give the right to give my opinion about it.

In addition, most of what I’m going to comment here comes from a long talk with Excel/VBA Hard Core colleagues and friends who work (and struggle) daily with VBA, including MVPs in Office.

Disclaimer

The original version of this article was written in Brazilian Portuguese, which is my first language. So, please, be aware that this might have some issues in English and some explanations will not reflect 100% the worldwide market, but what I could live so far in Brazil about it.

Target Audience

I intend to mainly target the VBA Developers audience. If you are interested in VBA for any other reason, you are very welcome! Anyway, you can read this article even if you have no idea about VBA, but I’m pretty sure you are going to get a bit confused in the next 2 to 3 paragraphs.

The Office Development: Current status

I’m writing this text on 2017’s Spring, so, keep this in mind if you are reading this in a far future. Having said that, I can describe the current Office Development as the follow:

  • VBA is still part of the Office (currently 2016/365) installation, but not for Office Online.
  • VBA has not been updated since 1999 despite some minor changes in 2003
  • Microsoft current approach for Office Development involves VSTO and Office Add-Ins created using Visual Studio and Javascript. These App can be installed through Office Store.
  • VBA is completely unstable and it looks like it’s getting worst on every new Office version

I’m going to add more facts that I know to endorse what I am about to write.

It’s undeniable that the VBA Development is far away to end. There are still huge communities supporting it and even more been created daily basis. I hold a forum (in Portuguese) which focus mostly in Excel and VBA and it’s usage only grows! I also have some friends in the same situation and they have been reported the same.

Alright, let’s check some numbers. Take a look at the chart below which I collected from Google Trends:

Google Trends - VBA, VSTO, Office Add Ins and Interop
Google Trends – VBA, VSTO, Office Add-Ins and Interop

It’s almost embarrassing for the alternatives in comparison to VBA. Some can say that VBA’s usage has been decreasing through the years, which is true, but let’s be blunt here. For a technology that was supposed to be dropped almost 20 years ago, such decreasing is almost insignificant, especially nowadays with a new language/framework/technology coming out every single week.

It’s time for starckoverflow.com numbers:

  • VBA: ~80 k mentions
  • VSTO: ~12 k mentions
  • Office JS: ~1,5 k mentions

We cannot consider Office Add-In search because it will consider all kinds of technology in which you can create an Office Add-In, including C++.

These are, in a nutshell, the numbers, and we know Microsoft for its epics success (Office, .NET, SQL Server, Azure) and ALSO for its enormous disasters (Windows Millennium, Vista, Infopath, Zune, Windows Phone).

That said, VBA is still there, strong, VSTO is a big failure and Office Add-Ins in Javascript is growing very slowly and to be honest, I’m not very optimistic about. We will talk more about it.

VBA and its current status

I like to describe the VBA current status as chaotic. But, chaotic does not mean necessarily “bad”.

What is really chaotic is Microsoft misdirection about it.

I’m translating this article right now. Come back in a few minutes… or hours… or days 🙂

C# – Instantiate a IQueryable variable for LINQ

It's not a good image for this article, but I like it
Super LINQ image

Simplicity is the secret for productivity. That is what this post is about.

It’s not a common usage, but sometimes you need to create a instance of a IQueryable variable. I mean, without a call to a LINQ expression or lambda method. You might ask, “why do you want to do this?” I can give you a bunch of reasons, but in my case, I’ve needed to serialize the results to JSON, and “null” was not an option, nor new List.

So, how do I solve it? Simple:

IQueryable listData = Enumerable.Empty<T>().AsQueryable()

It works! This variable serialized produces something like (“listData”: []). Perfect for me!

It has helped a lot and saved a bunch of ifs, new List and some levels of cyclomatic complexity.

Source: http://stackoverflow.com/a/29430798/1209721

Enfoy!