CloudFx Samples

The following sample code accompanies the Cloud Application Framework & Extensions (CloudFx) library and provides some basic "How-To" style samples as well as advanced samples demonstrating several CloudFx features at the same time.

C# (6.1 MB)
 
 
 
 
 
(3)
3,343 times
Add to favorites
6/16/2014
E-mail Twitter del.icio.us Digg Facebook

Solution explorer

C#
//======================================================================================
// CLOUD APPLICATION FRAMEWORK & EXTENSIONS (CloudFx)
//
// This project is part of a sample solution demonstrating the core capabilities in the
// CloudFx framework.
//--------------------------------------------------------------------------------------
// Copyright � 2011-2013 Microsoft Corporation. 
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this 
// file except in compliance with the License. You may obtain a copy of the License at 
// http://www.apache.org/licenses/LICENSE-2.0.
//
// UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, SOFTWARE DISTRIBUTED UNDER 
// THE LICENSE IS DISTRIBUTED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 
// ANY KIND, EITHER EXPRESS OR IMPLIED.
//
// See the License for the specific language governing permissions and limitations under 
// the License.
//======================================================================================
namespace PIMDemo.LoggingComponent
{
    #region Using Clauses
    using System;
    using System.Diagnostics;
    using System.Net;
    using System.Threading;

    using Microsoft.Experience.CloudFx.Framework.Compute;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Diagnostics;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.Storage;
    #endregion

    public class WorkerRole : RoleEntryPoint
    {
        #region Private Instance Variables
        /// <summary>
        /// Contains the time that the next check should be performed for handing off primary role.  This will be DateTime.MaxValue if no check is scheduled.
        /// </summary>
        private DateTime nextCheckToDrop = DateTime.MaxValue;

        /// <summary>
        /// True if the RoleEnvironment has indicated it is stopping.  
        /// </summary>
        private bool isStopping;
        #endregion

        #region Public RoleEnvironment Override Methods
        /// <summary>
        /// Runs code that is intended to be run for the life of the role instance.
        /// </summary>
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("PIMDemo.LoggingComponent entry point called", "Information");
            
            // Get settings for primary instance manager
            var instanceMonitorStorageConnectionString = RoleEnvironment.GetConfigurationSettingValue("InstanceMonitorStorageAccount");
            var containerName = RoleEnvironment.GetConfigurationSettingValue("containerName");
            var blobName = RoleEnvironment.GetConfigurationSettingValue("BlobSyncObjectName");

            // Create a new instance of the primary role manager and start it
            var instanceManager = new PrimaryInstanceManager(CloudStorageAccount.Parse(instanceMonitorStorageConnectionString), containerName, blobName, ChangeToPrimary, ChangeToSecondary);
            instanceManager.Start();

            while (true)
            {
                Thread.Sleep(10000);

                // Execute my primary logic.  You can also do secondary logic by performing the negative condition
                if(instanceManager.IsPrimary)
                {
                    Trace.TraceInformation("This is work done by the primary role");

                    if(nextCheckToDrop <= DateTime.UtcNow)
                    {
                        // When something occurs and the instance does not find it appropriate to remain primary
                        Trace.TraceInformation("Releasing the primary role");

                        // Release the primary role 
                        instanceManager.Stop();

                        // Reset so it does not check again until it becomes primary
                        nextCheckToDrop = DateTime.MaxValue;

                        // Sleep for a few seconds to let the role hand off before restarting
                        Thread.Sleep(1000);

                        // Start retrying for primary after delay
                        instanceManager.Start();
                    }
                }
            }
        }

        /// <summary>
        /// Runs code when a role instance is to be stopped.
        /// </summary>
        /// <returns>True if initialization succeeds, false otherwise.</returns>
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // Add a trace listener to get it working
            Trace.Listeners.Add(new DiagnosticMonitorTraceListener());

            // Capture the stopping event so when the RoleEnvironment is stopping it will not accept primary 
            RoleEnvironment.Stopping += (sender, args) =>
            {
                // Make sure the instance manager will not accept the primary role anymore
                isStopping = true;
            };

            return base.OnStart();
        }
        #endregion

        #region PrimaryInstanceManager Event Handlers
        /// <summary>
        /// Handles role change events that result in the instance being primary.
        /// </summary>
        /// <returns>True if the instance is currently capable of obtaining primary mode.</returns>
        private bool ChangeToPrimary()
        {
            var isPrimaryAccepted = false;

            if (!isStopping)
            {
                // Log the fact that primary role has been accepted
                Trace.TraceInformation("Accepting primary role.");

                // Perform additional logic here before accepting the primary.  If some logic makes acceptance of primary a bad decision
                // return false instead.
                isPrimaryAccepted = true;

                // Set the time to release the role to 2.5 minutes from now
                nextCheckToDrop = DateTime.UtcNow.AddSeconds(150);
            }
            else
            {
                // Log the fact that primary role is declined because the RoleEnvironment is stopping
                Trace.TraceInformation("Stopping could not accept primary role.");

                nextCheckToDrop = DateTime.MaxValue;
            }

            // Returns true if the role was accepted, false if it is not
            return isPrimaryAccepted;
        }

        /// <summary>
        /// Handles role change events that result in the instance being secondary.
        /// </summary>
        private void ChangeToSecondary()
        {
            // execute any additional logic required to change over to secondary mode
            Trace.TraceInformation("Accepting secondary role.");

            nextCheckToDrop = DateTime.MaxValue;
        }
        #endregion
    }
}