Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Azure, PHP, OpenXML, VSTS, ...

About the author

Maarten Balliauw is an MVP ASP.NET and is currently employed as .NET Software Engineer at RealDolmen. His interests are mainly web applications developed in ASP.NET (C#) or PHP.
More about me More about me
Send mail E-mail me


Microsoft Most Valuable Professional - MVP - ASP.NET

Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn RealDolmen - Rock-solid passion for ICT
I'm a speaker at TechDays Belgium and TechDays Finland

Search

Latest Twitter

    Follow me on Twitter...

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    © Copyright Maarten Balliauw 2010

    Introducing RealDolmenBlogs.com

    RealDolmenBlogs.com Here’s something I would like to share with you. A few months ago, our company (RealDolmen) started a new website, RealDolmenBlogs.com. This site syndicates content from employee blogs, people with lots of experience in their range of topics. These guys have lots of knowledge to share, but sometimes their blog does not have a lot of attention from, well, you. Since we would really love to share employee knowledge, RealDolmenBlogs.com was born.

    The following topics are covered:

    • .NET
    • Application Lifecycle Management
    • Architecture
    • ASP.NET
    • Biztalk
    • PHP
    • Sharepoint
    • Silverlight
    • Visual Studio

    Make sure to subscribe to the syndicated RSS feed and have quality content delivered to your RSS reader.

    The technical side

    Since I do not like to do blog posts on topic that do not have a technical touch, considered that the first few lines of text of this post are pure marketing in a sense, here’s the technical bit.

    RealDolmenBlogs.com is built on Windows Azure and SQL Azure. As a company we believe there is value in cloud computing, in this case we chose for cloud computing due to the fact that the setup costs for the website were very small (pay-per-use) and that we can easily scale-up the website if needed.

    The software behind the site is a customized version of BlogEngine.NET. It has been extended with a syndication feature, pulling content from employee blogs with a little help of the Argotic syndication framework. Running BlogEngine.NET on Windows Azure is not that hard, especially when you are using SQL Azure as well: the only thing to modify is the connection string to your database and you are done. Well… that is if you don’t care about images and attachments. We had to do some modifications to how BlogEngine.NET handles file uploads and made sure everything is now stored safe and sound in Windows Azure blob storage.

    That being said: enjoy the content that my colleagues are sharing, posts are definitely worth a read!


    Running PHP in the Cloud slides and sample code

    Just got back from London where I did a fun talk on PHP and Windows Azure yesterday evening. It was the first time I did a presentation after three beers, but I think it went allright. As promised, here's the slide deck and sample code (ImageCloud.rar (5.00 mb)).

    Abstract: "This session covers the basics of Microsoft’s Windows Azure cloud platform. Learn how you can develop and deploy a PHP application in Windows Azure, using the tools and libraries Microsoft provides. Creating a photo upload application, the different aspects of the Windows Azure platform are leveraged for creating a performant and scalable PHP application."

    Thanks for joining the conference and my session! Also, Robert Castelo, your talk on Drupal and its community was interesting. Did not know the active developer base and security teams were that big.


    Using Windows Azure Drive (aka X-Drive)

    Windows Azure X Drive With today’s release of the Windows Azure Tools and SDK version 1.1, also the Windows Azure Drive feature has been released. Announced at last year’s PDC as X-Drive, which has nothing to do with a well-known German car manufacturer, this new feature enables a Windows Azure application to use existing NTFS APIs to access a durable drive. This allows the Windows Azure application to mount a page blob as a drive letter, such as X:, and enables easily migration of existing NTFS applications to the cloud.

    This blog post will describe the necessary steps to create and/or mount a virtual hard disk on a Windows Azure role instance.

    kick it on DotNetKicks.com

    Using Windows Azure Drive

    In a new or existing cloud service, make sure you have a LocalStorage definition in ServiceDefinition.csdef. This local storage, defined with the name InstanceDriveCache below, will be used by the Windows Azure Drive API to cache virtual hard disks on the virtual machine that is running, enabling faster access times. Here’s the ServiceDefinition.csdef for my project:

    <?xml version="1.0" encoding="utf-8"?>
    <ServiceDefinition name="MyCloudService" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
      <WorkerRole name="MyWorkerRole" enableNativeCodeExecution="true">
        <LocalResources>
          <LocalStorage name="InstanceDriveCache"
                        cleanOnRoleRecycle="false"
                        sizeInMB="300" />
        </LocalResources>
        <ConfigurationSettings>
          <!-- … -->
       </ConfigurationSettings>
      </WorkerRole>
    </ServiceDefinition>

    Next, in code, fire up a CloudStorageAccount, I’m using development storage settings here:

    CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount;

    After that, the Windows Azure Drive environment has to be initialized. Remember the LocalStorage definition we made earlier? This is where it comes into play:

    LocalResource localCache = RoleEnvironment.GetLocalResource("InstanceDriveCache");
    CloudDrive.InitializeCache(localCache.RootPath, localCache.MaximumSizeInMegabytes);

    Just to be sure, let’s create a blob storage container with any desired name, for instance “drives”:

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    blobClient.GetContainerReference("drives").CreateIfNotExist();

    Ok, now we got that, it’s time to get a reference to a Windows Azure Drive. Here’s how:

    CloudDrive myCloudDrive = storageAccount.CreateCloudDrive(
        blobClient
            .GetContainerReference("drives")
            .GetPageBlobReference("mysupercooldrive.vhd")
            .Uri.ToString()
    );

    Our cloud drive will be stored in a page blob on the “drives” blob container, named “mysupercooldrive.vhd”. Note that when using development settings, the page blob will not be created on development storage. Instead, files will be located at C:\Users\<your.user.name>\AppData\Local\dftmp\wadd\devstoreaccount1.

    Next up: making sure our virtual hard disk exists.  Note that this should only be done once in a virtual disk’s lifetime. Let’s create a giant virtual disk of 64 MB:

    try
    {
        myCloudDrive.Create(64);
    }
    catch (CloudDriveException ex)
    {
        // handle exception here
        // exception is also thrown if all is well but the drive already exists
    }

    Great, our disk is created. Now let’s mount it, i.e. assign a drive letter to it. The drive letter can not be chosen, instead it is returned by the Mount() method. The 25 is the cache size that will be used on the virtual machine instance. The DriveMountOptions can be None, Force and FixFileSystemErrors.

    string driveLetter = myCloudDrive.Mount(25, DriveMountOptions.None);

    Great! Do whatever you like with your disk! For example, create some files:

    for (int i = 0; i < 1000; i++)
    {
        System.IO.File.WriteAllText(driveLetter + "\\" + i.ToString() + ".txt", "Test");
    }

    One thing left when the role instance is being shut down: unmounting the disk and makign sure all contents are on blob storage again:

    myCloudDrive.Unmount();

    Now, just for fun: you can also create a snapshot from a Windows Azure Drive by calling the Snapshot() method on it. A new Uri with the snapshot location will be returned.

    Full code sample

    The code sample described above looks like this when not going trough each line of code separately:

    public override void Run()

        CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount;

        LocalResource localCache = RoleEnvironment.GetLocalResource("InstanceDriveCache");
        CloudDrive.InitializeCache(localCache.RootPath, localCache.MaximumSizeInMegabytes);

        // Just checking: make sure the container exists
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        blobClient.GetContainerReference("drives").CreateIfNotExist();

        // Create cloud drive
        CloudDrive myCloudDrive = storageAccount.CreateCloudDrive(
            blobClient
            .GetContainerReference("drives")
            .GetPageBlobReference("mysupercooldrive.vhd")
            .Uri.ToString()
        );

        try
        {
            myCloudDrive.Create(64);
        }
        catch (CloudDriveException ex)
        {
            // handle exception here
            // exception is also thrown if all is well but the drive already exists
        }

        string driveLetter = myCloudDrive.Mount(25, DriveMountOptions.Force);

        for (int i = 0; i < 1000; i++)
        {
            System.IO.File.WriteAllText(driveLetter + "\\" + i.ToString() + ".txt", "Test");
        }

        myCloudDrive.Unmount();
    }

    Enjoy!

    kick it on DotNetKicks.com


    Categories: Azure | C# | General | ICT | Internet | Scalability

    Just Another Wordpress Weblog, But More Cloudy

    4322759659_6cab114506_b Slides of my talk at the PHPBenelux conference last weekend are online. Bit of a pity my live demo went wrong due to my www.azure.com trial account going into read-only mode while doing the demo.

    Abstract: "While working together with Microsoft on the Windows Azure SDK for PHP, we found that we needed an popular example application hosted on Microsoft’s Windows Azure. Wordpress was an obvious choice, but not an obvious task. Learn more about Windows Azure, the PHP SDK that we developed, SQL Azure and about the problems we faced porting an existing PHP application to Windows Azure."

    Thanks for joining the conference and my session! And thanks to the PHPBenelux crew for organizing their first conference ever, it rocked!


    Creating an external facing Azure Worker Role endpoint

    Internet facing Azure Worker Role When Windows Azure was first released, only Web Roles were able to have an externally facing endpoint. Since PDC 2009, Worker Roles can now also have an external facing endpoint, allowing for a custom application server to be hosted in a Worker Role. Another option would be to run your own WCF service and have it hosted in a Worker Role. Features like load balancing, multiple instances of the Worker are all available. Let’s see how you can create a simple TCP service that can display the current date and time.

    Here’s what I want to see when I connect to my Azure Worker Role using telnet (“telnet efwr.cloudapp.net 1234”):

    Telnet Azure Worker Role

    Let’s go ahead and build this thing. Example code can be downloaded here: EchoCloud.zip (9.92 kb)

    kick it on DotNetKicks.com

    Configuring the external endpoint

    Fire up your Visual Studio and create a new Cloud Service, named EchoCloud, with one Worker Role (named EchoWorker). After you complete this, you should have a Windows Azure solution containing one Worker Role. Right-click the worker role and select Properties. Browse to the Endpoints tab and add a new endpoint, like so:

    Configuring an external endpoint on a Windows Azure Worker Role

    This new endpoint (named EchoEndpoint) listens on an external TCP port with port number 1234. Note that you can also make this an internal endpoint, which is an endpoint that can only be reached within your Windows Azure solution and not from an external PC. This can be useful if you wan to host a custom application server in your project and make it available for other Web and Worker Roles in your solution.

    Building the worker role

    As you know, a Worker Role (in the WorkerRole.cs file in your newly created solution) consists of 3 methods that can be implemented: OnStart, Run and OnStop. There’s also an event handler RoleEnvironmentChanging available. The method names sort of speak for themselves, but allow me to explain quickly:

    • OnStart() is executed when the Worker Role is starting. Initializations and some checks can be done here.
    • Run() is the method which contains the actual Worker Role logic. The cool stuff goes in here :-)
    • OnStop() can be used to do things that should be done when the Worker Role is stopped.
    • RoleEnvironmentChanging() is the event handler that gets called when the environment changes: configuration changed, extra instances fired, … are possible triggers for this.

    Our stuff will go in the Run() method. We’ll be creating a new TcpListener which will sit and accept connections. Whenever a connection is available, it will be dispatched on a second thread that will be communicating with the client. Let’s see how we can start the TcpListener:

    public class WorkerRole : RoleEntryPoint
    {
        private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);

        public override void Run()
        {
            TcpListener listener = null;
            try
            {
                listener = new TcpListener(
                    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["EchoEndpoint"].IPEndpoint);
                listener.ExclusiveAddressUse = false;
                listener.Start();
            }
            catch (SocketException)
            {
                Trace.Write("Echo server could not start.", "Error");
                return;
            }

            while (true)
            {
                IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
                connectionWaitHandle.WaitOne();
            }
        }
    }

    First thing to notice is that the TcpListener is initialized using the IPEndpoint from the current Worker Role instance:

    listener = new TcpListener(
                    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["EchoEndpoint"].IPEndpoint);

    We could have started the TcpListener using a static configuration telling it to listen on TCP port 1234, but that would be difficult for the Windows Azure platform. Instead, we start the TcpListener using the current IPEndpoint configuration that we set earlier in this blog post. This allows the application to run on the Windows Azure production environment, as well as on the development environment available from the Windows Azure SDK. Here’s how it would work if we had multiple Worker Roles hosting this application:

    Multiple worker roles running a custom TCP server 

    Second thing we are doing is starting the infinite loop that accepts connections and dispatches the connection to the HandleAsyncConnection method that will sit on another thread. This allows for having multiple connections into one Worker Role. Let’s have a look at the HandleAsyncConnection method:

    private void HandleAsyncConnection(IAsyncResult result)
    {
        // Accept connection
        TcpListener listener = (TcpListener)result.AsyncState;
        TcpClient client = listener.EndAcceptTcpClient(result);
        connectionWaitHandle.Set();

        // Accepted connection
        Guid clientId = Guid.NewGuid();
        Trace.WriteLine("Accepted connection with ID " + clientId.ToString(), "Information");

        // Setup reader/writer
        NetworkStream netStream = client.GetStream();
        StreamReader reader = new StreamReader(netStream);
        StreamWriter writer = new StreamWriter(netStream);
        writer.AutoFlush = true;

        // Show application
        string input = string.Empty;
        while (input != "9")
        {
            // Show menu
            writer.WriteLine("…");

            input = reader.ReadLine();
            writer.WriteLine();

            // Do something
            if (input == "1")
            {
                writer.WriteLine("Current date: " + DateTime.Now.ToShortDateString());
            }
            else if (input == "2")
            {
                writer.WriteLine("Current time: " + DateTime.Now.ToShortTimeString());
            }

            writer.WriteLine();
        }

        // Done!
        client.Close();
    }

    Code speaks for itself, no? One thing that you may find awkward is the connectionWaitHandle.Set();. In the previous code sample, we did connectionWaitHandle.WaitOne();. This means that we are not accepting any new connection until the current one is up and running. connectionWaitHandle.Set(); signals the original thread to start accepting new connections again.

    Running the worker role

    When running the application using the development fabric, you can fire up multiple instances. I fired up 4 Worker Roles that provide the simple TCP service that we just created. This means that my application will be load balanced, and every incoming connection will be distributed over these 4 Worker Role instances. Nifty!

    Here’s a screenshot of my development fabric with two Worker Roles that I crashed intentionally. The service is still available, thanks to the fabric controller dispatching connections only to available Worker Role instances.

    Development fabric with crashed worker roles

    Example code

    Example code can be downloaded here: EchoCloud.zip (9.92 kb)

    Just a quick note: the approach described here can also be used to run a custom WCF host that has other bindings than for example basicHttpBinding.

    kick it on DotNetKicks.com 


    Categories: Azure | C# | General | ICT | Internet | Scalability | Webfarm

    Vote to help me speak at the MIX 2010 conference!

    Everybody knows the Microsoft MIX event, right? The one in Las Vegas? The one with all the fancy web-related stuff? Rings a bell? Ok, great. In the beginning of December 2009, Microsoft did an open call for speakers, which I answered with some session proposals. Who doesn’t want to go to Vegas, right?

    The open call proposals have been processed (150+ sessions submitted, wow!) and a voting has started. Yes, you hear me coming: please go ahead and vote for a session I submitted. Voting ends January 15th, 2010.

    Since I could not decide which color of the voting banner matched best with my blog’s theme, I decided to put them all three online:

    image

    Thanks in advance!

    Maarten

    PS: There's also Elijah Manor, Justin Etheredge, K. Scott Allen, and many others who submitted good looking sessions.

    kick it on DotNetKicks.com


    Cloud computing and the Windows Azure Services Platform (KU Leuven)

    It was a fun session yesterday at KU Leuven university! I did a session on cloud computing and Windows Azure there for the IEEE Student Branch Leuven.

    Abstract: "This session covers the basics of the Windows Azure Services Platform and drills into some architectural challenges. Learn what components the Windows Azure Services Platform is built of and how they can be leveraged in building a scalable and reliable application."

    If you want more info about Windows Azure and how to develop, architect or benefit from the platform as a whole, register freely at the Azure User Group Belgium.

    Thank you for attending!


    Categories: Azure | General | ICT | Internet | Presentations

    MSDN - Converting an existing ASP.NET application to Windows Azure

    Back from PDC 2009 with a lot of information on Windows Azure, I did an MSDN Live Meeting on ASP.NET and Windows Azure today. Here's the slide deck and demo code.

    Abstract: "Put your stuff in the cloud! Windows Azure allows you to take advantage of cloud computing infranstructure for hosting, computing, and storage of your applications. In this demo filled session we take an existing ASP.Net Application and move it to be hosted in Windows Azure, while taking advantage of Windows Azure storage."

    Example code can be downloaded here: MSDN - Converting an existing ASP.NET application to Windows Azure.zip (2.01 mb)

    If you want more info about Windows Azure and how to develop, architect or benefit from the platform as a whole, register freely at the Azure User Group Belgium.

    Before you get started, you need to have a Windows Azure token. Request a token by completing the application here. Tokens are generally issued within a few hours. Once you have received your token, redeem it at http://windows.azure.com. Afterwards, you can deploy your application using the interface at http://windows.azure.com or by issuing a right-click -> Publish... in your Visual Studio solution.

    Windos Azure Developer Portal

    Thank you for attending!

    kick it on DotNetKicks.com

    Microsoft PDC09 keynote highlights

    Finally found some time to write a short blog post on the announcements this morning at PDC 2009.Microsoft PDC keynote highlights Ray Ozzie started the keynote this morning, focusing on Microsoft’s “three-screen” vision for the future. There will be three screens connected to the cloud: TV, (handheld) devices and of course good old PC. This vision is driven by some key players: Windows 7, Internet Explorer, Silverlight and Windows Azure. Make sure to have a look at these four if you want to play in this future.

    Some announcements were made as well:

    Had a great day yesterday, driving trough the city of Los Angeles and looking at various places in town. Conference day one was also very interesting, lots of good sessions. Currently missing a session slot though, waiting for a Channel9 interview on the Windows Azure SDK for PHP. Stay tuned!


    Windows Azure Tools for Eclipse for PHP developers

    Pfew! Finally I can spread the word on this! While working on the Windows Azure SDK for PHP, I had the opportunity to test-drive the development builds of the WIndows Azure Tools for Eclipse. Today, the project has been released officially at www.windowsazure4e.org. Windows Azure Tools for Eclipse provides a series of wizards and utilities that allow developers to write, debug, and configure for and deploy PHP applications to Windows Azure.

    image

    The plug-in also bundles the existing Windows Azure SDK for PHP, which was introduced a few months ago. This SDK provides a simple API for PHP developers who use the Windows Azure storage component, making it very easy to use the blob, queue and table data storage features. Just visit the project site at http://phpazure.codeplex.com/.

    Some labs are available to help you get started with PHP on the WIndows Azure platform: http://www.windowsazure4e.org/learn/


    Categories: Azure | C# | General | ICT | Internet | PHP | Software