Monday, September 19, 2011

Managed Extensibility Framework (MEF)

MEF is a component of .net framework 4.0, to create lightweight, extensible applications. It avoid hard dependencies and lets application developer to discover and use extensions without any configuration required.

Why MEF?

Imagine a situation where an application is using several smaller components. And application is responsible for creating and running those components.
One possible solution could be including all the components as source code in the application. But you cannot add new components without modifying the source code.
Another solution could be to provide an interface for decoupling between application and components. So the component can implement the interface and interact with application. But this approach too has drawback. As application cannot discover components by itself, it must be explicitly told which components are required and loaded.
Here MEF comes into the picture. MEF provides a way to discover components via composition. A MEF component specifies both its dependencies (known as imports) and what capabilities (known as exports) it makes available.
Let’s understand it with the help of an example. Suppose you are having a simple calculator application which currently supports addition and subtraction.

Creating composition container and catalogue

Composition container keeps track of which components are available for composition and what are their dependencies. It provides a way by which application can get the instance of components to be composed. We need to include System.ComponentModel.Composition in reference.
   
   
    //An aggregate catalog that combines multiple catalogs
    var catalog = new AggregateCatalog();
    //Adds all the parts found in the same assembly as the current class
    catalog.Catalogs.Add(new AssemblyCatalog(typeof(this).Assembly));
 
    //If parts are placed at some other location then adds that directory path
    //catalog.Catalogs.Add(new DirectoryCatalog(componentsDirectoryPath));
 
 
    //Create the CompositionContainer with the parts in the catalog
    CompositionContainer _container = new CompositionContainer(catalog);
 
    //Fill the imports of this object
    try
    {
        this._container.ComposeParts(this);
    }
    catch (CompositionException compositionException)
    {
        Console.WriteLine(compositionException.ToString());
   }

catalog.Catalogs.Add(new AssemblyCatalog(typeof(this).Assembly));
This adds the components from the current assembly. To add the components from some specified folder location, add a directory catalogue like:
catalog.Catalogs.Add(new DirectoryCatalog(componentssDirectoryPath));
Where componentsDirectoryPath is the path of directory where components can be found.

Import and Exports

Define an interface like it.
[Import(typeof(IOperation))]
public interface IOperation
{
    string Operate(int leftOperand, int rightOperand);
}

This interface has an attribute Import. This ImportAttribute defines that the type IOperation needs to be imported. So we implement the IOperation class, and above the class we use ExportAttribute indicating that it has the capabilities of IOperation. Also it contains ExportMetadata attribute indicating that depending on the metadata Symbol the operation is performed.
[Export(typeof(IOperation))]
[ExportMetadata("Symbol", '+')]
class Add : IOperation
{
//Implementation of IOperation
}

Now we will do lazy initialization for getting objects like this:
[ImportMany]
IEnumerable<Lazy<IOperation, IMetadata>> operations;

Lazy initialization is used so that only operations that are needed are initialized. Based on the metadata it initializes what operation is to be performed. It contains ImportMany attribute because IOperation can be filled by many exports like add, subtract etc.

Lazy Initialization

As we see we declare an IEnumerable for lazy initialization. Now how does it work? When we run application, it initializes the catalogue and creates a container. Based on the Import attribute it finds the components which can be filled for it. Here we have only one class Add to fill it. So operations will contains only single Lazy object, and that object will be initialized when it will be accessed first time. So based on the operation we will call Operate function.
foreach (Lazy i in operations)
    {
        if (i.Metadata.Symbol.Equals(operation)) 
                 result= i.Value.Operate(left, right).ToString();
    }

I had a sample project to illustrate it. It contains 2 operations Add and Subtract in the assembly and Multiplication in a separate dll, which can be found in “\Extensions” folder.







Thursday, July 21, 2011

Extension Methods in .Net

In this article we will see what extension methods are, why we need them and how to create them.
Extension methods are methods which allow you to extend a type, even if you don’t have the source code for that type. Let’s understand it with a simple example: Suppose you want to add IsNumeric method to string class to check whether a string is numeric or not. What you will do?
1) Either you have to create a new class inheriting from string class and then add the IsNumeric method in it. Now this solution has 2 problems. First, what if the class you want to inherit, in this case string class, is sealed. You can’t inherit from it. Second, if any how you inherit the string class then you need to make sure everyone else is using your class not the string class
2) Or create a static StringHelper class and create a static IsNumeric function in it. But this solution also has a problem that user need to know a Helper class exist.
Prior to .Net Framework 3.5 second solution was the most popular solution. But in .Net Framework concept of extension methods is introduced. Now let’s see how to create extension methods. We need to create a static class StringHelper and a static method IsNumeric as we do in the second solution.
public static class StringHelper
{
public static bool IsNumeric(this string str)
{
double val;
return double.TryParse(str, out val);
}
}
The only difference from second solution is the “this” keyword in the IsNumeric parameter. By using this keyword we are indication that it is the extension of type next to the “this” keyword. Here we have written “this string” it means IsNumeric is the extension of string type.
To use it:
string nonNumericString = "123abc";
bool Result = nonNumericString.IsNumeric();
Another benefit of using extension method is that you can easily convert helper class into extension methods without breaking the existing functionality, i.e., following code still works:
bool Result = StringHelper.IsNumeric(nonNumericString);
So now you realize it is easy to create extension methods. J

Saturday, May 7, 2011

Initializing Windows Azure Diagnostic – Part 2

As you have read in my previous article how to initialize Windows Azure diagnostic monitor. Now we will see how to collect different diagnostic data. I am defining a connection string for the role. For that right click on the role and click on properties. Now from the connection tab you can add configuration string.
clip_image002

1) Collecting data from event logs
Open the Role entry point class. Add following code to the OnStart() function
var config = DiagnosticMonitor.GetDefaultInitialConfiguration();
config.WindowsEventLog.DataSources.Add("System!*");
config.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning;
config.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
DiagnosticMonitor.Start("DiagnosticsConnectionString", config);

So, first you need to get DiagnosticMonitorConfiguration object. Then you can add channel to the datasource. You can add multiple channels. Windows Azure cannot log Security channel. You can define log level filter, so that only those logs are transferred. You have to define schedule transfer period, so that after that time span logs are transferred to the account you specified in the configuration. Now start the diagnostic monitor with the connection and new configuration.

2) Collect data from Performance Counters
Open the Role entry point class. Add following code to the OnStart() function

var config = DiagnosticMonitor.GetDefaultInitialConfiguration();
config.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
{
CounterSpecifier = @"\Processor(_Total)\% Processor Time",
SampleRate = TimeSpan.FromMinutes(1.0),
});
config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(5.0);
DiagnosticMonitor.Start("DiagnosticsConnectionString", config);

Here I have defined a performance counter which takes sample for processor time in every minute. You can add multiple performance counters in the data souce. And then transfer the log to azure account defined in the connection string after every 5 minutes.

3) Collect data from IIS logs
IIS logs are collected only for web role because worker and VM roles don’t run under IIS.
To enable IIS logging add following code to the web.config.

<tracing>
<traceFailedRequests>
<add path="*">
<traceAreas>
<add provider="ASP" verbosity="Verbose" />
<add provider="ASPNET" areas="Infrastructure, Module, Page, AppServices" verbosity="Verbose" />
<add provider="ISAPI Extension" verbosity="Verbose" />
<add provider="WWW Server"
areas="Authentication, Security, Filter, StaticFile, CGI, Compression, Cache, RequestNotifications, Module"
verbosity="Verbose" />
</traceAreas>
<failureDefinitions statusCodes="400-599" />
</add>
</traceFailedRequests>
</tracing>
After adding this code IIS logs are automatically logged. No additional API calls are required.

4) Collect data from crash dumps
In the role entry point class add the following code;

Microsoft.WindowsAzure.Diagnostics.CrashDumps.EnableCollection(true);

Pass true for enabling complete crash dump data, or false for partial crash dump data.

Initializing Windows Azure Diagnostics- Part 1

As we have seen in my previous blog that some of diagnostics data is stored in table, while some in blob. For collecting diagnostics data, we must initialize Windows Azure diagnostic monitor. Windows Azure diagnostic monitor runs in Windows Azure and in the compute emulator and collects diagnostic data for a role instance. Only Windows Azure Logs, Windows Azure Diagnostic Infrastructure Logs and IIS logs are configured in the diagnostic monitor by default. We can collect other diagnostic data by importing diagnostic module. A role instance that imports the Diagnostic module starts, it starts the diagnostic monitor.
To start diagnostic monitor for a role open the role entry point class and make sure that you are using Microsoft.WindowsAzure.Diagnostics namespace in the class. Now on the Azure service project right click on the role and click Properties. Here I am configuring a web role.
clip_image002
Now in the configuration section check enable diagnostics. And specify the account credentials
clip_image004
You can either use development storage or can give your account credentials. Just click on “…” and will ask for the credentials.
clip_image006
Now when you open your .cscfg file it has a new setting for the webrole like
<ConfigurationSettings>
<Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=myaccountName;AccountKey=myAccountKey" />
</ConfigurationSettings>

And in the .csdef file it import the module like:
<Imports>
<Import moduleName="Diagnostics" />
</Imports>

If you are using a web role or worker role template for creating roles then in the web.config or app.config following code is added. Or you can just inherit a class from RoleEntryPoint and add the following code in the config file.


<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>


 If you want to create a web role just override OnStart() method, and if you want to create a workerrole override OnStart() and Run() method. We will see it in my next article.

Friday, March 11, 2011

Understanding Diagnostics in Windows Azure

 

Windows Azure diagnostics provides facility to store diagnostics data. Azure diagnostics supports logging and monitoring of diagnostics data. It uses blob service or table service to save diagnostics data, depending on the diagnostics data. Before logs are saved in a container they are indexed in WADDirectoriesTable table in the storage account.
Following diagnostics data is stored in table storage:
Data Source Table name in Azure Storage Detail
Windows Azure Logs WADLogsTable These are the application logs dumped from the application.
Windows Azure Diagnostics Infrastructure Logs WADDiagnosticInfrastructureLogsTable These are the logs about running of diagnostics service.
Windows Event logs WADWindowsEventLogsTable These are the logs generated on the instance where logs are running.
Performance counters WADPerformanceCountersTable These are the performance matrices like memory utilization, processor utilization, response time etc.
Following diagnostics data is stored in blob storage:
Data Source Container name in azure storage Detail
IIS Logs wad-iis-logfiles These are the IIS logs generated by role instances.
Failed Request Logs wad-iis-failedreqlogfiles These are the IIS failed requests logs generated by role instances.
Crash Dumps wad-crash-dumps These are the logs generated on the application crash.

Wednesday, March 9, 2011

Deploying an application in Windows Azure

In the previous article we have seen how to create a Hello World application in azure. In this article we will see how to deploy it in Windows azure. To deploy an application in azure, two files are needed- a package file and a configuration file. Configuration file is already in CloudService1 named ServiceConfiguration.cscfg. Now for the package file just right click on the CloudService project and click Publish.
clip_image002
Then it asks to create just a package file or to deploy it in azure.
clip_image004
If first option is selected then it creates the package file and opens the explorer.
clip_image006
Once we have a package file (.cspkg) and configuration file (.cscfg) then we can deploy it through management portal, or azure service management cmdlets, or Cerebrata’s CloudStorageStudio, or Cerebrata’s Azure management cmdlets. We can directly upload it through visual studio also, if we select second option from publish dialog. It needs a subscriptionId and a X509 v3 certificate as shown below:
clip_image008
Then we have to provide deployment environment and storage account.
Whichever option we had selected, we need:
a) A Windows Azure Subscription – when we sign up for azure, a subscription is associated with our live Id.
b) A Windows Azure Hosted Service – we need to create a hosted service for deployment. It provides two deployment environment- production and staging.
c) A Windows Azure storage account – When we deploy through visual studio then package file is first uploaded in blob storage of the storage account, and then deployed from the blob service.
So summarizing deployment through management portal in some simple steps:
1) We need a package file and a configuration file to deploy.
2) To create a package file click publish and create package only option from project.
3) Sign In the management portal.
4) Create a new hosted Service if you want to deploy in a new service.
5) Then in deployment environment either deploy in production or staging.
6) Then start the deployment.
7) You can see the progress of the deployment on the portal
8) To delete a deployment first click on stop, and when it is stopped delete it.

Tuesday, March 1, 2011

Creating a “Hello world” application in Azure

In this article we will see how to create a “Hello World!!!” application in azure in .net. I had used Visual Studio 2010 along with azure SDK 1.3 installed. Start visual studio and select a new project. In the cloud template select Windows Azure Cloud Service.
clip_image002
Once you click OK. It asks for selecting a Role. Here we are adding an ASP.Net Web role.
clip_image004
It will create two projects- CloudService1 (Azure Service Project) and WebRole1 (ASP.net Project). The Azure service project is used to configure the application, and to create a deployment package. ASP.Net project is like a normal web project.
clip_image006
Here I removed header div from the SiteMaster.
clip_image008
And add a text “Hello World!!!!” in the default.aspx
clip_image010
And we are done. Now Select Cloud Service as your startup project and run it. When you run it, azure simulation environment is initialized, and it starts development storage and development fabric.
clip_image012
And here you can see your Hello World!!!
clip_image014
If you select WebRole1 as your startup project and run the solution. It will run as a normal ASP.Net project and hosted locally on localhost.
If you click on the Azure Simulation and select “Show development Fabric UI” then it will show the azure services running on your machine.
clip_image016
Here My CloudService1 is running having a single instance of WebRole.
clip_image018