Connect(); Special Issue 2018

Volume 33 Number 13

[Azure]

7 Tips and Tricks for Azure App Service

By Michael Crump; Special Issue 2018

Azure Tips and Tricks (azuredev.tips) is a series that I created a year ago where I document my favorite secrets, shortcuts and handy features using Azure. I quickly came to appreciate the value of short and straight-to-the-point guidance for common scenarios that developers face every day. Over the last year I’ve gone from just a few posts to more than 150 tips spanning the entire Azure platform.

For this special edition of MSDN Magazine focused on the Microsoft Connect(); 2018 conference, I pulled together a collection of the seven most popular and valuable tips related to Azure App Service. These tips include working with files in the console, setting up staging environments and swapping between them, and routing traffic to different versions of your app to “Test in Production.” I’ll also cover how you can implement performance testing, adopt best practices for App Settings in Azure App Service, and clone a Web app that’s especially helpful if you have customers all over the world.

Working with Files in Azure App Service

In this tip I’ll look at the files inside an Azure App Service Web site that allows you to easily manage your Web app environment without leaving the Azure Portal. To begin, go to the Azure Portal and select an App Service that you’ve already created and click on Console under Development Tools. This brings up a command prompt from where you can work with your Azure App Service (see Figure 1).

The Console Inside Azure App Service
Figure 1 The Console Inside Azure App Service

As you can see in Figure 1, the prompt starts in D:\home\site\wwwroot. From here I can enter “dir” to see a current directory listing, as shown in Figure 2.

Figure 2 The wwwroot Directory Listing

Volume in drive D is Windows
Volume Serial Number is FE33-4717
 Directory of D:\home\site\wwwroot
09/21/2017  08:35 PM    <DIR>          .
09/21/2017  08:35 PM    <DIR>          ..
09/20/2017  09:03 PM    <DIR>          css
09/20/2017  09:03 PM             5,351 Default.html
09/20/2017  09:03 PM    <DIR>          js
09/20/2017  09:03 PM             1,950 jsQuizEngine.sln
09/20/2017  09:03 PM               304 jsQuizEngine.userprefs
09/20/2017  09:03 PM            31,744 jsQuizEngine.v12.suo
09/20/2017  09:03 PM    <DIR>          PrecompiledWeb
09/20/2017  09:03 PM    <DIR>          quiz
               4 File(s)         39,349 bytes
               7 Dir(s)   1,072,893,952 bytes free

I can perform basic commands here and use the command “type <filename>” to display the output of a file to the screen. You can create directories and rename files, but keep in mind that this is a sandbox environment. Some commands that require elevated permissions may not work from the Console inside of Azure App Service. For a list of available commands from the prompt, just type “help” in the console window.

Visual Studio Code Experience

There’s another option under Development Tools in the Azure App Service Portal called App Service Editor. You can find this item located just two spots down from the Console item that I described in the previous tip. Click App Service Editor and select a file, and you’ll see a screen similar to the image in Figure 3.

The App Service Editor
Figure 3 The App Service Editor

If you’re familiar with Visual Studio Code, you’ll find yourself right at home as you explore, search and manage Git. The App Service Editor also makes it easy to add, edit, or delete files, and just like in Visual Studio Code, you can modify your settings and even change your theme. You can also take advantage of the output window to review the Application Logs associated with your app service.

Kudu Diagnostic Console

No App Service tutorial is complete without mentioning Kudu Diagnostic Console. You can access it from within the App Service Editor by going to your app and then clicking Open Kudu Console, or by looking for the Advanced Tools option under Development Tools.

To navigate or type in a command, just click on the folder name. You can easily manipulate files from here, but I personally like the App Service Editor better for that functionality. I primarily use the Kudu Diagnostic Console to easily discover and work with the REST API and work with the Process explorer.

Creating a Deployment Slot

Let’s move on from the wonders of the App Service Editor to explore how to streamline testing of Web apps in production with Azure App Service. I’ll start with a look at deployment slots, an enormously useful feature that lets you deploy different versions of your Web app to different URLs. You can then test a specific version of your app and swap content and configuration between slots.

Start by going to the Azure Portal and selecting an existing App Service that you have running and under Deployment click Deployment Slots. Then click on the Add Slots button. Enter a descriptive name such as staging, then use an existing configuration source, as shown in Figure 4. For this example I’ll use a “production” Web app—the cool quiz application (github.com/mbcrump/jsQuizEngine) that’s already deployed.

Adding a Deployment Slot
Figure 4 Adding a Deployment Slot

Once that’s done, go back to Deployment Slots to see the status, which should read “Running.” Click on the new staging site that was just created. You’ll notice that it has appended the word staging. You’ll also notice that there’s a new site at yoursitename-staging.azurewebsites.net.

Let’s say you need to push a new version of the existing quiz application to this staging slot. Go to Deployment Center and select External and enter the following URL into the text box: github.com/mbcrump/jsQuizEngine.git. Click OK. You may find that you need to click Sync to make the changes take effect. A check mark should appear once the process has successfully completed.

Wait a couple minutes for your code to be pulled down from Git, then go to the new URL of your site. You can find the URL on your overview page. In my case it’s at myquizapplication-staging.azurewebsites.net. You should now see your new Web site, with jsQuizEngine version 2 displayed in large font.

At this point, I could return to the original app service that I created and swap between the two sites that I now have. For example, I might want to move the staging site over to the production site, and vice versa. The benefit of this is that your users won’t experience downtime while you tinker, and you can continue working in your preferred space until ready to move to production.

Test Web Apps in Production

In this tip, I’ll look at a feature called Testing in Production, which does exactly what it says. Not scary at all! But hold up. If you’re not familiar with deployment slots, you’ll want to look at the previous tip before you dive in.

To get started with this feature, go to the Azure Portal and select App Service and under Development Tools click Testing in Production. The first thing you’ll see is the title Static Routing and you’ll notice two options that are for a deployment slot name and traffic percentage (to which you’ll want to route).

What is Static Routing? It’s a feature of deployment slots that lets you control how traffic is distributed between your production and other slots. This is useful if you want to try out a new change with a reduced number of requests and then gradually increase the number of requests that get the new behavior.

You’ll want to split the traffic to your site into two groups to test the new site and see if customers like it. Because this is just a demo, you’ll want to send a large number of folks to the staging site as shown in Figure 5.

Adjusting the Static Routing Traffic Percentage for the Staging Site
Figure 5 Adjusting the Static Routing Traffic Percentage for the Staging Site

Now keep in mind that you have two versions of your site. One that’s production and one in staging. They’re identical except that the staging site includes text in a large font that reads “jsQuizEngine version 2.” You don’t want to swap these sites, rather you just want to distribute traffic between them.

You can test this by going to the production URL and constantly refreshing the site until the staging site is shown with the production URL.

What happens when the user leaves the site? By default, a cookie keeps track of the event. You can find this cookie yourself by bringing up the developer tools and looking for the cookie called “x-ms-routing-name.”

You could actually force the old production site by setting the x-ms-routing-name cookie to self or providing it in the URL query string, such as http://myquizapplication.azurewebsites.net/?x-ms-­routing-name=self. You could even use the URL to let your users test different versions of your site. For example, I could use http://myquizapplication.azurewebsites.net/?x-ms-routing-name=staging to let users try my new Web site before I push it live. This is very neat stuff, folks!

Load Test Web Apps

Next, let’s look at a simple and quick way to perform load testing of Web apps. Load Testing allows you to gauge your Web app’s performance and determine if it can handle increased traffic during peak times. Log into your Azure account and go to the App Service you created and look under Development Tools. You’ll see Performance Test there.

Inside the blade, select New to see the Configure Test option, which you can leave at the default setting of Manual Test or change to Visual Studio Web Test. The main difference between the two: Visual Studio Web Test lets you select multiple URLs and even use an HTTP Archive file (such as one created by Fiddler). For this walk-through, use the setting Manual Test and select a name and location, making sure you leave the defaults at 250 users for five minutes.

Imagine this use-case scenario. You have a Web app presenting an item for sale, with an upcoming promotion that last year resulted in 175 users being connected for five minutes. Users complained then that the site was slow, so you’re anxious to improve customer satisfaction by reducing the page load time. To help do this, you test your Web app with a heightened load of 250 (or even 2,500) users for five minutes.

Run the test and you’ll be presented with data such as successful and failed requests, performance under load, and more. For the scenario I ran, the average response time decreased, while requests per second increased. If I had chosen a larger time window, I’d probably have more detail to help locate where I could improve the performance of the Web app. You may also want to check out the Status Message panel for additional information about the test.

I was able to do this without writing code and with just a couple of clicks in the portal. Just keep in mind that there is a charge for performing a load test in terms of virtual users.

Working with App Settings

Here’s a trick to take advantage of App Settings to store a Key/Value pair securely in Azure and access it in your Web app.

App Settings are used to store configurable items without making any changes to the code. The key-value pairs are stored behind the scenes in a configuration store, which is nice because sensitive information never shows up in a web.config file or wherever else you store secrets. In order to take advantage of this, you must log into your Azure account and go to the App Service you created. Look under Settings to see Application Settings.

Let’s add an App Setting in Azure, with the key of Environment and the value set to Staging. Open or create an ASP.NET MVC app (for example) and modify the appSettings section of the web.config file to add the Environment key/value pair as shown here:

<appSettings>
  <add key="webpages:Version" value="3.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="Environment" value="Production" />
</appSettings>

Now it’s in the Web configuration section of the app. In order to see the value, you need to add it to a page inside of your app to display the value for this example.

Using ASP.NET MVC, navigate to your appname/Views/Home/Index.cshtml file and add the following using statement followed by a call to ConfigurationManager:

@using System.Configuration
@{
  ViewBag.Title = "Home Page";
}
<div class="jumbotron)
  <h1>Testing App Settings</h1>
  @ConfigurationManager.AppSettings["Environment"]
</div>

If you run the application locally, you’ll see Production as it’s coming from the web.config file, but if you run it inside Azure, you’ll see Staging as it’s coming from the App Settings configuration store located in Azure. Neat stuff!

You may have noticed Connection Strings visible right below the App Settings option and wondered when to use it. A general rule of thumb is to use Connection Strings for database connection strings and App Settings for key-value pair application settings. If you examine your web.config file, you’ll see that there’s also a section for connectionStrings, just as there’s a section for appSettings.

Cloning Web Apps

Cloning is the ability to clone an existing Web App to a newly created app that’s often in a different region. This enables customers to deploy a number of apps across different regions quickly and easily.

For instance, a company might have an existing Web app in the West U.S. region, and would like to clone the app to the East U.S. region to reduce latency and improve performance for users in that area.

To do this, log into your Azure account and go to the App Service you created and under Development Tools click Clone App. Enter the following information:

  • App Name: Make sure to use something unique as this site will live in something.azurewebsites.net
  • Resource Group: Create a new group or use an existing one
  • App Service Plan/Location: This is a good time to associate a new plan that will determine the location, features, cost and compute resources associated with your app

Besides changing the location, this is also a great time to determine the required app service plan. You might not need all the horsepower to serve this site if you expect very low traffic in that region.

  • Clone Settings: This will copy the content and certificates of your app into a newly created application—you can also copy things like App Settings, Connection Strings, Deployment Source and Custom Domains
  • Application Insights: Enable this service to help you detect and diagnose issues and more with .NET apps

Finally, there’s Automation Options, which brings you to the Azure Resource Manager templates that are so valuable. Learn more about Azure Resource Manager templates at bit.ly/2RTVfri.

Azure Resource Manager enables you to work with the resources in your solution as a group. You can deploy, update or delete all the resources for your solution in a single, coordinated operation. You use a template for deployment, and that template can work for different environments such as testing, staging and production. Resource Manager provides security, auditing and tagging features to help you manage your resources after deployment. Read more at bit.ly/2Pv9aY5.

Once everything is set up, press Create and you’ll see Deployment in Progress overlay on the screen. You can click on it while deploying to see details such as status, duration of deployment, location and more.

Working with Log Stream

Log Stream is the ability to see logging information in real time (or as close to it as possible). You can do this using the Azure Portal or through some of the CLI tooling such as PowerShell or BASH. To take advantage of this, log into your Azure account, go to your App Service and open the Log Stream item under Monitoring. You’ll see that most of the Application logs are switched off. To turn them on, you’ll need to go to the Diagnostic logs setting in the same panel.

Here you’ll see the following options:

  • Application Logging allows you to collect diagnostic traces from your Web code. This is required for the streaming log feature and turns itself off after 12 hours.
  • Application Logging (Blob) produces logs that are collected in the blob container specified under Storage Settings.
  • Web server logging gathers diagnostic information for your Web server.
  • Detailed error messages gathers detailed error messages from your Web app.
  • Failed request tracing gathers diagnostic information on failed requests.

You can easily change options such as the physical disk size of log files that Azure will store, as well as the number of days to keep the log files in retention. You can also download the log files via FTP and FTPS.

Go ahead and turn Application Logging(Filesystem) to On and the Level to Info and press save. Go back and click on the Log Stream setting and visit your Web page (that’s hosted on azurewebsites.net). You should see a log. If you look at the first couple of lines, you’ll see a ReadyForRequest on port 80, followed by a request from our Web browser that includes pulling down the favicon.ico file (which is the only image being sent down).

Add Trace Logging in Code

Using the ASP.NET MVC app from earlier, navigate to your appname/Controllers/HomeController.cs file (or wherever you’d like to test this functionality) and add the following line:

System.Diagnostics.Trace.WriteLine("Entering the About View");

Head back over to Diagnostic logs and ensure the Application Logging (Filesystem) Level is set to Verbose, then press save since we just used a WriteLine command. Switch back over to the Log Stream option and trigger the error by opening the site and navigating to the About page. Review the Application Log after it calls your Trace.WriteLine command. You should see the message “Entering the About View” that was specified in the Trace.WriteLine call.

Wrapping Up

Today you learned a number of tricks in Azure App Service that can help you be more productive. But this article barely scratches the surface of the things you can do. Over the past year I’ve compiled a library of valuable tips, tricks and secrets that cover such things as using .NET Core, Application Insights for rich analytics, user authentication and more. If you liked what you saw in this article, go check out the entire collection of Azure App Service tips at azuredev.tips, or visit videos.azuredev.tips to view short videos of many of these tips and tricks.


Michael Crump works at Microsoft on the Azure platform and is a coder, blogger and international speaker of various cloud development topics. He’s passionate about helping developers understand the benefits of the cloud in a no-nonsense way. You can reach him on Twitter: @mbcrump or by following his blog at michaelcrump.net.

Thanks to the following Microsoft technical expert for reviewing this article: Cecil Phillip


Discuss this article in the MSDN Magazine forum