Resolving “Value does not fall within the expected range” ArgumentException while reporting custom health events in Azure service fabric

Hi,

If you’re working with Azure Service Fabric, there are chances you might be using the cluster Health Management APIs provided by SF SDK. And if you’re using those, then you would obviously be posting some custom health events at either your service level, application level or instance level with a source Id, health property and a human-readable description.

Solution :  The one thing to note here is that the Description field of HealthInformation class has a limit of 4095 characters. This is nowhere mentioned in the documentation but it’s there. And if the description is more than that, while reporting you would get the below exception.

Exception Type : System.Argument Exception
Message : Value does not fall within the expected range.
Inner Exception :  null
Stack Trace : 
   at System.Fabric.Interop.NativeClient.IFabricHealthClient3.ReportHealth(IntPtr healthReport)
   at System.Fabric.FabricClient.HealthClient.ReportHealthHelper(HealthReport healthReport)
   at System.Fabric.Interop.Utility.<>c__DisplayClass13.<WrapNativeSyncInvoke>b__12()
   at System.Fabric.Interop.Utility.WrapNativeSyncInvoke[TResult](Func`1 func, String functionTag, String functionArgs)
   at System.Fabric.Interop.Utility.RunInMTA(Action action)
   at System.Fabric.FabricClient.HealthClient.ReportHealth(HealthReport healthReport)
   at ….. your file.

So, in case you run into this exception at the point of reporting, make sure you double-check the description length and in-general all the data that you’ve added to the health report object.

Hope this helps!

Posted in .NET, General | Tagged , , , , , , , , | Leave a comment

Check if service bus topic/subscription/queue exists with SAS key not having Manage permission

Hi,

Consider a scenario where you’ve developed an application health monitoring type system which validates your application at application startup/periodically. Now as part of that if your application uses Azure service bus queues, topics, subscriptions, then it would be good to verify that they all exist before your application actually starts its work.

So your initial thought would be to use NamespaceManager class from the Microsoft.ServiceBus assembly. This class provides <entity>Exists() methods for all the above. However, one point to note here is that NamespaceManager class requires Manage permission to be present to the SAS key from the connection string.

As a security measure, the general advise is to NOT use a SAS key with manage permission and to use one with Send/Listen permissions.

1

So for checking if the entities exist, we can use the TopicClient, SubscriptionClient, QueueClient classes from Microsoft.ServiceBus.Messaging assembly. Check below code. Click for full size image.

2_updated

 

In the above snippet, each of the .Peek() (Or PeekAsync()) methods will throw an exception (Entity not found) if the corresponding entity doesn’t exist and passes if they exist. This check can be used to determine if the entities exist or not.

P.S: There are other ways too but this is relevant if you do not want to send/receive from these service bus entities.

Hope this helps!

Posted in .NET, C#, General | Tagged , , , , , , , , , , , | Leave a comment

Out parameters in Async methods.

A little while ago, I wanted to have an asynchronous method that returned a string but also populated an integer “out” parameter. So I started writing the method as below

// Note: This will give compiler error.
private async Task<string> GetUserDetails(out int userRegionCode)
{
    userRegionCode=105;
    return "samplestring";
}

However, the compiler showed an error stating that out parameters were not allowed for an asynchronous method. After searching for it online and reading through this thread (gives a detailed explanation), I found that it’s a limitation of the CLR.

So instead I used a Tuple to return both the values that I wanted to use. You can read more about Tuple and its usages here.

Sample code below.

... 
... 
// calling code. 
var userDetails = await GetUserDetails(userId); 
Console.WriteLine("Username : {0}", userDetails.Item1); 
Console.WriteLine("User Region Id : {0}", userDetails.Item2); 
... 
... 

private async Tuple<string,int> GetUserDetails(int userId) 
{ 
    return new Tuple<string,int>("Amogh",105); 
    // Note that I can also use the existing helper method (Tuple.Create) here. Read more about it here. 
}

Hope this helps!

Posted in .NET | Tagged , , , | Leave a comment

Cannot access a disposed object. ‘System.Net.Http.StringContent’ While having retry logic.

Hi,

I faced this scenario today when I was trying to make an HttpPost call using a retry logic wherein I was getting an ObjectDisposedException while trying to retry for the first time.

Exception Message:

Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'

My calling code was something like this.

var httpContent = GetHttpContent();

retryPolicy.ExecuteWithRetry(async () => await httpClient.PostAsync(url, httpContent));

The problem with this code is, when the first call to PostAsync is made and it fails, the httpContent object is disposed. This is as designed in the HttpClient class. Refer the comment in this method. Although this seems odd, they intent to do this so that the user doesn’t have to do this explicitly and also to avoid the same request being Posted more than once.

So what happens is, when the first call fails, httpContent is disposed, then as we have retry mechanism, it tries to make the post call again, now with a disposed object and hence this time, the call fails with an ObjectDisposedException.

An easy way to resolve this is to NOT use a variable to store httpContent and instead, create http content directly while making the call. Something like this.

retryPolicy.ExecuteWithRetry(async () => await httpClient.PostAsync(url, GetHttpContent()));

This will make sure that every subsequent retry has a new httpContent object created.

Hope this helps!

References:

  1. http://stackoverflow.com/questions/19260060/retrying-httpclient-unsuccessful-requests
  2. http://stackoverflow.com/questions/29369945/objectdisposedexception-on-httpclient
  3. http://stackoverflow.com/a/15708633/2377928
  4. http://stackoverflow.com/a/25495500/2377928
  5. https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs
  6. https://github.com/dotnet/corefx/issues/1794
Posted in General | Tagged , , , , , , , , , , , , | Leave a comment

Resolving “make sure that the controller has a parameter less public constructor” error in WebAPIs

Hi,

If you’re working with WebAPIs and in the your API Controller, you have a constructor that takes parameters which are being injected by Unity or any IoC Container, then there might be a case where you will get the below error when you try to hit an API from your controller.

Make sure that the controller has a parameterless public constructor. Below screen shot is from Fiddler which shows the exception response in more detail. Click on the image to see it more clearly.

fiddler-response

The reason why it is expecting a default (parameterless) constructor is because the IoC Container was unable to resolve all or some of the parameters of the constructor. Say for example, your constructor is as shown below.

constructor

So, in this case, if the implementations of the above interfaces are in a different assembly than that of the interfaces itself and you have missed adding reference of the assembly which actually has the implementation, then the IoC Container cannot resolve the dependency and thus it will fail to call the above parametered constructor.

So when you make a call to one of the APIs, IoC Container fails to inject the dependencies in the above controller and thus expects it to have a default constructor which is absent in our case. Thus the above exception! So to fix this, make sure you have added all required references (All those which have implementations of the required interfaces) in your project.

Hope this helps!!

Posted in .NET | Tagged , , , , , , , , | Leave a comment

Resolving “Not Authorized to Connect” error while running Azure Service Fabric application

Hi,

If you’re relatively new to Azure Service Fabric, then there is a chance you might run into this issue wherein you start debugging your service fabric application in Visual Studio 2015 and you run into this exception.

Not Authorized to connect

The thing here to be noted is, when you create a service fabric application in Visual Studio 2015, there are 2 projects that get created: See below screen shot.

solution-explorer

In the above sample, the WebApi is the Fabric Service and the SFApplicationDemo is the Fabric App (The one with the sf-logo project logo).

You need to set THIS (the Fabric APP – the one with the above logo) as the startup project and NOT the Fabric Service. This will resolve the issue.

Hope this helps!!

[Refs]

https://social.msdn.microsoft.com/Forums/en-US/cd2d385a-104f-44f9-aa8f-09708909b150/while-creating-servicefabricruntime-i-am-getting-error-not-authorized-to-connect-is-coming?forum=AzureServiceFabric

Posted in .NET | Tagged , , , , , , , , , , , | Leave a comment

Resolving “CloudConfigurationManager does not exist in the current context” compiler error

Hi,

In case you get are trying to access the cloud configuration file in your Azure Cloud service and get the error “CloudConfigurationManager does not exist in the current context” on CloudConfigurationManager class, then all you need to do is add the nuget package “Microsoft.WindowsAzure.ConfigurationManager” to your project. And then, make sure you include the using statement “using Microsoft.Azure” in the class where you’re trying to access the cloud configuration file.

Hope this helps!!

[Update]

As pointed by Matthew Harris, this doesn’t seem to work for ASP.NET 5 json configs. While trying to read configuration specified in json file, please follow the approach mentioned in the below link.

http://stackoverflow.com/questions/30575689/how-do-we-use-cloudconfigurationmanager-with-asp-net-5-json-configs/30580006#30580006

Posted in .NET, C# | Tagged , | 4 Comments