Showing posts with label Azure. Show all posts
Showing posts with label Azure. Show all posts

Saturday, April 4, 2015

Server Socket (TCP) With Microsoft Azure

When we working on the real time applications Microsoft azure provides the facilities to run our all kind of applications from oldest to latest technologies. With my earlier post i explained how to create SignalR applications for real time operations

Today I'm gonna introduce create Server socket with the Azure .


1. Create new Azure Cloud project
















2. Create new Azure Worker Role  with the solution. I named it as Socket Worker 














3. Then you need to add endpoint to Worker role. If you are working on TCP Just add TCP endpoint in the worker role  as follows


















External clients use public port to send traffic to service using public port

actually they send traffic through this port .  Here is how people send traffic http://mysitedomain:2020/

Azure load balancer send the traffic (re route the traffic to Worker Role) through the private port to the Virtual Machine that run the worker role

(More)

4. Then Create your regular TCP Listener (It  may be UDP/TCP/Http/Https, Azure support all  ) Code inside the run

Replace the Run() as following with auto reset event

private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
public override void Run()
       {
           TcpListener listener = null;
           try
           {
               //Create TCp Listener to Listen endpoint define in the Worker Role
               listener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TcpEndpoint"].IPEndpoint);
               listener.ExclusiveAddressUse = false;
               listener.Start();
           }
           catch (SocketException)
           {
               Trace.Write("Echo server could not start.""Error");
               return;
           }
 
           //Listen to the all requests 
           while (true)
           {
               //Handle requests Asynchronously 
               IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
               connectionWaitHandle.WaitOne();
           }
       }

5. Then create Async request handle with following. **All important areas are commented


      /// <summary>
/// Handle Async requests 
/// </summary>
/// <param name="result"></param>
private void HandleAsyncConnection(IAsyncResult result)
{
    // Accept connection 
    TcpListener listener = (TcpListener)result.AsyncState;
    TcpClient client = listener.EndAcceptTcpClient(result);
    connectionWaitHandle.Set();
 
    // Setup reader/writer 
    NetworkStream netStream = client.GetStream();
    StreamReader reader = new StreamReader(netStream);
    // Show application 
    string input = string.Empty;
    while (true)
    {               
 
        //Get the input line 
        input = reader.ReadLine();
 
        Trace.TraceInformation(input);
    }
    // Done! 
    client.Close();
}

Run and enjoy  :)







Full Code In Media Fire 
http://bit.ly/SocketAzure













Tuesday, February 3, 2015

Tips to build Real time Applications (SignalR)

What is real time ? People who use the applications they need to see the actions one it happens . No delays or refreshing even it is desktop application, App , web or some other application.

How its possible ?

There is few options that developer can looking at.
1. Running background thread
2. Use SignalR

1st option that I describe here is not the best option in most of the times. Running background thread all times is resource consuming and it always use pulling (grab the data from the remote). And there is security concerns as well. But believe me there is some applications which we need to use this and thread is worth than other .


Most pf the time best option is SignalR

What is SignalR ?
 SignalR is series of abstractions around various methods of providing persistent Http Connections. Simply it makes real time communication without effort 

 Where ?
SignalR can be in
  1. Web application
  2. Desktop Applicaton 
  3. App (windows /iOs/Android/berry ) 

 It is cross platform tool  (totally open source) which capable of running with any platform.


SignalR is Client Server

To use SignalR you need to have Server (basically you can create serever with asp.net i'll add posts future)

And client application, (if you use javascript no need to have client nuget to consume SignalR) you can make any application by just adding SignalR nugets to your project.

Microsoft Asp.Net SignalR 









Modern servers from Windows Server 2012 is support SignalR (Real time Communication perfectly )

There is life beyond  Web Sockets


Lets meet with handons later :) enjoy

SignalR Coading 

Tuesday, January 13, 2015

Time Zone clonflictions with Cloud Services .. How to avoid .

There is problems when you are developing applications which based on cloud services. That is , time of your service (servers ) are different than the time that your application. If you are using time stamp based data pulling  from the cloud service you are in big trouble.

Here if two basic solutions that you can use in those scenarios
1. Use UTC (absolute) Time (highly recommended)
2. Change time zone of the server according to the  requirement

Use absolute time you can just do with simple DateTime object.
in C# simply like this
DateTime.UtcNow

Change Time zone of the Server ( Instances of cloud service )
This is the Task that you cannot find lot of documentation
 If you follow following steps You can easily change server time zone ( In azure (cloud) it will randomly create and no one can predict that which instance of the server will run entire service life cycle *Its never happens with cloud) in every running instance once it starting


1. Create batch (*.bat) file with flowing command
tzutil /s "Sri Lanka Standard Time" 
 

Here is time zone reference 

IndexName of Time ZoneTime
000Dateline Standard Time(GMT-12:00) International Date Line West
001Samoa Standard Time(GMT-11:00) Midway Island, Samoa
002Hawaiian Standard Time(GMT-10:00) Hawaii
003Alaskan Standard Time(GMT-09:00) Alaska
004Pacific Standard Time(GMT-08:00) Pacific Time (US and Canada); Tijuana
010Mountain Standard Time(GMT-07:00) Mountain Time (US and Canada)
013Mexico Standard Time 2(GMT-07:00) Chihuahua, La Paz, Mazatlan
015U.S. Mountain Standard Time(GMT-07:00) Arizona
020Central Standard Time(GMT-06:00) Central Time (US and Canada
025Canada Central Standard Time(GMT-06:00) Saskatchewan
030Mexico Standard Time(GMT-06:00) Guadalajara, Mexico City, Monterrey
033Central America Standard Time(GMT-06:00) Central America
035Eastern Standard Time(GMT-05:00) Eastern Time (US and Canada)
040U.S. Eastern Standard Time(GMT-05:00) Indiana (East)
045S.A. Pacific Standard Time(GMT-05:00) Bogota, Lima, Quito
050Atlantic Standard Time(GMT-04:00) Atlantic Time (Canada)
055S.A. Western Standard Time(GMT-04:00) Caracas, La Paz
056Pacific S.A. Standard Time(GMT-04:00) Santiago
060Newfoundland and Labrador Standard Time(GMT-03:30) Newfoundland and Labrador
065E. South America Standard Time(GMT-03:00) Brasilia
070S.A. Eastern Standard Time(GMT-03:00) Buenos Aires, Georgetown
073Greenland Standard Time(GMT-03:00) Greenland
075Mid-Atlantic Standard Time(GMT-02:00) Mid-Atlantic
080Azores Standard Time(GMT-01:00) Azores
083Cape Verde Standard Time(GMT-01:00) Cape Verde Islands
085GMT Standard Time(GMT) Greenwich Mean Time: Dublin, Edinburgh, Lisbon, London
090Greenwich Standard Time(GMT) Casablanca, Monrovia
095Central Europe Standard Time(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague
100Central European Standard Time(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb
105Romance Standard Time(GMT+01:00) Brussels, Copenhagen, Madrid, Paris
110W. Europe Standard Time(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna
113W. Central Africa Standard Time(GMT+01:00) West Central Africa
115E. Europe Standard Time(GMT+02:00) Bucharest
120Egypt Standard Time(GMT+02:00) Cairo
125FLE Standard Time(GMT+02:00) Helsinki, Kiev, Riga, Sofia, Tallinn, Vilnius
130GTB Standard Time(GMT+02:00) Athens, Istanbul, Minsk
135Israel Standard Time(GMT+02:00) Jerusalem
140South Africa Standard Time(GMT+02:00) Harare, Pretoria
145Russian Standard Time(GMT+03:00) Moscow, St. Petersburg, Volgograd
150Arab Standard Time(GMT+03:00) Kuwait, Riyadh
155E. Africa Standard Time(GMT+03:00) Nairobi
158Arabic Standard Time(GMT+03:00) Baghdad
160Iran Standard Time(GMT+03:30) Tehran
165Arabian Standard Time(GMT+04:00) Abu Dhabi, Muscat
170Caucasus Standard Time(GMT+04:00) Baku, Tbilisi, Yerevan
175Transitional Islamic State of Afghanistan Standard Time(GMT+04:30) Kabul
180Ekaterinburg Standard Time(GMT+05:00) Ekaterinburg
185West Asia Standard Time(GMT+05:00) Islamabad, Karachi, Tashkent
190India Standard Time(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi
193Nepal Standard Time(GMT+05:45) Kathmandu
195Central Asia Standard Time(GMT+06:00) Astana, Dhaka
200Sri Lanka Standard Time(GMT+06:00) Sri Jayawardenepura
201N. Central Asia Standard Time(GMT+06:00) Almaty, Novosibirsk
203Myanmar Standard Time(GMT+06:30) Yangon Rangoon
205S.E. Asia Standard Time(GMT+07:00) Bangkok, Hanoi, Jakarta
207North Asia Standard Time(GMT+07:00) Krasnoyarsk
210China Standard Time(GMT+08:00) Beijing, Chongqing, Hong Kong SAR, Urumqi
215Singapore Standard Time(GMT+08:00) Kuala Lumpur, Singapore
220Taipei Standard Time(GMT+08:00) Taipei
225W. Australia Standard Time(GMT+08:00) Perth
227North Asia East Standard Time(GMT+08:00) Irkutsk, Ulaanbaatar
230Korea Standard Time(GMT+09:00) Seoul
235Tokyo Standard Time(GMT+09:00) Osaka, Sapporo, Tokyo
240Yakutsk Standard Time(GMT+09:00) Yakutsk
245A.U.S. Central Standard Time(GMT+09:30) Darwin
250Cen. Australia Standard Time(GMT+09:30) Adelaide
255A.U.S. Eastern Standard Time(GMT+10:00) Canberra, Melbourne, Sydney
260E. Australia Standard Time(GMT+10:00) Brisbane
265Tasmania Standard Time(GMT+10:00) Hobart
270Vladivostok Standard Time(GMT+10:00) Vladivostok
275West Pacific Standard Time(GMT+10:00) Guam, Port Moresby
280Central Pacific Standard Time(GMT+11:00) Magadan, Solomon Islands, New Caledonia
285Fiji Islands Standard Time(GMT+12:00) Fiji Islands, Kamchatka, Marshall Islands
290New Zealand Standard Time(GMT+12:00) Auckland, Wellington
300Tonga Standard Time(GMT+13:00) Nuku'alofa

2. Add it in to the cloud service ( Not to the cloud service project )

*Add it to project which identifies as role (web, worker) by cloud project . In following example You need to add batch file into WebRole1 project


















3. Then R-Click on the batch file and select properties from visual studio . In properties under the Advanced change Copy To Output Directory property in to copy always.











4. Then go to the Cloud project and open the ServiceDefinition.csdf file






5. Under WebRole Tag add Start up task as follow .

 <WebRole name="*****" vmsize="Small">
    <Startup>
      <Task commandLine="NameOfBatchFile.bat" executionContext="elevated" taskType="simple"/>
    </Startup> 
     <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="Endpoint1" endpointName="Endpoint1" />
        </Bindings>
      </Site>
    </Sites>
    <Endpoints>
      <InputEndpoint name="Endpoint1" protocol="http" port="80" />
    </Endpoints>
  </WebRole>


Now it is done ... You free to go with your cloud service


Enjoy 






Saturday, October 11, 2014

Windows Azure Mobile Authentication Service

Magic with Azure mobile services is easy handling in Authentication for users. It allows you to authenticate users
1. Microsoft Account
2. Facebook Account
3. Twitter Account
4. Google Account
5. Azure Active Directory

What else developer need..

To enable all of those authentications you need to have apps running on those platforms. Url's for creating apps on each service provider is given below (Creating app on your hand *Get the developer manual help according to each technology)

1. Microsoft - https://account.live.com/developers/applications
2. Facebook - https://developers.facebook.com/ (Click on App's menu)
3. Twitter - https://apps.twitter.com/app/new
4. Google - https://console.developers.google.com/project

** In every instance that you create apps use your Azure Mobile Service Url 
HERE is URL for Microsoft Login
for json backend :https://<mobile_service>.azure-mobile.net/login/microsoftaccount
for .NET backend :https://todolist.azure-mobile.net/signin-microsoft


With later posts you can see how to use Azure Active directory

Start from the beginning

1. First login to your Azure portal and go to Mobile Services



2. Then select your Mobile Service , in here I have already created Mobile Service for the Azure Mobile Services post named as prabathblog. Select it and go inside. Then select IDENTITY  Tab from menu.














3. Fill the values according to the Login provider with details


4. Then go to the dashboard and download the app.

5. Use this code to authenticate in client side

        /// <summary>
        /// Simple authenticate
        /// </summary>
        /// <returns></returns>
        private async Task AuthenticateAsyncSimple()
        {
            while (user == null)
            {
                string message;
                try
                {
                    user = await App.MobileService
                        .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
                    message =
                        string.Format("You are now logged in - {0}", user.UserId);
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
 
                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }
        }


Enjoy your code







Saturday, September 13, 2014

Improve Performance of the Application

As and software producer all of us want to do is software product with correct functionality. Is that enough ? No. We need to give product with correct functionality with optimum resource consumption as well.

Today I'm going to tell you some tips and trikes about resource optimization. basically it is about Memory and CPU resources.

1. Switch for multiple If
 When you are using multiple If conditions ( Most of the time more than 2 ) CPU (Registry level) instructions check as far as use much If with code. It consume more registers in CPU. But with switch it just use check and Jump CPU instruction that far more faster than assignments. Using jump tables makes switches much faster than some if-statements

Use switch when ever possible once you find more than two if statements.

2. Use structures according to the situation
Execution of class is much more consume resources than class.  Whenever you don't need to use functions bind with objects and when you don't go with boxing and unboxing much with code.

3. Chunky calls
Don't let your functions to handle lot of task by itself. use modularity to avoid it.

4. Add Collections
Never try to assign collection items one by one to the another collection. Just try to use simple casting and try to add entire collection directly.

5. Working with strings.
When you are working with string most of the cases we try to concatenate string by '+'operator.(including me ). But sad story is there is more optimal solution than that. use string bulider to concatenate strings.

Here for start.

6. Use bits whenever as possible.
I saw most of the programmers use integers/strings to hold the simple states, flags. Please don't do that there is more than 2 states. Just use bit or bool to store states. It will optimize code and resource as well. ( Simply bit is smaller than more bits)

7. Array as possible
When we use simple basic array it will helpful to maintain machine instructions(registry). Other collections need more than array because most of them are derived form it. Array is basic element in modern machine instructions.

8. ObservableCollection vs List
Use List whenever that your items not binded with the UI. Observation collections are derived from List and it also holds the property changed notifications. If there is no use of property change go for List.  ObservableCollection check the property change when it on use and because of that it consume more.

9. For than foreach
Use while, for and do while loops wherever than foreah. foreach has good performance but basic loops are better than it.

10. ToString
Some  programmers use ToString method wherever elements are already strings. Use ToString wherever the element that con the string. don't use ToString as habit. With integers use
ToStringLookup will optimize memory heap that using with converting integer.

11. Don't sort collections already sorted.
Check collection already sorted or not before sort it.

12. Global variables.
Use global variables when you using same type of object frequently

13. Constant and static
Constants are not assignable memories but they are easy to load.

Static is more faster than instant creations. When load statics no need of run time to check the instance



Hope this is helps...



Sunday, August 24, 2014

Back-end operations with Cloud Service (Worker Roles)

With my previous post about Creating Cloud Service I mentioned two Roles in Azure.
1. Web Role
2. Worker Role

With this Post we will working with Worker Role . I'm using the same code that I use in Creating Cloud Service  post

What is Worker Role ??

Worker role is the component that doing background operations in Azure web service. If you need to implement background service such as background listener with your cloud service this is the component for you.

With physically Worker role is the Virtual machine which running the Server OS (Windows Server 2012 R2) without configuring IIS.( check the Web Role definition in Creating Cloud Service ).
Actually both of the Web Role and Worker Roles are derived from RoleEntryPoint Base class.

According to the OOP principles, yes Web Role can do the same Task that Worker Role can do. ( I hope to make discussion about it with later post ). We just give the chance to handle Web related tasks to web role and use worker role to handle non web based tasks. Because Web role may be over loaded when it try to handle all within it. Then Web role is free to handle more web based requests with more speed.

 Lets Code
,

1. Open the code in visual studio and check it is working (Creating Cloud Service). Then go to the solution explorer

2. On the AzureServiceDemo -> Roles -> R - click -> New Worker Role Project














Then Select Worker Role and give name.. I'm giving PrabathslWorkerRole as name















After add the worker role you can see that it will add Worker Role project to your solution ans that project contains only one class called WorkerRole.cs














I'll add that class here for explanation

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
namespace PrabathslWorkerRole
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.TraceInformation("PrabathslWorkerRole entry point called", "Information");
            while (true)
            {
                Thread.Sleep(10000);
                Trace.TraceInformation("Working", "Information");
            }
        }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            return base.OnStart();
        }
    }
}

Simply public override bool OnStart() method is called when Role Started then it called public override void Run() Method. Run method should contain what we need to do in background. In here I'm going to configure HTTP listener.It take some inputs and generate output.  If it needed to do repeatedly you need to add it inside forever while (true) loop

Also web role can forward jobs to the Worker role and Worker Role can also get inputs directly by it self. For that we can also insert our WCF service i worker role as well .

Replace the Run() with following code to listen port=4488 with HTTP protocol  ...
public override void Run()
       {
           HttpListener listner = new HttpListener();
           //This will ping to Http://myserviceurl:4488 port
           listner.Prefixes.Add("http://+:4488/");
           listner.Start();
  
           //Set the response to transformable format
           string responseMessage = "<html><title>Response from Worker</title><body><h1>Prabathsl.blogspot.com</h1></body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseMessage);
  
  
           while (true)
           {
               HttpListenerContext context = listner.GetContext();
  
               //then set the response
               HttpListenerResponse response = context.Response;
               response.ContentLength64 = buffer.Length;
               Stream output = response.OutputStream;
  
               //write output stream
               output.WriteAsync(buffer, 0, buffer.Length);
               output.Close();
           }
       }

This is local for the Azure VM.


Currently our VM's are haven't any external access.To allow access to the worker role we need change some configurations.

 That called input end point. Lets define input endpoints. it allows traffic to go through our VM


3. Goto AzureServiceDemo Solution and Roles then double click on PrabathslWorkerRole

4. Click on Endpoints -> Add Endpoint button and add endpoint. I named it as prabathslEndpoint









External clients use this port to send traffic to service using public port

actually they send traffic through this port .  Here is how people send traffic http://mysitedomain:4080/

Azure load balancer send the traffic (re route the traffic to Worker Role) through the private port to the Virtual Machine that run the worker role (4488)

**You can use any port as you wish

Now we are done and run it ..

Here is what i get when Listen to localhost
(http://127.0.0.1:4080/) We need to listen public port



















Full Code In Media Fire 
http://bit.ly/worker_role

 



Thursday, August 14, 2014

Creating Azure Serice with Active Directory Login

When we are working with different requirements in a project there may be issues like this. Clients want to available all data in the application (with application) just for authorized users. Ex: All management portals may just only available for mangers

In this kind of scenario developers need to maintain separate authentication mechanisms to authenticate users. Specially those mechanisms may not be the perfect in security point of view.

Azure provide great solution for it with the help of Visual Studio. You can use Azure Active Directory (AD)  users to authenticate. It will very secure and its just use Azure portal log in to your application. You can use log ins in your on premises Active Directory too. You need to just make tunnel between Azure active directory and your on premises AD. Then all changes in your on premises AD is Sync with Azure AD with help of Active Directory Federation Service (ADFS)

Lets start our project


1. First Login to Azure Portal manage.windowsazure.com and then go to the Click on Active Directory












2. If you don't have AD User Directory to use  Then Click on New -> Active Directory -> Directory->Custom create











3. From the wizard you can use existing directory or create new directory. If you use existing directory to create new directory all the users in that directory will be added to the new one. In here I'm going to create new directory

















4. Once directory created click on it and go to users . It will automatically added created user as user.


5. If you need to add user to AD Click on ADD User button in bottom and add user. May be existing AD , From Microsoft account or may be company user. In later in this post I'll tell you how to add company user



















Im adding Microsoft Account




















Fill the required data and you are done

Create New User



















If you enabled Multi-Factor Authentication it will ask for phone number verification with SMS when user login . Its Nice feature .......
Just like in Microsoft Store Login ....Its free

Then Create temproy Password















If you need sent password to the user















And Done :)

Lets go back ..



Now we have Azure AD with required users ..

Now go to Visual studio and start Azure Cloud service project as in my previous post Creating  Cloud Service Up to Step 3

Here is step 3


















In here click on Change Authentication button.


Then use Organizational Account option












Select Single sign On (here we just use Azure AD)











Enter your  Azure AD Domain and select the required authorities from Access level













Then click Ok we are done .......


Debug Tips ..

If you found user credential verification failed azure  error with visual studio
  1. Shut down Visual Studio
  2. Go to your Azure management portal, and create a new user account within the Active Directory you created (I set mine as a Global Admin).
  3. Open up VS again and go through the steps of creating the WebApi project. This time, when you choose Organizational Accounts for authentication, use the credentials of the user that you just created - it should work now.



Enjoy





Monday, August 11, 2014

Publish Cloud Services

Lets see how to publish your cloud service to Azure with visual studio. In here I'm going to use same loud service that we build in my previous post Creating Cloud Service.

1. Open your solution in Visual Studio and select your project R-Click and then Publish


















2. Then it will prompt Publish Windows Azure Application windows. Then sign in to your Azure Account and select your subscription that you want to use and click Next


3. Then it will gives you Publish Settings form from it if you already have created Cloud service in Azure you can select that service to publish. If not you can create new Service (i'm creating new Service here )
















Create new will prompt new window and add name to your service and Select nearest data center for the location.












4. Then you have to select your created service name and Environment to host. In Azure it provide two environment to host your services.
  • Production Environment 
  • Staging Environment
Production Environment contains the actual running application. Production environment is trusted and currently our customers are accessed this environment if we already punished this service and it is up and running.

When we are updating new version of same Service directly to the production environment meanwhile we doing the update our application will not functional. Our users cant access the application. And another hand we don't know that our new version is exactly functioning well within hosted environment. Sometimes there may be bugs.

To avoid those problems Azure provide us concept called Staging Environment if we publish app to the staging environment it will gives us separate URL for the newly published app mean wile our Production environment is up and running. We can verify that our new version is up and running meanwhile  older version will serve our customers. Once we verify that our new version is ready to go its single click away. There is SWAP (VIP Swap) button in azure portal in staging application. It will automatically connect the traffic to Staging application.

What it does is it swap the IP address between selected staging environment and Production. now Our staging is production and production become staging. Its called VIP Swap.

Azure allows you to have maximum 5 staging's per Application


Lets back to subject :)
 In my case im going to publish brand new application and therefore i can directly publish to production environment . but after that if you make new version go with best practices

and I'm using Release binaries and use service configuration file as cloud version. And with enable remote desktop i can loginto VM's that my service web role's is hosted ad username and password if you need remote desktop enabled
















With Advanced tab you can define the service hosted storage and configurations as you need.
















Then you can publish your Cloud service


Here is my published service URL : http://prabathblogdemo.cloudapp.net/

Here is Some publisher logs and you can understand what is happened when publishing (* My web roles have 2 instances )

6:59:40 PM - Connecting...
6:59:40 PM - Verifying storage account 'portalvhdsjf2mmx92gk60l'...
6:59:41 PM - Uploading Package...
7:02:35 PM - Creating...
7:03:23 PM - Created Deployment ID: XXXXXXXXXXXXXXXX.
7:03:23 PM - Instance 0 of role PrabathslWebRole is stopped
7:03:23 PM - Instance 1 of role PrabathslWebRole is stopped
7:03:24 PM - Starting...
7:03:41 PM - Initializing...
7:03:42 PM - Instance 0 of role PrabathslWebRole is creating the virtual machine
7:03:42 PM - Instance 1 of role PrabathslWebRole is creating the virtual machine
7:04:47 PM - Instance 0 of role PrabathslWebRole is starting the virtual machine
7:04:47 PM - Instance 1 of role PrabathslWebRole is starting the virtual machine
7:06:25 PM - Instance 0 of role PrabathslWebRole is in an unknown state
7:06:25 PM - Instance 1 of role PrabathslWebRole is in an unknown state
7:07:00 PM - Instance 0 of role PrabathslWebRole is busy
7:07:00 PM - Instance 1 of role PrabathslWebRole is busy

7:08:07 PM - Instance 0 of role PrabathslWebRole is ready
7:08:07 PM - Instance 1 of role PrabathslWebRole is ready
7:08:07 PM - Created Website URL: http://prabathblogdemo.cloudapp.net/
7:08:07 PM - Complete.


Hosted App











Here is created instances in Azure Portal
















You can connect those Hosted VM's using Connect button via remote desktop using given credentials when you publish app



Enjoy :)



Creating Cloud Service

Today we are going to create windows Azure cloud service. Not like my previous post about creating Azure mobile service today i'm going to totally working with visual studio and not going to the azure portal

before start ,
  1. you need to have Azure subscription
  2. Visual Studio ( http://www.visualstudio.com/ )
  3. Azure SDK (http://azure.microsoft.com/en-us/downloads/) -.NET

Unlike most of other cloud service providers azure provide SDK's for developers not only for .NET it supports java, Node.js , php, Python and Ruby . more will come later . Today im demonstrate codes with .NET SDK.

If you are installed and ready lets begin our task

First open Server explorer and if you configured your cloud SDK correctly it will display  Windows Azure menu. click on it and login to your Azure subscription

1. Open Visual Studio -> New -> Cloud Service  and give name to solution















2. Then Visual Studio will prompt you New Windows Azure Cloud Service Prompt.
Today I'm going to host website as a cloud service therefore I need to add WebRole (ASP .NET Web role ) to my cloud service.

 I select it and then rename it using edit button in the Azure cloud service solution list as PrabathslWebRole














**I'll explain what is web role in azure cloud service in late in this post.

3. Then it will prompt New ASP.NET web project window it is familiar one to all ASP.NET developers. I'm selecting MVC project to work on. You can create any site as your wish.


















My project is now created and you can see that in solution explorer there is two separate projects in the same solution.













One is our cloud service and next one is our ASP.NET MVC project. You can working on ASP.NET project as same as you previously worked with ASP.NET. I'll explain some additional things in regarding cloud service project


If you expand Cloud service project you can see that in roles folder there is my WebRole











What is WebRole ? 
 In Windows Azure it introduced concepts called Roles. There is two main roles in azure 
  1. Web Role
  2. Worker Role
 Actually each and every role will represent Virtual Machine (VM)  in Azure IaaS (Infranstructure As A Service). Wen we working with Cloud services it provide as PaaS (Platform As A Service) that means it automatically create required VM for us. To optimize resource consumption within VM's Azure IaaS contains predefined VM's for common tasks.

 If we working with Web Site we need IIS (Internet Information Service) within our hosted VM. Therefore Azure Web Role will contain VM that contain configured IIS wit it. If our Service not working with HTTP we don't need IIS
.Therefore It contains predefined VM without IIS it is Worker Role. (**I'll go through Worker role and its capabilities with separate post)

You can have multiple worker roles and Web roles within same Service.

If you have two worker roles within your Service it means when your application is up there is two different VM's is running on Azure fabric

let's go back to project

4. Lets run our code and see (* I made a mistake here. If i need to run application locally it need to start Azure Compute Emulator //feature with in azure SDK ad its allow to run and debus cloud applications locally// for that i need to run visual Studio as administrator)

Hopefully it is up and running.. 

Then R-Click on Azure  Emulator and go to Compute Emulator UI











Then you can see that my AzureServiceDemo Project is running and it contains PrabathSlWebRole  in VM. It has only one instance of VM. 





To gain efficiency and 99.5% up time that grantees by Azure you need to have at least two instances of each VM (in this case web role) 

to do that go back to the project and open PrabathSlWebRole .  In select configuration and make instance count at least 2 . and you can select VM sizes for each instance according to your requirement and traffic that expecting from clients. in my demo i don't need to maintain lot more traffic  and i select Small












Azure Load Balance

When we are working with two separate instance instance of VM's they have separate IP's as well. how we utilize it ? 

Answer is azure do every thing for you . Azure load balancer get the external (pubic) traffic and redirect it in to available VM's automatically according to resource availble and round robin like scheduling algorithms . 

to monitor that lets change our code slightly.  

Go to HomeController.cs and 

edit About() as follows

public ActionResult About()
       {
           //Lets add current instance Id to this message
           //need to reference using Microsoft.WindowsAzure.ServiceRuntime;
           ViewBag.Message = "current instance Id = " + RoleEnvironment.CurrentRoleInstance.Id.ToString() + "  Role " + RoleEnvironment.CurrentRoleInstance.Role.ToString();
           return View();
       }


Then run it and see the results .. click the about and check the value with several refreshes.. isn't it amazing :)  

And here Compute Emulator ,









Now it runs two instances of same PrabathSlWebRole. 


With in hosted environment these VM's are represent in separate Windows Server 2012 R2  VM's.

Lets meet with another post.