Creating a hosted service and dealing with the “Bad Request”

In several situations when working with the Azure Management API, I’ve found that the exception containing the message “The remote server returned an unexpected response: (400) Bad Request.” is not really useful. I’m using the NuGet package (Windows Azure Service Management Library Nuget Package) to communicate with the Azure Management REST API.
I’ve found the solution in the WCF ProtocolException receiving html

public void CreateHostedService(string name, string azureLocation)
{
    try
    {
        var createHostedServiceInput = new CreateHostedServiceInput
            {
                Label = ServiceManagementHelper.EncodeToBase64String(name),
                ServiceName = name,
                Location = azureLocation
            };

        Channel.CreateHostedService(SubscriptionId, createHostedServiceInput);
    }
    catch (ProtocolException e)
    {
        throw CreateUsableException(e);
    }
}

private static Exception CreateUsableException(ProtocolException protocolException)
{
    var webException = protocolException.InnerException as WebException;
    if (webException != null && webException.Response != null)
    {
        var responseStream = webException.Response.GetResponseStream() as MemoryStream;
        if (responseStream != null)
        {
            var responseBytes = responseStream.ToArray();
            var responseString = Encoding.UTF8.GetString(responseBytes);
            return new Exception(responseString);
        }
    }

    return new Exception("No return message could be extracted from the exception!");
}
Advertisements

About Tamas Nemeth

Husband and proud father of two daughters in Nürnberg. I'm working as a Senior Software Developer and an enthusiastic Clean-Coder. I spend most of my free time with my family (playing, hiking, etc...). I also play table-tennis and badminton sometimes...
This entry was posted in Technical Interest and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s