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

Thursday, February 24, 2011

Overview of Windows Azure

Windows Azure


Windows azure is Microsoft’s cloud platform. It includes Windows Azure operating system that serves as the Platform-as-a-Service (PAAS) and Infrastructure-as-a Service (IAAS). In order to understand AAS lets take an example-

1) To deploy or use software we first need servers, firewalls, switches etc.

2) Once server is setup then we need an OS then application server or database.

3) Then we have to install the actual application.

So we need some infrastructure, then platform and software. Windows Azure provides platform and infrastructure by providing a scalable and cost-effective computing, storage and networking resources on demand.

Windows Azure has three main components in azure: Compute, Storage and Fabric.

1) Windows Azure Compute:

Windows azure provides hosting environment for managed code. It provides computation service through roles. Windows azure supports 3 types of roles:

a) Web roles used for web application programming and supported by IIS7

b) Worker roles used for background processing of web roles.

c) Virtual Machine (VM) roles used for migrating windows server applications to Windows azure in an easy way.

Within a subscription one can have zero or more hosted service. Each hosted service can have deployment- either production or staging. And each deployment can have one or more roles of any types. Each role can have multiple instances.

2) Windows Azure Storage:

Windows azure provides storage in cloud. It provides 4 types of storage services:

a) Queues for messaging between web roles and worker roles.

b) Tables for storing structural data.

c) BLOBs (Binary Large Objects) to store text, files or large data.

d) Windows Azure Drives (VHD) to mount a page blob. These can be uploaded and downloaded via blobs.


3) Windows Azure AppFabric:

AppFabric provides infrastructure services for developing, deploying and managing Windows azure application. It provides 5 services:

a) Service bus It provides secure connectivity between distributed and disconnected applications in cloud.

b) Access control It grants access control to application and services based on the identity user. So the authorization decisions are pulled out from application into a set of rules that can transform incoming security claims into claims that applications understand.

c) Caching It provides caching for high speed access, scaling, and high availability of data to application. It is available for developer preview only.

d) Integration It provides integration between windows azure application and other SAAS. It will be available by CTP 2011.

e) Composite App It provides a hosting environment for WCF web services and workflows. It will be available by CTP 2011.

Monday, June 28, 2010

Creating commands in powerShell

Learn how to create commands in few simple steps:
For creating commands in powerShell, I had installed templates for it, which I get from here: http://channel9.msdn.com/ShowPost.aspx?PostID=256835. There are VB.NET and C# ones.
clip_image002
clip_image004
1) Now select a powerShell project as shown:
clip_image006
The project contains a PSSnapin file and a reference to the assembly System.Management.Automation
2) In the PSSnapIn.cs fill information as required.
[RunInstaller(true)]
public class WindowsPowerShell1SnapIn : PSSnapIn
{
public override string Name
{
get { return "MyFirstSnapIn"; }
}
public override string Vendor
{
get { return "Reeta"; }
}
public override string VendorResource
{
get { return "WindowsPowerShell1,"; }
}
public override string Description
{
get { return "Registers the CmdLets and Providers in this assembly"; }
}
public override string DescriptionResource
{
get { return "WindowsPowerShell1,Registers the CmdLets and Providers in this assembly"; }
}
}
3) Now add a new cmdlet class.
clip_image008
4) In this cmdlet we simply add a value to a parameter and output it.
[Cmdlet(VerbsCommon.Get, "Hello", SupportsShouldProcess = true)]
In this attribute “Get” is our verb and “Proc” is subject. Different verbs can be used. Read http://msdn.microsoft.com/en-us/library/ms714428(VS.85).aspx for more information.
5) To add parameter write :
[Parameter(Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Enter a name")]
[ValidateNotNullOrEmpty]
public string Name
{
get;
set;
}
To validate a parameter we can add different attribute on a parameter. We can add help message for the parameter By “HelpMessage”. We can indicate that a parameter is mandatory by adding “Mandatory= true”. We can add position for a parameter.
6) Now add a code to write the parameter value in ProcessRecord(). When this command runs it execute code written in Processrecord().
WriteObject will write values on the commandlet.
7) For running the power shell we first need to install the dll.
On visual studio command prompt use - installUtil yourAssemblyPath.dll
8) Now add the SnapIn in the power shell using command:
Add-PSSnapin MyFirstSnapIn
clip_image010
9) Now get the registered SnapIn list by command :
Get-PSSnapIn –registered
10) Now run the command using:
Get-Hello –Name Reeta
It will output – Hello Reeta
Since we had written position in the Parameter attribute we don’t need to specify –Name. if we write- Get-Hello Reeta, it gives same output.
If we don’t provide any parameter then it says that it is mandatory.
These are just simple steps for creating a command in powerShell. I get help from this blog http://blogs.msdn.com/b/daiken/archive/2007/02/07/creating-a-windows-powerShell-cmdlet-using-the-visual-studio-windows-powerShell-templates.aspx

Friday, February 26, 2010

How to create a Captcha

Step 1: Create a new website. In Default.aspx page put this code:
<table>
<tr>
<td>
<img height="30" alt="" src="BuildCaptcha.aspx" width="80" />
</td>
</tr>
<tr>
<td>
<asp:TextBox runat="Server" ID="txtCaptcha"/>
</td>
<td>
<asp:Button runat="Server" ID="btnSubmit" OnClick="btnSubmit_Click" Text="Submit" />
</td>
</tr>
</table>
Step 2: In Default.aspx.cs page write this code for Submit button click:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid && (txtCaptcha.Text.ToString() == Session["RandomStr"].ToString()))
{
Response.Write("Code verification Successful.");
txtCaptcha.Text = string.Empty;
}
else
{
Response.Write("Please enter code correctly.");
}
}
Step 3: Now add a new Page named BuildCaptcha.aspx.
On this page we choose random numbers and create a bitmap image from them. To do this write this code on the page load:
protected void Page_Load(object sender, EventArgs e)
{
//That is to create the random # and add it to our string
Bitmap objBMP = new Bitmap(60, 20);
Graphics objGraphics = Graphics.FromImage(objBMP);
objGraphics.Clear(Color.YellowGreen);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
//' Configure font to use for text
Font objFont = new Font("Arial", 8, FontStyle.Italic);
string randomStr = "";
char[] myArray = new char[5];
int x;
Random autoRand = new Random();
for (x = 0; x < 5; x++)
{
myArray[x] = System.Convert.ToChar(autoRand.Next(65, 90));
randomStr += (myArray[x].ToString());
}
//This is to add the string to session, to be compared later
Session.Add("RandomStr", randomStr);
//' Write out the text
objGraphics.DrawString(randomStr, objFont, Brushes.Blue, 3, 3);
//' Set the content type and return the image
Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
Now you are done. When you run website it looks like this:
clip_image002

Friday, November 20, 2009

How to read RSS and atom feed

Before .Net 3.5 we had to go for separate framework to read the feeds and parse it. In that case we need to refer the framework in our project and install that assembly in Bin or GAC. We need to parse RSS and atom feeds separately. But now, with .Net 3.5, life has become much easier.
With the namespace 'System.ServiceModel.Syndication' it is just few lines of code to read and parse the feeds either RSS or Atom. Just have a look on the code:
string Link;
string Copyright;
StringBuilder rssFeed= new StringBuilder();
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
String Title = feed.Title.Text;
if (feed.BaseUri != null)
{
       Link = feed.BaseUri.ToString();
}
else
{
       Link = feed.Links[0].Uri.ToString();
}
if (feed.Copyright != null)
{
      CopyRight = feed.Copyright.Text;
}
rssFeed.Append(“Title: ”+Title);
rssFeed.Append(“Link: “+Link);
rssFeed.Append(“\nCopyRight: “+CopyRight);
foreach (var item in feed.Items)
{
    string title = "";
    string description = "";
    string link = "";
    DateTime PublishDate;
    String AuthorName;
    String AuthorUri;
   if (item.Title != null)
   {
        title = item.Title.Text;
   }
   if (item.Content != null)
  {
    description = ((System.ServiceModel.Syndication. TextSyndicationContent)(item.Content)).Text;
   }
   else
   {
         if (item.Summary != null)
         {
               description = item.Summary.Text;
         }
    }
    if (item.Links != null && item.Links.Count > 0)
    {
          link = item.Links[0].Uri.ToString();
          for (int i = 1; i < item.Links.Count; i++)
          {
                 link += "\n" + item.Links[i].Uri.ToString();
           }
     }
     if (item.PublishDate != null)
    {
         PublishDate = item.PublishDate.DateTime;
     }
     if (item.Authors != null && item.Authors.Count > 0)
    {
           StringBuilder Authors = new StringBuilder(item.Authors[0].Name + ",");
          StringBuilder AuthorsUri = new StringBuilder(item.Authors[0].Uri + ",");
         for (int i = 1; i < item.Authors.Count; i++)
        {
                Authors += "\n" + item.Authors[i].Name + ",";
                AuthorsUri += "\n" + item.Authors[i].Uri + ",";
      }
     AuthorName = Authors;
      AuthorUri = AuthorsUri;
   }
    rssFeed.Append(“\n\nLink: ”+link);
    rssFeed.Append(“\nTitle: ”+title);
   rssFeed.Append(“\nDescription: ”+ description);
   rssFeed.Append(“\nPublishDate: ”+ PublishDate.ToString();
   rssFeed.Append(“\nAuthorName: ”+ AuthorName.ToString();
   rssFeed.Append(“\nAuthorUri: ”+ AuthorUri.ToString();
}

Saturday, September 19, 2009

Asynchronous Event Handling

Asynchronous Event handling
Why need Async Event Handling?
Let’s consider an example that you need some data in your application. So you call a method GetData(…) and it will give you the data. But untill you get the data your UI Thread is blocked. So you need something like that you call the method GetData(…) and return, and when data is done an event is raised to the UI that OK I am done and you process the data.
So here are the simple steps for Asynchronous event handling:
Suppose that I had a class “Myclass” which contains a mehod “GetData” which I want to call asynchronously, So that it raise an event when it get all the data without blocking main thread.
Step 1: Create MyEventArgs.cs
First decide what you parameters are needed after Get Data Return. These are the properties in MyEventArgs class. Suppose that we need a UserState, Result, and if any exception occurs then Error. So my class will look like this:
public class MyEventArgs
{
public object Result { get; set; }
public Exception Error { get; set; }
public object UserState { get; set; }
}
Above the class I define a delegate eventhandler like this:
public delegate void MyEventHandler(object sender, MyEventArgs e);
Step 2: Create MyEventController.cs
For asynchronous handling we create a delegate for the method. It has the same parameters as in Myclass’ s GetData method. If the GetData has some out parameters then we can also use them. If not then no need to define out parameter.:
public delegate object MyEventDelegate(string param1,out Exception Excep);
Now define a controller class like this:
public class MyEventController
{
public event MyEventHandler MyEventComplete;
MyEventDelegate _MyEventDelegate;
MyClass myClass;
public MyEventController()
{
myClass = new MyClass ();
_ MyEventDelegate = new MyEventDelegate(MyMethod);
}
private void OnMyEventComplete(MyEventArgs e)
{
if(MyEventComplete !=null)
{
MyEventComplete(this,e);
}
}
public void GetData(string param1, object UserState)
{
Exception Excep = null;
object[] _AsyncUserStats = new object[1];
_AsyncUserStats[0] = UserState;
_MyEventDelegate.BeginInvoke(param1, out Excep, new AsyncCallback(MyMethodCallBack), _AsyncUserStats);
}
private object MyMethod(string param1, out Exception exception)
{
return myClass.GetData(param1,out exception);
}
private void MyMethodCallBack(IAsyncResult ar)
{
Exception Excep = null;
AsyncResult aresult = (AsyncResult)ar;
object Result = ((MyEventDelegate)aresult.AsyncDelegate ).EndInvoke(out Excep, ar);
object[] _AsyncUserState = ar.AsyncState as object[];
MyEventArgs result = new MyEventArgs()
{
Error=Excep,
Result =Result,
UserState = _AsyncUserState[0],
};
OnMyEventComplete(result);
}
}
Let’s see what happens in the controller class. It define an event MyEventComplete which will be raised when GetData complete. For this we define a function “OnMyEventComplete” which raise the event when we get all the data. It also defines an object of the delgate we define above “MyEventDelegate”. In the constructer we register the method (MyMethod here) with the delegate which we want to call. In this method we actually call the GetData of MyClass.
Now look at the GetData of MyController class. This is the method which we call when we want to get the data. In this method we call the BeginInvoke of the delegate. In the BeginInvoke it accepts the same parametrs as in the GetData metod of MyClass and two extra parameters of type AsyncCallback and object or object[]. The AsyncCallback contains the method which will be called when it gets the data. The syntax for implementation of this callback method is :
private void MyMethodCallBack(IAsyncResult ar)
And in the MyMethodCallBack we get the result and raise the event by calling OnMyEventComplete method.
So the flow is like this:
clip_image002

In the UI we create a class of the controller and call the GetData of controller. Event “MyEventComplete” will be raised when get Data complete. Before calling the method you have to register the event like this :
MyEventController _myController= new MyEventController();
_myController.MyEventComplete += new MyEventHandler (myController_MyEventComplete);
void myController_MyEventComplete(object sender, MyEventArgs e)
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
{
/////.. event is raised and we get the result in the e.Result
}));
}
Since this event complete is returned in another thread we neet to use Dispatcher like above.
And when we need the data we use _myController.GetData(….);