Wednesday, April 30, 2014

Programming Azure Cache

Programming Azure Cache


Programming with Windows Azure Caching

In order to work with Windows Azure Caching from client apps, you need to add the following namespace in your client app:
using Microsoft.ApplicationServer.Caching;
To programmatically access the Windows Azure Caching, you first need to create an instance of DataCache class.
The following code block will create a cache client by creating an instance of DataCache which will take the settings from configuration file.
//Creating a cache object
DataCacheFactory cacheFactory = new DataCacheFactory();
DataCache dataCache = cacheFactory.GetDefaultCache();
The above code block will create the cache client object by using DataCacheFactory object. The GetDefaultCache method of DataCacheFactory object will return the DataCache object.

Adding and Retrieving Data from the Windows Azure Cache

To add an item to Cache object, we can use either Add or Put method of DataCache object. The Add method adds an object to the Cache object with a specified key and will generate an exception if the item is already exists with the same key. The put method adds the object to the Cache object with a specified key if the key does not exist, and replaces if the key is already exists.
The following code block adds the collection of data objects to Cache:
//Query from DB and adding data to Cache 
var categories = categoryRepository.GetAll();
dataCache.Add("categories", categories);
In the above code block, querying data from Database and adding this data to Cache object with a key name “categories” and we can take the data from Cache for the subsequent requests for the same data which can avoid database round trips and improve the performance of the application.
Using the overloads of the Add and Put methods of DataCache object, we can override the timeout interval, which are specified in the Cache Roles settings.
The following code block adds the data to the Cache with time span that allows to specify when the object should expired from Cache.
dataCache.Add("categories", categories, TimeSpan.FromMinutes(45));
The above code block adds the data to the Cache object with a key categories and specified the timeout as 45 minutes.
The following code block retrieves the data from Cache:
//Getting the Cache item with key "categories"
IEnumerable category = dataCache.Get("categories") as IEnumerable;
The Get method of the DataCache object retrieves the data from Cache where you have to give the key as the parameter value for the Get method. The above code block retrieves the data and casting it for the appropriate data type.

Working with a Cache Provider Class

In the previous steps, we have discussed how to perform data caching with Windows Azure Caching. Let’s create a Cache provider class that will help us better manage Data in the cache. Let’s create a contract type for the Cache provider.
public interface ICacheProvider
{
    object Get(string key);
    void Add(string key, object data);
    void Put(string key, object data);
    void Add(string key, object data, TimeSpan? timeout);
    void Put(string key, object data, TimeSpan? timeout);
    bool IsSet(string key);
    void Remove(string key);
}
The Get method returns the cached item based on the given key and Add and Put methods adds and puts an item into Cache. The IsSet method will return true if an item added on the Cache. The Remove method will remove an item from the Cache.
Let’s create a concrete implementation for the ICacheProvider. The below AzureCacheProvider Class is an implementation of ICacheProvider for Windows Azure Caching.
public class  AzureCacheProvider : ICacheProvider
{
private DataCache dataCache=null;
public AzureCacheProvider()
{
    //Creating a cache object by using DataCacheFactory
    DataCacheFactory cacheFactory = new DataCacheFactory();
     dataCache = cacheFactory.GetDefaultCache();
}
//Get cached item
public object Get(string key)
{
   return dataCache.Get(key);
}
public void Add(string key, object data)
{
    Add(key, data, null);
}       
public void Add(string key, object data, TimeSpan? timeout)
{
   //Add item to Cache
    if (timeout.HasValue)
    {
        dataCache.Add(key, data, timeout.Value);
    }
    else
    {
        dataCache.Add(key, data);
    }
}
public void Put(string key, object data)
{
    Put(key, data, null);
}
public void Put(string key, object data, TimeSpan? timeout)
{
    //Put item to Cache
    if (timeout.HasValue)
    {
        dataCache.Put(key, data, timeout.Value);
    }
    else
    {
        dataCache.Put(key, data);
    }
}
//Returns true if Cache item is exist
public bool IsSet(string key)
{            
    return (dataCache.Get(key) != null);
}
public void Remove(string key)
{
    dataCache.Remove(key);
}
}
In the below code block, we are using the ICacheProvider from an ASP.NET MVC application
private readonly ICacheProvider cache;
public CategoryController(ICategoryRepository categoryRepository,ICacheProvider cache)
{            
    this.categoryRepository = categoryRepository;
    this.cache = cache;
}      
public ActionResult Index()
{
    IEnumerable categories;
    var cachedCategories=cache.Get("categories");
    if (cachedCategories != null)
    {
        categories = cachedCategories as IEnumerable;
    }
    else
    {
        categories = categoryRepository.GetAll();
        cache.Put("categories", categories);
    }            
    return View(categories);
}
      
In the Index action method, we are taking the data from Cache, if the cached item exists. If the item does not exist, we retrieve the data from Database and put it on Cache so that we can take the data from Cache for the subsequent requests. In this sample code, we are injecting an instance of AzureCacheProvider class through constructor for the contract type ICacheProvider.

Tuesday, April 8, 2014

Working with Cache in Azure

Working with Caching in Azure

Windows Azure Caching

Windows Azure is providing a caching service which can be used as a caching layer for your Cloud apps hosted on Windows Azure. Windows Azure Caching service is a highly scalable, distributed, in-memory Cache which allows developers to cache all data types, thus reducing the load on databases and improving the performance of the Windows Azure applications.
Using Windows Azure Caching, you can do the following:
  • Cache data on Windows Azure Caching
  • Use as storage mechanism for ASP.NET session state and ASP.NET page output caching
The new Windows Azure Caching allows you to deploy Cache on the virtual machines in which you have hosted your Windows Azure Cloud Services. Now you can cache on Web Roles and Worker Roles that can be easily scaled, managed and monitored just like your Cloud Services. You can also use the existing Windows Azure Shared Caching along with the new Caching option on the Cloud Services.

Cache Cluster

Cache Cluster is the Cloud Service role instance that you use for hosting your Cache. You can deploy the cache cluster in two different ways. You can deploy in a dedicated VM as well as you can share Caching with your Role instances.
The following are the two types of deployment options available for configuring cache.
· Co-located Role caching - The Cache shares the Virtual Machine resources with the Cloud Service application. In this option, you can share the resources of Web Role and Worker Role for Cache.
· Dedicated Role caching - The role instances dedicated only for your caching. In this way, you would be deploy the Cache in a dedicated VM by using a Cache Worker Role.

Configuring Co-located Role Cache Cluster

If you want to configure your cache along with your Role instances, you can choose the co-located Role cache cluster as the deployment option.
The following steps will configure the Windows Azure Role for using co-located Role Caching
1. In Visual-Studio, right-click on the Windows Azure Role, and click properties.
2. In the properties window, choose the 'Caching' tab.
pic-1-co-located-role
3. In the Caching tab, check the 'Enable Caching (Preview Release)' checkbox.
4. Choose 'Co-located Role' for the Cache Cluster settings. By default, this will be 'Co-located Role' when we enable Caching.
5. Choose the percentage of Cache size. By default Cache size will be 30 percentage. This means that 30 percentage of VM memory allocated for Cache. You can change the Cache size whatever you want for your caching solution.
6. Configure the settings of Caches. We can specify the 'Time to Live (min)' for the time interval of Cache for expiry and 'Expiration Type' for specifying the expiration type of Cache object.
By default, value of “The Time to Live” would be 10 minutes and the Expiration Type would be Absolute. The Absolute expiration type is specifying that the timer for the expiration would be start after the data added into Cache object. If the expiration time is 10 minutes, the cache will be expire after 10 minutes when the item is added into Cache. The other expiration types are 'Sliding Window' and 'None'. If the Expiration Type is 'Sliding Window', the timer for the expiration time would be reset after each item is retrieved from the Cache. If expiration type is 'None', items in the cache will not be expired. In this scenario, you have to specify “Time to Live (min)” as 0.
pic-1.1-co-located-role-settings

Configuring Dedicated Role Cache Cluster

If you want to host your cache in a dedicated VM, you can choose the Dedicated Role cache cluster as the deployment option.
The following steps will configure the Dedicated Role cache cluster
1. Add Cache Worker Role project - To configure Dedicated Role cache cluster, you need to add a Cache Worker Role to your solution. Add a New Cache Worker Role project onto
your Windows Azure project.
pic-2-new-workerrole
pic-3-cacheworkerrole-template
When we are adding a new Cache Worker Role project, it will automatically enable Caching with Dedicated Role as the Cache cluster.
pic-4-workerrole-caching-properties
2. Configure the settings for Dedicated Cache Role - Right-click on the Cache Worker Role from the Windows Azure project, and click properties and choose Configuration
pic-5-dedicatedcacherole-properties
By default, the VM instance count would be 1 and Virtual Machine size would be small. You can change these setting based on your hosting plan for Dedicated Role Cache Cluster.
3. Configure the Cache settings for expiration time and expiration type.
pic-1.1-co-located-role-settings

Working with Cache Clients

In order to work with Windows Azure caching from Cloud Services applications, we need to install Windows Azure Caching client library onto your Web Role and Worker Role applications. The following steps will add a Windows Azure client library to a Web Role application. We can install the Windows Azure Caching client library by using NuGet.
From the following NuGet packages, Install Microsoft.WindowsAzure.Caching
pic-7-install-nuget-package
The Windows Azure Caching NuGet package will install the necessary assmebly reference and will also add the configuartion setting on the configuaration file. You can also manually add the necessary assmeblies from the folder C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\2012-06\ref\CachingPreview if you have installed Windows Azure SDK 1.7 on your system. At the time of this writing, Azure SDK 1.8 is the latest.
The Windows Azure Caching NuGet package will add a configuration element dataCacheClients into the web.config file.
The following configuration setting in the web.config file will configured a cache client for a web role application.
    
   


  
  
    
    
      
      
    

  

The identifier in the config settings specifies the name of the role that hosts the cache cluster

Thursday, March 6, 2014

Working Azure App Fabrics

Working with Azure App Fabrics

Windows Azure AppFabric provides a comprehensive cloud middleware platform for developing, deploying and managing applications on the Windows Azure Platform.  It delivers additional developer productivity, adding in higher-level Platform-as-a-Service (PaaS) capabilities on top of the familiar Windows Azure application model.  It also enables bridging your existing applications to the cloud through secure connectivity across network and geographic boundaries, and by providinga consistent developmentmodelfor both Windows Azure and Windows Server.Finally, it makes development more productiveby providing a higher abstraction for building end-to-end applications,and simplifies management and maintenance of the application as it takes advantage of advances in the underlying hardware and software infrastructure.
There are three key components of Windows Azure AppFabric:
Middleware Services:platform capabilities as services, which raise the level of abstraction and reduce complexity of cloud development.
Composite Applications: a set of new innovative frameworks, tools and composition engine to easily assemble, deploy, and manage a composite application as a single logical entity
Scale-outapplication infrastructure:optimized for cloud-scale services and mid-tier components.
Following is a high-level overview of these Windows Azure AppFabric components and features.

Middleware Services

Windows Azure AppFabric provides pre-built, higher level middleware services thatraise the level of abstraction and reduce complexity of cloud development.  These services are open and interoperable across languages (.NET, Java, Ruby, PHP…) and give developers a powerful pre-built “class library" for next-gen cloud applications. Developers can use each of the services stand-alone, or combine services to provide a composite solution.
Service Bus(Commercially available now; updated CTP delivered October 2010)provides secure messaging and connectivity capabilities that enable building distributed and disconnected applications in the cloud, as well as hybrid applications across both on-premise and the cloud. It enables using various communication and messaging protocols and patterns, and removes the need for the developer to worry about delivery assurance, reliable messaging and scale.
Access Control (Commercially available now; updated CTP delivered August 2010)enables an easy way to provide identity and access control to web applications and services, while integrating with standards-based identity providers, including enterprise directories such as  Active Directory®, and web identities such as Windows Live ID, Google, Yahoo! and Facebook.
Caching (New CTP service delivered October 2010; commercially available in H1 CY11)accelerates performance of Windows Azure and SQL Azure based apps by providing a distributed, in-memory application cache, provided entirely as a service (no installation or management of instances, dynamically increase/decrease cache size as needed).  Pre-integration with ASP.NET enables easy acceleration of web applications without having to modify application code.
Integration(New CTP service coming in CY11) will provide common BizTalk Server integration capabilities (e.g. pipeline, transforms, adapters) on Windows Azure, using out-of-box integration patterns to accelerate and simplify development.  It will also deliver higher level business user enablement capabilities such as Business Activity Monitoring and Rules, as well as self-service trading partner community portal and provisioning of business-to-business pipelines.
Composite App(New CTP service coming in H1 CY11)will provide a multi-tenant, managed service which consumes the .NET based Composition Model definition and automates the deployment and management of the end to end application - eliminating manual steps needed by both developers and ITPros today.  It also executes application components to provide a high-performance runtime optimized for cloud-scale services and mid-tier components (automatically delivering scale out, availability, multi-tenancy and sandboxing of application components). Finally, it delivers a complete hosting environment for web services built using Windows Communication Foundation (including WCF Data Services and WCF RIA Services) and workflows built using Windows Workflow Foundation.
It’s a key characteristic of all AppFabric Middleware Services that they are consistently delivered as true multi-tenant services – you simply provision, configure, and use (no installation or management of machines/instances).



Composite Applications

AppFabric Composition Model
& Visual Designer

As developers build next-generation applications in the cloud, they are increasingly assembling their application as a composite from many pre-built components and services (either developed in house or consumed from third parties cloud services).  Also, given that many cloud applications need to access critical on-premises business applications and data, there is a need to be able to compose from on-premises services easily and securely.  Finally, the highly distributed nature of these composite applications require more sophisticated deployment and management capabilities for managing all of the distributed elements that span the web, middle-tier and database tier.
Microsoft is advancing its Windows Azure AppFabric cloud middleware platform to provide a full composite application environment for developing, deploying and managing composite applications.  The AppFabric composition environment delivers three main benefits:
Composition Model A set of .NET Framework extensions for composing applications on the Windows Azure platform.  This builds on the familiar Azure Service Model concepts and adds new capabilities for describing and integrating the components of an application.  It also provides a consistent composition model for both Windows Azure and Windows Server.
Visual Design ExperienceA new Visual Studio based designer experience allows you assemble code from your existing application components, along with newer cloud services, and tie them together as a single logical entity.
Managed as a serviceThe Composite Application service is a multi-tenant, managed service which consumes the Composition Model definition and automates the deployment and management of the end to end application - eliminating manual steps needed by both developers and ITPros today.
The composite application environmentoffers the following benefits:
§  Greater developer productivity through rapid assembly, linking of components and automated deployment of the entire end-to-end application;
§  Easier configuration and control of entire application and individual components;
§  End-to-end application monitoring (events, state, health and performance SLAs);
§  Easier troubleshooting (through richer diagnostics and debugging of the whole application);
§  Performance optimization of the whole application (scale-out/in, fine-tuning, migration, etc);
§  Integrated operational reporting (usage, metering, billing).



Scale-out Application Infrastructure

Both the AppFabric Services and your own composite applications built using the Composition Model are built upon anadvanced,high-performance application infrastructure that has been optimized for cloud-scale services and mid-tier components.  The AppFabric Container provides base-level infrastructure such as automatically ensuring scale out, availability, multi-tenancy and sandboxing of your application components.The main capabilities provided by the AppFabric Container are:
Composition RuntimeThis manages the full lifecycle of an application component including loading, unloading, starting, and stopping of components. It also supports configurations like auto-start and on-demand activation of components.
Sandboxing and Multi-tenancy This enables high-density and multi-tenancyof the hosted components. The container captures and propagates the tenant context to all the application and middleware components.
State Management This provides data and persistence management for application components hosted in the container. 
Scale-out and High AvailabilityThe container provides scale-out by allowing application components to be cloned and automatically distributed; for stateful components, the container provides scale-out and high availability using partitioning and replication mechanisms. The AppFabric Container shares the partitioning and replication mechanisms of SQL Azure.
Dynamic Address Resolution and Routing In a fabric-based environment, components can be placed or reconfigured dynamically. The container automatically and efficiently routes requests to the target components and services.

Bridging On-Premises and Cloud

Finally, one of the important capabilities needed by businesses as they begin their journey to the cloud is being able to leverage existing on-premise LOB systems and to expose them selectively and securely into the cloud as web services. However, since most organizations are firewall protected, the on-premise LOB systems are typically not easily accessible to cloud applications running outside the organization’s firewall.
AppFabric Connect allows you to leverageyour existing LOB integration investments inWindows Azure using the Windows Azure AppFabric Service Bus, and Windows Server AppFabric.  This new set of simplified tooling extends BizTalk Server 2010 to help accelerate hybrid on/off premises composite application scenarios which we believe are critical for customers starting to develop hybrid applications.

(AppFabric Connect is available now as a free add-on for BizTalk Server 2010 to extend existing systems to both Windows Azure AppFabric and Windows Server AppFabric.)

Tuesday, February 4, 2014

Deploy and Host Web Apps in azure using VS.NET


You'll learn:
  • How to create a new App Service web app while you create a new web project in Visual Studio.
  • How to deploy a web project to an App Service web app by using Visual Studio.
The diagram illustrates what you do in the tutorial.
Visual Studio create and deploy diagram
At the end of the tutorial, a Troubleshooting section gives ideas on what to do if something doesn't work, and a Next steps section provides links to other tutorials that go into more depth about how to use Azure App Service.
As this is a getting-started tutorial, the web project it shows how to deploy is a simple one that doesn't use a database and doesn't do authentication or authorization. For links to more advanced deployment topics, see How to deploy an Azure web app.
Apart from the time required to install the Azure SDK for .NET, this tutorial will take about 10-15 minutes to complete.

Prerequisites

Set up the development environment

The tutorial is written for Visual Studio 2015 with the Azure SDK for .NET 2.9 or later.
  • Download the latest Azure SDK for Visual Studio 2015. The SDK installs Visual Studio 2015 if you don't already have it.
    Note:
    Depending on how many of the SDK dependencies you already have on your machine, installing the SDK could take a long time, from several minutes to a half hour or more.
If you have Visual Studio 2013 and prefer to use that, you can download the latest Azure SDK for Visual Studio 2013. Some screens may look different from the illustrations.

Configure a new web project

Your next step is to create a web project in Visual Studio and a web app in Azure App Service. In this section of the tutorial you configure the new web project.
  1. Open Visual Studio 2015.
  2. Click File > New > Project.
  3. In the New Project dialog box, click Visual C# > Web > ASP.NET Web Application.
  4. Make sure that .NET Framework 4.5.2 is selected as the target framework.
  5. Azure Application Insights monitors your web app for availability, performance, and usage. The Add Application Insights to Project check box is selected by default the first time you create a web project after installing Visual Studio. Clear the check box if it's selected but you don't want to try Application Insights.
  6. Name the application MyExample, and then click OK.
    New Project dialog box
  7. In the New ASP.NET Project dialog box, select the MVC template, and then click Change Authentication.
    For this tutorial, you deploy an ASP.NET MVC web project. If you want to learn how to deploy an ASP.NET Web API project, see the Next steps section.
    New ASP.NET Project dialog box
  8. In the Change Authentication dialog box, click No Authentication, and then click OK.
    No Authentication
    For this getting-started tutorial you're deploying a simple app that doesn't do user log-in.
  9. In the Microsoft Azure section of the New ASP.NET Project dialog box, make sure thatHost in the cloud is selected and that App Service is selected in the drop-down list.
    New ASP.NET Project dialog box
    These settings direct Visual Studio to create an Azure web app for your web project.
  10. Click OK

Configure Azure resources for a new web app

Now you tell Visual Studio about the Azure resources that you want it to create.
  1. In the Create App Service dialog, click Add an account, and then sign in to Azure with the ID and password of the account that you use to manage your Azure subscription.
    Sign in to Azure
    If you already signed in earlier on the same computer, you might not see the Add an account button. In that case, you can skip this step or you might need to reenter your credentials.
  2. Enter a Web App Name that is unique in the azurewebsites.net domain. For example, you can name it MyExample with numbers to the right to make it unique, such as MyExample810. If a default web name is created for you, it will be unique and you can use that.
    If someone else has already used the name that you enter, you see a red exclamation mark to the right instead of a green check mark, and you have to enter a different name.
    The URL for your application is this name plus .azurewebsites.net. For example, if the name is MyExample810, the URL is myexample810.azurewebsites.net.
    You can also use a custom domain with an Azure web app. For more information, seeConfigure a custom domain name in Azure App Service.
  3. Click the New button next to the Resource Group box, and then enter "MyExample" or another name if you prefer.
    Create App Service dialog
    A resource group is a collection of Azure resources such as web apps, databases, and VMs. For a tutorial, it's generally best to create a new resource group because that makes it easy to delete in one step any Azure resources that you create for the tutorial. For more information, see Azure Resource Manager overview.
  4. Click the New button next to the App Service Plan drop-down.
    Create App Service dialog
    The Configure App Service Plan dialog appears.
    Configure App Service dialog
    In the following steps, you configure an App Service plan for the new resource group. An App Service plan specifies the compute resources that your web app runs on. For example, if you choose the free tier, your API app runs on shared VMs, while for some paid tiers it runs on dedicated VMs. For more information, see App Service plans overview.
  5. In the Configure App Service Plan dialog, enter "MyExamplePlan" or another name if you prefer.
  6. In the Location drop-down list, choose the location that is closest to you.
    This setting specifies which Azure datacenter your app will run in. For this tutorial, you can select any region and it won't make a noticeable difference. But for a production app, you want your server to be as close as possible to the clients that are accessing it, to minimizelatency.
  7. In the Size drop-down, click Free.
    For this tutorial, The free pricing tier will provide good enough performance.
  8. In the Configure App Service Plan dialog, click OK.
  9. In the Create App Service dialog box, click Create.

Visual Studio creates the project and web app

In a short time, usually less than a minute, Visual Studio creates the web project and the web app.
The Solution Explorer window shows the files and folders in the new project.
Solution Explorer
The Azure App Service Activity window shows that the web app has been created.
Web app created in Azure App Service Activity window
The Cloud Explorer window lets you view and manage Azure resources, including the new web app that you just created.
Web app created in Cloud Explorer

Deploy the web project to the Azure web app

In this section, you deploy the web project to the web app.
  1. In Solution Explorer, right-click the project, and choose Publish.
    Choose Publish in Visual Studio menu
    In a few seconds, the Publish Web wizard appears. The wizard opens to a publish profilethat has settings for deploying the web project to the new web app.
    The publish profile includes a user name and password for deployment. These credentials have been generated for you, and you don't have to enter them. The password is encrypted in a hidden user-specific file in the Properties\PublishProfiles folder.
  2. On the Connection tab of the Publish Web wizard, click Next.
    Click Next on Connection tab of Publish Web wizard
    Next is the Settings tab. Here you can change the build configuration to deploy a debug build for remote debugging. The tab also offers several File Publish Options.
  3. On the Settings tab, click Next.
    Settings tab of Publish Web wizard
    The Preview tab is next. Here you have an opportunity to see what files are going to be copied from your project to the API app. When you're deploying a project to an API app that you already deployed to earlier, only changed files are copied. If you want to see a list of what will be copied, you can click the Start Preview button.
  4. On the Preview tab, click Publish.
    Preview tab of Publish Web wizard
    When you click Publish, Visual Studio begins the process of copying the files to the Azure server. This may take a minute or two.
    The Output and Azure App Service Activity windows show what deployment actions were taken and report successful completion of the deployment.
    Visual Studio Output window reporting successful deployment
    Upon successful deployment, the default browser automatically opens to the URL of the deployed web app, and the application that you created is now running in the cloud. The URL in the browser address bar shows that the web app is loaded from the Internet.
    Web app running in Azure
    Tip:
    You can enable the Web One Click Publish toolbar for quick deployment. ClickView > Toolbars, and then select Web One Click Publish. You can use the toolbar to select a profile, click a button to publish, or click a button to open the Publish Web wizard. Web One Click Publish Toolbar