AZ 203T02A ENU TrainerHandbook
AZ 203T02A ENU TrainerHandbook
AZ 203T02A ENU TrainerHandbook
AZ-203T02
Develop Azure Platform
as a Service compute
solutions
MCT USE ONLY. STUDENT USE PROHIBITED
AZ-203T02
Develop Azure Platform as a
Service compute solutions
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
Contents
Start Here
Welcome
Welcome to the Develop Azure Platform as a Service compute solutions course. This course is part of
a series of courses to help you prepare for the AZ-203: Developing Solutions for Microsoft Azure1
certification exam.
1 https://www.microsoft.com/en-us/learning/exam-az-203.aspx
MCT USE ONLY. STUDENT USE PROHIBITED 2 Welcome to the course
Course description
In this course students will gain the knowledge and skills needed to implement Azure Platform as a
Service features and services in their development solutions. Students will learn how to create and
manage Azure App Service resources, integrate push and offline sync in their mobile apps, and how to
document an API. Students will also learn how to create and test Azure Functions.
Level: Intermediate
Audience:
●● Students in this course are interested in Azure development or in passing the Microsoft Azure Devel-
oper Associate certification exam.
●● Students should have 1-2 years experience as a developer. This course assumes students know how to
code and have a fundamental knowledge of Azure.
●● It is recommended that students have some experience with PowerShell or Azure CLI, working in the
Azure portal, and with at least one Azure-supported programming language. Most of the examples in
this course are presented in C# .NET.
Course Syllabus
Module 1: Create App Service web apps
●● Azure App Service core concepts
●● Creating an Azure App Service web app
●● Creating background tasks by using WebJobs in Azure App Service
Module 2: Creating Azure App Service mobile apps
●● Getting started with mobile apps in App Service
●● Enable push notifications for your app
●● Enable offline sync for your app
Module 3: Create Azure App Service API apps
●● Creating APIs
●● Using Swagger to document an API
Module 4: Implement Azure Functions
●● Azure Functions overview
●● Develop Azure Functions using Visual Studio
MCT USE ONLY. STUDENT USE PROHIBITED
Start Here 3
●● Security and compliance - App Service is ISO, SOC, and PCI compliant. Authenticate users with Azure
Active Directory or with social login (Google, Facebook, Twitter, and Microsoft. Create IP address
restrictions and manage service identities.
●● Application templates - Choose from an extensive list of application templates in the Azure Market-
place, such as WordPress, Joomla, and Drupal.
●● Visual Studio integration - Dedicated tools in Visual Studio streamline the work of creating, deploy-
ing, and debugging.
●● API and mobile features - Web Apps provides turn-key CORS support for RESTful API scenarios, and
simplifies mobile app scenarios by enabling authentication, offline data sync, push notifications, and
more.
●● Serverless code - Run a code snippet or script on-demand without having to explicitly provision or
manage infrastructure, and pay only for the compute time your code actually uses.
Besides Web Apps in App Service, Azure offers other services that can be used for hosting websites and
web applications. For most scenarios, Web Apps is the best choice. For microservice architecture, consider
Service Fabric. If you need more control over the VMs that your code runs on, consider Azure Virtual
Machines.
Note: App Service Free and Shared (preview) hosting plans are base tiers that run on the same Azure VM
as other App Service apps. Some apps may belong to other customers. These tiers are intended to be
used only for development and testing purposes.
Each tier also provides a specific subset of App Service features. These features include custom domains
and SSL certificates, autoscaling, deployment slots, backups, Traffic Manager integration, and more. The
higher the tier, the more features are available. To find out which features are supported in each pricing
tier, see App Service plan details.
How it works
The authentication and authorization module runs in the same sandbox as your application code. When
it's enabled, every incoming HTTP request passes through it before being handled by your application
code.
User claims
For all language frameworks, App Service makes the user's claims available to your code by injecting
them into the request headers. For ASP.NET 4.6 apps, App Service populates ClaimsPrincipal.
Current with the authenticated user's claims, so you can follow the standard .NET code pattern, includ-
ing the [Authorize] attribute. Similarly, for PHP apps, App Service populates the _SERVER['REMOTE_
USER'] variable.
For Azure Functions, ClaimsPrincipal.Current is not hydrated for .NET code, but you can still find the user
claims in the request headers.
For more information, see Access user claims1.
Token store
App Service provides a built-in token store, which is a repository of tokens that are associated with the
users of your web apps, APIs, or native mobile apps. When you enable authentication with any provider,
this token store is immediately available to your app. If your application code needs to access data from
these providers on the user's behalf, such as:
●● post to the authenticated user's Facebook timeline
●● read the user's corporate data from the Azure Active Directory Graph API or even the Microsoft Graph
You typically must write code to collect, store, and refresh these tokens in your application. With the
token store, you just retrieve the tokens when you need them and tell App Service to refresh them when
they become invalid.
The id tokens, access tokens, and refresh tokens cached for the authenticated session, and they're
accessible only by the associated user.
If you don't need to work with tokens in your app, you can disable the token store.
Identity providers
App Service uses federated identity, in which a third-party identity provider manages the user identities
and authentication flow for you. Five identity providers are available by default:
1 https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#access-user-claims
MCT USE ONLY. STUDENT USE PROHIBITED 10 Create Azure App Service Web Apps
When you enable authentication and authorization with one of these providers, its sign-in endpoint is
available for user authentication and for validation of authentication tokens from the provider. You can
provide your users with any number of these sign-in options with ease. You can also integrate another
identity provider or your own custom identity solution.
Authentication flow
The authentication flow is the same for all providers, but differs depending on whether you want to sign
in with the provider's SDK:
●● Without provider SDK: The application delegates federated sign-in to App Service. This is typically
the case with browser apps, which can present the provider's login page to the user. The server code
manages the sign-in process, so it is also called server-directed flow or server flow. This case applies to
web apps. It also applies to native apps that sign users in using the Mobile Apps client SDK because
the SDK opens a web view to sign users in with App Service authentication.
●● With provider SDK: The application signs users in to the provider manually and then submits the
authentication token to App Service for validation. This is typically the case with browser-less apps,
which can't present the provider's sign-in page to the user. The application code manages the sign-in
process, so it is also called client-directed flow or client flow. This case applies to REST APIs, Azure
Functions, and JavaScript browser clients, as well as web apps that need more flexibility in the sign-in
process. It also applies to native mobile apps that sign users in using the provider's SDK.
Note: Calls from a trusted browser app in App Service calls another REST API in App Service or Azure
Functions can be authenticated using the server-directed flow. For more information, see Customize
authentication and authorization in App Service2.
The table below shows the steps of the authentication flow.
2 https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to
MCT USE ONLY. STUDENT USE PROHIBITED
Azure App Service core concepts 11
Authorization behavior
In the Azure portal, you can configure App Service authorization with a number of behaviors.
3 https://technet.microsoft.com/security/bulletins.aspx
4 https://azure.microsoft.com/blog/topics/security/
MCT USE ONLY. STUDENT USE PROHIBITED
Azure App Service core concepts 13
Deprecated versions
When an older version is deprecated, the removal date is announced so that you can plan your runtime
version upgrade accordingly.
5 https://github.com/projectkudu/kudu/wiki/Kudu-console
MCT USE ONLY. STUDENT USE PROHIBITED 14 Create Azure App Service Web Apps
To find all possible outbound IP addresses for your app, regardless of pricing tiers, run the following
command in the Cloud Shell.
az webapp show --resource-group <group_name> --name <app_name> --query
possibleOutboundIpAddresses --output tsv
How it works
The Hybrid Connections feature consists of two outbound calls to Azure Service Bus Relay. There is a
connection from a library on the host where your app is running in App Service. There is also a connec-
tion from the Hybrid Connection Manager (HCM) to Service Bus Relay. The HCM is a relay service that
you deploy within the network hosting the resource you are trying to access.
Through the two joined connections, your app has a TCP tunnel to a fixed host:port combination on the
other side of the HCM. The connection uses TLS 1.2 for security and shared access signature (SAS) keys
for authentication and authorization.
When your app makes a DNS request that matches a configured Hybrid Connection endpoint, the
outbound TCP traffic will be redirected through the Hybrid Connection.
Note: This means that you should try to always use a DNS name for your Hybrid Connection. Some client
software does not do a DNS lookup if the endpoint uses an IP address instead.
6 https://docs.microsoft.com/azure/service-bus-relay/relay-hybrid-connections-protocol/
MCT USE ONLY. STUDENT USE PROHIBITED 16 Create Azure App Service Web Apps
Routing methods
Azure Traffic Manager uses four different routing methods. These methods are described in the following
list as they pertain to Azure App Service.
●● Priority: use a primary app for all traffic, and provide backups in case the primary or the backup apps
are unavailable.
●● Weighted: distribute traffic across a set of apps, either evenly or according to weights, which you
define.
●● Performance: when you have apps in different geographic locations, use the “closest” app in terms of
the lowest network latency.
●● Geographic: direct users to specific apps based on which geographic location their DNS query
originates from.
MCT USE ONLY. STUDENT USE PROHIBITED
Azure App Service core concepts 17
7 https://docs.microsoft.com/en-us/azure/traffic-manager/traffic-manager-routing-methods
MCT USE ONLY. STUDENT USE PROHIBITED 18 Create Azure App Service Web Apps
While many web apps use one or all of these features, some web apps just need a high-performance,
read-only content store that they can run from with high availability. These apps can benefit from a VM
instance of a specific local cache.
The Azure App Service Local Cache feature provides a web role view of your content. This content is a
write-but-discard cache of your storage content that is created asynchronously on-site startup. When the
cache is ready, the site is switched to run against the cached content. Web apps that run on Local Cache
have the following benefits:
●● They are immune to latencies that occur when they access content on Azure Storage.
●● They are immune to the planned upgrades or unplanned downtimes and any other disruptions with
Azure Storage that occur on servers that serve the content share.
●● They have fewer app restarts due to storage share changes.
Dedicated environment
An ASE is dedicated exclusively to a single subscription and can host 100 App
Service Plan instances. The range can span 100 instances in a single App Service plan to 100 single-in-
stance App Service plans, and everything in between.
8 https://docs.microsoft.com/en-us/azure/app-service/environment/app-service-app-service-environment-layered-security
MCT USE ONLY. STUDENT USE PROHIBITED 20 Create Azure App Service Web Apps
An ASE is composed of front ends and workers. Front ends are responsible for
HTTP/HTTPS termination and automatic load balancing of app requests within an
ASE. Front ends are automatically added as the App Service plans in the ASE are scaled out.
Workers are roles that host customer apps. Workers are available in three fixed sizes:
●● One vCPU/3.5 GB RAM
●● Two vCPU/7 GB RAM
●● Four vCPU/14 GB RAM
Customers do not need to manage front ends and workers. All infrastructure is
automatically added as customers scale out their App Service plans. As App
Service plans are created or scaled in an ASE, the required infrastructure is
added or removed as appropriate.
There is a flat monthly rate for an ASE that pays for the infrastructure and
doesn't change with the size of the ASE. In addition, there is a cost per App
Service plan vCPU. All apps hosted in an ASE are in the Isolated pricing SKU.
For information on pricing for an ASE, see the App Service pricing9 page and
review the available options for ASEs.
9 http://azure.microsoft.com/pricing/details/app-service/
MCT USE ONLY. STUDENT USE PROHIBITED
Creating an Azure App Service Web App 21
Azure CLI
The Azure CLI 2.0 is Microsoft's cross-platform command line experience for managing Azure resources.
You can use it in your browser with Azure Cloud Shell, or install it on macOS, Linux, or Windows and run it
from the command line.
Azure CLI 2.0 is optimized for managing and administering Azure resources from the command line, and
for building automation scripts that work against the Azure Resource Manager. Using the Azure CLI 2.0,
you can create VMs within Azure as easily as typing the following command:
az vm create -n MyLinuxVM -g MyResourceGroup --image UbuntuLTS
Use the Cloud Shell to run the CLI in your browser, or installit on macOS, Linux, or Windows. Read the
Get Started11 article to begin using the CLI. For information about the latest release, see the release
notes12.
A detailed reference13 is also available that documents how to use each individual Azure CLI 2.0 com-
mand.
Azure PowerShell
Azure PowerShell provides a set of cmdlets that use the Azure Resource Manager model for managing
your Azure resources. You can use it in your browser with Azure Cloud Shell, or you can install it on your
local machine and use it in any PowerShell session.
10 https://docs.microsoft.com/en-us/azure/cloud-shell/features#tools
11 https://docs.microsoft.com/en-us/cli/azure/get-started-with-azure-cli?view=azure-cli-latest
12 https://docs.microsoft.com/en-us/cli/azure/release-notes-azure-cli?view=azure-cli-latest
13 https://docs.microsoft.com/en-us/cli/azure/reference-index
MCT USE ONLY. STUDENT USE PROHIBITED 22 Create Azure App Service Web Apps
Use the Cloud Shell to run the Azure PowerShell in your browser, or install14 it on own computer. Then
read the Get Started15 article to begin using it. For information about the latest release, see the release
notes16.
Command Notes
az group create Creates a resource group in which all resources are
stored.
az appservice plan create Creates an App Service plan.
az webapp create Creates an Azure web app.
az webapp deployment source config Get the details for available web app
deployment profiles.
Sample script
Below is a sample script for creating a web app with a source deployment from GitHub. For more samples
please see the Azure CLI Samples17 page.
#!/bin/bash
14 https://docs.microsoft.com/en-us/powershell/azure/install-azurerm-ps?view=azurermps-6.5.0
15 https://docs.microsoft.com/en-us/powershell/azure/get-started-azureps?view=azurermps-6.5.0
16 https://docs.microsoft.com/en-us/powershell/azure/release-notes-azureps?view=azurermps-6.5.0
17 https://docs.microsoft.com/en-us/azure/app-service/app-service-cli-samples
MCT USE ONLY. STUDENT USE PROHIBITED
Creating an Azure App Service Web App 23
# Copy the result of the following command into a browser to see the web
app.
echo http://$webappname.azurewebsites.net
Clean up deployment
After the sample script has been run, the following command can be used to remove the resource group
and all resources associated with it.
az group delete --name myResourceGroup
Command Notes
New-AzureRmResourceGroup Creates a resource group in which all resources are
stored.
New-AzureRmAppServicePlan Creates an App Service plan.
New-AzureRmWebApp Creates an Azure web app.
Set-AzureRmResource Modifies a resource in a resource group.
Sample script
Below is a sample script for creating a web app with a source deployment from GitHub. For more samples
please see the Azure PowerShell Samples18 page.
# Replace the following URL with a public GitHub repo URL
$gitrepo="https://github.com/Azure-Samples/app-service-web-dotnet-get-
started.git"
$webappname="mywebapp$(Get-Random)"
$location="West Europe"
18 https://docs.microsoft.com/en-us/azure/app-service/app-service-powershell-samples
MCT USE ONLY. STUDENT USE PROHIBITED 24 Create Azure App Service Web Apps
# Configure GitHub deployment from your GitHub repo and deploy once.
$PropertiesObject = @{
repoUrl = "$gitrepo";
branch = "master";
isManualIntegration = "true";
}
Set-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName
myResourceGroup -ResourceType Microsoft.Web/sites/sourcecontrols -Resource-
Name $webappname/web -ApiVersion 2015-08-01 -Force
Clean up deployment
After the script sample has been run, the following command can be used to remove the resource group,
web app, and all related resources.
Remove-AzureRmResourceGroup -Name myResourceGroup -Force
The Azure portal provides a template to create a web app. This template requires the following fields:
●● App name: The name of the web app.
●● Subscription: A valid and active subscription.
●● Resource group: A valid resource group. The sections below explain in detail what a resource group
is.
●● OS: The operating system. The options are: Windows, Linux, and Docker containers. On Windows, you
can host any type of application from a variety of technologies. The same applies to Linux hosting,
though on Linux, any ASP.NET apps must be ASP.Net Core on the .NET Core framework. The final
option is Docker containers, where you can deploy your containers directly over containers hosted
and maintained by Azure.
●● App Service plan/location: A valid Azure App Service plan. The sections below explain in detail what
an App Service plan is.
●● Applications Insights: You can turn on the Azure Application Insights option and benefit from the
monitoring and metric tools that the Azure portal offers to help you keep an eye on the performance
of your apps.
The Azure portal gives you the upper hand in managing, monitoring, and controlling your web app
through the many available tools.
Deployment slots
Using the Azure portal, you can easily add deployment slots to an App Service web app. For instance,
you can create a staging deployment slot where you can push your code to test on Azure. Once you are
MCT USE ONLY. STUDENT USE PROHIBITED 26 Create Azure App Service Web Apps
happy with your code, you can easily swap the staging deployment slot with the production slot. You do
all this with a few simple mouse clicks in the Azure portal.
Resource groups allow you to easily manage and delete resources. They also provide a way to monitor,
control access, provision, and manage billing for collections of resources that are required to run an
application or are used by a client.
MCT USE ONLY. STUDENT USE PROHIBITED
Creating background tasks by using WebJobs in Azure App Service 29
WebJob Types
There are two types of WebJobs, continuous and triggered. The following table describes the differences.
Continuous Triggered
Starts immediately when the WebJob is created. To Starts only when triggered manually or on a
keep the job from ending, the program or script schedule.
typically does its work inside an endless loop. If
the job does end, you can restart it.
Runs on all instances that the web app runs on. Runs on a single instance that Azure selects for
You can optionally restrict the WebJob to a single load balancing.
instance.
Supports remote debugging. Doesn't support remote debugging.
Note: A web app can time out after 20 minutes of inactivity. Only requests to the scm (deployment) site
or to the web app's pages in the portal reset the timer. Requests to the actual site don't reset the timer. If
your app runs continuous or scheduled WebJobs, enable Always On to ensure that the WebJobs run
reliably. This feature is available only in the Basic, Standard, and Premium pricing tiers.
19 https://docs.microsoft.com/en-us/azure/azure-functions/functions-compare-logic-apps-ms-flow-webjobs
MCT USE ONLY. STUDENT USE PROHIBITED 30 Create Azure App Service Web Apps
3.
4. In the WebJobs page, select Add.
5.
6. Use the Add WebJob settings as specified in the table
20 https://portal.azure.com/
MCT USE ONLY. STUDENT USE PROHIBITED
Creating background tasks by using WebJobs in Azure App Service 31
7.
10.
3.
4. In the WebJobs page, select Add.
21 https://portal.azure.com/
MCT USE ONLY. STUDENT USE PROHIBITED
Creating background tasks by using WebJobs in Azure App Service 33
5.
6. Use the Add WebJob settings as specified in the table
7.
Triggers Manual
8. Click OK.
9. The new WebJob appears on the WebJobs page.
10.
MCT USE ONLY. STUDENT USE PROHIBITED
Review questions 35
Review questions
Module 1 review questions
Azure App Service plans
In App Service, an app runs in an App Service plan. An App Service plan defines a set of compute re-
sources for a web app to run. These compute resources are analogous to the server farm in conventional
web hosting. One or more apps can be configured to run on the same computing resources (or in the
same App Service plan).
Which App Service plan is available only to function apps?
Routing methods
Azure Traffic Manager uses four different routing methods. These methods are described in the following
list as they pertain to Azure App Service.
●● Priority: use a primary app for all traffic, and provide backups in case the primary or the backup apps
are unavailable.
MCT USE ONLY. STUDENT USE PROHIBITED 36 Create Azure App Service Web Apps
●● Weighted: distribute traffic across a set of apps, either evenly or according to weights, which you
define.
●● Performance: when you have apps in different geographic locations, use the “closest” app in terms of
the lowest network latency.
●● Geographic: direct users to specific apps based on which geographic location their DNS query
originates from.
MCT USE ONLY. STUDENT USE PROHIBITED
Create Azure App Service mobile apps
●● Connect to your enterprise systems: With the Mobile Apps feature, you can add corporate sign-in in
minutes, and connect to your enterprise on-premises or cloud resources.
●● Build offline-ready apps with data sync: Make your mobile workforce more productive by building
apps that work offline, and use Mobile Apps to sync data in the background when connectivity is
present with any of your enterprise data sources or software as a service (SaaS) APIs.
●● Push notifications to millions in seconds: Engage your customers with instant push notifications on
any device, personalized to their needs, and sent when the time is right.
Prerequisites
The following step-by-step instructions show you how to use the Mobile Apps Quickstart feature to
create a moble app backend for the Windows platform. If you want to try this on your own, you will need
the following:
●● An active Azure account. If you don't have an account, you can sign up for an Azure trial and get up to
10 free mobile apps that you can keep using even after your trial ends. For details, see Azure Free
Trial1.
●● Visual Studio Community 20152 or a later version.
4.
5. In the results list, select Mobile Apps Quickstart, and then select Create.
6. Choose a unique App name. This will also be part of the domain name for your App Service.
7. Under Resource Group, select an existing resource group or create a new one (using the same name
as your app).
8. Click Create. Wait a few minutes for the service to be deployed successfully before proceeding. Watch
the Notifications (bell) icon in the portal header for status updates.
1 https://azure.microsoft.com/pricing/free-trial/
2 https://go.microsoft.com/fwLink/p/?LinkID=534203
3 https://portal.azure.com/
MCT USE ONLY. STUDENT USE PROHIBITED 40 Create Azure App Service mobile apps
2.
3. If a database connection is not configured, create one by doing the following:
4.
5. a. Create a new SQL database and server.
6.
7. b. Wait until the data connection is successfully created.
8.
9. Under 2. Create a table API, select Node.js for Backend language.
MCT USE ONLY. STUDENT USE PROHIBITED
Getting Started with mobile apps in App Service 41
10. Accept the acknowledgment, and then select Create TodoItem table. This action creates a new to-do
item table in your database.
11. Note: Switching an existing back end to Node.js overwrites all contents. To create a .NET back end
instead, see Work with the .NET back-end server SDK for Mobile Apps4.
2.
3. (Optional) Add the UWP app project to the same solution as the server project. This makes it easier to
debug and test both the app and the backend in the same Visual Studio solution, if you choose to do
so. To add a UWP app project to the solution, you must be using Visual Studio 2015 or a later version.
4. With the UWP app as the startup project, press the F5 key to deploy and run the app.
5. In the app, type meaningful text, such as Complete the tutorial, in the Insert a TodoItem text box, and
then click Save.
4 https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-dotnet-backend-how-to-use-server-sdk#create-app
MCT USE ONLY. STUDENT USE PROHIBITED 42 Create Azure App Service mobile apps
6.
MCT USE ONLY. STUDENT USE PROHIBITED
Enabling push notifications for your app 43
5.
5 https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-dotnet-backend-how-to-use-server-sdk
MCT USE ONLY. STUDENT USE PROHIBITED 44 Create Azure App Service mobile apps
3.
Now you have connected a notification hub to your Mobile Apps back-end project. Later you configure
this notification hub to connect to a platform notification system (PNS) to push to devices.
2.
3. In the wizard, click Next, sign in with your Microsoft account, type a name for your app in Reserve a
new app name, then click Reserve.
4. After the app registration is successfully created, select the new app name, click Next, and then click
Associate. This adds the required Microsoft Store registration information to the application manifest.
5. Navigate to the Windows Dev Center6, sign-in with your Microsoft account, click the new app
registration in My apps, then expand Services > Push notifications.
6. In the Push notifications page, click Live Services site under Microsoft Azure Mobile Services.
7. In the registration page, make a note of the value under Application secrets and the Package SID,
which you will next use to configure your mobile app backend.
6 https://dev.windows.com/en-us/overview
MCT USE ONLY. STUDENT USE PROHIBITED 46 Create Azure App Service mobile apps
8.
Important: The client secret and package SID are important security credentials. Do not share these
values with anyone or distribute them with your app. The Application Id is used with the secret to
configure Microsoft Account authentication.
3.
Your back end is now configured to use WNS to send push notifications.
3. In the PostTodoItem method, add the following code after the call to InsertAsync:
// Get the settings for the server project.
HttpConfiguration config = this.Configuration;
MobileAppSettingsDictionary settings =
this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSet-
tings();
4. This code tells the notification hub to send a push notification after a new item is insertion.
5. Republish the server project.
table.insert(function (context) {
// For more information about the Notification Hubs JavaScript SDK,
// see http://aka.ms/nodejshubs
logger.info('Running TodoItem.insert');
// Define the WNS payload that contains the new item Text.
var payload = "<toast><visual><binding template=\ToastText01\><text
7 https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-node-backend-how-to-use-server-sdk#download-quick-
start
8 https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-node-backend-how-to-use-server-sdk#online-editor
MCT USE ONLY. STUDENT USE PROHIBITED
Enabling push notifications for your app 49
id=\"1\">"
+ context.item.text + "</text></binding></
visual></toast>";
module.exports = table;
3. This sends a WNS toast notification that contains the item.text when a new todo item is inserted.
4. When editing the file on your local computer, republish the server project.
2. In the same file, add the following InitNotificationsAsync method definition to the App class:
private async Task InitNotificationsAsync()
{
// Get a channel URI from WNS.
var channel = await PushNotificationChannelManager
.CreatePushNotificationChannelForApplicationAsync();
await App.MobileService.GetPush().RegisterAsync(channel.Uri);
}
3. This code retrieves the ChannelURI for the app from WNS, and then registers that ChannelURI with
your App Service Mobile App.
4. At the top of the OnLaunched event handler in App.xaml.cs, add the async modifier to the method
definition and add the following call to the new InitNotificationsAsync method, as in the following
example:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
await InitNotificationsAsync();
// ...
}
5. This guarantees that the short-lived ChannelURI is registered each time the application is launched.
6. Rebuild your UWP app project. Your app is now ready to receive toast notifications.
MCT USE ONLY. STUDENT USE PROHIBITED
Enabling offline sync for your app 51
●● If you want to opt out of incremental sync, pass null as the query ID. In this case, all records are
retrieved on every call to PullAsync, which is potentially inefficient.
●● Purging: You can clear the contents of the local store using IMobileServiceSyncTable.Pur-
geAsync. Purging may be necessary if you have stale data in the client database, or if you wish to
discard all pending changes.
●● A purge clears a table from the local store. If there are operations awaiting synchronization with the
server database, the purge throws an exception unless the force purge parameter is set.
●● As an example of stale data on the client, suppose in the “todo list” example, Device1 only pulls items
that are not completed. A todoitem "Buy milk" is marked completed on the server by another device.
However, Device1 still has the “Buy milk” todoitem in local store because it is only pulling items that
are not marked complete. A purge clears this stale item.
Next
The rest of this lesson shows you how to add offline support to a Universal Windows Platform (UWP) app
using an Azure Mobile App backend. The steps for enabling offline sync follow a similar pattern for
whichever platform you are targeting.
1. Ensure the client app supports offline features
2. Ensure the app can disconnect from the backend
3. Ensure the app can reconnect to your Mobile App backend
Requirements
The next part of this course builds on a UWP app project. If you want to follow along in your own project
be sure to have:
●● Visual Studio 2013 running on Windows 8.1 or later.
●● Complete the online tutorial Create a Windows app9. You'll be modifying this app to enable offline
sync.
●● Azure Mobile Services SQLite Store10
●● SQLite for Universal Windows Platform development11
9 https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-windows-store-dotnet-get-started
10 https://www.nuget.org/packages/Microsoft.Azure.Mobile.Client.SQLiteStore/
11 https://marketplace.visualstudio.com/items?itemName=SQLiteDevelopmentTeam.SQLiteforUniversalWindowsPlatform
MCT USE ONLY. STUDENT USE PROHIBITED
Enabling offline sync for your app 53
your table through the IMobileServiceSyncTable interface. SQLite is used as the local store on the
device.
1. Install the SQLite runtime for the Universal Windows Platform12.
2. In Visual Studio, open the NuGet package manager for the UWP app project that you completed in
the Create a Windows app tutorial. Search for and install the Microsoft.Azure.Mobile.Client.SQLite-
Store NuGet package.
3. In Solution Explorer, right-click References > Add Reference… > Universal Windows > Extensions,
then enable both SQLite for Universal Windows Platform and Visual C++ 2015 Runtime for
Universal Windows Platform apps.
4.
5. Open the MainPage.xaml.cs file and uncomment the #define OFFLINE_SYNC_ENABLED definition.
6. In Visual Studio, press the F5 key to rebuild and run the client app. The app works the same as it did
before you enabled offline sync. However, the local database is now populated with data that can be
used in an offline scenario.
12 http://sqlite.org/2016/sqlite-uwp-3120200.vsix
MCT USE ONLY. STUDENT USE PROHIBITED 54 Create Azure App Service mobile apps
1. You can also demonstrate offline behavior by disabling wifi and cellular networks on the device or use
airplane mode.
2. Press F5 to build and run the app. Notice your sync failed on refresh when the app launched.
3. Enter new items and notice that push fails with a CancelledByNetworkError status each time you click
Save. However, the new todo items exist in the local store until they can be pushed to the mobile app
backend. In a production app, if you suppress these exceptions the client app behaves as if it's still
connected to the mobile app backend.
4. Close the app and restart it to verify that the new items you created are persisted to the local store.
5. (Optional) In Visual Studio, open Server Explorer. Navigate to your database in Azure->SQL Data-
bases. Right-click your database and select Open in SQL Server Object Explorer. Now you can
browse to your SQL database table and its contents. Verify that the data in the backend database has
not changed.
6. (Optional) Use a REST tool such as Fiddler or Postman to query your mobile backend, using a GET
query in the form https://<your-mobile-app-backend-name>.azurewebsites.net/
tables/TodoItem.
API summary
To support the offline features of mobile services, we used the IMobileServiceSyncTable interface
and initialized MobileServiceClient.SyncContext with a local SQLite database. When offline, the
normal CRUD operations for Mobile Apps work as if the app is still connected while the operations occur
against the local store. The following methods are used to synchronize the local store with the server:
●● PushAsync: Because this method is a member of IMobileServicesSyncContext, changes across
all tables are pushed to the backend. Only records with local changes are sent to the server.
MCT USE ONLY. STUDENT USE PROHIBITED
Enabling offline sync for your app 55
●● PullAsync: A pull is started from a IMobileServiceSyncTable. When there are tracked changes in
the table, an implicit push is run to make sure that all tables in the local store along with relationships
remain consistent. The pushOtherTables parameter controls whether other tables in the context are
pushed in an implicit push. The query parameter takes an IMobileServiceTableQuery or OData
query string to filter the returned data. The queryId parameter is used to define incremental sync.
●● PurgeAsync: Your app should periodically call this method to purge stale data from the local store.
Use the force parameter when you need to purge any changes that have not yet been synced.
MCT USE ONLY. STUDENT USE PROHIBITED 56 Create Azure App Service mobile apps
Review questions
Module 2 review questions
App Service push notifications
Push notifications are delivered through platform-specific infrastructures called Platform Notification
Systems (PNSes). They offer barebone push functionalities to deliver a message to a device with a
provided handle, and have no common interface. Can you describe how a push works?
5.
Offline sync
What is the general pattern you need to follow to enable offline sync regardless of the app platform?
Creating APIs
API Management overview
API Management (APIM) helps organizations publish APIs to external, partner, and internal developers to
unlock the potential of their data and services. Businesses everywhere are looking to extend their opera-
tions as a digital platform, creating new channels, finding new customers and driving deeper engagement
with existing ones. API Management provides the core competencies to ensure a successful API program
through developer engagement, business insights, analytics, security, and protection. You can use Azure
API Management to take any backend and launch a full-fledged API program based on it.
Overview
To use API Management, administrators create APIs. Each API consists of one or more operations, and
each API can be added to one or more products. To use an API, developers subscribe to a product that
contains that API, and then they can call the API's operation, subject to any usage policies that may be in
effect. Common scenarios include:
●● Securing mobile infrastructure by gating access with API keys, preventing DOS attacks by using
throttling, or using advanced security policies like JWT token validation.
●● Enabling ISV partner ecosystems by offering fast partner onboarding through the developer portal
and building an API facade to decouple from internal implementations that are not ripe for partner
consumption.
●● Running an internal API program by offering a centralized location for the organization to communi-
cate about the availability and latest changes to APIs, gating access based on organizational accounts,
all based on a secured channel between the API gateway and the backend.
The system is made up of the following components:
●● The API gateway is the endpoint that:
●● Accepts API calls and routes them to your backends.
●● Verifies API keys, JWT tokens, certificates, and other credentials.
MCT USE ONLY. STUDENT USE PROHIBITED 58 Create Azure App Service API apps
Products
Products are how APIs are surfaced to developers. Products in API Management have one or more APIs,
and are configured with a title, description, and terms of use. Products can be Open or Protected.
Protected products must be subscribed to before they can be used, while open products can be used
without a subscription. When a product is ready for use by developers, it can be published. Once it is
published, it can be viewed (and in the case of protected products subscribed to) by developers. Sub-
scription approval is configured at the product level and can either require administrator approval, or be
auto-approved.
Groups are used to manage the visibility of products to developers. Products grant visibility to groups,
and developers can view and subscribe to the products that are visible to the groups in which they
belong.
MCT USE ONLY. STUDENT USE PROHIBITED
Creating APIs 59
Groups
Groups are used to manage the visibility of products to developers. API Management has the following
immutable system groups:
●● Administrators - Azure subscription administrators are members of this group. Administrators
manage API Management service instances, creating the APIs, operations, and products that are used
by developers.
●● Developers - Authenticated developer portal users fall into this group. Developers are the customers
that build applications using your APIs. Developers are granted access to the developer portal and
build applications that call the operations of an API.
●● Guests - Unauthenticated developer portal users, such as prospective customers visiting the develop-
er portal of an API Management instance fall into this group. They can be granted certain read-only
access, such as the ability to view APIs but not call them.
In addition to these system groups, administrators can create custom groups or leverage external groups
in associated Azure Active Directory tenants. Custom and external groups can be used alongside system
groups in giving developers visibility and access to API products. For example, you could create one
custom group for developers affiliated with a specific partner organization and allow them access to the
APIs from a product containing relevant APIs only. A user can be a member of more than one group.
Developers
Developers represent the user accounts in an API Management service instance. Developers can be
created or invited to join by administrators, or they can sign up from the Developer portal. Each develop-
er is a member of one or more groups, and can subscribe to the products that grant visibility to those
groups.
When developers subscribe to a product, they are granted the primary and secondary key for the prod-
uct. This key is used when making calls into the product's APIs.
Policies
Policies are a powerful capability of API Management that allow the Azure portal to change the behavior
of the API through configuration. Policies are a collection of statements that are executed sequentially on
the request or response of an API. Popular statements include format conversion from XML to JSON and
call rate limiting to restrict the number of incoming calls from a developer, and many other policies are
available.
Policy expressions can be used as attribute values or text values in any of the API Management policies,
unless the policy specifies otherwise. Some policies such as the Control flow and Set variable policies are
based on policy expressions. For more information, see Advanced policies and Policy expressions.
Developer portal
The developer portal is where developers can learn about your APIs, view and call operations, and
subscribe to products. Prospective customers can visit the developer portal, view APIs and operations,
and sign up. The URL for your developer portal is located on the dashboard in the Azure portal for your
API Management service instance.
MCT USE ONLY. STUDENT USE PROHIBITED 60 Create Azure App Service API apps
3.
4. In the API Management service window, enter settings.
MCT USE ONLY. STUDENT USE PROHIBITED 62 Create Azure App Service API apps
5.
Clean up resources
When no longer needed, you can remove the resource group and all related resources by following these
steps:
1. In the Azure portal, select All services.
2. Input resource groups in the search box and click on the result.
3. Find your resource group and click on it.
4. Click Delete resource group.
5. Confirm the deletion by inputting the name of your resource group.
6. Click Delete.
Create an API
1. Login to the Azure Portal and select the APIM instance you created earlier.
2. Select APIs from under API MANAGEMENT.
3. From the left menu, select + Add API.
4. Select Blank API from the list.
MCT USE ONLY. STUDENT USE PROHIBITED 64 Create Azure App Service API apps
5.
6. Enter settings for the API.
Add an operation
1. Select the API you created in the previous step.
2. Click + Add Operation.
3. In the URL, select GET and enter /get in the resource.
4. Enter FetchData for Display name.
5. Select Save.
MCT USE ONLY. STUDENT USE PROHIBITED 66 Create Azure App Service API apps
Test an operation
Test the operation in the Azure portal. Alternatively, you can test it in the Developer portal.
1. Select the Test tab.
2. Select FetchData.
3. Press Send.
The response that the http://httpbin.org/get operation generates appears.
1. Select Products in the menu on the left to display the Products page.
2. Select + Add. When you add a product, you need to supply the following information:
Name Description
Display name The name as you want it to be shown in the
Developer portal.
Name A descriptive name of the product.
Description The Description field allows you to provide
detailed information about the product such as its
purpose, the APIs it provides access to, and other
useful information.
State Press Published if you want to publish the
product. Before the APIs in a product can be
called, the product must be published. By default
new products are unpublished, and are visible only
to the Administrators group.
Requires subscription Check Require subscription if a user is required
to subscribe to use the product.
MCT USE ONLY. STUDENT USE PROHIBITED 68 Create Azure App Service API apps
Name Description
Requires approval Check Require approval if you want an adminis-
trator to review and accept or reject subscription
attempts to this product. If the box is unchecked,
subscription attempts are auto-approved.
Subscription count limit To limit the count of multiple simultaneous
subscriptions, enter the subscription limit.
Legal terms You can include the terms of use for the product
which subscribers must accept in order to use the
product.
APIs Products are associations of one or more APIs. You
can include a number of APIs and offer them to
developers through the developer portal. You can
add an existing API during the product creation.
You can add an API to the product later, either
from the Products Settings page or while creating
an API.
3. Select Create to create the new product.
Package installation
Here's how to install the Swashbuckle.AspNetCore package in Visual studio:
●● From the Package Manager Console window:
●● Go to View > Other Windows > Package Manager Console
●● Navigate to the directory in which the TodoApi.csproj file exists
●● Execute the following command:
Install-Package Swashbuckle.AspNetCore
In the Startup.Configure method, enable the middleware for serving the generated JSON document
and the Swagger UI:
public void Configure(IApplicationBuilder app)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
app.UseMvc();
}
1 https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-2.1#swagger-specifica-
tion-swaggerjson
MCT USE ONLY. STUDENT USE PROHIBITED 72 Create Azure App Service API apps
Enabling XML comments provides debug information for undocumented public types and members.
Undocumented types and members are indicated by the warning message. For example, the following
message indicates a violation of warning code 1591:
warning CS1591: Missing XML comment for publicly visible type or member
'TodoController.GetAll()'
To suppress warnings project-wide, define a semicolon-delimited list of warning codes to ignore in the
project file. Appending the warning codes to $(NoWarn); applies the C# default values too.
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
To suppress warnings only for specific members, enclose the code in #pragma warning preprocessor
directives. This approach is useful for code that shouldn't be exposed via the API docs. In the following
example, warning code CS1591 is ignored for the entire Program class. Enforcement of the warning code
is restored at the close of the class definition. Specify multiple warning codes with a comma-delimited
list.
namespace TodoApi
{
#pragma warning disable CS1591
public class Program
{
public static void Main(string[] args) =>
BuildWebHost(args).Run();
Configure Swagger to use the generated XML file. For Linux or non-Windows operating systems, file
names and paths can be case-sensitive. For example, a TodoApi.XML file is valid on Windows but not
CentOS.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
{
Version = "v1",
Title = "ToDo API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact
{
Name = "Shayne Boyer",
Email = string.Empty,
Url = "https://twitter.com/spboyer"
},
License = new License
{
Name = "Use under LICX",
Url = "https://example.com/license"
}
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.
xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
In the preceding code, Reflection is used to build an XML file name matching that of the Web API project.
The AppContext.BaseDirectory property is used to construct a path to the XML file.
Adding triple-slash comments to an action enhances the Swagger UI by adding the description to the
section header. Add a <summary> element above the Delete action:
/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>
[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
var todo = _context.TodoItems.Find(id);
if (todo == null)
{
return NotFound();
}
_context.TodoItems.Remove(todo);
_context.SaveChanges();
return NoContent();
}
MCT USE ONLY. STUDENT USE PROHIBITED
Using Swagger to document an API 75
The Swagger UI displays the inner text of the preceding code's <summary> element:
Add a <remarks> element to the Create action method documentation. It supplements information
specified in the <summary> element and provides a more robust Swagger UI. The <remarks> element
content can consist of text, JSON, or XML.
MCT USE ONLY. STUDENT USE PROHIBITED 76 Create Azure App Service API apps
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
public ActionResult<TodoItem> Create(TodoItem item)
{
_context.TodoItems.Add(item);
_context.SaveChanges();
namespace TodoApi.Models
MCT USE ONLY. STUDENT USE PROHIBITED
Using Swagger to document an API 77
{
public class TodoItem
{
public long Id { get; set; }
[Required]
public string Name { get; set; }
[DefaultValue(false)]
public bool IsComplete { get; set; }
}
}
The presence of this attribute changes the UI behavior and alters the underlying JSON schema:
"definitions": {
"TodoItem": {
"required": [
"name"
],
"type": "object",
"properties": {
"id": {
"format": "int64",
"type": "integer"
},
"name": {
"type": "string"
},
"isComplete": {
"default": false,
"type": "boolean"
}
}
}
},
Add the [Produces("application/json")] attribute to the API controller. Its purpose is to declare
that the controller's actions support a response content type of application/json:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
private readonly TodoContext _context;
The Response Content Type drop-down selects this content type as the default for the controller's GET
actions:
MCT USE ONLY. STUDENT USE PROHIBITED 78 Create Azure App Service API apps
As the usage of data annotations in the Web API increases, the UI and API help pages become more
descriptive and useful.
The Swagger UI now clearly documents the expected HTTP response codes:
MCT USE ONLY. STUDENT USE PROHIBITED 80 Create Azure App Service API apps
Review questions
Module 3 review questions
API Management groups
Groups are used to manage the visibility of products to developers. Products grant visibility to groups,
and developers can view and subscribe to the products that are visible to the groups in which they
belong. Can you name the three immutable system groups and their capabilities?
Integrations
Azure Functions integrates with various Azure and 3rd-party services. These services can trigger your
function and start execution, or they can serve as input and output for your code. The following service
integrations are supported by Azure Functions:
●● Azure Cosmos DB
●● Azure Event Hubs
●● Azure Event Grid
●● Azure Notification Hubs
●● Azure Service Bus (queues and topics)
●● Azure Storage (blob, queues, and tables)
●● On-premises (using Service Bus)
●● Twilio (SMS messages)
1 https://docs.microsoft.com/en-us/azure/azure-functions/functions-scale
MCT USE ONLY. STUDENT USE PROHIBITED
Azure Functions overview 83
Important: You must choose the type of hosting plan during the creation of the function app. You can't
change it afterward.
On an App Service plan, you can scale between tiers to allocate different amount of resources. On the
Consumption plan, Azure Functions automatically handles all resource allocation.
Consumption plan
When you're using a Consumption plan, instances of the Azure Functions host are dynamically added and
removed based on the number of incoming events. This serverless plan scales automatically, and you're
charged for compute resources only when your functions are running. On a Consumption plan, a function
execution times out after a configurable period of time.
Note: The default timeout for functions on a Consumption plan is 5 minutes. The value can be increased
for the Function App up to a maximum of 10 minutes by changing the property functionTimeout in
the host.json project file.
Billing is based on number of executions, execution time, and memory used. Billing is aggregated across
all functions within a function app.
The Consumption plan is the default hosting plan and offers the following benefits:
●● Pay only when your functions are running.
●● Scale out automatically, even during periods of high load.
Always On
If you run on an App Service plan, you should enable the Always on setting so that your function app
runs correctly. On an App Service plan, the functions runtime goes idle after a few minutes of inactivity,
so only HTTP triggers will “wake up” your functions. Always on is available only on an App Service plan.
On a Consumption plan, the platform activates function apps automatically.
Runtime scaling
Azure Functions uses a component called the scale controller to monitor the rate of events and deter-
mine whether to scale out or scale in. The scale controller uses heuristics for each trigger type. For
example, when you're using an Azure Queue storage trigger, it scales based on the queue length and the
age of the oldest queue message.
The unit of scale is the function app. When the function app is scaled out, additional resources are
allocated to run multiple instances of the Azure Functions host. Conversely, as compute demand is
reduced, the scale controller removes function host instances. The number of instances is eventually
scaled down to zero when no functions are running within a function app.
MCT USE ONLY. STUDENT USE PROHIBITED
Azure Functions overview 85
Overview
A trigger defines how a function is invoked. A function must have exactly one trigger. Triggers have
associated data, which is usually the payload that triggered the function.
Input and output bindings provide a declarative way to connect to data from within your code. Bindings
are optional and a function can have multiple input and output bindings.
Triggers and bindings let you avoid hardcoding the details of the services that you're working with. Your
function receives data (for example, the content of a queue message) in function parameters. You send
data (for example, to create a queue message) by using the return value of the function. In C# and C#
script, alternative ways to send data are out parameters and collector objects.
When you develop functions by using the Azure portal, triggers and bindings are configured in a func-
tion.json file. The portal provides a UI for this configuration but you can edit the file directly by changing
to the Advanced editor.
MCT USE ONLY. STUDENT USE PROHIBITED 86 Implement Azure functions
When you develop functions by using Visual Studio to create a class library, you configure triggers and
bindings by decorating methods and parameters with attributes.
The first element in the bindings array is the Queue storage trigger. The type and direction
properties identify the trigger. The name property identifies the function parameter that receives the
queue message content. The name of the queue to monitor is in queueName, and the connection string
is in the app setting identified by connection.
The second element in the bindings array is the Azure Table Storage output binding. The type and
direction properties identify the binding. The name property specifies how the function provides the
new table row, in this case by using the function return value. The name of the table is in tableName,
and the connection string is in the app setting identified by connection.
To view and edit the contents of function.json in the Azure portal, click the Advanced editor option on
the Integrate tab of your function.
Note: The value of connection is the name of an app setting that contains the connection string, not
the connection string itself. Bindings use connection strings stored in app settings to enforce the best
practice that function.json does not contain service secrets.
Here's C# script code that works with this trigger and binding. Notice that the name of the parameter
that provides the queue message content is order; this name is required because the name property
value in function.json is order.
#r "Newtonsoft.Json"
using Microsoft.Extensions.Logging;
MCT USE ONLY. STUDENT USE PROHIBITED
Azure Functions overview 87
using Newtonsoft.Json.Linq;
// From an incoming queue message that is a JSON object, add fields and
write to Table storage
// The method return value creates a new row in Table Storage
public static Person Run(JObject order, ILogger log)
{
return new Person() {
PartitionKey = "Orders",
RowKey = Guid.NewGuid().ToString(),
Name = order["Name"].ToString(),
MobileNumber = order["MobileNumber"].ToString() };
}
Binding direction
All triggers and bindings have a direction property in the function.json file:
●● For triggers, the direction is always in
●● Input and output bindings use in and out
●● Some bindings support a special direction inout. If you use inout, only the Advanced editor is
available in the Integrate tab.
MCT USE ONLY. STUDENT USE PROHIBITED 88 Implement Azure functions
When you use attributes in a class library to configure triggers and bindings, the direction is provided in
an attribute constructor or inferred from the parameter type.
C# example
Here's C# code that uses the return value for an output binding:
[FunctionName("QueueTrigger")]
[return: Blob("output-container/{id}")]
public static string Run([QueueTrigger("inputqueue")]WorkItem input, ILog-
ger log)
{
string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
log.LogInformation($"C# script processed queue message. Item={json}");
return json;
}
Most expressions are identified by wrapping them in curly braces. For example, in a queue trigger
function, {queueTrigger} resolves to the queue message text. If the path property for a blob output
binding is container/{queueTrigger} and the function is triggered by a queue message HelloW-
orld, a blob named HelloWorld is created.
Types of binding expressions
●● App settings
●● Trigger file name
●● Trigger metadata
●● JSON payloads
●● New GUID
●● Current date and time
●● InsertionTime
●● NextVisibleTime
●● PopReceipt
These metadata values are accessible in function.json file properties. For example, suppose you use a
queue trigger and the queue message contains the name of a blob you want to read. In the function.json
file, you can use queueTrigger metadata property in the blob path property.
Service Bus topics are useful if you require message filtering before processing.
Event hubs are useful to support high volume communications.
If you have a shared assembly referenced in multiple .Net functions, put it in a common shared folder.
Reference the assembly with a statement similar to the following example if using C# Scripts (.csx):
#r "..\Shared\MyAssembly.dll".
Otherwise, it is easy to accidentally deploy multiple test versions of the same binary that behave differ-
ently between functions.
Don't use verbose logging in production code. It has a negative performance impact.
2 https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json
MCT USE ONLY. STUDENT USE PROHIBITED 94 Implement Azure functions
Prerequisites
Azure Functions Tools is included in the Azure development workload of Visual Studio 2017 version 15.5,
or a later version. Make sure you include the Azure development workload in your Visual Studio 2017
installation. Also make sure that your Visual Studio is up-to-date and that you are using the most recent
version of the Azure Functions tools.
You will also need:
●● An active Azure subscription
●● An Azure Storage account.
Creating a function
In pre-compiled functions, the bindings used by the function are defined by applying attributes in the
code. When you use the Azure Functions Tools to create your functions from the provided templates,
these attributes are applied for you.
1. In Solution Explorer, right-click on your project node and select Add > New Item. Select Azure
Function, type a Name for the class, and click Add.
2. Choose your trigger, set the binding properties, and click Create. The following example shows the
settings when creating a Queue storage triggered function.
3.
4. This trigger example uses a connection string with a key named QueueStorage. This connection
string setting must be defined in the local.settings.json file.
5. Examine the newly added class. You see a static Run method, that is attributed with the Function-
Name attribute. This attribute indicates that the method is the entry point for the function.
6. For example, the following C# class represents a basic Queue storage triggered function:
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("QueueTriggerCSharp")]
public static void Run([QueueTrigger("myqueue-items", Connection =
"QueueStorage")]string myQueueItem, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueue-
Item}");
MCT USE ONLY. STUDENT USE PROHIBITED
Develop Azure Functions using Visual Studio 97
}
}
}
7. A binding-specific attribute is applied to each binding parameter supplied to the entry point method.
The attribute takes the binding information as parameters. In the previous example, the first parame-
ter has a QueueTrigger attribute applied, indicating queue triggered function. The queue name and
connection string setting name are passed as parameters to the QueueTrigger attribute.
You can use the above procedure to add more functions to your function app project. Each function in
the project can have a different trigger, but a function must have exactly one trigger.
5. The connection to Queue storage is obtained from the AzureWebJobsStorage setting. For more
information, see the reference article for the specific binding.
3 https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs
MCT USE ONLY. STUDENT USE PROHIBITED 98 Implement Azure functions
Publish to Azure
1. In Solution Explorer, right-click the project and select Publish.
2. Select Azure Function App, choose Create New, and then select Publish.
3. If you haven't already connected Visual Studio to your Azure account, select Add an account….
4. In the Create App Service dialog, use the Hosting settings as specified in the table below:
4 https://docs.microsoft.com/en-us/azure/azure-functions/functions-test-a-function
MCT USE ONLY. STUDENT USE PROHIBITED
Develop Azure Functions using Visual Studio 99
This displays the Application Settings dialog for the function app, where you can add new application
settings or modify existing ones.
You can also manage application settings in one of these other ways:
●● Using the Azure portal.
●● Using the --publish-local-settings publish option in the Azure Functions Core Tools.
●● Using the Azure CLI.
MCT USE ONLY. STUDENT USE PROHIBITED 100 Implement Azure functions
C# script
public static async Task<object> Run(DurableOrchestrationContext ctx)
{
try
{
var x = await ctx.CallActivityAsync<object>("F1");
var y = await ctx.CallActivityAsync<object>("F2", x);
var z = await ctx.CallActivityAsync<object>("F3", y);
return await ctx.CallActivityAsync<object>("F4", z);
}
catch (Exception)
{
// error handling/compensation goes here
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 101
}
}
Note: There are subtle differences while writing a precompiled durable function in C# vs the C# script
sample shown before. A C# precompiled function would require durable parameters to be decorated
with respective attributes. An example is [OrchestrationTrigger] attribute for DurableOrches-
trationContext parameter. If the parameters are not properly decorated, the runtime would not be
able to inject the variables to the function and would give error.
The values “F1”, "F2", “F3”, and "F4" are the names of other functions in the function app. Control flow is
implemented using normal imperative coding constructs. That is, code executes top-down and can
involve existing language control flow semantics, like conditionals, and loops. Error handling logic can be
included in try/catch/finally blocks.
The ctx parameter (DurableOrchestrationContext) provides methods for invoking other functions
by name, passing parameters, and returning function output. Each time the code calls await, the
Durable Functions framework checkpoints the progress of the current function instance. If the process or
VM recycles midway through the execution, the function instance resumes from the previous await call.
More on this restart behavior later.
With normal functions, fanning out can be done by having the function send multiple messages to a
queue. However, fanning back in is much more challenging. You'd have to write code to track when the
queue-triggered functions end and store function outputs. The Durable Functions extension handles this
pattern with relatively simple code.
C# script
public static async Task Run(DurableOrchestrationContext ctx)
{
var parallelTasks = new List<Task<int>>();
await Task.WhenAll(parallelTasks);
The fan-out work is distributed to multiple instances of function F2, and the work is tracked by using a
dynamic list of tasks. The .NET Task.WhenAll API is called to wait for all of the called functions to finish.
Then the F2 function outputs are aggregated from the dynamic task list and passed on to the F3 func-
tion.
The automatic checkpointing that happens at the await call on Task.WhenAll ensures that any crash
or reboot midway through does not require a restart of any already completed tasks.
Durable Functions provides built-in APIs that simplify the code you write for interacting with long-run-
ning function executions. Once an instance is started, the extension exposes webhook HTTP APIs that
query the orchestrator function status. The following example shows the REST commands to start an
orchestrator and to query its status. For clarity, some details are omitted from the example.
> curl -X POST https://myfunc.azurewebsites.net/orchestrators/DoWork -H
"Content-Length: 0" -i
HTTP/1.1 202 Accepted
Content-Type: application/json
Location: https://myfunc.azurewebsites.net/admin/extensions/DurableTaskEx-
tension/b79baf67f717453ca9e86c5da21e03ec
{"id":"b79baf67f717453ca9e86c5da21e03ec", ...}
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 103
{"runtimeStatus":"Running","lastUpdatedTime":"2017-03-16T21:20:47Z", ...}
{"runtimeStatus":"Completed","lastUpdatedTime":"2017-03-16T21:20:57Z", ...}
Because the state is managed by the Durable Functions runtime, you don't have to implement your own
status tracking mechanism.
Even though the Durable Functions extension has built-in webhooks for managing long-running orches-
trations, you can implement this pattern yourself using your own function triggers (such as HTTP, queue,
or Event Hub) and the orchestrationClient binding. For example, you could use a queue message
to trigger termination. Or you could use an HTTP trigger protected by an Azure Active Directory authenti-
cation policy instead of the built-in webhooks that use a generated key for authentication.
// HTTP-triggered function to start a new orchestrator function instance.
public static async Task<HttpResponseMessage> Run(
HttpRequestMessage req,
DurableOrchestrationClient starter,
string functionName,
ILogger log)
{
// Function name comes from the request URL.
// Function input comes from the request content.
dynamic eventData = await req.Content.ReadAsAsync<object>();
string instanceId = await starter.StartNewAsync(functionName, eventDa-
ta);
Using Durable Functions, multiple monitors that observe arbitrary endpoints can be created in a few lines
of code. The monitors can end execution when some condition is met, or be terminated by the Dura-
bleOrchestrationClient, and their wait interval can be changed based on some condition (i.e.
exponential backoff.) The following code implements a basic monitor.
C# script
public static async Task Run(DurableOrchestrationContext ctx)
{
int jobId = ctx.GetInput<int>();
int pollingInterval = GetPollingInterval();
DateTime expiryTime = GetExpiryTime();
When a request is received, a new orchestration instance is created for that job ID. The instance polls a
status until a condition is met and the loop is exited. A durable timer is used to control the polling
interval. Further work can then be performed, or the orchestration can end. When the ctx.Curren-
tUtcDateTime exceeds the expiryTime, the monitor ends.
This pattern can be implemented using an orchestrator function. The orchestrator would use a durable
timer to request approval and escalate in case of timeout. It would wait for an external event, which
would be the notification generated by some human interaction.
C# script
public static async Task Run(DurableOrchestrationContext ctx)
{
await ctx.CallActivityAsync("RequestApproval");
using (var timeoutCts = new CancellationTokenSource())
{
DateTime dueTime = ctx.CurrentUtcDateTime.AddHours(72);
Task durableTimeout = ctx.CreateTimer(dueTime, timeoutCts.Token);
Result);
}
else
{
await ctx.CallActivityAsync("Escalate");
}
}
}
The durable timer is created by calling ctx.CreateTimer. The notification is received by ctx.Wait-
ForExternalEvent. And Task.WhenAny is called to decide whether to escalate (timeout happens
first) or process approval (approval is received before timeout).
An external client can deliver the event notification to a waiting orchestrator function using either the
built-in HTTP APIs or by using DurableOrchestrationClient.RaiseEventAsync API from another function:
public static async Task Run(string instanceId, DurableOrchestrationClient
client)
{
bool isApproved = true;
await client.RaiseEventAsync(instanceId, "ApprovalEvent", isApproved);
}
The technology
Behind the scenes, the Durable Functions extension is built on top of the Durable Task Framework, an
open-source library on GitHub for building durable task orchestrations. Much like how Azure Functions is
the serverless evolution of Azure WebJobs, Durable Functions is the serverless evolution of the Durable
Task Framework. The Durable Task Framework is used heavily within Microsoft and outside as well to
automate mission-critical processes. It's a natural fit for the serverless Azure Functions environment.
start in order to rebuild the local state. If during this replay the code tries to call a function (or do any
other async work), the Durable Task Framework consults with the execution history of the current orches-
tration. If it finds that the activity function has already executed and yielded some result, it replays that
function's result, and the orchestrator code continues running. This continues happening until the
function code gets to a point where either it is finished or it has scheduled new async work.
Language support
Currently C# (Functions v1 and v2), F# and JavaScript (Functions v2 only) are the only supported languag-
es for Durable Functions. This includes orchestrator functions and activity functions. In the future, we will
add support for all languages that Azure Functions supports. See the Azure Functions GitHub repository
issues list to see the latest status of our additional language support work.
Prerequisites
To complete this tutorial:
●● Install Visual Studio 20175 and ensure that the Azure development workload is also installed.
●● Make sure you have the latest Azure Functions tools6.
●● Verify you have the Azure Storage Emulator7 installed and running.
If you don't have an Azure subscription, create a free account before you begin.
3.
4. Use the settings specified in the table that follows the image.
5 https://azure.microsoft.com/downloads/
6 https://docs.microsoft.com/en-us/azure/azure-functions/functions-develop-vs#check-your-tools-version
7 https://docs.microsoft.com/en-us/azure/storage/common/storage-use-emulator
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 109
5.
2.
3. Verify Azure Function is selected from the add menu, and give your C# file a name. Press Add.
4. Select the Durable Functions Orchestration template and click Ok.
5.
A new durable function will be added to the app. Open the new file to view the contents. This durable
function is a simple function chaining example.
●● The RunOrchestrator method is associated with the orchestrator function. This function will start,
create a list, and add the result of three functions calls to the list. When the three function calls are
completed, it will return the list. The function it is calling is the SayHello method (default it will be
called “_Hello”).
●● The SayHello function will return a hello.
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 111
●● The HttpStart method describes the function that will start instances of the orchestration. It is
associated with an HTTP trigger that will start a new instance of the orchestrator and return back a
check status response.
Now that you've created your function project and a durable function, you can test it on your local
computer.
3.
4. Paste the URL for the HTTP request into your browser's address bar and execute the request. The
following shows the response in the browser to the local GET request returned by the function:
5.
6. The response is the initial result from the HTTP function letting us know the durable orchestration has
started successfully. It is not yet the end result of the orchestration. The response includes a few useful
URLs. For now, let's query the status of the orchestration.
7. Copy the URL value for statusQueryGetUri and pasting it in the browser's address bar and
execute the request.
8. The request will query the orchestration instance for the status. You should get an eventual response
that looks like the following. This shows us the instance has completed, and includes the outputs or
results of the durable function.
{
"instanceId": "d495cb0ac10d4e13b22729c37e335190",
"runtimeStatus": "Completed",
"input": null,
MCT USE ONLY. STUDENT USE PROHIBITED 112 Implement Azure functions
"customStatus": null,
"output": [
"Hello Tokyo!",
"Hello Seattle!",
"Hello London!"
],
"createdTime": "2018-11-08T07:07:40Z",
"lastUpdatedTime": "2018-11-08T07:07:52Z"
}
3.
4. When you enable Run from Zip, your function app in Azure is run directly from the deployment
package.
5. Caution: When you choose Select Existing, all files in the existing function app in Azure are overwrit-
ten by files from the local project. Only use this option when republishing updates to an existing
function app.
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 113
6. If you haven't already connected Visual Studio to your Azure account, select Add an account….
7. In the Create App Service dialog, use the Hosting settings as specified in the table below the image:
8.
11.
3. Paste this new URL for the HTTP request into your browser's address bar. You should get the same
status response as before when using the published app.
Scenario overview
In this sample, the functions upload all files under a specified directory recursively into blob storage. They
also count the total number of bytes that were uploaded.
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 115
It's possible to write a single function that takes care of everything. The main problem you would run into
is scalability. A single function execution can only run on a single VM, so the throughput will be limited
by the throughput of that single VM. Another problem is reliability. If there's a failure midway through, or
if the entire process takes more than 5 minutes, the backup could fail in a partially-completed state. It
would then need to be restarted.
A more robust approach would be to write two regular functions: one would enumerate the files and add
the file names to a queue, and another would read from the queue and upload the files to blob storage.
This is better in terms of throughput and reliability, but it requires you to provision and manage a queue.
More importantly, significant complexity is introduced in terms of state management and coordination if
you want to do anything more, like report the total number of bytes uploaded.
A Durable Functions approach gives you all of the mentioned benefits with very low overhead.
The functions
This lesson explains the following functions in the sample app:
●● E2_BackupSiteContent
●● E2_GetFileList
●● E2_CopyFileToBlob
The following sections explain the configuration and code that are used for C# scripting. The code for
Visual Studio development is shown at the end of the lesson.
C#
#r "Microsoft.Azure.WebJobs.Extensions.DurableTask"
if (string.IsNullOrEmpty(rootDirectory))
{
throw new ArgumentException("A directory path is required as an
input.");
}
if (!Directory.Exists(rootDirectory))
{
throw new DirectoryNotFoundException($"Could not find a directory
named '{rootDirectory}'.");
}
await Task.WhenAll(tasks);
module.exports = df.orchestrator(function*(context){
const rootDirectory = context.df.getInput();
if (!rootDirectory) {
throw new Error("A directory path is required as an input.");
}
// wait for all the Backup Files Activities to complete, sum total
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 117
bytes
const results = yield context.df.Task.all(tasks);
const totalBytes = results.reduce((prev, curr) => prev + curr, 0);
// return results;
return totalBytes;
});
C#
#r "Microsoft.Azure.WebJobs.Extensions.DurableTask"
#r "Microsoft.Extensions.Logging"
return files;
}
readdirp(
{root: rootDirectory, entryType: 'all'},
function (fileInfo) {
if (!fileInfo.stat.isDirectory()) {
allFilePaths.push(fileInfo.fullPath);
}
},
function (err, res) {
if (err) {
throw err;
}
The JavaScript implementation of E2_GetFileList uses the readdirp module to recursively read the
directory structure.
Note: You might be wondering why you couldn't just put this code directly into the orchestrator function.
You could, but this would break one of the fundamental rules of orchestrator functions, which is that they
should never do I/O, including local file system access.
The function.json file for E2_CopyFileToBlob is similarly simple:
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 119
{
"bindings": [
{
"name": "filePath",
"type": "activityTrigger",
"direction": "in"
}
],
"disabled": false
}
The C# implementation is also pretty straightforward. It happens to use some advanced features of Azure
Functions bindings (that is, the use of the Binder parameter), but you don't need to worry about those
details for the purpose of this walkthrough.
C#
#r "Microsoft.Azure.WebJobs.Extensions.DurableTask"
#r "Microsoft.Azure.WebJobs.Extensions.Storage"
#r "Microsoft.Extensions.Logging"
#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Blob;
return byteCount;
MCT USE ONLY. STUDENT USE PROHIBITED 120 Implement Azure functions
blobService.createBlockBlobFromStream(container, blobPath,
readStream, stats.size, function (error) {
if (error) {
throw error;
}
context.done(null, stats.size);
});
});
});
};
The implementation loads the file from disk and asynchronously streams the contents into a blob of the
same name in the “backups” container. The return value is the number of bytes copied to storage, that is
then used by the orchestrator function to compute the aggregate sum.
MCT USE ONLY. STUDENT USE PROHIBITED
Implement Durable Functions 121
Note: This is a perfect example of moving I/O operations into an activityTrigger function. Not only
can the work be distributed across many different VMs, but you also get the benefits of checkpointing
the progress. If the host process gets terminated for any reason, you know which uploads have already
completed.
"D:\\home\\LogFiles"
Note: The HttpStart function that you are invoking only works with JSON-formatted content. For this
reason, the Content-Type: application/json header is required and the directory path is encod-
ed as a JSON string. Moreover, HTTP snippet assumes there is an entry in the host.json file which
removes the default api/ prefix from all HTTP trigger functions URLs. You can find the markup for this
configuration in the host.json file in the samples.
This HTTP request triggers the E2_BackupSiteContent orchestrator and passes the string D:\home\
LogFiles as a parameter. The response provides a link to get the status of the backup operation:
HTTP/1.1 202 Accepted
Content-Length: 719
Content-Type: application/json; charset=utf-8
Location: http://{host}/admin/extensions/DurableTaskExtension/instances/
b4e9bdcc435d460f8dc008115ff0a8a9?taskHub=DurableFunction-
sHub&connection=Storage&code={systemKey}
(...trimmed...)
Depending on how many log files you have in your function app, this operation could take several
minutes to complete. You can get the latest status by querying the URL in the Location header of the
previous HTTP 202 response.
GET http://{host}/admin/extensions/DurableTaskExtension/instances/b4e9bdc-
c435d460f8dc008115ff0a8a9?taskHub=DurableFunctionsHub&con-
nection=Storage&code={systemKey}
{"runtimeStatus":"Running","input":"D:\\home\\LogFiles","output":null,"cre-
atedTime":"2017-06-29T18:50:55Z","lastUpdatedTime":"2017-06-29T18:51:16Z"}
MCT USE ONLY. STUDENT USE PROHIBITED 122 Implement Azure functions
In this case, the function is still running. You are able to see the input that was saved into the orchestrator
state and the last updated time. You can continue to use the Location header values to poll for comple-
tion. When the status is “Completed”, you see an HTTP response value similar to the following:
HTTP/1.1 200 OK
Content-Length: 152
Content-Type: application/json; charset=utf-8
{"runtimeStatus":"Completed","input":"D:\\home\\LogFiles","out-
put":452071,"createdTime":"2017-06-29T18:50:55Z","lastUpdated-
Time":"2017-06-29T18:51:26Z"}
Now you can see that the orchestration is complete and approximately how much time it took to com-
plete. You also see a value for the output field, which indicates that around 450 KB of logs were upload-
ed.
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;
namespace VSSample
{
public static class BackupSiteContent
{
[FunctionName("E2_BackupSiteContent")]
public static async Task<long> Run(
[OrchestrationTrigger] DurableOrchestrationContext backupCon-
text)
{
string rootDirectory = backupContext.GetInput<string>()?.
Trim();
if (string.IsNullOrEmpty(rootDirectory))
{
rootDirectory = Directory.GetParent(typeof(BackupSiteCon-
tent).Assembly.Location).FullName;
}
await Task.WhenAll(tasks);
[FunctionName("E2_GetFileList")]
public static string[] GetFileList(
[ActivityTrigger] string rootDirectory,
ILogger log)
{
log.LogInformation($"Searching for files under '{rootDirecto-
ry}'...");
string[] files = Directory.GetFiles(rootDirectory, "*",
SearchOption.AllDirectories);
log.LogInformation($"Found {files.Length} file(s) under {rootDi-
rectory}.");
return files;
}
[FunctionName("E2_CopyFileToBlob")]
public static async Task<long> CopyFileToBlob(
[ActivityTrigger] string filePath,
Binder binder,
ILogger log)
{
long byteCount = new FileInfo(filePath).Length;
Stream>(
new BlobAttribute(outputLocation, FileAccess.Write)))
{
await source.CopyToAsync(destination);
}
return byteCount;
}
}
}
MCT USE ONLY. STUDENT USE PROHIBITED
Review questions 125
Review questions
Module 4 review questions
Azure Functions consumption plans
Azure Functions run within a service plan. What service plans support Azure Functions and how to they
differ?
Durable Functions
The primary use case for Durable Functions is simplifying complex, stateful coordination problems in
serverless applications. Function chaining and Fan-in/fan-out are two of the typical application patterns
that can benefit from Durable Functions.
Can you briefly describe how they operate?