Module 4 Microsoft Azure Messaging Services

Similar documents
Enable IoT Solutions using Azure

Course Outline. Lesson 2, Azure Portals, describes the two current portals that are available for managing Azure subscriptions and services.

Developing Microsoft Azure Solutions (70-532) Syllabus

Developing Microsoft Azure Solutions: Course Agenda

Course Outline. Developing Microsoft Azure Solutions Course 20532C: 4 days Instructor Led

Whiteboard 6 feet by 4 feet (minimum) Whiteboard markers Red, Blue, Green, Black Video Projector (1024 X 768 resolutions)

COURSE 20487B: DEVELOPING WINDOWS AZURE AND WEB SERVICES

Developing Windows Azure and Web Services

White Paper / Azure Data Platform: Ingest

Windows Azure Services - At Different Levels

Stanislav Harvan Internet of Things

Developing Microsoft Azure Solutions (70-532) Syllabus


[MS20487]: Developing Windows Azure and Web Services

#techsummitch

Azure Integration Services

Index. Scott Klein 2017 S. Klein, IoT Solutions in Microsoft s Azure IoT Suite, DOI /

Developing Microsoft Azure Solutions

Techno Expert Solutions

BAX Energy Innovation Project Intro

Course Outline. Introduction to Azure for Developers Course 10978A: 5 days Instructor Led

Developing Microsoft Azure Solutions (MS 20532)

High Availability Distributed (Micro-)services. Clemens Vasters Microsoft

Developing Microsoft Azure Solutions (70-532) Syllabus

MS-20487: Developing Windows Azure and Web Services

BraindumpsQA. IT Exam Study materials / Braindumps

20532D: Developing Microsoft Azure Solutions

Cisco Tetration Analytics

WebJobs & Azure Functions in modern and Serverless applications. Paris Polyzos Software Engineer at ZuluTrade Inc Microsoft Azure MVP

Developing Microsoft Azure Solutions

Microsoft Cloud Workshops. Internet of Things (IoT) Hackathon Leader Guide

Vlad Vinogradsky

Developing Microsoft Azure and Web Services. Course Code: 20487C; Duration: 5 days; Instructor-led

High Volume Messaging with IBM MessageSight for use in Mobile, Web and M2M solutions

Deccansoft Software Services

Azure Learning Circles

Hosted Azure for your business. Build virtual servers, deploy with flexibility, and reduce your hardware costs with a managed cloud solution.

Microsoft Azure Course Content

Microsoft Cloud Workshops

OSIsoft Cloud Services Core Infrastructure for Developing Partner Applications

See how cloud templates provide default diagnostic monitoring setup.

Participant Handbook

Developing Enterprise Cloud Solutions with Azure

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions

Event Sponsors. Expo Sponsors. Expo Light Sponsors

70-532: Developing Microsoft Azure Solutions

Deccansoft Software Services

Azure File Sync. Webinaari

Microsoft Cloud Workshop. Intelligent Analytics Hackathon Learner Guide

Workflow Scheduler Installation Guide. Version Page 1 of 19

Essential Features of an Integration Solution

Programming Functions. Debugging and testing

Building a Real-time Notification System

Azure Certification BootCamp for Exam (Developer)

Real-Time SignalR. Overview

Sentinet for Microsoft Azure SENTINET

IERG 4080 Building Scalable Internet-based Services

IEMS 5722 Mobile Network Programming and Distributed Server Architecture

IEMS 5780 / IERG 4080 Building and Deploying Scalable Machine Learning Services

Alexander Klein. #SQLSatDenmark. ETL meets Azure

17/05/2017. What we ll cover. Who is Greg? Why PaaS and SaaS? What we re not discussing: IaaS

Hidden Gems in JD Edwards Orchestrator and AIS Server

Developing Microsoft Azure Solutions

Introduction to Windows Azure Cloud Computing Futures Group, Microsoft Research Roger Barga, Jared Jackson, Nelson Araujo, Dennis Gannon, Wei Lu, and

Architectural challenges for building a low latency, scalable multi-tenant data warehouse

Let s say that hosting a cloudbased application is like car ownership

HDInsight > Hadoop. October 12, 2017

Exam Questions

Azure Cloud Architecture

Azure Free Training. Module 1 : Azure Governance Model. Azure. By Hicham KADIRI October 27, Naming. Convention. A K&K Group Company

Qualys Cloud Platform

Exam Questions

Chapter 1 Getting Started

Azure Application Building Blocks

microsoft. Number: Passing Score: 800 Time Limit: 120 min.

COMP6511A: Large-Scale Distributed Systems. Windows Azure. Lin Gu. Hong Kong University of Science and Technology Spring, 2014

Hands-On Lab. Worker Role Communication. Lab version: Last updated: 11/16/2010. Page 1

[MS10992]: Integrating On-Premises Core Infrastructure with Microsoft Azure

Using and Developing with Azure. Joshua Drew

StreamSets Control Hub Installation Guide

Cloud has become the New Normal

70-532: Developing Microsoft Azure Solutions

Sentinet for BizTalk Server SENTINET

Service Bus Guide. September 21, 2018 Version For the most recent version of this document, visit our documentation website.

Exam : Implementing Microsoft Azure Infrastructure Solutions

Configuring and Operating a Hybrid Cloud with Microsoft Azure Stack

BIG DATA COURSE CONTENT

Azure Development Course

Scaling DreamFactory


Libelium Cloud Hive. Technical Guide

Lesson 5 Nimbits. Chapter-6 L05: "Internet of Things ", Raj Kamal, Publs.: McGraw-Hill Education

AWS Lambda: Event-driven Code in the Cloud

Deploying enterprise applications on Dell Hybrid Cloud System for Microsoft Cloud Platform System Standard

Saranya Sriram Developer Evangelist Microsoft Corporation India

PeopleSoft 9.1 PeopleBook: Events and Notifications Framework

Amazon S3 Glacier. Developer Guide API Version

Azure Data Factory VS. SSIS. Reza Rad, Consultant, RADACAD

Fluentd + MongoDB + Spark = Awesome Sauce

ThoughtSpot on AWS Quick Start Guide

Transcription:

Module 4 Microsoft Azure Messaging Services Service Bus Azure Service Bus is a generic, cloud-based messaging system for connecting just about anything applications, services and devices wherever they are. Connect apps running on Azure, on-premises systems, or both. Microsoft Azure Service Bus is a reliable information delivery service. The purpose of this service is to make communication easier. When two or more parties want to exchange information, they need a communication facilitator. Service Bus is a brokered, or third-party communication mechanism. This is similar to a postal service in the physical world. Postal services make it very easy to send different kinds of letters and packages with a variety of delivery guarantees, anywhere in the world. Similar to the postal service delivering letters, Service Bus is flexible information delivery from both the sender and the recipient. The messaging service ensures that the information is delivered even if the two parties are never both online at the same time, or if they aren't available at the exact same time. In this way, messaging is similar to sending a letter, while non-brokered communication is similar to placing a phone call (or how a phone call used to be - before call waiting and caller ID, which are much more like brokered messaging). Brokered messaging In contrast to the relay scheme, Service Bus messaging with queues, topics, and subscriptions can be thought of as asynchronous, or "temporally decoupled." Producers (senders) and consumers (receivers) do not have to be online at the same time. The messaging infrastructure reliably stores messages in a "broker" (for example, a queue) until the consuming party is ready to receive them. This enables the components of the distributed application to be disconnected, either voluntarily; for example, for maintenance, or due to a component crash, without affecting the entire system. Furthermore, the receiving application may only have to come online during certain times of the day, such as an inventory management system that only is required to run at the end of the business day. Different situations call for different styles of communication. Sometimes, letting applications send and receive messages through a simple queue is the best solution. In other situations, an ordinary queue isn't enough; a queue with a publish-and-subscribe mechanism is better. In some cases, all that's really needed is a connection between applications; queues aren't required. Service Bus provides all three options, enabling your applications to interact in several different ways. Queues, which allow one-directional communication. Each queue acts as an intermediary (sometimes called a broker) that stores sent messages until they are received. Each message is received by a single recipient. Topics, which provide one-directional communication using subscriptions-a single topic can have multiple subscriptions. Like a queue, a topic acts as a broker, but each subscription can optionally use a filter to receive only messages that match specific criteria. Relays, which provide bi-directional communication. Unlike queues and topics, a relay doesn't store in-flight messages-it's not a broker. Instead, it just passes them on to the destination application.

Event Hubs, which provide event and telemetry ingress to the cloud at massive scale, with low latency and high reliability. Connecting applications has always been part of building complete solutions, and the range of scenarios that require applications and services to communicate with each other is set to increase as more applications and devices are connected to the internet. By providing cloud-based technologies for achieving communication through queues, topics, and relays, Service Bus aims to make this essential function easier to implement and more broadly available. Service Bus is a multi-tenant cloud service, which means that the service is shared by multiple users. Each user, such as an application developer, creates a namespace, then defines the communication mechanisms she needs within that namespace Ref - https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-fundamentalshybrid-solutions Suppose you decide to connect two applications using a Service Bus queue. The process is simple: A sender sends a message to a Service Bus queue, and a receiver picks up that message at some later time. A queue can have just a single receiver, as Figure shows, or multiple applications can read from

the same queue. In the latter situation, each message is read by just one receiver-for a multi-cast service you should use a topic instead. Useful as they are, queues aren't always the right solution. Sometimes, Service Bus topics are better. A topic is similar in many ways to a queue. Senders submit messages to a topic in the same way that they submit messages to a queue, and those messages look the same as with queues. The big difference is that topics enable each receiving application to create its own subscription by defining a filter. A subscriber will then see only the messages that match that filter. For example, Figure shows a sender and a topic with three subscribers, each with its own filter Both queues and topics provide one-way asynchronous communication through a broker. Traffic flows in just one direction, and there's no direct connection between senders and receivers. But what if you don't want this? Suppose your applications need to both send and receive messages, or perhaps you want a direct link between them and you don't need a broker to store messages. To address scenarios such as this, Service Bus provides relays, as Figure shows. The obvious question to ask about relays is this: why would I use one? Even if I don't need queues, why make applications communicate via a cloud service rather than just interact directly? The answer is that talking directly can be harder than you might think. Service Bus relay can help. To communicate bi-directionally through a relay, each application establishes an outbound TCP connection with Service Bus, then keeps it open. All communication between the two applications travels over these connections. Because each connection was established from inside the datacenter, the firewall allows incoming traffic to each application without opening new ports.

Unlike queues and topics, applications don't explicitly create relays. Instead, when an application that wishes to receive messages establishes a TCP connection with Service Bus, a relay is created automatically. When the connection is dropped, the relay is deleted. To enable an application to find the relay created by a specific listener, Service Bus provides a registry that enables applications to locate a specific relay by name. Relays are the right solution when you need direct communication between applications. For example, consider an airline reservation system running in an on-premises datacenter that must be accessed from check-in kiosks, mobile devices, and other computers. Applications running on all of these systems could rely on Service Bus relays in the cloud to communicate, wherever they might be running. Azure Service Bus Queue Step 1: Navigate to Azure Portal. Step 2: Click on +New -> Enterprise Integration -> Service Bus

Step 3: Enter Service Bus Namespace Name, Choose Pricing Tier, Resource Group, Location

Step 4: Click on + Queue to create new Queue Step 5: Enter Queue Name, Max Size, Message time to live, Lock duration,etc. Queue created successfully.

Step 6: Start Visual Studio & Choose Visual C# Template. Create New Console Application Step 7: Right click on Project Name & select Manage NuGet Packages

Step 8: Search for service bus & install WindowsAzure.ServiceBus packages. Step 9: Navigate to Azure Portal & Select Connection String option.

Click on Copy option & paste into program.cs file

Step 10: Add Service Bus Namespace using Microsoft.ServiceBus.Messaging; namespace SBQueueSender class Program static string ConnectionString = "Endpoint=sb://azureservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageS haredaccesskey;sharedaccesskey=<copy-servicebus-sharedkey-from-azure-portal>"; static string QueuePath = "sbqueue"; static void Main(string[] args) //Service Bus Queue Sender var queueclient = QueueClient.CreateFromConnectionString(ConnectionString, QueuePath); for (int i = 0; i < 10; i++) var message = new BrokeredMessage("Sender's Message ==> " + i); // message.sessionid = test ; queueclient.send(message); Console.Write("\nSent Message : = " + i ); Console.WriteLine("Press Enter to Exit..."); Console.ReadLine(); queueclient.close();

Step 11: Now run the Sender program

Again Navigate to Service Bus Queue option Step 12: Create one more project for Receiver using Visual Studio.

Create Console Application. repeat the same steps to install NuGet Packages of Azure Service Bus.

Search for service bus & install NuGet Packages.

Step 13: Add Service Bus Namespace using Microsoft.ServiceBus.Messaging; Get ConnectionString & QueueName from Azure Portal or copy from Sender s Project.

namespace SBQueueReceiver class Program static string ConnectionString = "Endpoint=sb://azureservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageS haredaccesskey;sharedaccesskey=<copy-servicebus-sharedkey-from-azure-portal>"; static string QueuePath = "sbqueue"; static void Main(string[] args) //Service Bus Queue Receiver var queueclient = QueueClient.CreateFromConnectionString(ConnectionString, QueuePath); queueclient.onmessage(msg => ProcessMessage(msg)); Console.WriteLine("Press Enter to Exit..."); Console.ReadLine(); queueclient.close(); private static void ProcessMessage(BrokeredMessage msg) var text = msg.getbody<string>(); Console.WriteLine("\nReceived Messages : " + text);

Step 14: Now run the Receiver project. Navigate to Azure Portal.

Service Bus Topics Step 1: Navigate to Azure Portal. Step 2: Click on +New -> Enterprise Integration -> Service Bus

Step 3: Enter Service Bus Namespace Name, Choose Pricing Tier, Resource Group, Location

Step 4: Click on + Topics to create new Topics Enter Topics Name, Max Size, etc

Step 5: Start Visual Studio & Choose Visual C# Template. Create New Console Application Step 6: Right click on Project Name & select Manage NuGet Packages

Step 7: Navigate to Azure Portal & Select Connection String option.

Click on Copy option & paste into program.cs file Step 8: Add Service Bus Namespace using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; namespace SBTopicsChatApp class Program static string ConnectionString = "Endpoint=sb://azureservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageS haredaccesskey;sharedaccesskey=<copy-servicebus-sharedkey-from-azure-portal>"; static string TopicPath = "sbtopics"; static void Main(string[] args) Console.WriteLine("Enter Name - "); var username = Console.ReadLine(); var manager = NamespaceManager.CreateFromConnectionString(ConnectionString); if (!manager.topicexists(topicpath)) manager.createtopic(topicpath); var description = new SubscriptionDescription(TopicPath, username); description.autodeleteonidle = TimeSpan.FromMinutes(5); manager.createsubscription(description); var factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

username); var topicclient = factory.createtopicclient(topicpath); var subscriptionclient = factory.createsubscriptionclient(topicpath, subscriptionclient.onmessage(msg => ProcessMessage(msg)); var hellomessage = new BrokeredMessage("Has entered the Room..."); hellomessage.label = username; topicclient.send(hellomessage); while (true) string text = Console.ReadLine(); if (text.equals("exit")) break; var chatmessage = new BrokeredMessage(text); chatmessage.label = username; topicclient.send(chatmessage); var goodbyemessage = new BrokeredMessage("Has left the building..."); goodbyemessage.label = username; topicclient.send(goodbyemessage); factory.close(); static void ProcessMessage(BrokeredMessage message) string user = message.label; string text = message.getbody<string>(); Console.WriteLine(user + ">" + text); Step 9: Now run the project Enter Name Step 10: Don t Stop the project & right-click on project name -> Debug -> Start new instance

Enter another Name

Navigate to Service Bus Topics on Azure Portal

Event hub Azure Event Hubs is a highly scalable data streaming platform and event ingestion service capable of receiving and processing millions of events per second. Event Hubs can process and store events, data, or telemetry produced by distributed software and devices. Data sent to an event hub can be transformed and stored using any real-time analytics provider or batching/storage adapters. With the ability to provide publish-subscribe capabilities with low latency and at massive scale, Event Hubs serves as the "on ramp" for Big Data. Why use Event Hubs? Event Hubs event and telemetry handling capabilities make it especially useful for: Application instrumentation User experience or workflow processing Internet of Things (IoT) scenarios For example, Event Hubs enables behaviour tracking in mobile apps, traffic information from web farms, in-game event capture in console games, or telemetry collected from industrial machines, connected vehicles, or other devices. Event Hubs contains the following key elements: Event producers/publishers: An entity that sends data to an event hub. An event is published via AMQP 1.0 or HTTPS. Capture: Enables you to capture Event Hubs streaming data and store it in an Azure Blob storage account. Partitions: Enables each consumer to only read a specific subset, or partition, of the event stream. SAS tokens: Identifies and authenticates the event publisher. Event consumers: An entity that reads event data from an event hub. Event consumers connect via AMQP 1.0. Consumer groups: Provides each multiple consuming application with a separate view of the event stream, enabling those consumers to act independently. Throughput units: Pre-purchased units of capacity. A single partition has a maximum scale of 1 throughput unit.

The common role that Event Hubs plays in solution architectures is the "front door" for an event pipeline, often called an event ingestor. An event ingestor is a component or service that sits between event publishers and event consumers to decouple the production of an event stream from the consumption of those events. Azure Notification Hubs Azure Notification Hubs provide an easy-to-use, multi-platform, scaled-out push engine. With a single cross-platform API call, you can easily send targeted and personalized push notifications to any mobile platform from any cloud or on-premises backend. Notification Hubs works great for both enterprise and consumer scenarios. Here are a few examples customers use Notification Hubs for: Send breaking news notifications to millions with low latency. Send location-based coupons to interested user segments. Send event-related notifications to users or groups for media/sports/finance/gaming applications. Push promotional contents to apps to engage and market to customers. Notify users of enterprise events like new messages and work items. Send codes for multi-factor authentication. What are Push Notifications? Push notifications is a form of app-to-user communication where users of mobile apps are notified of certain desired information, usually in a pop-up or dialog box. Users can generally choose to view or dismiss the message, and choosing the former will open the mobile app that had communicated the notification.

Push notifications is vital for consumer apps in increasing app engagement and usage, and for enterprise apps in communicating up-to-date business information. It is the best app-to-user communication because it is energy-efficient for mobile devices, flexible for the notifications senders, and available while corresponding apps are not active. For more information on push notifications for a few popular platforms: ios Android Windows At a high level, here is how push works: - The client app decides it wants to receive pushes hence contacts the corresponding PNS to retrieve its unique and temporary push handle. The handle type depends on the system (e.g. WNS has URIs while APNS has tokens). - The client app stores this handle in the app back-end or provider. - To send a push notification, the app back-end contacts the PNS using the handle to target a specific client app. - The PNS forwards the notification to the device specified by the handle. Why Use Notification Hubs? Notification Hubs eliminates all complexities associated with enabling push on your own. Its multiplatform, scaled-out push notification infrastructure reduces push-related codes and simplifies your

backend. With Notification Hubs, devices are merely responsible for registering their PNS handles with a hub, while the backend sends messages to users or interest groups, as shown in the figure Stream Analytics Azure Stream Analytics is a fully managed event-processing engine that lets you set up real-time analytic computations on streaming data. The data can come from devices, sensors, web sites, social media feeds, applications, infrastructure systems, and more Use Stream Analytics to examine high volumes of data flowing from devices or processes, extract information from the data stream, and look for patterns, trends, and relationships. Based on what's in the data, you can then perform application tasks. For example, you might raise alerts, kick off automation workflows, feed information to a reporting tool such as Power BI, or store data for later investigation. Examples: Personalized, real-time stock-trading analysis and alerts offered by financial services companies. Real-time fraud detection based on examining transaction data. Data and identity protection services. Analysis of data generated by sensors and actuators embedded in physical objects (Internet of Things, or IoT). Web clickstream analytics. Customer relationship management (CRM) applications, such as issuing alerts when customer experience within a time frame is degraded. This diagram illustrates the Stream Analytics pipeline, showing how data is ingested, analyzed, and then sent for presentation or action.

Stream Analytics starts with a source of streaming data. The data can be ingested into Azure from a device using an Azure event hub or IoT hub. The data can also be pulled from a data store like Azure Blob Storage. To examine the stream, you create a Stream Analytics job that specifies where the data is coming from. The job also specifies a transformation how to look for data, patterns, or relationships. For this task, Stream Analytics supports a SQL-like query language that lets you filter, sort, aggregate, and join streaming data over a time period. Finally, the job specifies an output to send the transformed data to. This lets you control what to do in response to the information you've analyzed. For example, in response to analysis, you might: -Send a command to change a device's settings. -Send data to a queue that's monitored by a process that takes action based on what it finds. -Send data to a Power BI dashboard for reporting. -Send data to storage like Data Lake Store, SQL Server database, or Azure Blob or Table storage.

Azure Stream Analytics Event Hub Service Bus Storage Demo Step Create Stream Analytics Service in Azure Portal.

Now Create Event Hub for Data Input Create Event Hub and Select Pricing Tier - Standard

Add Event Hub

Open Shared Access Policies -> RootManageSharedAccessKey -> Copy and Paste Connection String in Notepad, Now We need to create Console Application of Event Hub to send Messages to Stream Analytics. Open Visual Studio and Click File -> New Project - > Console Application and Copy and Paste below code and in that Code change Connection String of Event hub with your connection string. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using Microsoft.ServiceBus.Messaging; using Newtonsoft.Json; namespace EHubSender class Program

static string eventhubname = "eventhub1"; static string connectionstring = "Endpoint=sb://eventhubinput.servicebus.windows.net/;SharedAccessKeyName=RootManageSha redaccesskey;sharedaccesskey=blfyzqeflscwokn1j/xin3m+ltnwarrtn8atgcglqca="; static void Main(string[] args) Console.WriteLine("Press Ctrl-C to stop the sender process"); Console.WriteLine("Press Enter to start now"); Console.ReadLine(); SendingRandomMessages(); static void SendingRandomMessages() double temp; var eventhubclient = EventHubClient.CreateFromConnectionString(connectionString, eventhubname); while (true) try // Simulate reading Temperature var rand = new Random(); double humi = 45 + rand.nextdouble() * 4-2; if (rand.nextdouble() > 0.8) temp = 22 + rand.nextdouble() * 4 + 10; else temp = 22 + rand.nextdouble() * 4-2; var messageinfo = new ; temperature = temp var serialjson = JsonConvert.SerializeObject(messageInfo); EventData data = new EventData(Encoding.UTF8.GetBytes(serialJson)); Console.WriteLine("0 > Sending Temperature value: 1", DateTime.Now, messageinfo); eventhubclient.send(data); catch (Exception exception) Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("0 > Exception: 1", DateTime.Now, exception.message); Console.ResetColor();

Thread.Sleep(200); This Console Application will keep sending random temperature to Stream Analytics. Now Add Event Hub as a Input of Stream Analytics Service in Azure Portal

Add Event Hub Now Create a Storage Account

Create Service Bus for another output of Stream Analytics

Add Queue in Service Bus

Copy and Paste Connection String of Service Bus in Notepad

Now Add Output of Stream Analytics 1. Storage and 2. Service Bus Queue two Output one for cold storage another for hot storage. Add Cold Storage as a Azure Storage Now Add Hot Storage as a Service Bus

Now add Query in Stream Analytics Type Query

SELECT * INTO [COLDSTORAGE] FROM [INPUT] SELECT * INTO [HOTSTORAGE] FROM [INPUT] WHERE [temperature] > 29 All Temperature Data will go to Azure Storage but Temperature > 29 data will goes to Service Bus Queue. Click on SAVE Now Create Visual Studio Console Application for Service Bus Queue to read Service Bus Hot Temperature Data. In VS 2015 - > File -> New Project -> Console Application Add Below Code and replace your service bus connection string using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ServiceBus.Messaging; namespace ServiceBusRECEIVER class Program

static string ConnectionString = "Endpoint=sb://outputservicebus1.servicebus.windows.net/;SharedAccessKeyName=RootManag esharedaccesskey;sharedaccesskey=hfxnhhaph6or819wfw4ip0bj7ameeiyj4jneqjcatxy="; static string QueuePath = "sbqueue"; static void Main(string[] args) //Service Bus Queue Receiver var queueclient = QueueClient.CreateFromConnectionString(ConnectionString, QueuePath); queueclient.onmessage(msg => ProcessMessage(msg)); Console.WriteLine("Press Enter to Exit..."); Console.ReadLine(); queueclient.close(); private static void ProcessMessage(BrokeredMessage msg) var text = msg.getbody<string>(); Console.WriteLine("\nReceived Messages : " + text); Now Click Start Button of Stream Analytics Service in Portal

Now Start Event Hub Console App to produce Temperature Data and it will keep sending that data to stream analytics and stream analytics will keep store data in storage blob and Temperature value > 29 data will be stored in Service Bus Queue. And also start service bus console application to read that Hot Temperature values.

Cloud Services Cloud Services is an example of Platform-as-a-Service (PaaS). Like App Service, this technology is designed to support applications that are scalable, reliable, and cheap to operate. Just like an App Service is hosted on VMs, so too are Cloud Services, however, you have more control over the VMs. You can install your own software on Cloud Service VMs and you can remote into them. More control also means less ease of use. Unless you need the additional control options, it's typically quicker and easier to get a web application up and running in Web Apps in App Service compared to Cloud Services. There are two types of Cloud Service roles. The only difference between the two is how your role is hosted on the virtual machine. Web role Automatically deploys and hosts your app through IIS. Worker role Does not use IIS and runs your app standalone. For example, a simple application might use just a single web role, serving a website. A more complex application might use a web role to handle incoming requests from users, then pass those requests on to a worker role for processing. (This communication could use Service Bus or Azure Queues.) As the preceding figure suggests, all the VMs in a single application run in the same cloud service. Users access the application through a single public IP address, with requests automatically load balanced across the application's VMs. The platform scales and deploys the VMs in a Cloud Services application in a way that avoids a single point of hardware failure. Even though applications run in virtual machines, it's important to understand that Cloud Services provides PaaS, not IaaS. Here's one way to think about it: With IaaS, such as Azure Virtual Machines, you first create and configure the environment your application runs in, then deploy your application into this environment. You're responsible for managing much of this world, doing things such as

deploying new patched versions of the operating system in each VM. In PaaS, by contrast, it's as if the environment already exists. All you have to do is deploy your application. Management of the platform it runs on, including deploying new versions of the operating system, is handled for you. Scaling and management With Cloud Services, you don't create virtual machines. Instead, you provide a configuration file that tells Azure how many of each you'd like, such as three web role instances and two worker role instances, and the platform creates them for you. You still choose what size those backing VMs should be, but you don't explicitly create them yourself. If your application needs to handle a greater load, you can ask for more VMs, and Azure creates those instances. If the load decreases, you can shut down those instances and stop paying for them. Monitoring Cloud Services also provides monitoring. Like Azure Virtual Machines, it detects a failed physical server and restarts the VMs that were running on that server on a new machine. But Cloud Services also detects failed VMs and applications, not just hardware failures. Unlike Virtual Machines, it has an agent inside each web and worker role, and so it's able to start new VMs and application instances when failures occur. Demo Web Role Worker Role Example Description : when web role works it shows web page. Web page will add message to queue. Worker Role is running in back ground will track the queue and insert the record in the database. Step - In Azure portal Create a Sevice bus Queue name queue1 [copy the Connection String to Notepad] Create sqlserver database name it demodb [copy the Server name url to Notepad] Create table using following script CREATE TABLE [dbo].[table1] ( [Id] INT IDENTITY (1, 1) NOT NULL, [item] VARCHAR (50) NULL, [status] VARCHAR (50) NULL, PRIMARY KEY CLUSTERED ([Id] ASC) ); Step - Using visual studio create cloudservice project Add package reference ServiceBus to both the projects. Step - in webrole project add class class1 and add the following code(yellow black ground text only): public class Class1

public string Name get; set; Step - Update the HomeController.cs file with (yellow black ground text only) using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.ServiceBus.Messaging; namespace WebRole1.Controllers public class HomeController : Controller public ActionResult Index() Class1 obj = new Class1(); return View(obj); public string save() string ConnectionString = "Endpoint=sb://queue11.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAcc esskey;sharedaccesskey=ht8suaatbq7duqpixrpwwpt1/10h2tltpszb9hkqhns="; string QueuePath = "queue"; var queueclient = QueueClient.CreateFromConnectionString(ConnectionString, QueuePath); string str = Request.Form["name"]; var message = new BrokeredMessage(str); queueclient.send(message); queueclient.close(); return "data saved on queue : " + str; public ActionResult About() ViewBag.Message = "Your application description page."; return View(); public ActionResult Contact() ViewBag.Message = "Your contact page."; return View(); Step - Update Code in Index.csHtml (remove all the code and paste the following code) @model WebRole1.Class1 @

ViewBag.Title = "Index"; <h2>index1</h2> @using (Html.BeginForm("save", "Home", FormMethod.Post)) @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>class1</h4> <hr /> @Html.ValidationSummary(true, "", new @class = "text-danger" ) <div class="form-group"> @Html.LabelFor(model => model.name, htmlattributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.EditorFor(model => model.name, new htmlattributes = new @class = "form-control" ) @Html.ValidationMessageFor(model => model.name, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="save" class="btn btn-default" /> @*<a href="/home/second?name=@model.name">save</a>*@ </div> </div> </div> <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts @Scripts.Render("~/bundles/jqueryval") Step update WorkerRole.cs file using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using Microsoft.ServiceBus.Messaging; using System.Data.SqlClient; using System.Text;

namespace WorkerRole1 public class WorkerRole : RoleEntryPoint private readonly CancellationTokenSource cancellationtokensource = new CancellationTokenSource(); private readonly ManualResetEvent runcompleteevent = new ManualResetEvent(false); //Provide your connection string static string ConnectionString = "Endpoint=sb://queue11.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAcc esskey;sharedaccesskey=ht8suaatbq7duqpixrpwwpt1/10h2tltpszb9hkqhns="; //quepath is the name of your queue static string QueuePath = "queue"; public override void Run() var queueclient = QueueClient.CreateFromConnectionString(ConnectionString, QueuePath); queueclient.onmessage(msg => ProcessMessage(msg)); private static void ProcessMessage(BrokeredMessage msg) var text = msg.getbody<string>(); Thread.Sleep(9000); System.Diagnostics.Debug.WriteLine("hello worker role"); SqlConnection con; string constr = "Server=tcp:demodbserver1.database.windows.net,1433;Initial Catalog=demoDB;Persist Security Info=False;User ID=demoadmin;Password=demouser@123;MultipleActiveResultSets=False;Encrypt=True;TrustSe rvercertificate=false;connection Timeout=30;"; con = new SqlConnection(constr); string querytext = "insert into table1(item,status) values('" + text + "','deliver');"; SqlCommand com = new SqlCommand(queryText, con); com.connection.open(); com.executenonquery(); com.connection.close(); msg.complete(); 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 https://go.microsoft.com/fwlink/?linkid=166357. bool result = base.onstart(); Trace.TraceInformation("WorkerRole1 has been started"); return result; public override void OnStop() Trace.TraceInformation("WorkerRole1 is stopping");

this.cancellationtokensource.cancel(); this.runcompleteevent.waitone(); base.onstop(); Trace.TraceInformation("WorkerRole1 has stopped"); private async Task RunAsync(CancellationToken cancellationtoken) // TODO: Replace the following with your own logic. while (!cancellationtoken.iscancellationrequested) Trace.TraceInformation("Working"); await Task.Delay(1000);