Sorted By: Tag (windows-azure)

Windows Azure Management Client Libraries for .NET and It Supports Portable Class Library

One of the missing pieces of the Windows Azure story is within our reach now! A few days ago Azure folks have released Windows Azure .NET Management Client Libraries
2013-10-30 06:17
Tugberk Ugurlu


One of the missing pieces of the Windows Azure story is within our reach now! Awesome Azure folks have released Windows Azure .NET Management Client Libraries which also support portable class library (PCL). It is now possible to build custom Windows Azure management applications in .NET ecosystem with possible minimum effort. Brady Gaster has a very detailed blog post about the first release of these libraries if you would like to get started with it really quickly. In this post, I'll look at the these libraries in a web developer point of view.

Management libraries are available as NuGet packages and they are at the pre-release stage for now (ignore the HdInsight package below):

image

Some packages are there for the infrastructural purposes such as tracing, exception handling, etc. and other packages such as Storage and Compute has .NET clients to manage specific services which is good and bad at the same time. When we take a first look at the libraries, we can see a few great things:

  • All operations are based on the HttpClient. This gives us the opportunity to be very flexible (if the client infrastructure allows us) by injecting our inner handler to process the requests.
  • All client operations are asynchronous from top to bottom.
  • It supports Portable Class Library.

Getting started is also very easy. The following code is all I needed to do to query the storage accounts I have inside my subscription:

static void Main(string[] args)
{
	const string CertThumbprint = "your-cert-thumbprint";
	const string SubscriptionId = "your-subscription-id";
	X509Certificate2 cert = Utils.FindX509Certificate(CertThumbprint);
	SubscriptionCloudCredentials creds = 
		new CertificateCloudCredentials(SubscriptionId, cert);

	StorageManagementClient storageClient = 
		CloudContext.Clients.CreateStorageManagementClient(creds);

	StorageServiceListResponse response = storageClient.StorageAccounts.List();
	foreach (StorageServiceListResponse.StorageService storageService in response)
	{
		Console.WriteLine(storageService.Uri);
	}

	Console.ReadLine();
}

The client certificate authentication is performed to authenticate our requests. Notice that how easy it was to get a hold of a storage client. By using the CloudContext class, I was able to create the storage client by using the CreateStorageManagementClient extension method which lives under the Microsoft.WindowsAzure.Management.Storage assembly.

How HttpClient is Used Underneath

If we look under the carpet, we will see that each time I call the CreateStorageManagementClient, we'll use a different instance of the HttpClient which is not we would want. However, I assume that StorageManagementClient's public members are thread safe which means that you can use one instance of that class throughout our web applications but I'm not sure. Nevertheless, I would prefer an approach which is similar to the following one:

// single instance that I would hold onto throughout my application lifecycle. I would most
// probably handle this instance through my IoC container.
using (CloudContext cloudContex = new CloudContext(creds))
{
    // These StorageManagementClient instances are either the same reference or 
    // use the same HttpClient underneath.
    StorageManagementClient storageClient = 
        cloudContex.CreateStorageManagementClient();
}

On the other hand, we need to perform a similar operation to create a compute management client to manage our could service and virtual machines: call the CreateComputeManagementClient extension method on the CloudContext.Clients. Here, we have the same behavior in terms of HttpClient instance.

A Sample Usage in an ASP.NET MVC Application

I created a very simple ASP.NET MVC application which only lists storage services, hosted services and web spaces. I used an IoC container (Autofac) to inject the clients through the controller constructor. Below is the registration code I have in my application.

protected void Application_Start()
{
    // Lines removed for brevity...

    // Get a hold of the credentials.
    const string CertThumbprint = "your-cert-thumbprint";
    const string SubscriptionId = "your-subscription-id";
    X509Certificate2 cert = FindX509Certificate(CertThumbprint);
    SubscriptionCloudCredentials creds =
        new CertificateCloudCredentials(SubscriptionId, cert);

    // Get the ContainerBuilder ready and register the MVC controllers.
    ContainerBuilder builder = new ContainerBuilder();
    builder.RegisterControllers(Assembly.GetExecutingAssembly());

    // Register the clients
    builder.Register(c => CloudContext.Clients.CreateComputeManagementClient(creds))
        .As<IComputeManagementClient>().InstancePerHttpRequest();
    builder.Register(c => CloudContext.Clients.CreateStorageManagementClient(creds))
        .As<IStorageManagementClient>().InstancePerHttpRequest();
    builder.Register(c => CloudContext.Clients.CreateWebSiteManagementClient(creds))
        .As<IWebSiteManagementClient>().InstancePerHttpRequest();

    // Set the dependency resolver.
    AutofacDependencyResolver dependencyResolver = 
        new AutofacDependencyResolver(builder.Build());

    DependencyResolver.SetResolver(dependencyResolver);
}

Noticed that I registered the management client classes as per-request instance. This option will create separate client instances per each request. As the underlying architecture creates separate HttpClient instances per each client creating, I'll not be using the same HttpClient throughout my application lifecycle. I'm also not sure whether the client classes are thread safe. That's why I went for the per-request option.

My controller is even simpler.

public class HomeController : Controller
{
    private readonly IComputeManagementClient _computeClient;
    private readonly IStorageManagementClient _storageClient;
    private readonly IWebSiteManagementClient _webSiteClient;

    public HomeController(
        IComputeManagementClient computeClient, 
        IStorageManagementClient storageClient, 
        IWebSiteManagementClient webSiteClient)
    {
        _computeClient = computeClient;
        _storageClient = storageClient;
        _webSiteClient = webSiteClient;
    }

    public async Task<ActionResult> Index()
    {
        Task<StorageServiceListResponse> storageServiceResponseTask = 
            _storageClient.StorageAccounts.ListAsync();
        Task<HostedServiceListResponse> hostedServiceResponseTask = 
            _computeClient.HostedServices.ListAsync();
        Task<WebSpacesListResponse> webSpaceResponseTask = 
            _webSiteClient.WebSpaces.ListAsync();

        await Task.WhenAll(storageServiceResponseTask, 
            hostedServiceResponseTask, webSpaceResponseTask);

        return View(new HomeViewModel 
        { 
            StorageServices = storageServiceResponseTask.Result,
            HostedServices = hostedServiceResponseTask.Result,
            WebSpaces = webSpaceResponseTask.Result
        });
    }
}

public class HomeViewModel
{
    public IEnumerable<StorageServiceListResponse.StorageService> StorageServices { get; set; }
    public IEnumerable<HostedServiceListResponse.HostedService> HostedServices { get; set; }
    public IEnumerable<WebSpacesListResponse.WebSpace> WebSpaces { get; set; }
}

Notice that I used Task.WhenAll to fire all the asynchronous work in parallel which is best of both worlds. If you also look at the client classes, you will see that operations are divided into logical groups. For example, here is the IComputeManagementClient interface:

public interface IComputeManagementClient
{
    Uri BaseUri { get; }
    SubscriptionCloudCredentials Credentials { get; }

    IDeploymentOperations Deployments { get; }
    IHostedServiceOperations HostedServices { get; }
    IOperatingSystemOperations OperatingSystems { get; }
    IServiceCertificateOperations ServiceCertificates { get; }
    IVirtualMachineDiskOperations VirtualMachineDisks { get; }
    IVirtualMachineImageOperations VirtualMachineImages { get; }
    IVirtualMachineOperations VirtualMachines { get; }

    Task<Models.ComputeOperationStatusResponse> GetOperationStatusAsync(
        string requestId, 
        CancellationToken cancellationToken);
}

HostedServices, OperatingSystems, VirtualMachines and so on. Each logical group of operations are separated as class properties.

Getting Inside the HTTP Pipeline

The current implementation of the libraries also allow us to get into the HTTP pipeline really easily. However, the way we do it today is a little ugly but it depends on the mentioned HttpClient usage underneath. Nevertheless, this extensibility is really promising. Every management client class inherits the ServiceClient<T> class and that class has a method called WithHandler. Every available client provides a method with the same name by calling the underlying WithHandler method from ServiceClient<T>. By calling this method with a DelegatingHandler instance, we can get into the HTTP pipeline and have a chance to manipulate the request processing. For example, we can inject an handler which has a request retry logic if certain error cases are met. Windows Azure Management Library provides an abstract class for a retry handler which has the basic functionality: LinearRetryHandler. As this is an abstract class, we can inherit this class to create our own retry handler. If we need, we can always override the ShouldRetry method but for our case, we don't need it.

public class CustomRetryHandler : LinearRetryHandler
{
}

Now, we can use our retry handler to create the management clients:

RetryHandler retryHandler = new CustomRetryHandler();
IComputeManagementClient client = 
    CloudContext.Clients.CreateComputeManagementClient(creds).WithHandler(retryHandler)

Now, if a request to a Windows Azure Management API fails with some of the certain status codes, the handler will retry the request.

There are More…

There are more features that are worth mentioning but it will make a very lengthy blog post :) Especially the unit testing and tracing are the topics that I'm looking forward to blogging about.

Cleaning up With PowerShell After Removing a Windows Azure Virtual Machine

Removing a Windows Azure Virtual Machine doesn't remove everything for you. This post is all about cleaning up with PowerShell after removing a Windows Azure VM
2013-04-28 14:10
Tugberk Ugurlu


When you remove a Windows Azure virtual machine, you are not actually removing everything. I hear you saying "What!!!"? Let's dive in then Smile

As each VM is kept under a cloud service, that cloud service is one of those things that remain after you remove your VM. Other thing is the disk (or disks, depends on your case) which is attached to your VM. If you didn't attach any data disks, at least your OS disk will remain inside your storage account even if you remove your VM. However, you cannot go and directly delete that VHD file just like a typical blob because there is a lease on that blob as it's still viewed as one of your registered disks.

Let's look at a case of mine on removing a Windows Azure VM. Yesterday, I created two VMs for demonstration purposes on a presentation and after the presentation, I removed those VMs by running "Remove-AzureVM" PowerShell command. So far, so good. When I go to the portal, I don't see those VMs as expected and I don't see any cloud services.

If you create a VM, the new portal is not showing that you have a cloud service but it implicitly creates one for you under the covers. As soon as you attach another VM to that cloud service, the cloud service shows up on the new portal as well. In either of these cases, the generated cloud service is completely visible to you through the REST management API. So, you can view them through PowerShell Cmdlets.

Let's run "Get-AzureService" PowerShell command to see my cloud services:

image

These are the generated cloud services which belong to my removed VMs. As far as I know, these cloud services won't cost me anything as they contain no deployments but it would be nice to remove them as I don't need them.

image

I got rid of the unnecessary cloud services. The next and final step of this cleaning is to remove the OS disks I have. This's actually more important because disk VHD files are stored inside the Windows Azure storage as blobs and each OS disk is approx. 127GB in size. So, I will pay for them as long as I keep them. Through new Windows Azure Storage PowerShell Cmdlets, I can view my VHD container to see which VHD files I have:

image

As you can see, I have two unnecessary VHD files which remained after my VM removal. At this stage, you might think directly deleting these blobs but as mentioned before, it will fail if we try to do that.

image

The error message I got is very descriptive actually: There is currently a lease on the blob and no lease ID was specified in the request. Let's run another PowerShell command to see which disks I have registered:

image

I have those two blobs registered as my disks and this prevents me from directly deleting them which is perfectly reasonable. To prove that this is actually the case, I will view the HTTP headers of one of those disks through CloudBerry Explorer for Azure Blob Storage:

image

You can see that "x-ms-lease-status" header is set to "locked" which states that there is a lease on the blob. Let's remove the "IstBootcampDemoTugberk-IstBootcampVM1-2013-4-27-132" disk from my registered disks:

image

Now, let's look at the HTTP headers of the blob again:

image

The lease is now taken out and it's now possible to delete the blob:

image

However, you can delete the disk from your registered disks list and the storage container in one go by running "Remove-AzureDisk" PowerShell Cmdlet with "DeleteVHD" switch:

image

The VHD file is completely gone. I hope the post was helpful Smile

Windows Azure PowerShell Cmdlets In a Nutshell

Windows Azure PowerShell Cmdlets is a great tool to manage your Windows Azure services but if you are like me, you would wanna know where all the stuff is going. This post is all about it.
2013-04-26 05:05
Tugberk Ugurlu


Managing your Windows Azure services is super easy with the various management options and my favorite among these options is Windows Azure PowerShell Cmdlets. It's very well-documented and if you know PowerShell enough, Windows Azure PowerShell Cmdlets are really easy to grasp. In this post I would like to give a few details about this management option and hopefully, it'll give you a head start.

Install it and get going

Installation of the Windows Azure PowerShell Cmdlets is very easy. It's also well-documented. You can reach the download link from the "Downloads" section on Windows Azure web site. From there, all you need to do is follow the instructions to install the Cmdlets through Web Platform Installer.

After the installation, we can view that we have the Windows Azure PowerShell Cmdlets installed on our system by running "Get-Module -ListAvailable" command:

image

To get you started using Cmdlets, you can see the "Get Started with Windows Azure Cmdlets" article which explains how you will set up the trust between your machine and your Windows Azure account. However, I will cover some steps here as well.

First thing you need to do is download your publish settings file. There is a handy cmdlet to do this for you: Get-AzurePublishSettingsFile. By running this command, it will go to your account and create a management certificate for your account and download the necessary publish settings file.

Next step is to import this publish settings file through another handy cmdlet: Import-AzurePublishSettingsFile <publishsettings-file-path>. This command is actually setting up lots of stuff on your machine.

  • Under "%appdata%\Windows Azure Powershell", it creates necessary configuration files for the cmdlets to get the authentication information.

image

  • These configuration files don't actually contain certificate information on its own; they just hold the thumbprint of our management certificate and your subscription id.
  • Actual certificate is imported inside your certificate store. You can view the installed certificate by running "dir Cert:\CurrentUser\My" command.

image

Now you are ready to go. Run "Get-AzureSubscription" command to see your subscription details and you will see that it's set as your default subscription. So, from now on, you don't need to do anything with your subscription. You can just run the commands without worrying about your credentials (of course, this maybe a good or bad thing; depends on your situation). For example, I ran the Get-AzureVM command to view my VMs:

image

So, where is my stuff?

We installed the stuff and we just saw that it's working. So, where did all the stuff go and how does this thing even work? Well, if you know PowerShell, you also know that modules are stored under specific folders. You can view these folders by running the '$env:PSModulePath.split(';')' command:

image

Notice that there is a path for Windows Azure PowerShell Cmdlets, too. Without knowing this stuff, we could also view the module definition and get to its location from there:

Get-Module -ListAvailable -Name Azure

image

"C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure" directory is where you will find the real meat:

image

On the other hand, when we imported the publish settings, it puts a few stuff about my subscription under "%appdata%\Windows Azure Powershell". The certificate is also installed under my certificate store as mentioned before.

Clean Up

When you start managing your Windows Azure services through PowerShell Cmdlets, you have your Windows Azure account information and management certificate information at various places on your computer. Even if you uninstall your Windows Azure PowerShell Cmdlets from your machine, you are not basically cleaning up everything. Let's start by uninstalling the Cmdlets from your computer.

Simply go to Control Panel > Programs > Programs and Features and find the installed program named as Windows Azure PowerShell and uninstall it. You will be done.

image

Next step is to go to "%appdata%\Windows Azure Powershell" directory and delete the folder completely. One more step to go now: delete your certificate. Find out what the thumbprint of your certificate is:

image

Then, run the Remove-Item command to remove the certificate:

Remove-Item Cert:\CurrentUser\My\507DAAF6F285C4A72A45909ACCEE552B4E2AE916 –DeleteKey

You are all done uninstalling Windows Azure PowerShell Cmdlets. Remember, Windows Azure is powerful but it's more powerful when you manage it through PowerShell Smile

References

Istanbul Part of Global Windows Azure Bootcamp Events

Global Windows Azure Bootcamp will be happening on the 27th of April, 2013 all over the World and Microsoft Istanbul office will also be hosting one of these events.
2013-04-19 15:28
Tugberk Ugurlu


Global Windows Azure Bootcamp will be happening on the 27th of April, 2013 all over the World and Istanbul will be also hosting one of these events. Global Windows Azure Bootcamp Istanbul will be held at Microsoft Istanbul office and the registration is open. You can register the event through Eventbrite.

azure

Daron Yondem, Ilkay Ilknur and myself will be presenting on several topics and you can view the list of sessions on the event registration page as well. See you there Smile

Microsoft Web Camps Istanbul on the 6th of April

One leg of Microsoft Web Camps spring 2013 tour will be held in Microsoft Istanbul office on the 6th of April, 2013.
2013-03-23 16:21
Tugberk Ugurlu


WebCamps-Spring-2013

This is an awesome news that I am proud of to write about. I think it all started out with my reply to Brady Gaster on twitter:

And it's now a real deal thanks to awesome Web Camps team! One leg of Microsoft Web Camps spring 2013 tour will be held in Microsoft Istanbul office on the 6th of April, 2013. It will be a full day event. Jon Galloway, Umit Sunar and me will be giving talks on various latest Microsoft Web Stack technologies including Windows Azure, ASP.NET Web API, ASP.NET SignalR, ASP.NET MVC and so on. You can see the typical agenda of Web Camps here.

You can also find more about Web Camps spring 2013 tour from Jon Galloway's and Brady Gaster's blog posts:

There are finite number of seats available. So, register ASAP to participate this great event from the following link:

https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032548038&Culture=TR-TR&community=0

See you at Web Camps Smile

Tags