azure tips and tricks - download.microsoft.comthe azure platform. in this volume, like i did in...

97
Azure Tips and Tricks azuredev.tips Volume 2 ISBN 978-1-7327041-3-8

Upload: others

Post on 13-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Azure Tips and Tricks azuredev.tips

Volume 2ISBN 978-1-7327041-3-8

Page 2: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,
Page 3: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Introduction

Welcome to volume 2 of Azure Tips & Tricks. If you haven’t read volume 1 yet, that’s okay! These eBooks can be enjoyed in any order. As I’ve been presenting topics on Azure, I’ve found that most folks aren’t aware of how powerful the Azure platform really is. I often get asked, “How did you do that?” I address that question with over 175 tips in the form of blog posts, videos, conference talks, and now a series of eBooks that span the entire universe of the Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity, AI + Machine Learning, and Containers. Before we launch, you’ll notice my pixelated form throughout these pages. These graphics represent:

You can stay up to date with the latest Azure Tips and Tricks at:

• Blog - azuredev.tips • Videos - videos.azuredev.tips• eBook - ebook.azuredev.tips• Survey - survey.azuredev.tips I hope you enjoy reading this eBook and learning about features and tools that help you get the most out of the Azure platform.

Thanks,Michael Crump (@mbcrump)

Something I found interesting and you

may too.

Additional resources to get the most out

of this tip.

A key takeaway from the tip.

Hi, folks!

Page 4: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Table of Contents

1

3

4

2

AZURE APP SERVICE

AI + MACHINE LEARNING

CONTAINERS

PRODUCTIVITY

Page 5: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Azure App Service

You’re probably aware that Azure App Service is a comprehensive platform for hosting your web applications, mobile back ends, and REST APIs. What you may not be aware of are all of the features that make building, testing, debugging, and deploying your app smoother and easier. In this section, you’ll learn several tricks to enhance your experience with Azure App Service, including how to set up email alerts, how to create locks to prevent changes to your resources, how to easily deploy an app using only the Azure CLI, and more.

Return

Page 6: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Alerts allow you to receive an alert based on monitoring metrics for your Azure App Service. You can be notified in a variety of ways, such as the Azure Portal, Webhooks, or Email. In this tip, we’ll set up an alert based on a 404-error message and send it to ourselves via email.

In order to take advantage of the alert feature, you’ll need to log in to your Azure account and go to your App Service that you created. When you look under Monitor you will see Alert. Open it and scroll to the bottom of the page where you will see a link to classic alerts. Follow that link and click Add metric alert (classic).

Note the following options:

• Name — You’ll need to give it a unique name• Description (optional) — Provide a description of the

alert. Though this is optional, I’d recommend adding one• Metric — You can set an alert to trigger based on a

particular metric or event

Setting Up Email Alerts with Azure App Service

Metric vs. Event A metric would be something

like, “If we receive 5 or more Http

Server Errors over a 5-minute period

then trigger an alert”. An Event

would be if something Started, Stopped, Deleted – or did all of the above – and our

App Service would send an alert.

Page 7: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Quick Tip You can type help from the console window for

a list of available commands.

In this example, we are going to trigger an alert based on a metric. Go ahead and select a resource and provide a Name and Description. Select Http 404 for the metric with the Greater than condition set for 1 threshold and Over the last 5 minutes. Go ahead and add a checkmark for the Notify via email and provide an email address.

Press OK to save the alert.

Head back to your website (*.azurewebsites.net) and enter an invalid page to trigger a 404 error. In my case, I entered http://<appname>.azurewebsites.net/TESTING/. It should throw an error unless you have a custom error page defined.Server Error in ‘/’ Application.

Server Error in ‘/’ Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /TESTING/

Page 8: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Take a look at your email and you should see an email from Azure that looks like the following:

Go back into the Azure Portal, search for Alerts (classic), and find the alert that you just created. You can see when it was last triggered, as well as other pertinent information. If you click on the alert, you’ll see that you can set up additional functionality, such as running a logic app when this alert is triggered. Note that you can also set up this functionality when creating the Alert.

Page 9: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Now that you know how to set up an alert triggered by a given condition in your monitoring data, you’re probably wondering if there’s a simple way to proactively detect and diagnose performance issues in your web apps and web services. Good news – there is, and it’s called Application Insights.

I’ll walk you through adding Application Insights to an ASP.NET MVC application. To start, log in to your Azure account and go to your App Service that you created. Look under Settings and you will see Application Insights. Open it and make sure the Enable box is selected, or click Turn on site extension.

Using Application Insights with Azure App Service

Page 10: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Scroll down and you’ll see that you can instrument your ASP.NET app and choose to turn options off or leave them on. Click on Apply and you will see the following prompt:

Click Yes to restart your app. Once the restart is complete, visit your app and refresh two or three times. Then go back and take a look at the live stream. I’ve included a sample on the next page:

Page 11: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

public ActionResult ThrowNewError() { throw new InvalidOperationException(“The app just threw an error!”); }

It is working as expected, but let’s add an error into our application to see what happens and what we can learn about the error using Application Insights. Go to your appname/Controllers/HomeController.cs and add the following code:

Deploy your app that you made changes to and go back to your site. Depending on where you placed it, you can invoke the code by going to *.azurewebsites.net/Home/ThrowNewError. If you switch back over to Application Insights you’ll see the errors are being reported.

Page 12: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You can drill down deeper by clicking on Open in Application Insights. From here you can see how many Failed Requests were reported.

You can even identify what URL was called to trigger the error.

Page 13: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

So far we’ve been focused on issues in Azure App Service — specifically, how to identify them and what to do about them. But what if everything is going well and we want to maintain that state by making sure critical resources aren’t accidentally changed or deleted? That’s where locks come in.

A quick way to add Application

Insights to your ASP.NET

Framework Web Visual Studio project is by

right-clicking the project and then adding Configure

Application Insights. This will walk you through the

steps to quickly add Application Insights to your

project and set up your Account. You

can learn more about that by

clickinghere.

Let’s walk through creating a lock together. Log in to your Azure account, go to your App Service that you created, and look under Settings. There you will see Locks. Open it and click Add, and you’ll see the following:

Prevent Changes to Resources in Azure App Service

Locks allow you to prevent changes to a subscription or resource. They

also prevent other users from

accidentally deleting or modifying critical

resources.

Page 14: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You’ll want to provide the following information. Only the Lock type is required, but I recommend you include the additional information as well:• Name — Give it any name that you want• Lock Type — This can be Read-only or Delete• Notes — A description of the Lock

Fill out the form and press OK as shown below.

You can delete the lock by clicking on the ellipsis.

Protecting your app from unauthorized changes is just one way to make sure it continues running smoothly. If you’re using the Basic or Standard plan in Azure App Service, an-other way to keep your app healthy is by activating Always On, which is covered in the next tip.

Delete means that you can’t delete the resource, but your users can still read

and modify it. Read-only means users can read a

resource, but they can’t delete or

modify the resource.

No Portal, No Problem!

If you don’t want to use the portal, then you can also

use Templates, PowerShell, Azure

CLI or the REST API. The choice is yours! You can learn more about those options

here.

Page 15: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Have you ever noticed that your Azure web app loads slowly after publishing or restarting, but then when you refresh with F5 it loads normally again? Wonder why? By default, web apps are unloaded after they have been idle. It is recommended that you enable Always On by going into the Application Settings for the App Service in the portal and activate Always On. This will keep your web app hy-drated and responsive.

Keep in mind that you will not be able to turn this feature on when using the free version of Azure App Service. It is only available in Basic or Standard plans.

One truly great aspect of Azure App Service is that you have the ability to do things different ways. While I love working with the Azure Portal, or even Visual Studio, it is sometimes nice to do everything from the command line.

Keep Your Azure Web App Hydrated and Responsive

If your app runs continuous WebJobs

or runs WebJobs triggered using a CRON expression, you should enable Always On so the web jobs will run

reliably.

Page 16: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Note: You’ll see a JSON response after each “az” command

Next we’ll need a resource group. I’m going to put mine in the West US.

az group create --name StaticResourceGroup --location “West US”

We’ll also need an Azure App Service Plan. I’ll use the free one for this example:

ticResourceGroup --sku FREE

Now we’ll create an Azure Web App and deploy it using local Git.

az webapp create --name MyQuizApplication --re-source-group StaticResourceGroup --plan StaticAppService-Plan --deployment-local-git

Look for the following JSON string and make note of the URL:

“deploymentLocalGitUrl”: https://[email protected]/MyQuizApplication.git

In this tutorial I’ll be using the Azure CLI and BASH to deploy an Azure Web App using only the command line.

Create a folder by typing “mkdir webapp” and then “cd webapp”.

Next, run the following command: git clone https://github.com/mbcrump/jsQuizEngine.git

Change your working directory to jsQuizEngine/src. Now we’ll need to create a deployment user that can deploy the web app through Git:

Deploy an Azure Web App Hosted on GitHub Using Only the Azure CLI

az webapp deployment user set --user-name mbcrump --password ArEALLYlONGpW123

az group create --name StaticResourceGroup --location “West US”

az appservice plan create --name StaticAppServicePlan --resource-group StaticResourceGroup --sku FREE

“deploymentLocalGitUrl”: https://[email protected]/MyQuizApplication.git

az webapp create --name MyQuizApplication --resource-group Stat-icResourceGroup --plan StaticAppServicePlan --deployment-lo-cal-git

Page 17: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Next, we’ll need to add Azure to our local Git repo.

git remote add azure https://[email protected]/MyQuizApplication.git

Push the changes and enter your password when prompted.

git push azure master

Now you can navigate to our new site <name>.azurewebsites.net

Once you get a hang of using the CLI, these steps become natural, and you’ll find that there are a number of actions you can perform quickly and easily using the command line.

git push azure master

git remote add azure https://[email protected]/MyQuizApplication.git

Page 18: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Deployment Slots are a feature of Azure App Service. They are live apps with their own hostnames. You can create different slots for your application (for example: Dev, Test, or Stage). The Production slot is the slot where your live app resides. With deployment slots, you can validate app changes in staging before swapping with your production slot to make the changes live. In this tip, we’ll work with deployment slots using the command line.

Keep in mind that you will not be able to turn this feature on when using the free version of Azure App Service. It is only available in Standard or Premium plans.Open Command Prompt or Terminal and enter following command: az login

To list deployment slots in an Azure App Service, execute the following command:

az webapp deployment slot list -n “web-app-name” -g “resource-group-name”

To create a new deployment slot in an Azure App Service, execute the following command: az webapp deployment slot create -n “web-app-name” -g “resource-group-name”-s “deployment-slot-name”

To swap a deployment slot in an Azure App Service, execute the following command: az webapp deployment slot swap -n “web-app-name” -g “resource-group-name”-s “source-slot-name” --target-slot “target-slot”

To delete a deployment slot in an App Service, execute the following command: az webapp deploymevnt slot create “web-app-name” -g “resource-group-name”-s “deployment-slot-name”

Now you can deploy an app using CLI. Did you know you can also deploy a site to Azure Web Apps or Azure Functions from a zip file? I’ll walk you through that method in the next tip.

Deployment Slots for Web Apps Using the Azure CLI

`

You can read more about working with deployment slots

here.

Although Azure portal is a great way to perform most of the Azure-related

actions, sometimes using the CLI is

the easiest. Listing, creating, swapping,

and deleting deployment slots

are all as simple as entering a one-line command using the

Azure CLI.

az webapp deployment slot list -n “web-app-name” -g “resource-group-name”

az webapp deployment slot list -n “web-app-name” -g “resource-group-name”

slot swap -n “web-app-name” -g “resource-group-name”-s “source-slot-name” --target-slot “target-slot”

create “web-app-name” -g “resource-group-name”-s “deployment-slot-name”

Page 19: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

With Run-From-Zip there is no longer a deployment step that copies the files to wwwroot, such as git, ftp, etc. Instead, the zip file that you point to in your App Settings (from Azure App Service) that gets mounted on wwwroot as read-only.

To get started:

Download and open Azure Storage Explorer, create a blob storage container and upload your compressed website as a zip file.

Select Generate SAS Signature as shown below:

Use Run-From-Zip to deploy a site to Azure Web Apps or Functions

You can clone this sample website

for testing - https://github.com/mbcrump/

jsQuizEngine.git

Page 20: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Hit Create and then Copy.

Now head back over to the Azure Portal and select your existing App Service. Scroll down to Setting, then Application Settings, and create a new key/value pair. Give it a name of WEBSITE_RUN_FROM_ZIP and point it to your zip file location that we generated earlier.

Mine looks like this: WEBSITE_RUN_FROM_ZIP=https://REMOVED.blob.core.windows.net/michael-test/MichaelSampleApp.zip?st=2018-06-24T22%3A16%3A40Z&se=2018-06-25T22%3A16%3A40Z&sp=rl&sv=2017-07-29&sr=b&sig=01h%3D

Wait a few seconds and you should see your site that was deployed via a zip file.

WEBSITE_RUN_FROM_ZIP=https://REMOVED.blob.core.windows.net/michael-test/MichaelSampleApp.zip?st=2018-06-24T22%3A16%3A40Z&se=2018-06-25T22%3A16%3A40Z&sp=rl&sv=2017-07-29&sr=b&sig=01h%3D

Page 21: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Azure Productivity

Everyone wants to be more productive, and Azure offers a number of tools to help you achieve that goal. In this section, I share my top tips for increasing your productivity with Azure, including how to easily use tools like ARM Templates, Azure Advisor, and other Azure dashboards.

Return

Page 22: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

ARM Templates Demystified

If you have trouble with ARM templates, you’re not alone. I’ve heard feedback that people don’t understand them, don’t know how to use them, or have found them too hard to use. This feedback calls for demystification. In this tip, I’m going to explain what ARM templates are and how you can easily create and use them.

First off, the name might be confusing. ARM stands for Azure Resource Manager. In this context, it doesn’t have anything to do with CPU architecture that is used in phones and tablets, which would be an honest misunderstanding. In Azure, we refer to your stuff—such as virtual machines, databases, storage accounts, containers, web apps, bots, etc.—as “resources”. Azure Resource Manager is how you organize all your resources.

You have probably found that you create many related items together in Azure. For example, a web app and a database will be contained in a single resource group. But what if you have to do this frequently for many different clients? Wouldn’t it be nice to have an easy way to keep track of all the repeatable groups of resources you’re creating for people? Good news—this is exactly what ARM templates do!

Page 23: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

When you need an easy way to repeat infrastructure deployments on Azure, ARM templates are the way to go and will save you a lot of time. For example, if you ever need to share your infrastructure with other people—like for open source projects, blogs, tutorials, or documentation—ARM templates will be a lifesaver and will let your readers and users replicate what you did. If you just need a way to keep track of what you deployed on Azure, ARM templates are a great way to help you stay organized.

ARM templates are JSON files that act like blueprints for the related resources you want to deploy together. You’ll also hear this called “infrastructure as code,” which is geek speak for being able to upload your infrastructure notes to GitHub if you want to. An ARM template is a structured format for keeping track of your Azure infrastructure that also gives you superpowers.

The example on the next page hows an ARM template that creates a Notification Hub. You’ll see that it contains things that the deployment needs, such as Name, Location, etc. We’ll go into greater detail on this later!

Real-World Scenarios for Using ARM Templates

An ARM Template Is Just a JSON File

One of the most useful ARM template

superpowers is the ability to use

templates to automate your infrastructure

deployments, because Azure knows how to

read them.

Page 24: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

{ “$schema”: “https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json”, “contentVersion”: “1.0.0.0”, “parameters”: { “namespaceName”: {

“type”: “string”, “metadata”: { “description”: “The name of the Notification Hubs namespace.” } }, “location”: {

“type”: “string”, “defaultValue”: “[resourceGroup().location]”, “metadata”: { “description”: “The location in which the Notification Hubs resources should be deployed.” } } }, “variables”: { “hubName”: “MyHub” }, “resources”: [ { “apiVersion”: “2014-09-01”, “name”: “[parameters(‘namespaceName’)]”, “type”: “Microsoft.NotificationHubs/namespaces”, “location”: “[parameters(‘location’)]”, “kind”: “NotificationHub”, “resources”: [ { “name”: “[concat(parameters(‘namespaceName’), ‘/’, variables(‘hubName’))]”, “apiVersion”: “2014-09-01”, “type”: “Microsoft.NotificationHubs/namespaces/notificationHubs”, “location”: “[parameters(‘location’)]”, “dependsOn”: [ “[parameters(‘namespaceName’)]” ] } ] } ]}

Page 25: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You can make an ARM template in Visual Studio, in Visual Studio Code, or in the Azure portal. The last way is probably the easiest since it walks you through the process.

To create an ARM template in the Azure portal, simply start creating a resource the way you normally would: by clicking on Create Resource on your Azure Portal Dashboard. Now select what you’d like to create. I’m going to create a Web App for the purpose of this example.

Look at the bottom of this page and you’ll see Automation options:

You’re probably wondering, “What does that unassuming Automation options link do?” You might never have noticed it before, or been afraid to mess with it. The time has come for you to click that link and get on the road to creating an ARM template for your resource.

Creating an ARM Template

`

If you want to learn about creating ARM templates in Visual Studio you can go here, and if you

want to use Visual Studio Code you can

go here.

You’ve already seen that you can automate

deploying a web app (and many

other resources), but did you know that you also copy

configuration information like app settings with your ARM template? It’s

true!

Page 26: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

After you click Automation options, this is what you will see:

As I’ve mentioned before, the ARM template to create a web app (or any other Azure resource) is simply a JSON file with multiple values describing how your web app is going to be deployed.

Create Static App Settings for Your Azure App Service

To make things as easy as possible, let’s assume for now that you want to add the exact same settings every time you deploy your web app template.

Go to Deploy, then click Edit Template and paste the following settings fragment to overwrite your template’s resource section. You could, of course, add as many keys as your web app needs.

Make note that we are adding 3 names and 3 values for MyFirstName, MyLastName, and MySSN.

Page 27: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Press Save and ensure the BASICS and SETTINGS fields are filled out. Agree to the terms and click the Purchase button.

Quick Tip: If it says failure to deploy, then give it another shot. I have had this happen, possibly because I use

the Preview.

“resources”: [ { “apiVersion”: “2016-03-01”, “name”: “[parameters(‘name’)]”, “type”: “Microsoft.Web/sites”, “properties”: { “name”: “[parameters(‘name’)]”, “siteConfig”: { “appSettings”: [ { “name”: “MyFirstName”, “value”: “Michael” }, { “name”: “MyLastName”, “value”: “Crump” }, { “name”: “MySSN”, “value”: “355-643-3356” } ] }, “serverFarmId”: “[concat(‘/subscriptions/’, parameters(‘subscriptionId’),’/resourcegroups/’, parameters(‘serverFarmResourceGroup’), ‘/providers/Microsoft.Web/serverfarms/’, parameters(‘hostingPlanName’))]”, “hostingEnvironment”: “[parameters(‘hostingEnvironment’)]” }, “location”: “[parameters(‘location’)]” }],

Page 28: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Your Azure App Settings (for MyFirstName, MyLastName, and MySSN) will now be deployed.

After deployment, navigate to your App Service and go to Application Settings. You’ll see your site deployed along with the settings (for MyFirstName, MyLastName, and MySSN) that we specified earlier.

Page 29: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You’ve seen that you can automate deploying static configuration information like app settings with your ARM template, but what about providing parameters that allow end-users to input values before deployment? You can do that, too!

Use Dynamic App Settings for Your Azure App Service

Go ahead and search for Templates inside the Azure Portal and click Add to create a new one. Enter a name and a description on the ARM Template.

We want to have dynamic settings that are customizable every time you deploy your web app instead of having them be the same each time, you just need to add the parameter values for what you want to your ARM template.Below is a sample of three values (FirstNameValue, LastNameValue and SSNValue) that we hard-coded previously:

Page 30: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

FirstNameValue”: { “type”: “string” }, “LastNameValue”: { “type”: “string” }, “SSNValue”: { “type”: “string” },

We’ll add the same parameters called FirstNameValue , LastNameValue and SSNValue to the parameters collection of the template. From now on, every time you deploy this template, you will be prompted to enter a value for each one.

“siteConfig”: { “appSettings”: [ { “name”: “MyFirstName”, “value”: “[parameters(‘FirstNameValue’)]” }, { “name”: “MyLastName”, “value”: “[parameters(‘LastNameValue’)]” }, { “name”: “MySSN”, “value”: “[parameters(‘SSNValue’)]” } ] }

Our full template file looks like this:

“FirstNameValue”: { “type”: “string” }, “LastNameValue”: { “type”: “string” }, “SSNValue”: { “type”: “string” },

“siteConfig”: { “appSettings”: [ { “name”: “MyFirstName”, “value”: “[parameters(‘FirstNameValue’)]” }, { “name”: “MyLastName”, “value”: “[parameters(‘LastNameValue’)]” }, { “name”: “MySSN”, “value”: “[parameters(‘SSNValue’)]” } ]}

{ “$schema”: “https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#”, “contentVersion”: “1.0.0.0”, “parameters”: { “appServiceName”: { “type”: “string”, “minLength”: 1, “maxLength”: 10 }, “appServicePlanName”: { “type”: “string”, “minLength”: 1

Page 31: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

}, “FirstNameValue”: { “type”: “string” }, “LastNameValue”: { “type”: “string” }, “SSNValue”: { “type”: “string”` }, “appServicePlanSkuName”: { “type”: “string”, “defaultValue”: “S1”, “allowedValues”: [ “F1”, “D1”, “B1”, “B2”, “B3”, “S1”, “S2”, “S3”, “P1”, “P2”, “P3”, “P4” ], “metadata”: { “description”: “Describes plan’s pricing tier and capacity. Check details at https://azure.microsoft.com/en-us/pricing/details/app-service/” } } }, “variables”: { “appHostingPlanNameVar”: “[concat(parameters(‘appServicePlanName’),’-apps’)]” }, “resources”: [ {

Page 32: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

“name”: “[variables(‘appHostingPlanNameVar’)]”, “type”: “Microsoft.Web/serverfarms”, “location”: “[resourceGroup().location]”, “apiVersion”: “2015-08-01”, “sku”: { “name”: “[parameters(‘appServicePlanSkuName’)]” }, “dependsOn”: [], “tags”: { “displayName”: “appServicePlan” }, “properties”: { “name”: “[variables(‘appHostingPlanNameVar’)]”, “numberOfWorkers”: 1 } }, { “name”: “[parameters(‘appServiceName’)]”, “type”: “Microsoft.Web/sites”, “location”: “[resourceGroup().location]”, “apiVersion”: “2015-08-01”, “dependsOn”: [ “[resourceId(‘Microsoft.Web/serverfarms’, variables(‘appHostingPlanNameVar’))]” ], “tags”: { “[concat(‘hidden-related:’, resourceId(‘Microsoft.Web/serverfarms’, variables(‘appHostingPlanNameVar’)))]”: “Resource”, “displayName”: “webApp” }, “properties”: { “name”: “[parameters(‘appServiceName’)]”, “serverFarmId”: “[resourceId(‘Microsoft.Web/serverfarms’, variables(‘appHostingPlanNameVar’))]”, “siteConfig”: { “appSettings”: [ { “name”: “MyFirstName”, “value”:

Page 33: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

If you save the template, the next time you deploy resources using this ARM template, you will be required to put in a new value for the First Name, Last Name, and SSN that will be used in your application settings.

“[parameters(‘FirstNameValue’)]” }, { “name”: “MyLastName”, “value”: “[parameters(‘LastNameValue’)]” }, { “name”: “MySSN”, “value”: “[parameters(‘SSNValue’)]” } ] } } } ], “outputs”: {}}

Page 34: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

After deployment, you can check your App Settings:

ARM templates can save you a lot of time and energy. Another way to save time and energy in Azure is by applying best practices across your Azure resources. Wouldn’t it be cool if you had your own advisor to review your resources and provide recommendations that are specific to you? In a way, you do! It’s called the Azure Advisor dashboard.

Page 35: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Get the most out of Azure Advisor

Azure Advisor is a simple dashboard that helps you implement best practices across your Azure resources. I’ll walk you through the types of recommendations it provides and show you how easy it is to implement them.

Advisor looks at the Azure resources in your subscriptions and comes up with recommendations that fall into these categories:

• High Availability — Suggestions that are important for business-critical and production-worthy applications

• Security — Advice to help you prevent and detect threats or security vulnerabilities

• Performance — Recommendations that are tailored to the configrations of your resources and that compile together items from SQL Database Advisor, Redis Cache Advisor, and other best practices

• Cost — Information on past usage of things like VMs generates cost-saving recommendations, as well as sizing and other resource configurations that affect cost

Inside the Azure portal, search for Advisor and open the Advisor recommendations dashboard. At first glance, we can see Advisor has a few recommendations for me: two for high availability, three for security, and one for performance. If you’re following along in your own Azure subscription, chances are good you have some recommendations available on the Advisor dashboard as well.

At the bottom of the screen, you’ll notice that you can export

the recommendations to PDF or CSV files

— which is great for mangers to prove you need to work on this

task. It is very cool that Azure is watching my back “out of the box”!

Page 36: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Let’s take a look at the High Availability recommendations I have. Click on the High Availability box in the dashboard.

You now see more information about the recommendations, including the impact (high, medium, low), description, potential benefits, impacted resources, and the last time the recommendation was updated.

Click on an item in the recommendation list to learn the complete details.

Page 37: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

The recommendation I selected was “Enable Soft Delete to protect blob data.” In my case, I do think it’s a good idea to turn that on for one of the two storage accounts it lists. I clicked on the “Enable Soft Delete to protect blob data” link to get to where I can turn that feature on. Isn’t that cool? Not only did it tell me it was a good idea, but it walked me through what I needed to do to follow the recommendation!

Once I clicked Enabled, I set the Retention policies to 30 days and clicked Save. That’s it! Now I can use the breadcrumbs at the top to go back to the Enable Soft Delete list.

Next, I want to select Postpone for the other storage account.

Since I know I don’t want soft delete enabled on this account, I can postpone this recommendation to Never and click the Postpone button so it doesn’t make the recommendation next time I take a look at Advisor.

If you click on the Security tab and drill into a recommendation, you’ll see an actual secure score. This allows you to quickly see which security recommendations pose the greatest threat.

Page 38: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

To sum it up, the flow for all four categories of recommendations is:1. Select the recommendation category in the dashboard.2. Select the individual recommendation.3. If you want to implement the recommendation, select the recommendation item and Advisor will walk you through the steps you need to implement it.4. If you want to ignore the recommendation, you can postpone (or, for security recommendations, use “dismiss”) it.

Implementing best practices is that easy!

As you explore new ways to be more productive in Azure, you may find yourself referring to the Azure Activity Log. In the next tip, I’ll walk you through archiving the Activity Log so you can stay organized while maintaining access to important data.

Archive the Azure Activity Log

The Azure Activity Log is a subscription log that provides insight into subscription-level events that have occurred in Azure. This includes a range of data, from Azure Resource Manager operational data to updates on Service Health events. You may want to Archive the Azure Activity Log if you want to retain your Activity Log longer than 90 days. In this tip, I’ll show you how to archive it with just a couple of clicks.

In the portal, search for the Activity Log service. Now click on the Export to Event Hub button.

You may want to retain the data in

your Azure Activity Log indefinitely for

audit, static analysis, or backup purposes. When you archive the Azure Activity log, you maintain

full control over the retention policy.

Page 39: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Select a Subscription and Region and place a checkmark in the Export to an Azure Storage Account box. Now use the slider to select a number of days (0 to 365) for which Activity Log events should be kept in your storage account. You can also select 0 to save it indefinitely. Once you have settled on a number, click Save.

Now your logs are safe and sound for the time you specified.

Another way you can optimize your productivity in Azure is by using Azure dashboards. Once upon a time, you had to use a separate tool like Azure Resource Explorer to get data from an Azure dashboard. Now you have the ability to download or upload an existing Azure dashboard with just a couple of clicks.

Page 40: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Easily Upload and download Azure dashboards

In this tip, I’ll show you how easy it is to download or upload an Azure dashboard. Previously, you had to use a separate tool like Azure Resource Explorer to get this data. You’ll see Download and Upload options on your Azure Dashboard as shown below:

When you download the file it will be in a JSON format. Below is a short snippet that lists my Linux VM that is on my portal page.

“1”: {“position”: { “x”: 4, “y”: 0, “colSpan”: 4, “rowSpan”: 6},“metadata”: { “inputs”: [ { “name”: “queryInputs”, “value”: { “metrics”: [ { “resourceId”: “/subscriptions/d1ecc7ac-c1d8-40dc-97d6-2507597e7404/resourcegroups/crumplinux-rg/providers/microsoft.compute/virtualmachines/crumplinux”, “name”: “Disk Read Bytes” },

Page 41: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Note the colSpan and rowSpan values here. You could edit this to change the colSpan and rowSpan to be a smaller tile by changing them to:

Now save the file and upload it and you have your new tile:

Keep in mind that you can also do more sophisticated things such as use this to programmatically create dashboards by using Azure Resource Manager APIs.

“colSpan”: 2, “rowSpan”: 2

Page 42: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

AI + Machine Learning

Azure makes it easier for developers to work with Machine Learning us-ing familiar languages (such as C# and F#) and tools like Visual Studio. ML.NET is the machine learning framework that Microsoft Research created to help leap into this space. In this section, we’ll see how we can easily integrate custom machine learning into your applications without any prior expertise in developing or tuning machine learning models. You’ll also learn how to unlock even greater potential in the Azure portal by combining Azure with Cognitive Services.

Return

Page 43: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Machine Learning with ML.NET and Azure Functions

When you are ready to deploy your ML.NET algorithm, you can use serverless architecture through Azure Functions — the “don’t worry about it” option for when you want to get an app up and running, but don’t necessarily want to mess around with servers and containers. You will use ML.NET locally to train your machine learning model. Then you will create an Azure environment with a storage account and Azure Function to host your machine learning app. The final step will be building an app that uses your model.

Create Your Model

For the ML.NET portion of this quick project, let’s build the iris flower categorization model from the Getting started in 10 minutes ML.NET tutorial. As a prerequisite, you’ll want to install Azure CLI 2.0, Azure Functions Core Tools and a recent version of .NET Core.

Page 44: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Open a command prompt and create a new folder for your ML.NET project.

Next, create a new solution as well as a new console project and install the ML.NET package.

Create a data directory under model.

Create a data directory under model.

Open the UCI Machine Learning Repository: Iris Data Set, copy and paste the data into VS Code (or your text editor of choice), and save it as iris-data.txt in the data directory. Now it’s time to write some code. Open up your project in Visual Studio Code and create a couple of data structure classes: IrisData.cs and IrisPrediction.cs.

> mkdir demo > cd demo

> dotnet new solution > dotnet new console -o model > dotnet sln add model/model.csproj > cd model > dotnet add package Microsoft.ML --version 0.7.0 > dotnet restore

> mkdir data

Page 45: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Open a command prompt and create a new folder for your ML.NET project.

using Microsoft.ML.Runtime.Api;

public class IrisData { [Column(“0”)] public float SepalLength;

[Column(“1”)] public float SepalWidth;

[Column(“2”)] public float PetalLength;

[Column(“3”)] public float PetalWidth;

[Column(“4”)] [ColumnName(“Label”)] public string Label; }

public class IrisPrediction { [ColumnName(“PredictedLabel”)] public string PredictedLabels; }

Add a model class to perform the machine learning training.

Page 46: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

using System.Threading.Tasks;using Microsoft.ML;using Microsoft.ML.Data;using Microsoft.ML.Trainers;using Microsoft.ML.Transforms;

class Model { public static async Task<PredictionModel<IrisData, IrisPrediction>> Train(LearningPipeline pipeline, string dataPath, string modelPath) { // Load Data pipeline.Add(new TextLoader(dataPath).CreateFrom<IrisData>(separator: ‘,’));

// Transform Data // Assign numeric values to text in the “Label” column, because // only numbers can be processed during model training pipeline.Add(new Dictionarizer(“Label”));

// Vectorize Features pipeline.Add(new ColumnConcatenator(“Features”, “SepalLength”, “SepalWidth”, “PetalLength”, “PetalWidth”));

// Add Learner pipeline.Add(new StochasticDualCoordinateAscentClassifier());

// Convert Label back to text pipeline.Add(new PredictedLabelColumnOriginalValueConverter() { PredictedLabelColumn = “PredictedLabel” });

// Train Model var model = pipeline.Train<IrisData, IrisPrediction>();

// Persist Model await model.WriteAsync(modelPath);

return model; } }

Page 47: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

class Program { static void Main(string[] args) { string dataPath = “/Users/mbcrump/Documents/demo/model/data/iris-data.txt”;

string modelPath = “/Users/mbcrump/Documents/demo/model/model.zip”;

var model = Model.Train(new LearningPipeline(), dataPath, modelPath).Result;

// Test data for prediction var prediction = model.Predict(new IrisData() { SepalLength = 3.3f, SepalWidth = 1.6f, PetalLength = 0.2f, PetalWidth = 5.1f });

Console.WriteLine($”Predicted flower type is: {prediction.PredictedLabels}”);

} }

Michaels-MacBook-Pro:model mbcrump$ dotnet run Automatically adding a MinMax normalization transform, use ‘norm=Warn’ or ‘norm=No’ to turn this behavior off. Using 4 threads to train. Automatically choosing a check frequency of 4. Auto-tuning parameters: maxIterations = 9996. Auto-tuning parameters: L2 = 2.668802E-05. Auto-tuning parameters: L1Threshold (L1/L2) = 0. Using best model from iteration 500. Not training a calibrator because it is not needed. Predicted flower type is: Iris-virginica

Place your logic inside the Program.cs file to run through the process:

Run the model project to create a new model.zip file in your root directory. Below are the results that I got:

Congratulations! You’ve trained a machine learning model with ML.NET that categorizes irises.

Page 48: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Set up your Azure environment using Cloud Shell Now we’ll use Azure Cloud Shell, which uses the Azure CLI, to set up our Azure environment. The easiest way to do this is to sign in to your Azure portal account and click on the cloud shell icon shown below to open a bash shell. You can also go to shell.azure.com.

Once logged in, create a new resource group for this project in the bash shell (and replace “mlnetdemo” as well as the location with a name and location of your own).

Add storage to this resource group. You’ll have to change the name below to something unique.

Create your Azure Function and configure it to use the beta runtime, which supports .NET Core.

Next, you will deploy your machine learning model. To get your model up to the server, you will need to get the key to your storage account. Use the following command in the bash window to get it:

>_

$ az group create --name mlnetdemo --location westus

$ az storage account create --name mlnetdemostorage --location westus --resource-group mlnetdemo --sku Standard_LRS

$ az functionapp create --name mlnetdemoazfunction1 --storage-account mlnetdemostorage1 --consumption-plan-location westus --resource-group mlnetdemo $ az functionapp config appsettings set --name mlnetdemoazfunction1 --resource-group mlnetdemo --settings FUNCTIONS_EXTENSION_VERSION=beta

Page 49: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

$ az storage account keys list --account-name mlnetdemostorage1 --resource-group mlnetdemo

$ az storage container create --name models --account-key YOURKEY --account-name mlnetdemostorage1

[ { “keyName”: “key1”, “permissions”: “Full”, “value”: “YOURKEY” }, { “keyName”: “key2”, “permissions”: “Full”, “value”: “NONEYOBUSINESS” }]

You’ll see the following:

Use the following command to create a new directory called models to put your model in, using your account key (this can be found in the navigation window under Settings | Access keys):

Since we are using Cloud Shell, it will be easier to use the Azure Portal for this step. You can also use the Azure CLI if you wish. Browse to your version of the mlnetdemo resource group and drill down to your storage resource that you created earlier. Dig into the blobs and you’ll see the new folder models subdirectory. Upload the model.zip (found on your hard drive) here.

Page 50: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Identify Irisis Like a Machine

Note: Make sure you have the Azure Workload installed to see this template.

Open up the demo solution in Visual Studio and create a new project using the Azure Functions project template called serverless_ai.

Page 51: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

When prompted, select the Http trigger option and connect it to your Azure storage account for the project (I’m using mlnetdemostorage1 for this tip). Then complete the following steps:

1. Use NuGet to add the Microsoft.ML package to your project. 2. Copy the IrisData.cs and IrisPrediction.cs files from your model project to the serverless_ai project. You’ll need them both again.3. Change the name of the Http trigger class Function1 to Predict and copy in the following code:

using Newtonsoft.Json; using Microsoft.ML;

namespace serverless_ai { public static class Predict { [FunctionName(“Predict”)] public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, “get”, “post”, Route = null)]HttpRequest req, [Blob(“models/model.zip”, FileAccess.Read, Connection = “AzureWebJobsStorage”)] Stream serializedModel, TraceWriter log) { if (typeof(Microsoft.ML.Runtime.Data.LoadTransform) == null || typeof(Microsoft.ML.Runtime.Learners.LinearClassificationTrainer) == null || typeof(Microsoft.ML.Runtime.Internal.CpuMath.SseUtils) == null || typeof(Microsoft.ML.Runtime.FastTree.FastTree) == null) { log.Error(“Error loading ML.NET”); return new StatusCodeResult(500); }

Place your logic inside the Program.cs file to run through the process:

Page 52: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

//Read incoming request body string requestBody = new StreamReader(req.Body).ReadToEnd();

log.Info(requestBody);

//Bind request body to IrisData object IrisData data = JsonConvert.DeserializeObject<IrisData>(requestBody);

//Load prediction model var model = PredictionModel.ReadAsync<IrisData, IrisPrediction>(serializedModel).Result;

//Make prediction IrisPrediction prediction = model.Predict(data);

//Return prediction return (IActionResult)new OkObjectResult(prediction.PredictedLabels); } } }

These lines use your model to evaluate new iris data to make a prediction. Now your app is ready for testing.

Test Locally Before Deploying To test the Azure Function app on your local machine, check your local.settings.json file to make sure that AzureWebJobsStorage has a value associated with it. This is how your local app will find your uploaded model on your Azure storage account. If this has a value (and it should if you bound the project to your account when you created it), you can just F5 the serverless_ai project in order to run it. Now open up Postman (or a similar REST API tool) and send a POST call to http://localhost:7071/api/Predict with the following body:

{ “SepalLength”: 3.3, “SepalWidth”: 1.6, “PetalLength”: 0.2, “PetalWidth”: 5.1 }

Page 53: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

If all is well, the categorizer will return “Iris-verginica”.

To deploy Skynet …or whatever AI you are deploying from Visual Studio, go to your build settings in the toolbar.

Select “Publish serverless_ai” to deploy your Azure Function app.

Page 54: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

To test the app deployment in the Azure Portal, select your Azure Function app under mlnetdemo (or whichever name you used) and then pick the Predict function under that. Use the Test panel to the right of the screen to see your deployed app in action. This will place your iris categorizer out on Azure for other people to try.

Congratulations! You are now able to deploy artificial intelligences to the cloud.

Now that you have learned how to take advantage of several aspects of machine learning within Azure, let’s take a tour of the Azure Machine Learning Studio and discuss some of the things you can do without writing any code.

Guided Tour of Azure Machine Learning Studio

In a world where there are WYSIWIG editors for practically everything, have you ever wondered why there isn’t a drag-and-drop web app for machine learning? Well, actually there is: Azure Machine Learning Studio. Today, I want to give you a personal tour of ML Studio and give you an idea of just how much you can do without writing any code. You could think of Azure ML Studio as the low bar for machine learning that makes it easy for everyone to get into AI.

ML Studio has a completely free tier that gives you two hours of compute time a month so you aren’t racking up a bill while you are trying things out. You’ll want to take advantage of that.

Page 55: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

The ML Studio home screen is called your workspace. This is where you’ll collect goodies like datasets, predictive models, experiments, and notebooks, which you can organize under different projects.

Here is some vocabulary to get you started:

Projects are collections of experiments, datasets, notebooks, and other resources.• Experiments are what you create with the drag-and-drop tool.• Web services are deployed from your experiments.• Notebooks are Jupyter notebooks where you collect code snippets,

equations, links, and figures. It’s awesome. • Datasets are really important in machine learning, since your

predictions are only as good as the data you work with. Fortunately, ML Studio gives you access to lots of interesting datasets.

• Trained models are your machine learning output. You plug them into your apps.

• Settings hold your account configuration.

There are lots of great things in the ML Studio home screen, but I want to call out two in particular: the Experiments tab and the Data Transformation node.

Page 56: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

First, the Experiments tab is where you put together a machine learning project visually and with no actual code. This is one of the best ways to learn machine learning by playing around and seeing how things connect together. The tray to the left of your work area gives you access to algorithms, data, and workflows you can pull into your experiment. Let’s take a closer look at some of the functionality packaged there for you.

To work with machine learning, your first step is always going to be to find training data to work with. The easiest thing to do is to expand the Saved Datasets node in the navigation window and drag one of the Sample datasets, like “Movie Ratings”, into your experiment.

Page 57: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

The Data Transformation node in the navigation window gives you a lot of choices in how to select and filter your datasets. You can drag “Select Columns in Dataset” into your experiment and draw an arrow to it from Movie Ratings to add it into your workflow and pick some data columns to use.

The Data Transformation node in the navigation window gives you a lot of choices in how to select and filter your datasets. You can drag “Select Columns in Dataset” into your experiment and draw an arrow to it from Movie Ratings to add it into your workflow and pick some data columns to use.

Page 58: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

To complete a rudimentary experiment, add Machine Learning | Train Model as the next step in your workflow and select Machine Learning | Initialize Model | Classification | Two-Class Neural Network as the kind of learning algorithm you want to create. Finally, score and evaluate your model by adding those nodes and Run your experiment.

To see how good your model is, left click on the Evaluate Model module and select Visualize.

Page 59: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

This will now show you how good your machine learning algorithm is (hint: not very good in this case). There are several things you can do next to improve your model, like splitting off some of your data for training and some of it for scoring, but I’ll leave that to you to experiment with.

Write this downThe other thing I especially want to highlight is the Notebooks tab. It took me a long time to understand how cool Jupyter Notebook is, and I don’t want you to miss out like I did.

Page 60: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

As you can see above, it looks like a scientist’s book of secret formulas. What makes it extra neat is that it’s also an application that can run live code, create visualizations, clean data, and even make predictive models for you. Jupyter Notebook is a broadly used tool in the world of data science. Whether you plan to use ML Studio or not, you should still make a point to become familiar with it.

Page 61: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

When you browse the AI Gallery and find an experiment you like, just click on the Open in Studio button to conveniently copy the whole thing directly into ML Studio. Until we finally get to the point where AI is training our models for us, using drag-and-drop in Azure ML Studio may be the best thing going.

For those less inclined to create machine learning projects from scratch, we can take advantage of the Cognitive Services APIs to harness the power of machine learning and bring advanced intelligence into our product without the need to have a team of data scientists on hand.

Using OCR to extract text from images from the Azure PortalzzI found myself in a situation where I needed to extract text from an image. After taking a quick peek at free sites (that I don’t trust), I took it upon myself to use the power of the Azure Portal, Cognitive Services and PowerShell to accomplish what I needed. I’ll walk you though my process in this tip.

1) Open the Azure Portal and select Cloud Shell from the top menu. Now change the scripting language from BASH to PowerShell.

`

Still intimidated? That’s okay. The Azure AI Gallery

has many prebuilt experiments written by other people that you can simply load into your workspace and modify to learn.

You can also go to store.docker.com and create a repository. You’ll also notice that they provide

the CLI commands as well.

Page 62: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

2) We now need to install the PowerShell Cognitive Services module. You can do so by typing Install-Module PSCognitiveservice -Verbose -Force. Sample output is below:

PS Azure:\> Install-Module PSCognitiveservice -Verbose -ForceVERBOSE: Using the provider ‘PowerShellGet’ for searching packages.VERBOSE: The -Repository parameter was not specified. PowerShellGet will use all of the registered repositories.VERBOSE: Getting the provider object for the PackageManagement Provider ‘NuGet’.VERBOSE: The specified Location is ‘https://www.powershellgallery.com/api/v2/’ and PackageManagementProvider is ‘NuGet’.VERBOSE: Searching repository ‘https://www.powershellgallery.com/api/v2/FindPackagesById()?id=’PSCognitiveservice’’ for ‘’....VERBOSE: Module ‘pscognitiveservice’ was installed successfully to path ‘C:\Users\ContainerAdministrator\Documents\WindowsPowerShell\Modules\pscognitiveservice\0.3.5’.Azure:\PS Azure:\>

3 ) Import the module by typing Import-Module PSCognitiveservice -V.Sample output is on the next page.

Page 63: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

PS Azure:\> Import-Module PSCognitiveservice -VerboseVERBOSE: Loading module from path ‘C:\Users\ContainerAdministrator\Documents\WindowsPowerShell\Modules\PSCognitiveservice\0.3.5\PSCognitiveservice.psd1’.VERBOSE: Populating RepositorySourceLocation property for module PSCognitiveservice.VERBOSE: Loading module from path ‘C:\Users\ContainerAdministrator\Documents\WindowsPowerShell\Modules\PSCognitiveservice\0.3.5\PSCognitiveService.psm1’.VERBOSE: Importing function ‘ConvertTo-Thumbnail’.VERBOSE: Importing function ‘Get-Face’.VERBOSE: Importing function ‘Get-ImageAnalysis’....VERBOSE: Importing alias ‘analyze’.VERBOSE: Importing alias ‘bing’....VERBOSE: Importing alias ‘ocr’.VERBOSE: Importing alias ‘sentiment’.VERBOSE: Importing alias ‘tag’.VERBOSE: Importing alias ‘thumbnail’.Azure:\

4) Now you’ll need to create a cognitive services account. You can do so either in the portal (you may already have one) or by typing New-CognitiveServiceAccount AccountType ComputerVision –Verbose. Just make sure you select Free.

Page 64: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

5) Load the configuration into your environment variables with lcfg -fromAzure –Verbose. Sample output is below:

6) Type the following line and just replace the URL with the image that you’d like to extract text from:

And now you have your text!

PS Azure:\> lcfg -fromAzure -VerboseVERBOSE: Testing Azure loginVERBOSE: Logged in.VERBOSE: Fetching AzureRM Cognitive Service accountsVERBOSE: 1 Service found in AzureRM [ComputerVision]VERBOSE: Setting $env:API_SubscriptionKey_ComputerVision for Cognitive Service: ComputerVisionVERBOSE: Setting $env:API_Location_ComputerVision for Cognitive Service: ComputerVision

Name Value---- -----ServiceName ComputerVisionLocation westusSubscriptionKey yourkeyEndPoint https://westus.api.cognitive.microsoft.com/vision/v1.0

ocr -URL https://s3-us-west-2.amazonaws.com/i.cdpn.io/10994.zekgx.4df25d8a-eb50-4007-a0df-6ae0aaf87974.png -Verbose | ForEach-Object {$_.regions.lines} | ForEach-Object { $_.words.text -join ‘ ‘}

Page 65: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

When you use Cognitive Services with the Azure portal you have a powerful combination at your disposal. In these next tips, instead of using an image, we will use the Text Analysis API to dive deeper into the following capabilities:

• Key Phrase Extraction – Automatically extract key phrases to quickly identify the main points.

• Language Detection – For up to 120 languages, detect which language the input text is written in and report a single language code for every document submitted on the request.

• Sentiment Analysis – Find out what customers think of your brand or topic by analyzing raw text for clues about positive or negative sentiment.

Key Phrase Extraction with Cognitive Services and AzureIf you open the Azure portal and look for AI and Cognitive Services then you’ll see the following:

`

What are Key Phrases? They

automatically extract key phrases to

quickly identify the main points.

Page 66: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Select Keys and copy the value of Key 1.

We’ll use Postman to test. Go ahead and download it if you haven’t already.

Once complete, you’ll use the keyPhrases endpoint:

https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases

Copy the https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases URL into Postman and set the following three header properties:

•Ocp-Apim-Subscription-Key = should be your Key 1 (from our discussion earlier).•Content-Type = Set it to application/json.•Accept = Set it to application/json.

Your screen should look like the following:

`

If you’re not already familiar with

Postman, you can learn more about

how you can use it by clicking here.

Page 67: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Now switch over to Body, then Raw, and post the following JSON (from some of my tweets):

{ “documents”: [ { “language”: “en”, “id”: “1”, “text”: “Top 10 .NET Development Tweets that Broke the Web in 2017 - http://mcrump.me/2ot58Co #dotnet” }, { “language”: “en”, “id”: “2”, “text”: “Setting up a managed container cluster with AKS and Kubernetes in the #Azure Cloud running .NET Core in minutes - http://mcrump.me/2op9mek #dotnet” } ]}

Page 68: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Now press Send and it will return key phrases from my tweets.

{ “documents”: [ { “keyPhrases”: [ “Web”, “.NET Development Tweets”, “dotnet” ], “id”: “1” }, { “keyPhrases”: [ “Kubernetes”, “Azure Cloud”, “minutes -”, “AKS”, “.NET Core” ], “id”: “2” } ], “errors”: []}

Page 69: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

There are several SDKs you can play with – for example, you can use Text Analytics with Power BI.

Go here to learn more.

In the next tip we’ll look at Language Detection, another part of Cognitive Services available inside the Azure Portal.

Language Detection with Cognitive Service and AzureIf you open the Azure portal and look for AI and Cognitive Services then you’ll see the Text Analysis API that we’ve been working with. As we did previously, select Keys and copy the value of KEY 1 if you no longer have this on your clipboard.

Working with Language Detection and PostmanJust like with Key Phrases, we need an endpoint to begin calling the API. If you look at the Overview option inside your cognitive service, then you’ll see the following:

Page 70: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

While that is the endpoint, it is missing the feature of the Text Analysis that you might want to call. A complete list is below:

sentiment keyPhrases languages

We want to use the languages endpoint in this tip.

Copy the https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages URL into Postman and set the following three header properties:• Ocp-Apim-Subscription-Key = should be your Key 1 (from our discussion earlier)• Content-Type = Set it to application/json.• Accept = Set it to application/json.

Your screen should look like the following:

`

What are languages?

This feature detects which language the input text is written in and

reports a single language code for every document

submitted on the request. The language code is paired with a score indicating

the strength of the score.

Page 71: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

{ “documents”: [ { “id”: “1”, “text”: “Azure Tips and Tricks - English” }, { “id”: “2”, “text”: “Consejos y trucos de Azure - Inglés” }, { “id”: “3”, “text”: “하늘빛 팁과 트릭 - 영어” } ] }

Now switch over to Body, then Raw, and post the following JSON:

id 1 is obviously English, 2 is Spanish, and 3 is Korean

Page 72: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

I hope you find this as helpful as I have! Another useful function within cognitive services is sentiment analysis, which we will discuss in the next tip.

Sentiment Analysis with Cognitive Services and AzureIn this tip, we’ll look at sentiment analysis, which is part of Cognitive Services and is now inside the Azure Portal.

Working with Sentiment Analysis and PostmanOnce again, look at the Overview option inside your cognitive service. We want to use the sentiment endpoint for this tip.

“id”: “1”, “detectedLanguages”: [{ “name”: “English”, “iso6391Name”: “en”, “score”: 1.0 }] }, { “id”: “2”, “detectedLanguages”: [{ “name”: “Spanish”, “iso6391Name”: “es”, “score”: 1.0 }] }, { “id”: “3”, “detectedLanguages”: [{ “name”: “Korean”, “iso6391Name”: “ko”, “score”: 1.0 }] }], “errors”: []}

`

What is sentiment analysis?

Find out what customers think of your brand or topic

by analyzing raw text for clues about positive or negative sentiment. This API returns a sentiment

score between 0 and 1 for each

document, where 1 is the most positive.

Page 73: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Copy the https://westus.api.cognitive.microsoft.com/text/ana-lytics/v2.0/sentiment URL into Postman and set the following three header properties:• Ocp-Apim-Subscription-Key = should be your Key 1 (from our discussion earlier).• Content-Type = Set it to ap plication/json.• Accept = Set it to application/json.

Your screen should look like the following:

Now switch over to Body, then Raw, and post the following JSON:

{ “documents”: [ { “language”: “en”, “id”: “1”, “text”: “How to become master writing C# code - http://mcrump.me/2oLeg5i #dotnet #csharp” }, { “language”: “en”, “id”: “2”, “text”: “#Azure Tips and Tricks Part 71 - Language Detection with Cognitive Service and Azure.” }, { “language”: “en”, “id”: “3”, “text”: “Deploy http://ASP.NET Core apps to #Azure - Day 16 - 24 days of Front-end Development with http://ASP.NET Core, #Angular, and Bootstrap - http://mcrump.me/2Be9vqY #aspnet #webdev #javascript #webdev #dotnet” } ] }

Page 74: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

These are a couple of tweets from my timeline:

Now press Send and it will return the sentiment of the text.

Notice this API returns a sentiment score between 0 and 1 for each document, where 1 is the most positive.

{ “documents”: [{ “score”: 0.81279480457305908, “id”: “1” }, { “score”: 0.5, “id”: “2” }, { “score”: 0.5, “id”: “3” }], “errors”: []}

I used some technology tweets for this tutorial, but think of using this API for customer tweets such as I

*LOVE* this hotel or I am not impressed with this hotel. There are many use cases for this.

Page 75: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Here is an example of a fictitious airline that has a strong dislike and like:

Page 76: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Containers

I have found that containers can be confusing to a lot of people, myself included, and my goal with my Azure Tips and Tricks is to try to make things easier. In this next section, I’ll walk you through Docker and how I use it with Azure.

Return

Page 77: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Docker Registry vs. Docker RepositoryTo kick us off, I’ll cover the differences between Docker Registry and Docker Repository.

Docker Registry

Docker Registry is a service that stores your Docker images, but it could be hosted by a third party and even privately if you need so. A couple of examples are:

• Azure Container Registry• Docker Hub• Quay Enterprise

There are also other choices such as Google or AWS Container Registry.

Docker Repository

A Docker Repository is a collection of related images with same name, that have different tags. Tags are an alphanumeric identifier attached to images within a repository (e.g., 1.1 or latest).

So the command docker pull microsoft/aspnetcore:latest will download the image tagged latest within the microsoft/aspnetcore repository from the Docker Hub registry.

To wrap it up, look at the image below. We have a Docker Repository named microsoft/aspnetcore that is stored in a Docker Registry using Docker Hub.

`

Docker is an open-source project

that autom`ates the deployment of applications inside

software containers. It automates the repetitive tasks of setting up

and configuring development

environments so that developers can focus on what they

do best: developing.

Page 78: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

We could click on tags and pull the latest version with pull microsoft/aspnetcore:latest.

Page 79: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

I know this can be very confusing, so I hope this helps to make sense of it all. In the next tip we’ll get started using Docker with Azure.

Getting Started with Docker and AzureHead over to Docker and you’ll want to download the Community Edition. Keep in mind that there are two channels: the Stable version and Edge version. As you can imagine, the stable build is… well… stable, and the edge build is for those that want the latest features (which may not be tested). You can pick your poison, but for this book, we’ll use the Stable version.

Once it has been downloaded and installed, you should see a green light that indicates that Docker is running.

Page 80: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You can easily verify it was installed properly by opening terminal or a command prompt and typing docker info.

Great, so now let’s pull an image since it is up and running properly. Head over to store.docker.com and search for aspnetcore-build. I’ll use this image because I want to run an ASP.NET Core without installing the tools, platform, and SDK on my local machine.

If you search for aspnetcore-build then you’ll land on this page. Pay close attention to the following command (highlighted below) that we’ll use to copy into our terminal/command prompt to pull down the image.

Note the structure of the command: docker pull microsoft/aspnetcore-build. If you’re familiar with git, then this syntax feels familiar. You can also type docker help for a full list of commands.

Page 81: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You’ll see Docker pulled the image from Docker Store, and when it completes, you can type docker images to list all the images that are available to use.

We’ll work with that image in the next tip.

Create an App to Run Inside a Container Image with DockerBegin by opening two tab instances of either command prompt or terminal. In the right tab, enter the following command to see what Docker images are available.

Michaels-MacBook-Pro:~ mbcrump$ docker images REPOSITORY TAG IMAGE ID CREATED microsoft/aspnetcore-build latest c0c285a7a306 37 hours ago SIZE1.85GB

Michaels-MacBook-Pro:~ mbcrump$ docker images REPOSITORY TAG IMAGE ID microsoft/aspnetcore-build latest c0c285a7a306 CREATED SIZE39 hours ago 1.85GB

Page 82: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Let’s run the following command passing the run parameter an interactive terminal, naming our app, and setting the image id. The first couple of letters (found with the above command) are good enough.

After this command executes, I’ll be inside my container.

I can validate this by running dotnet --info

I know this because I don’t have .NET core tools installed on my Mac. Very cool! You now have a running container that has the .NET core tools by entering just a couple of commands.

docker run -it --name myapp c0

root@40bac5113803:/# dotnet --info .NET Command Line Tools (2.0.2)

Product Information: Version: 2.0.2 Commit SHA-1 hash: a04b4bf512 ...

Michaels-MacBook-Pro:~ mbcrump$ docker images REPOSITORY TAG IMAGE ID microsoft/aspnetcore-build latest c0c285a7a306 CREATED SIZE39 hours ago 1.85GB

Page 83: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

root@40bac5113803:/# uname -r 4.9.49-moby root@40bac5113803:/# uname Linux

We could further validate this by running uname -r or just uname.

Let’s go ahead and create an app. Run through the following commands to create a new dotnet core console app.

root@40bac5113803:~# mkdir myapproot@40bac5113803:~# cd myapproot@40bac5113803:~/myapp# dotnet new consoleroot@40bac5113803:~/myapp# dotnet restoreroot@40bac5113803:~/myapp# dotnet run

Hello World!`

Page 84: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Awesome! So now you have a container that is running your .NET Core app. But what can we do with this? How about creating a version of your app that you could give to anyone that is ready to go? We’ll cover that in the next tip.

Creating a Container Image with DockerIn this post, we’ll create a new image that we can distribute that con-tains our new app.

Remember how we used the dotnet build command in the last post? If you navigate the file structure of our existing console app, then you’ll see there is a myapp.dll that contains the executable code.

If you navigate back to the root directory, then you can run dotnet run -p /myapp/myapp.csproj to see the Hello World! output.

Let’s save this into a file that we can run later.

Type cd /usr/local/bin and then cat > startmyapp.sh. Add #!/bin/bash to the first line and then dotnet run -p /myapp/myapp.csproj to the second line. Press CTRL-D to exit out.

Try out the command by typing sh startmyapp.sh and your app should run.

root@40bac5113803:~/myapp/bin/Debug/netcoreapp2.0# dir myapp.deps.json myapp.dll myapp.pdb myapp.runtimeconfig.dev.json myapp.runtimeconfig.json

Page 85: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Type exit and you’ll return to Terminal or command prompt window.

Now we want to add our application to a container.

Run docker ps -a to see what the name of our container is.

Now run docker commit 7c mbcrump:awesomeapp to add the app to a container. After Docker commit, we took the first two characters of the container id, created the name mbcrump, and gave it a tag of awesomeapp.

Now we can run docker images to see our new image!

Now run docker run 82 startmyapp.sh where 82 is the image id and startmyapp.sh is the shell script that we created earlier.

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7c5da93bf968 c0 “bash” 10 minutes ago Exited (0) 51 seconds ago myapp

Michaels-MacBook-Pro:~ mbcrump$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE mbcrump mynewapp 82eb1e5914dc About a minute ago 1.85GB mbcrump awesomeapp 1f254a9917aa 16 minutes ago 1.85GB microsoft/aspnetcore-build latest c0c285a7a306 44 hours ago 1.85GB

Page 86: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Nice! We now have a container that contains our .NET Core app that we can distribute via the Docker Store and other avenues. Anyone who grabs our image will have an environment that they can get started with right away without having to worry about configuration, platform, etc. Now we’re cooking with Docker! In the next tip, we’ll push the container image to a Docker repo.

Pushing a Container Image to a Docker RepoType docker login at the terminal or command prompt to ensure we are authenticated.

Now in order to push to a new repo, you’ll need to tag the existing image. You can do so by typing docker tag mbcrump:mynewapp mbcrump/firstimage where mbcrump:mynewapp is the existing image that contains our new app. Our repo name will be mbcrump/firstimage. Pay close attention to the mbcrump/firstimage part, as mbcrump is your Docker username.

Once that is complete, then use docker push mbcrump/firstimage to move it to a repository.

Michaels-MacBook-Pro:~ mbcrump$ docker login Login with your Docker ID to push and pull images from Docker Hub. If you don’t have a Docker ID, head over to https://hub.docker.com to create one. Username (mbcrump): mbcrump Password: Login Succeeded

Michaels-MacBook-Pro:~ mbcrump$ docker push mbcrump/firstimage The push refers to a repository [docker.io/mbcrump/firstimage] 1fd4467b1c0e: Pushed 0a3794bad5d4: Pushed 54f3762778cc: Pushed 88f0e0eb260c: Pushed 1361e5e30088: Pushed 52121b397f2e: Pushed 480d03264b1d: Pushed a4212622fd11: Pushed a4af43f268c6: Pushed c2dca236d8e6: Pushed d4417cb76edb: Pushed 0dc1ec77adb3: Pushed

Page 87: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You’ll see that it provides instructions to push a new version of the image as well as the commands to do so from the CLI.

In these last few tips, we have:

• Installed and set up Docker• Verified installation through the CLI• Taken a look at the Docker Store• Used an image from the Docker Store to build upon• Run a Container and created a .NET Core app to it• Created a Shell Script to call the app through the new image• Added our app to a new container image• Called the app through the command line and executed our program• Packaged up the image container to send to a Docker repo• Pushed our image container to Docker through the CLI

You can also go to store.docker.com and

create a repository. You’ll also notice that they provide the CLI commands as well.

Great! Now you can log into your account on store.docker.com and if you click on repos, then you’ll see it.

Page 88: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

In the next series of tips, we’ll go even further by getting a .NET Core WebAPI project ready for Docker.

Getting a .NET Core WebAPI Project Ready for DockerHow hard do you think it is to create and publish a .NET Core WebA-PI project? How about to add it to a Docker container using Docker Compose, push it to Docker Hub, and then use it in Azure with Web App for Containers? Don’t worry, I’ll make it easy for you in these next few tips – starting with preparing a .NET Core WebAPI Project for Docker.

Create a .NET Core WebAPI ProjectEnsure .NET Core is installed and then follow the direction below:

Create a directory on your HDD mkdir mbcwebapi. Now cd mbcwebapi into it.

Create another directory inside your mbcwebapi folder mkdir mbcwebapi. Now cd mbcwebapi into that.

Run dotnet new webapi to scaffold a new ASP.NET WebAPI Project.

Michaels-MacBook-Pro:mbcwebapi mbcrump$ dotnet new webapi The template “ASP.NET Core Web API” was created successfully. This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.

Processing post-creation actions... Running ‘dotnet restore’ on /Users/mbcrump/mbcwebapi/mbcwebapi.csproj... Restoring packages for /Users/mbcrump/mbcwebapi/mbcwebapi.csproj... Restore completed in 35.83 ms for /Users/mbcrump/mbcwebapi/mbcwebapi.csproj. Generating MSBuild file /Users/mbcrump/mbcwebapi/obj/mbcwebapi.csproj.nuget.g.props. Generating MSBuild file /Users/mbcrump/mbcwebapi/obj/mbcwebapi.csproj.nuget.g.targets. Restore completed in 1.96 sec for /Users/mbcrump/mbcwebapi/mbcwebapi.csproj.

Restore succeeded.

Page 89: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

If you use dotnet run you’ll have a URL that you can paste into your browser.

Add http://localhost:5000/api/values to see a response from `the WebAPI, otherwise the site will give a 404 error.

You should see [“value1”,”value2”]. Nice! It is working properly!

Publish the .NET Core WebAPIThe dotnet publish command packs the application and its dependencies into a folder for deployment to a hosting system. We are going to prep our project for Docker, so use dotnet publish-c Release -o ./obj/Docker/publish.

Michaels-MacBook-Pro:mbcwebapi mbcrump$ dotnet publish -c Release -o ./obj/Docker/publishMicrosoft (R) Build Engine version 15.3.409.57025 for .NET CoreCopyright (C) Microsoft Corporation. All rights reserved.

mbcwebapi -> /Users/mbcrump/mbcwebapi/bin/Release/netcoreapp2.0/mbcwebapi.dll mbcwebapi -> /Users/mbcrump/mbcwebapi/obj/Docker/publish/Michaels-MacBook-Pro:mbcwebapi mbcrump$

Page 90: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

If you navigate to the /obj/Docker/publish folder, then you will see our WebAPI is packaged and ready for deployment.

Success! We now have created and published a .NET Core WebAPI project. In the next tip, we’ll add our image to a Docker Container using Docker Compose Web App for Containers.

Use .NET Core WebAPI and Docker ComposeNow that we have created and published a .NET Core WebAPI project, we’ll resume by using Docker Compose to create an image.

Think of this as a three-step process:1) We need a file called “Dockerfile” so that Docker understands the image we are creating.

2) We need a docker-compose.yml file to pass to the Docker Compose Command

3) We need to run the Docker Compose command.

Step 1Let’s begin by creating a Dockerfile.

Copy and paste the following, name it Dockerfile without an extension, and place it in the same folder as your source code:

11/19/2017 12:12 PM 178 appsettings.Development.json11/19/2017 12:12 PM 228 appsettings.json11/19/2017 12:41 PM 284,199 mbcwebapi.deps.json11/19/2017 12:41 PM 6,656 mbcwebapi.dll11/19/2017 12:41 PM 1,312 mbcwebapi.pdb11/19/2017 12:41 PM 2,560 mbcwebapi.PrecompiledViews.dll11/19/2017 12:41 PM 7,680 mbcwebapi.PrecompiledViews.pdb11/19/2017 12:41 PM 221 mbcwebapi.runtimeconfig.json11/19/2017 12:41 PM 383 web.config

`

What is a DockerFile?

It is simply a text file containing the instructions

needed to create a new container

image. These instructions include identification of an existing image to be used as a base,

commands to be run during the image creation process, and a command

that will run when new instances of

the container image are deployed. In

other words, this file defines your app’s environment so it

can be reproduced anywhere.

Page 91: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

FROM microsoft/aspnetcore:2.0 ARG source WORKDIR /app EXPOSE 80 COPY ${source:-obj/Docker/publish} . ENTRYPOINT [“dotnet”, “mbcwebapi.dll”]

version: ‘3’

services: mbcwebapi: image: mbcrump/mbcwebapi build: context: ./mbcwebapi dockerfile: Dockerfile

Let’s go over the main instructions this code is giving:

•The FROM instruction sets the container image that will be used during the new image creation process. In this case, we’re using the base ASP.NET Core image from Microsoft.

•The EXPOSE instruction sets the port number.

•The COPY instruction provides the source it is going to pull the final release from. •The ENTRYPOINT instruction provides the entry point into the application, and in our case, we specify the release .dll.

Step 2We need a docker-compose.yml file to pass to the Docker Compose Command

`

What is docker-compose.yml?

This file defines the services that make

up your app so they can be run together

in an isolated environment.

Page 92: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

When composing this Docker image, we will use the mbcwebapi project and build an image called mbcrump/mbcwebapi. We’ll set the context to look in the ./mbcwebapi folder and there it will find the Dockerfile.

Note: The image name mbcrump/mbcwebapi was based on my Docker username and then the app name.

Step 3We need to simply run docker-compose up and Docker Compose will start and run your entire app.

Michaels-MacBook-Pro:mbcwebapi mbcrump$ docker-compose upCreating network “mbcwebapi_default” with the default driverBuilding mbcwebapiStep 1/6 : FROM microsoft/aspnetcore:2.0 ---> 757f574feed9Step 2/6 : ARG source ---> Using cache ---> 96deb3aec068Step 3/6 : WORKDIR /app ---> Using cache ---> c0fecb757aa4Step 4/6 : EXPOSE 80 ---> Using cache ---> e4f034c54397Step 5/6 : COPY ${source:-obj/Docker/publish} . ---> 6bd68f6553c4Step 6/6 : ENTRYPOINT dotnet mbcwebapi.dll ---> Running in 7036d9913baa ---> 90384b8ed543Removing intermediate container 7036d9913baaSuccessfully built 90384b8ed543Successfully tagged mbcrump/mbcwebapi:latestWARNING: Image for service mbcwebapi was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.Creating mbcwebapi_mbcwebapi_1 ... Creating mbcwebapi_mbcwebapi_1 ... doneAttaching to mbcwebapi_mbcwebapi_1mbcwebapi_1 | warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]mbcwebapi_1 | Storing keys in a directory ‘/root/.aspnet/DataProtection-Keys’ that

Page 93: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.mbcwebapi_1 | warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]mbcwebapi_1 | No XML encryptor configured. Key {70d9c953-b38f-4e26-92d2-6a07557aaefc} may be persisted to storage in unencrypted form.mbcwebapi_1 | Hosting environment: Productionmbcwebapi_1 | Content root path: /appmbcwebapi_1 | Now listening on: http://[::]:80mbcwebapi_1 | Application started. Press Ctrl+C to shut down.

Excellent! We now have an ASP.NET WebAPI project living inside a Docker Container that we can push to Docker Hub.

Go ahead and push to Docker Cloud.

Next, log in to Docker Cloud and create a repository. In my case, I used mbcrump/mbcwebapi just like in the docker-compose.yml example earlier.

Page 94: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You can go back to Docker Cloud to verify that it pushed successfully.

Nice! The only thing left to do now is push it to Azure using Web App for Containers, which we’ll do in the next tip.

Deploy a .NET Core WebAPI Project to Web App for Containers

In the last tip we pushed our Docker Image to Docker Cloud. We also created a repository in Docker Cloud and headed back to our command prompt (or terminal) and ran the following commands:

docker login to authenticate and docker push mbcrump/mbcwebapi:latest to push your image to Docker Cloud.

Now that we have a Docker Cloud repository, we can push it to Azure using Web App for Containers.

Go ahead and log into the Azure Portal and search for Web App for Containers. You should see the following:

Page 95: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

You should be familiar with these pieces (name, resource group, etc.) with the exception being the Configure Container section.

Here we will use Docker Hub (think Docker Cloud), our repo is public, and the name of the image. This follows the format docker username/our app name:tag.

After your Web App for Container is deployed, you can simply go to your new URL and append /api/values to see your new site.

Press the Create button and you should see this:

That’s it. You now have a WebAPI running inside a Docker Container hosted on Azure with a public site that you can call from. That was too easy!

Page 96: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

`

Conclusion

Thank you for joining me for Azure Tips & Tricks eBook volume 2! On this leg of our journey across the universe of Azure, we took an in-depth tour of ARM Templates and made sense of creating and deploying one. We learned how to get the most out of our Azure services by using Azure Advisor (free help!), logging application details, and sharing Azure dashboards with just a couple of clicks. We also explored the vast frontier of the Azure Machine Learning Studio and unleashed the power of Cognitive Services – and there are still more tips and tricks where these came from!

Explore the entire collection of tips at http://azuredev.tips/, and if you prefer videos, go to http://videos.azuredev.tips.

If you liked this eBook, then check out all the other Volumes at http://ebook.azuredev.tips

If you aren’t already using Azure, you can get started for free and get:

• $200 to explore any Azure service for 30 days

• 12 months of popular free services

• 25+ always-free services

Start free

Until next time,

Michael Crump @mbcrump

Page 97: Azure Tips and Tricks - download.microsoft.comthe Azure platform. In this volume, like I did in volume 1, I’ve collected the top tips in four categories: Azure App Service, Productivity,

Azure Tips and Tricks azuredev.tips

Copyright © 2019 by Microsoft Corporation. All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher.

Made with love By Red Door Collaborative.com