X Blogs

who you gonna call?

Azure AppFabric Cache HowTo

clock May 3, 2011 04:24 by author Rok Bermež
Well since we now have Azure AppFabric Cache available, let’s get a head start on how to use it in your Cloud ASP.NET (MVC) application. First, you need to have AppFabric 1.0 April Refresh SDK installed on your machine so grab it at here.
Next, go to Windows Azure Management portal. Log in, go to AppFabric/Cache and create new service namespace: wait for the service to be activated.

Then click 'View Client Configuration Button'

you will get a nice pre prepared configuration settings (with all those pesky security information included) for your app:
now we have all the pieces of the puzzle ready, all we have to do is to add references to caching dlls (located at C:\Program Files\Windows Azure AppFabric SDK\V1.0\Assemblies\NET4.0\Cache) to our application and change web.config with the settings given by previous step.

You would always need to put cache section in <configSections> node:
<section name="dataCacheClients" 
             type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection,
Microsoft.ApplicationServer.Caching.Core"
allowLocation="true" allowDefinition="Everywhere"/>
and configure your Cache EndPoints:
<dataCacheClients>
    <dataCacheClient name="default">
      <hosts>
        <host name="ntkonferenca.cache.windows.net" cachePort="22233" />
      </hosts>
      <securityProperties mode="Message">
        <messageSecurity
authorizationInfo="1AmN0tT371NgUtH@T">
        </messageSecurity>
      </securityProperties>
    </dataCacheClient>
    <dataCacheClient name="SslEndpoint">
      <hosts>
        <host name="ntkonferenca.cache.windows.net" cachePort="22243" />
      </hosts>
      <securityProperties mode="Message" sslEnabled="true">
        <messageSecurity
authorizationInfo="1AmN0tT371NgUtH@T">
        </messageSecurity>
      </securityProperties>
    </dataCacheClient>
  </dataCacheClients>
If your application uses Session State and you want it to use Azure AppFabric Cache (which you do) you change your <sessionState> node to:
    <sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
      <providers>
        <add name="AppFabricCacheSessionStoreProvider"
             type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, 
Microsoft.Web.DistributedCache"
cacheName="default" useBlobMode="true" dataCacheClientName="default" /> </providers> </sessionState>
and the same for OutputCache by changing <caching> note:
<caching>
    <outputCacheSettings enableFragmentCache="true" defaultProvider="DistributedCache">
      <outputCacheProfiles>
        <add name="default" duration="43000" />
        <add name="DistributedCache"
                       type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, 
Microsoft.Web.DistributedCache"
cacheName="default" dataCacheClientName="default" /> </outputCacheProfiles> </outputCacheSettings> </caching>
That’s it, nothing needs to be changed in your code, your app is configured and ready to be published to the cloud. AppFabric Cache is not a free service even if you won’t be charged anything for its use prior to August 1, 2011. After that the prices are:
  • 128 MB cache for $45.00/month
  • 256 MB cache for $55.00/month
  • 512 MB cache for $75.00/month
  • 1 GB cache for $110.00/month
  • 2 GB cache for $180.00/month
  • 4 GB cache for $325.00/month
In my next post, Ill tackle with using AppFabric Cache without using prepared providers by simple GET and PUT statements (lets get rid of HttpRuntime.Cache as well).

 



Windows Azure AppFabric Caching Service Released

clock April 30, 2011 19:52 by author Rok Bermež

Finally the Azure thingy I’ve been waiting for the most. From the official source:

Today we are excited to announce that the Caching service has been released as a production service.  

The Caching service is a distributed, in-memory, application cache service that accelerates the performance of Windows Azure and SQL Azure applications by allowing you to keep data in-memory and saving you the need to retrieve that data from storage or database.

We provide 6 different cache size options for you to choose from, varying from 128MB to 4GB.  In order for customers to be able to start using the service and evaluate your needs we are running a promotion period in which we will not be charging for the service for billing periods prior to August 1, 2011.

To learn more about the Caching service please use the following resources:

·        Windows Azure AppFabric Caching availability announced!! blog post, including more information on pricing.

·        Video: Introduction to the Windows Azure AppFabric Cache

·        Video: Windows Azure AppFabric Caching – How to Set-up and Deploy a Simple Cache

·        Windows Azure AppFabric FAQ on MSDN

·        MSDN Documentation

The service is already available in our production environment at: http://appfabric.azure.com.

For questions on the Caching service please visit the Windows Azure Storage Forum.

Customers can take advantage of our free trial offer to get started with the Caching service and Windows Azure AppFabric. Just click on the image below and get started today!

 



Windows Azure Cache Dependency

clock April 11, 2011 08:07 by author Rok Bermež

We are supposed to get Windows AppFabric Cache real soon, but till than form time to time we need to synchronize content cached inside our Web roles. SqlDependency is one way, but it cannot solve all problems (especialy those that are not based on SQL data). So to help with the matter I wrote AzureStorageCacheDependency that uses Azure storage to know when data is outdated and cache shloul be cleared. If anyone is in need of something similar, here it goes:

public class AzureStorageCacheDependency : System.Web.Caching.CacheDependency
    {
        private System.Threading.Timer _timer;
        private int _poolTime;
        private CloudBlob _blob;
        private string _key;

        public AzureStorageCacheDependency(string connectionString, string conteinerAddress, string blobAddress, int poolTime = 5000)
        {
            _poolTime = poolTime;
            using (AzureContext azureContext = new AzureContext(true))
            {
                var storageAccount = CloudStorageAccount.Parse(connectionString);
                CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobStorage.GetContainerReference(conteinerAddress.ToLower());
                container.CreateIfNotExist();
                _blob = container.GetBlockBlobReference(blobAddress.ToLower());
                if (!Exists(_blob))
                {
                    Reset();
                }
                else
                {
                    _key = _blob.DownloadText();
                }
            }
            _timer = new Timer(new System.Threading.TimerCallback(CheckDependencyCallback), this, 0, _poolTime);
        }



        public void Reset()
        {
            _key = Guid.NewGuid().ToString();
            _blob.UploadText(_key);
        }

        private void CheckDependencyCallback(object sender)
        {
                if (!Exists(_blob) || _key != _blob.DownloadText())
                {
                    NotifyDependencyChanged(this, EventArgs.Empty);
                    _timer.Dispose();
                }
        }

        public static bool Exists(CloudBlob blob)
        {
            try
            {
                blob.FetchAttributes();
                return true;
            }
            catch (StorageClientException e)
            {
                if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
                {
                    return false;
                }
                else
                {
                    throw;
                }
            }
        }
    }

    public class AzureContext : IDisposable
    {
        HttpContext _oldHttpContext;
        bool _restoreOldHttpContext = false;


        public AzureContext(bool forceSettingContextToNull = false)
        {
            if (forceSettingContextToNull)
            {
                _oldHttpContext = HttpContext.Current;
                HttpContext.Current = null;
                _restoreOldHttpContext = true;
            }
            else
            {
                try
                {
                    HttpResponse response = HttpContext.Current.Response;
                }
                catch (HttpException)
                {
                    _oldHttpContext = HttpContext.Current;
                    HttpContext.Current = null;
                    _restoreOldHttpContext = true;
                }
            }
        }


        public void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_restoreOldHttpContext)
                {
                    HttpContext.Current = _oldHttpContext;
                }
            }
        }


        public void Dispose()
        {
            Dispose(true);
        }


        ~AzureContext()
        {
            Dispose(false);
        }
    }


ASP.NET MVC 3 AJAX REDIRECT RESULT

clock April 5, 2011 23:31 by author Rok Bermež
From time to time, we need to selectively redirect the browser to another location as a 
result of an AJAX action. Just returning RedirectResult won’t do the trick (even if we
are used to similar functionality in ASP.NET AJAX in combination with WebForms ). Here
is a very simple RedirectResult thet will be appropriate in those scenarios:

public class AjaxRedirectResult : RedirectResult { public AjaxRedirectResult(string url): base(url){} public override void ExecuteResult(ControllerContext context) { if (context.RequestContext.HttpContext.Request.IsAjaxRequest()) { JavaScriptResult result = new JavaScriptResult() { Script = String.Format("window.location='{0}';",
UrlHelper.GenerateContentUrl(Url, context.HttpContext)) }; result.ExecuteResult(context); } else base.ExecuteResult(context); } }


Windows Azure Platform SDK 1.4 Released

clock March 11, 2011 18:14 by author Rok Bermež

SDK 1.4 is available and it  fixes several significant bugs including the nasty RDP bug and adds capabilities like multiple administrator support from the enhanced Windows Azure Connect portal.

Bug Fixes:

  • Resolved an issue that caused full IIS fail when the web.config file was set to read-only.
  • Resolved an issue that caused full IIS packages to double in size when packaged.
  • Resolved an issue that caused a full IIS web role to recycle when the diagnostics store was full.
  • Resolved an IIS log file permission Issue which caused diagnostics to be unable to transfer IIS logs to Windows Azure storage.
  • Resolved an issue preventing csupload to run on x86 platforms.
  • User errors in the web.config are now more easily diagnosable.
  • Enhancements to improve the stability and robustness of Remote Desktop to Windows Azure Roles.

New Features

  • Windows Azure Connect:
    • Multiple administrator support on the Admin UI.
    • An updated Client UI with improved status notifications and diagnostic capabilities.
    • The ability to install the Windows Azure Connect client on non-English versions of Windows.
  • Windows Azure CDN:
    • Windows Azure CDN for Hosted Services: Developers can now use the Windows Azure Web and VM roles as"origin" for objects to be delivered at scale via the Windows Azure CDN. Static content in a website can be automatically edge-cached at locations through out the United States, Europe, Asia, Australia and South America to provide maximum bandwidth and lower latency delivery of website content to users.
    • Serve secure content from the Windows Azure CDN: A new checkbox option in the Windows Azure management portal enables delivery of secure content via HTTPS through any existing Windows Azure CDN account.

You may download the new Windows Azure 1.4 SDK here.



Windows Azure SDK 1.3 Refresh

clock February 3, 2011 04:09 by author Rok Bermež

Due to numerous bugs, the 'hotfix' for SDK was released recently.
I havent tried it yet but sure hope that some annoying things will go away. "The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state" really is a mood killer. Hope for the best and upgrade here. (32 bit version also available here)



Windows Azure Full IIS

clock January 11, 2011 08:00 by author Rok Bermež

Some time ago I wrote how to deploy multitenant application to the Cloud. The process was tricky at best. With new Windows Azure SDK 1.3 things just got a lot simpler and I absolutely love it. The feature is called Full IIS and allows your web roles to access the full range of web server features that are available in on-premise IIS installations. However if you choose to use them, there are a few differences from the classic Azure Hosted Web Core (HWC) model.

First you need to tell Windows Azure SDK to use Full IIS instead of HWC and you do this by adding a valid <Sites> section to your ServiceDefinition.csdef  file.  By default Visual Studio will create HWC model definition like this:

    <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="Endpoint1" endpointName="Endpoint1" />
        </Bindings>
      </Site>
    </Sites>

You can easily customize it to define multiple web sites, or virtual apps (virtual directories are also supported now):

<Sites>
  <Site name="MainSite">
    <VirtualApplication name="WebApp1" physicalDirectory="D:\Delo\Projects\WebApp1\" />
    <Bindings>
      <Binding name="HttpIn" endpointName="HttpIn" />
    </Bindings>
  </Site>
  <Site name="AnotherSiteOrSubDomain" physicalDirectory="D:\Delo\Projects\ AnotherSiteOrSubDomain ">
    <Bindings>
      <Binding hostHeader="anothersiteorsubdomain.myall.si" name="HttpIn" endpointName="HttpIn"/>
    </Bindings>
  </Site>
</Sites>

Things are much more similar to on-premises application then in HWC model. While RoleEntryPoint  runs under different process (WaIISHost.exe) than your web roles  (w3wp.exe), OnStart method still gets called but configuration settings work a bit differently. You cannot register or store some static values to be available to all websites. Remember its running in a different process... so you wont be able to access its data. What I mean by this is, probably everyone dealing with Azure Development has something similar to this in their role onstart method:

CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>{
    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
});

While code is still perfectly sound, it wont do any good to our web roles, so the proper place to register it would by global.asax on ApplicationStart event. It all kind of makes sense, since different websites need different resources anyway.



MultipleGenericBindingGenerator for Ninject.Extensions.Conventions

clock January 11, 2011 02:55 by author Rok Bermež

Ninject.Extensions.Conventions provides convention based binding for Ninject modeled after the StructureMap 2.5 AssemblyScanner by Jeremy Miller.

When StructureMap users can use something like:

Scan(scanner =>
                {
                    scanner.AssembliesFromApplicationBaseDirectory(assembly => assembly.FullName.StartsWith("Ntk.Infrastructure."));
                    scanner.ConnectImplementationsToTypesClosing(typeof (IMessageHandler <,>));
                    scanner.ConnectImplementationsToTypesClosing(typeof (IMessageHandler <>));
                });

Ninject.Extensions.Conventions using GenericBindingGenerator can not:

            kernel.Scan(scanner =>
            {
                scanner.FromAssembliesMatching( "Ntk.Infrastructure.*.dll" );  
                scanner.BindWith(new GenericBindingGenerator(typeof(IMessageHandler<>)));
                scanner.BindWith(new GenericBindingGenerator(typeof(IMessageHandler<,>)));
                scanner.InTransientScope();
            });

So slightly modified version of GenericBindingGenerator called MultipleGenericBindingGenerator comes to the rescue:

            kernel.Scan(scanner =>
            {
                scanner.FromAssembliesMatching("Ntk.Infrastructure.*.dll");
                scanner.BindWith(new MultipleGenericBindingGenerator(typeof(IMessageHandler<>),typeof(IMessageHandler<,>)));
                scanner.InTransientScope();
            });

If anyone needs anything like this, here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ninject;
using Ninject.Activation;
using Ninject.Extensions.Conventions;

namespace TestProj{
    public class MultipleGenericBindingGenerator  : IBindingGenerator
    {
        private static readonly Type TypeOfObject = typeof (object);
        private readonly Type[] _contractTypes;

        /// <summary>
        /// Initializes a new instance of the <see cref="MultipleGenericBindingGenerator"/> class.
        /// </summary>
        /// <param name="contractTypes">Types of the contract.</param>
        public MultipleGenericBindingGenerator(params Type[] contractTypes)
        {
            foreach (var type in contractTypes)
            {
                if (!(type.IsGenericType || type.ContainsGenericParameters))
                {
                    throw new ArgumentException(String.Format("The contract must be an open generic type ({0}).",type.Name), "contractTypes");
                } 
            }
            _contractTypes = contractTypes;
        }

        #region Implementation of IBindingGenerator

        /// <summary>
        /// Processes the specified type creating kernel bindings.
        /// </summary>
        /// <param name="type">The type to process.</param>
        /// <param name="scopeCallback">the scope callback.</param>
        /// <param name="kernel">The kernel to configure.</param>
        public void Process( Type type, Func<IContext, object> scopeCallback, IKernel kernel )
        {
            Type interfaceType = ResolveClosingInterface( type );
            if ( interfaceType != null )
            {
                kernel.Bind( interfaceType ).To( type ).InScope( scopeCallback );
            }
        }

        #endregion

        /// <summary>
        /// Resolves the closing interface.
        /// </summary>
        /// <param name="targetType">Type of the target.</param>
        /// <returns></returns>
        public Type ResolveClosingInterface( Type targetType )
        {
            if ( targetType.IsInterface || targetType.IsAbstract )
            {
                return null;
            }

            do
            {
                Type[] interfaces = targetType.GetInterfaces();
                foreach ( Type @interface in interfaces )
                {
                    if ( !@interface.IsGenericType )
                    {
                        continue;
                    }

                    if (_contractTypes.Contains(@interface.GetGenericTypeDefinition()))
                    {
                        return @interface;
                    }
                }
                targetType = targetType.BaseType;
            } while ( targetType != TypeOfObject );

            return null;
        }
    }
}



T4MVC templates for strongly typed ASP.MVC

clock January 10, 2011 21:19 by author Rok Bermež

T4 templates for strongly typed ASP.MVC

 

MVC is a software pattern, that has been first introduced 1979 by Norwegian scientist Trygve Reenskaug.  The idea was to decouple the tight knot between views and models, to have a much more control over the software.

For example, very known ASP.NET 2.0 technology had the implementation of views, but controllers and models were combined in the code behind, which has the impact on the testing and other features, which is needed to build a easy proficient sustainable web solution.

Year ago Microsoft has launched a framework ASP.NET MVC for supporting software pattern and add additional value with different view engines , such as Razor, to eliminate this requirement. Since then, developers are having  few consideration about choosing between ASP.NET WebForms and ASP.NET MVC, but that is topic for another blog post.

MVC grew very quickly and alot of developers are using the new .NET framework to write efficient, light weight, powerfull web apps. Even though we do have a great enviroment for writing, testing, debugging  .NET apps, there is still a lack of string and mis-machted typos.

Consider following example:

<%:Html.ActionLink(»My link«,«Indeks«,«Home«) %>

This is a link to the Home controller, with a method Indeks. But wait, there is no indeks method there. It is a typo. Since we forgot to write x, instead of ks, we got a runtime error. We have to run the site, click of the link, read the error message, ask ourself, what did we do, use the debugger, run the site, check again, go through bunch of step, just because we made a typo.

This is the reason, why expert developers, such as david Ebbo, created a helper (T4 templates), that goes through the code and created a strongly typed strings for controllers, views, even a content.

Fixed upper example:

<%:Html.ActionLink(»My link«, MVC.Home.Index)%>

Its so easy. No more runtime checking, no repro bugs, even intellisense helps us understand, which name and even parameters we will use. 

You can use the following strongly typed helpers in the whole app, not only the views ( also in controllers, etc.)

It is quite simple to use it:

1.       Download the zip file on the codeplex site

2.       Required watching the David Ebbo intro with examples

3.       Unzip the file

4.       Add the 2 files in the root of your MVC app (T4MVC.tt and T4MVC.setting.t4)

5.       Build it

6.       Use it J

You can change the setting for t4 in the settings file to bend it to you will J

Happy no-typo coding.



... azure looks back at you

clock January 8, 2011 23:22 by author Rok Bermež

It’s been a month since Azure SKD 1.3 has been released with a lot of new features. Let’s take a look at the ability to user Remote Desktop Connection to your roles first.

In order to enable this feature we must configure our deployments to support it. The easiest way to do so is to right click on cloud service project in visual studio and choose deploys. There you can click on 'Configure Remote Desktop connections'.

Here you can enable RDP connections for all roles and you must set the required security credentials. So let’s create a security certificate first.

Then we set user credentials for our RDP account and set its expiration date.

After that, we export the security certificate so we can upload it to the cloud (you can click on view to open it directly).

We also export private key

And then we upload exported file through the Windows Azure Management portal to our chosen hosted service.

If we take a closer look at what our Visual Studio Wizard did, we can open ServiceDefinition.csdef and ServiceConfiguration.cscfg and see xml additions.


Now we can deploy our solution anyway we like.

Once the deployment is complete and our role is in 'ready' state we can download or open .rdp file through Azure Management portal.

Now we can finally connect to our instance

... and azure looks back at you

NOTE: Changes made to instance will NOT be persisted. This was meant for easier debugging. If you want to take full advantage of IIS configuration you will need to use ‘Full IIS’ feature, which will be covered in my next post.



About the author

Rok Bermež is Slovenian Windows Azure MVP, he works as a Software Engineer and Microsoft Certified Trainer at Kompas Xnet. His primary interests include cloud computing and web development. With extensive experience in development and architecture he participated in many projects and since the CTP release of Windows Azure much of those projects are based on Windows Azure platform. Rok has been delivering courses, writing code and speaking at conferences and community events on Microsoft technologies for the last couple of years. You can also find him on Twitter (@Rok_B).

Month List

Sign In