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.


Monday, August 4, 2014

Test Your OOP and C# Knoledge Free


Visit      bit.ly/oopcsharp