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(….);

Friday, August 28, 2009

.NET RIA Service

.Net RIA Services bring together the ASP.NET and Silverlight platforms. It provides a pattern to write application logic that runs on the mid-tier. It integrates with Silverlight components on the client and ASP.NET on the mid-tier. Get more information about RIA services from http://www.nikhilk.net/NET-RIA-Services-Vision-Architecture.aspx.
In this blog we see how to create a simple .NET RIA Service enabled project. It only provides a brief overview of.Net RIA Services.
Step 1: First Create a new Silverlight Project as:pic1
Step 2: Then enable .Net Ria Services like this:
clip_image004[1]
Step 3 : Now to mid-tier i.e., on RiaTest.Web project add a new item and select the Data category as follows:
clip_image006[1]
we will access the Northwind database using the Entity Framework. We choose 2 tables from the northwind for this application.
clip_image008[1]
Step 4 : After building project create a DomainService on the mid-tier. A DomainService is a class that exposes entities and operations for a specific data domain. It is also where the developer adds application logic. To create a Domain Service Add new item to the mid-tier and in the Web category add DomainService class as follows:
clip_image010
Step 5 : Now we select only one table Orders , we will not set Enable Editing for the table because we want only read only table. Generate metada will create metadata of table on client.
clip_image012
It will generate a class as follows:
clip_image014
It has following characteristics:
· It is derived from LinqToEntitiesDomainService, an abstract base class built into the .NET RIA service framework3.
· It is bound to NorthwindEntities1 class we created earlier
· A single GetOrders() query method is generated because we select only Orders table
· This.Context.Orders in GetOrders() will give all the order in table.
· OrderService is marked with [EnableClientAccess] indicating it is visble on client tier
When we build project and click on Show all files on client tier we see some Gnerated code as:
clip_image016
This is the client proxy class which is generated from the Domain service class which we create on mid-tier.
Step 6 : Now in MainPage.xaml add a data Grid named “MyGrid” as follows:
image
Don’t forget to include System.Controls.Data.dll in references.
Step 7 : Now in MainPage.xaml.cs add 2 references :
· System.Windows.Ria.Data
· RiaTest.Web
Now create an object of OrderContext and then load entities of Orders and set the itemsource of the datagrid.
image
When you run the project you see all the orders in the data grid.

Monday, March 30, 2009

Data Binding of ListBox in Silverlight

In this post I'll show how to use data binding with the listbox in silverlight. Suppose that you have a class Person which contains ID, Name, Address like this:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Now i have a List lstPerson. And i want to show Name in the ListBox.
So in the .xaml I define a listbox as:
<ListBox x:Name="ListBoxPerson">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ForeignKeyName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

And now in .xaml.cs i define the itemSource of the ListBox as ListBoxPerson.ItemSource=lstPerson;
So, this is so simple to use data binding in ListBox.