Quantcast
Channel: Http Client Protocol Issues (and other fun stuff I support)
Viewing all 140 articles
Browse latest View live

Create a Staging Slot for Migrated Azure Mobile Service

$
0
0

 

When you Migrate your Existing Azure Mobile Service to an App Service you may want to take advantage of the slots available to you and create a Staging (and other) slot to test you code in.  This will walk you through an easy way to do this.

Create the new slot in the portal and choose the parent site as the configuration source:

create

Test the slot to see if you can access it (note the difference in the domain… it is azurewebsites.net with –staging after the parent name):

test slot

Go to Kudu and download the entire parent site:

gotosourcekudu

In Kudu, choose Debug Console and CMD… Click on the drive icon to download the entire site:

kudu download

Now open the staging slot in Kudu and upload it.

Click on the Site folder and drag the zip file you just downloaded onto the right side of the directory as shown:

draghere

This will unzip the site and you will have a copy of that site!

drag result

You can test this staging site in Postman or Fiddler if you like and you will see it is still hitting the same database:

postman

 

It is a good idea not to mess with production database so we will create a copy and point the staging slot to this copy.

Go to the Mobile Service database and choose Copy (in this case I am using the same server.  If you choose a different server it gets more complicated and so I leave that to another post).

 

You will need to change the database connection string in the slot application settings to point to your test database.

copydb

Once that is finished it has copied the database schema and user login information from the original database.

All you need to do now is open the staging slot and change the database name in the connection strings:

slotsettings

Look for the Database part of the three connection strings listed below:

For example change:

Database=jsandersMultiAuthMobile_db;  To  Database=jsandersMultiAuthMobile_db_Staging;

For these strings:

UserConnectionString

MS_SqlConnectionString

MS_TableConnectionString (this one is used for Easy Tables)

Finally test in Postman by adding a record to the Staging site and ensure when you get the record it is not reflected in the production database!

Please drop me a note if you found this post useful!


Manually Attach a Debugger to Azure Web Apps

$
0
0

For various reasons you may have difficulty attaching your debugger to an Azure Web App.  This quick blog will show you a method that may work for you if you get into this situation.  I will NOT attempt to diagnose your issue in this blog so please don’t post a question asking why the normal methods don’t work for you (like right clicking your resource in Server Explorer of Visual Studio).

Step 1. From the main menu, click on the Debug menu item and select Attach to Process …

 

snip_20160209113425

Type in the URL of your Azure Web App and add the :4020 port (default debugging port) then hit enter and a credential dialog will appear:

snip_20160209114253

For the User name and Password you can download the Publish Profile and extract it from there:

snip_20160209114840

Look for “userName” and “userPWD” in that file.  Note when you enter the user name you will need to also include the domain.  For example: if the username is ‘$constowebapp’ when you enter it in the credential dialog it should be entered like this ‘$contosowebapp\$contosowebapp’.

Now that you are authenticated choose the w3wp.exe process:

snip_20160209115800

I know this was a quick and dirty blog but let me know if this helped you out.  Again… My intent is not to troubleshoot your connection issues (firewall could be in the way, invalid or outdated publish profile could be associated with your app… The list goes on and on) but to get you unblocked so you can debug!

Azure Mobile Apps–How to remove the notification hub and get the wizard back

$
0
0

I noticed that you cannot change the notification hub in the UI.  There is a simple workaround (it will be fixed by the way).

Here is a picture of what I mean:

capture20160219144141503

Run this powershell script from the Azure Powershell (or do similar using the Azure CLI):

Remove-AzureRmResource -ResourceId /subscriptions/<SUBCRIPTION_ID>/resourcegroups/<RESOURCE_GROUP>/providers
/Microsoft.Web/sites/<APP_NAME>/providers/Microsoft.Resources/links/mobile-notificationhub

snip_20160219145313

And I get my wizard back!

capture20160219145117858

Let me know if this is helpful by dropping me a note!

How to Add Custom Domains to Azure Web Apps Using Powershell

$
0
0

Just another quicky post:

If you need to add a custom domain to an Azure Web App you can use Powershell.  Powershell does the same verification that the UI does and is just another way to accomplish setting the custom domain or domains.

Note that you don’t set, nor can you change the default azurewebsites.net domain.

Here is an example.  Lets say I have an azure webapp: jsandersprod.azurewebsite.net and I want to add the www.jsanders.com and dev.jsanders.com sub domains to it.  Assuming I have set this up already with my domain provider here is how I do it in powershell:

Get-AzureWebsite -Name "jsandersprod" | Set-AzureWebsite -HostNames @("dev.jsanders.com",www.jsanders.com)

That is all there is to it!

Please drop me a note if you found this useful!

Troubleshooting Retrieving Certificates in Azure App Services

$
0
0

You can upload and use Certificates securely in your Azure App Service (Azure Web App, Azure Mobile App etc… ).  If you are having trouble, here are some basic troubleshooting steps.

Example error: ”cannot find certificate with thumbprint”

Is your certificate loaded in your Resource Group?  You can search for the thumbprint using the Azure Resource Explorer

Is your site at least Basic SKU?  This is required.

Did you set the Web App setting: WEBSITE_LOAD_CERTIFICATES?  Try setting the WEBSITE_LOAD_CERTIFICATES  value to * for testing purposes

What is your code doing?  Here is how you can load all certificates and display the first one.  See the original article for picking one by thumbprint.

static string testcert()
        {

            string strRes = "no certs found";

            //Cert Store for CurrentUser is the only one we can get certificates for
            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            //Open it read only
            certStore.Open(OpenFlags.ReadOnly);

            // if we have any certificates...
            if (certStore.Certificates.Count > 0)
            {
                //Just get the first one
                X509Certificate2 cert = certStore.Certificates[0];

                // Use certificate
                // In this case get the subject
                strRes = cert.Subject;
                Console.WriteLine(strRes);
            }

            //Don't forget to CLOSE the store
            certStore.Close();
            return strRes;
        }

 

Debug the app to see what is going on in your Cert Code!  If the cert shows up in the Portal for your web app then it must be loaded in the resource group.

Ensure the StoreName.My and StoreLocation.CurrentUser is where you are looking for the cert!

 

I know this is simple but sometimes it helps to have a checklist!  Let me know if this was useful to you by dropping a comment!

Azure Mobile Service Creation fails "this name is already in use"

$
0
0

Just a quick blog on this…

Problem

You cannot create an Azure Mobile Service.  You enter a unique name when creating the Mobile Service but get an error:  “this name is already in use” and a red exclamation mark.

 

Reason

Mobile Services are deprecated, that is why you cannot create one. Please see this article: https://azure.microsoft.com/en-us/blog/transition-of-azure-mobile-services/

 

Solution

You must create a Mobile App instead in https://portal.azure.com. Here is a quick start for you to follow: https://azure.microsoft.com/en-us/documentation/learning-paths/appservice-mobileapps/

and

https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-windows-store-dotnet-get-started/

 

No the error is not intuitive and we are getting that fixed!

Easy tables, Easy APIs error message ‘Unsupported Service’

$
0
0

Overview

When you try to access or create Easy tables or Easy APIs in Azure App Services or Azure Mobile Apps you may get this error message in the portal: Unsupported service.

Cause

Easy tables and Easy APIs are only available to an Azure Mobile App that has been created initially as an Azure Mobile App and with a Node.Js backend in the quckstart OR to an Azure Mobile App Quickstart.

Fix

Create a new Azure Mobile App, choose quickstart and select Node.js when you are prompted for the backend OR choose Mobile Apps Quickstart and create your Easy Tables.

capture20160824100433414

FAQ:

But I don’t want to create a new Azure Mobile App, what can I do? – You can grab the necessary Node.js code from a quickstart you have created and then edit the code to add tables.  You can use https://NAMEOFYOURAPP.scm.azurewebsites.net/dev to see and edit the table and api code (see below on how this works).  You can view you tables with your favorite database access tool.

How does the Easy Table/API functionality work if I don’t see them in the UI? – The mobile app node.js packages look for certain files in the Tables and API directories (mytable.js and mytable.json for example).  It uses express middle ware and when it sees them they dynamically add then to the expressroute.

What if I need more help? –  StackOverflow and MSDN forums are you first option, creating a support case is another.

More Info:

You can also not use easy tables/apis and manually define the routes and add your code:

https://shellmonger.com/30-days-of-azure-mobile-apps-the-table-of-contents/

https://shellmonger.com/2016/04/15/30-days-of-zumo-v2-azure-mobile-apps-day-8-table-controller-basics/

https://shellmonger.com/2016/05/13/30-days-of-zumo-v2-azure-mobile-apps-day-20-custom-api/ (Version 2: The Node.js Custom API)

How to deny HTTP methods (or verbs) in Azure Web Apps

$
0
0

If you want to deny HTTP methods or verbs in Azure Web Apps you can do this be changing your web.config file.

Add the following or create the following sections if they do not exist in your <configuration> section of your Azure Web App, web.config file:

<system.webServer>
    <validation validateIntegratedModeConfiguration=”false” />
    <modules runAllManagedModulesForAllRequests=”true” />
    <handlers>
        <add name=”DenyOTH” verb=”OPTIONS,TRACE,HEAD” path=”*” type=”System.Web.HttpMethodNotAllowedHandler” />
</handlers>
</system.webServer>

 

Once you add this, the response to any HTTP Verb in the verb list (in this case “OPTIONS,TRACE,HEAD”) will result in a response: 405 Method Not Allowed.

 

Let me know if this helped you out!

Also, see this blog post for removing headers: Remove ‘Server’ and ‘X-Powered-By’ headers from your Azure Mobile Apps


Execute Transactions from Azure Mobile App API (node.js)

$
0
0

Using the Azure Mobile App API interface (like: https://mymobileapp.azurewebsites.net/api/doTransActionStuff ) with a node.js backend, I found documentation around executing SQL Transactions a little light.  So… Here are some options you could use:

1. Call a stored procedure that does everything for you

This would be the way I would do it!  Stick all of the logic in a stored procedure and make the Azure SQL Database do the work for you.  This also is the best performing solution since there is only one call to the Database and the Database is doing the work for me.  This assumes you can write a stored procedure of course!  Simply call the stored procedure with arguments from within the API using something like this:

// an example of executing a stored procedure that internally is using transactions
     post: (request, response, next) => {
             var query = {
                     sql: 'EXEC completeAllStoredProcedure @completed',
                 parameters: [
                     { name: 'completed', value: request.query.completed }
             ]
         };


         request.azureMobile.data.execute(query)
             .then(function (results) {
                     response.json(results);
                 });
     }

Sample: https://github.com/Azure/azure-mobile-apps-node/blob/master/samples/custom-api-sql-stmt/api/completeall.js

Note: The parameters are passed in via the client.  The raw HTTP would look something like this –> http://mymobileapp.azurewebsites.net/api/doTransActionStuff?completed=true.  For .NET Clients you would use InvokeApiAsync https://msdn.microsoft.com/en-us/library/azure/dn268343(v=azure.10).aspx
iOS clients: InvokeApi https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-ios-how-to-use-client-library/

 

2. Call execute and build your statements into a query

Yet another way that would be fairly efficient is to build up the SQL statement as a string and embedded any passed in parameters (like above) if necessary and call execute

"get": function (req, res, next) {
    var query = {
        sql: "SET XACT_ABORT ON \
                    BEGIN TRANSACTION \
                    <”normal” statement that works> \
                    <”invalid” statement that goes against a constraint I created> \
                    COMMIT TRANSACTION \
                    SET XACT_ABORT OFF",
        parameters: []
    };
    req.azureMobile.data.execute(query);
}

 

3. User the built in Driver Transaction functionality

I would use this if I am already familiar with driver (like tedious) and want all my code to be in the Mobile App.  Not the most efficient and results in several calls to the Database:

module.exports = {
    "get": function (req, res, next) {

        var globalErrMessage = "";
        function handleErr(source, err) {
            var theError = source + ": " + err;
            console.error(theError);
            globalErrMessage = globalErrMessage + theError;
            globalSuccess = false;
        }

        var sql = require('mssql');

        var config = {
            driver: 'tedious', // use tedious driver
            server: 'jsandersmobileappdbserver.database.windows.net',
            user: 'username@jsandersmobileappdbserver',
            password: 'password',
            port: '1433',
            options: {
                encrypt: true,
                database: 'jsandersmobileDb',
                debug: {
                    packet: true,
                    data: true,
                    payload: true,
                    token: false,
                    log: true
                }
            }
        };

        var rolledBack = false;
        var globalSuccess = true;

        console.info("starting");
        sql.connect(config, function (err) {
            if (err) {
                handleErr("sql.connect", err);
            }
            else {
                // ... error checks - todo
                console.info("OK:connected");
                var transaction = new sql.Transaction(/* [connection] */);
                transaction.begin(function (err) {
                    // ... error checks
                    if (err) {
                        handleErr("transaction.begin", err);
                    }
                    //Rollback event
                    transaction.on('rollback', function (aborted) {
                        // emited with aborted === true
                        console.info("Event:transaction.on('rollback')");
                        rolledBack = true;
                    });

                    var request = new sql.Request(transaction);
                    request.query('insert into mytable (bitcolumn) values (2)', function (err, recordset) {
                        // insert should fail because of invalid value

                        if (err) {
                            handleErr("ERR:request.query", err);

                            // if not rolled back then rollback this transaction
                            if (!rolledBack) {
                                transaction.rollback(function (err) {
                                    if (err) {
                                        handleErr("ERR:transaction.rollback", err);
                                    }
                                    else {
                                        console.info("OK:transaction.rollback");
                                    }
                                });
                            }
                        } else {
                            transaction.commit(function (err) {
                                // ... error checks
                                if (err) {
                                    console.log("ERR:transaction.commit");
                                    console.log(err);
                                }
                                else {
                                    console.log("OK:transaction.commit");
                                }
                            });
                        }
                    });

                });
            }
        });

        if (rolledBack) {
            res.json("Rolled Back");
        }
        else if (globalSuccess) {
            res.json("success");
        }
        else {
            res.json("error");
        }
    }
};


 

I hope this is useful in getting you jumpstarted!

Drop me a note if you find this useful!

Automating EasyTables for Azure Mobile Apps

$
0
0

You could use the Azure CLI to create Azure Mobile Service tables for the node.js backend.  You can no longer do this but there is a much easier solution.  You can simply drop a .json file in the ‘Tables’ directory and when the app starts it will create the table in the database and make it accessible to the /tables/ route in your Azure Mobile App.  This only works for the node.js backend.

Scenario

You want to be able to add a table to your Azure Mobile App through scripting or automation.  You are using the node SDK for Azure Mobile Apps.  In this example I am adding a table called ‘testdrop’.

Setup

Start with the quickstart code that gets generated for you when you go through the portal and choose the quickstart option and node.js backend.

Details

The node SDK quickstart has the following directory structure:

capture20160930094545240

TIP:  You can view your app files using the App Service Editor, available in the Azure Portal or by typing https://<NAMEofYourMobileAppHere>.scm.azurewebsites.net/dev.

If you open the tables directory you will see some .json and .js files that correspond to each table you have defined so far in your mobile app:

capture20160930095254434

The .json files define the table attributes like columns, dynamic schema and permissions.  The .js files define the code (if any) used when accessing the table Insert, Read, Update, Undelete or Delete functions (open them and check them out).

In this example I want to add a table called ‘testdrop’ to my Azure Mobile App with the following columns:

"columns": {
    "userid": "string",
    "text": "string",
    "complete": "boolean",
    "due": "datetime",
    "alert": "number"
  },

I also want to turn off dynamic schema and turn on soft delete and I do not want to do any special processing on the data.

All I need to do is to create a file called ‘testdrop.json’ and put it in the ‘Tables’ directory.  When the Mobile App runs (if you are using the quickstart the new file will trigger an app restart) the new table will be created for me and be accessible to my Azure Mobile App clients.

Sample json file contents:

{

  "columns": {
    "userid": "string",
    "text": "string",
    "complete": "boolean",
    "due": "datetime",
    "alert": "number"
  },
  "dynamicSchema": false,
  "autoIncrement": false,
  "softDelete": true,
  "read": {
    "access": "anonymous"
  },
  "insert": {
    "access": "anonymous"
  },
  "update": {
    "access": "anonymous"
  },
  "delete": {
    "access": "anonymous"
  },
  "undelete": {
    "access": "anonymous"
  }
}

 

Once you have this file then you need to get it into the Tables directory of your app.  If you are scripting this through automation simply use FTP to transfer this file to your Azure Mobile App:  https://github.com/projectkudu/kudu/wiki/Accessing-files-via-ftp

If you are not scripting you can create the file in the App Service Editor or at the Kudu command prompt or drag and drop the file into the directory using Kudu Console:  https://github.com/projectkudu/kudu/wiki/Kudu-console

More info

You can also add the testdrop.js file and add appropriate code for your solution if you want to do something to the data that is not just standard CRUD operations. 

You can define the table in your app.js file as well:  mobileApp.tables.add(‘TodoItem’); // Create a table for ‘TodoItem’ with default settings  (see: https://azure.github.io/azure-mobile-apps-node/https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-node-backend-how-to-use-server-sdk/ )

You can define the table schema in the .js files as well with syntax like this:  https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-node-backend-how-to-use-server-sdk/ see: How to: Define tables using a static schema

 

Conclusion

There are many different ways to add tables to the Node SDK based backend.  This super simple method may help you out in your solution.  If so drop a comment letting me know how this worked for you!

Run an async task in a console app and return a result

$
0
0

I had someone ask how to run an async task in Main of a console app.  Yes there are different ways to do it and this is just one!

 

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace UrlAuth
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Start a task - calling an async function in this example
                Task<string> callTask = Task.Run(() => CallHttp());
                // Wait for it to finish
                callTask.Wait();
                // Get the result
                string astr = callTask.Result;
                // Write it our
                Console.WriteLine(astr);
            }
            catch (Exception ex)  //Exceptions here or in the function will be caught here
            {
                Console.WriteLine("Exception: " + ex.Message);
            }


        }

        // Simple async function returning a string...
        static public async Task<string> CallHttp()
        {
            // Just a demo.  Normally my HttpClient is global (see docs)
            HttpClient aClient = new HttpClient();
            // async function call we want to wait on, so wait
            string astr = await aClient.GetStringAsync("http://microsoft.com");
            // return the value
            return astr;
        }
    }
}

Drop me a note if this helped you out!

How to use Fiddler to Debug Azure App Service issues (with authentication)

$
0
0

Sometimes it is difficult to isolate Azure App Service issues to determine is the problem is the client or server.  You can remove the client easily using a tool like Fiddler or Postman however is you are using authentication there are some tricks you need to use.  I will demonstrate this with Azure Mobile Apps, but this will work with any Azure App Service using authentication.

Step 1 – Ensure authentication is set up correctly

This is easy to test:  Simply try to hit the /.auth/login/<provider> endpoint of your Azure App Service and see if this succeeds.

For example:  https://jsandersrockstest.azurewebsites.net/.auth/login/facebook to test if my facebook provider has been set up correctly.

capture20161110105813225

If there is an issue, you cannot proceed.  If you DO get an error, this method of using the /.auth/login/<provider> in the browser will tell you what the problem is, for examples:

URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.

Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

Fix these issues then proceed.

Step 2 – Get the x-zumo-auth token

This is the authentication token from Step 1.  It is actually part of the return URI in the address bar (starts at #token).  What I do is use Fiddler Text Wizard to help grab this.

Copy the entire address bar from the browser (you can use <ctrl><a> <ctrl><c>) open Fiddler, stop capturing (click on the bottom left corner of Fiddler) and go to Tools, Text Wizard.  As you see below the wizard will automatically to a URL Decode transform and you can see the JSON of the token.  What we want is the highlighted portion you see below which is the value of the “authenticationToken”.  Do NOT grab the enclosing quotes.  This will be the value we use for the x-zumo-auth token.

 

capture20161110113903465

Handy tip:  To see the JWT contents use the Text Wizard to perform a ‘From Base64’ transform

Step 3 – Use the x-zumo-auth token to authenticate a request

 

Fiddler and Postman have the ability to construct a request.  I will use the Fiddler Composer tab and make an authenticated request to my Azure Mobile Apps backend.

Open the composer tab in Fiddler and create an HTTPS request to the endpoint.  In my case I am going after the /tables/todoitem endpoint.  I add the x-zumo-auth from the previous step to the headers section and since this is an Azure Mobile App I need to also add the zumo-api-version: 2.0.0 header.  If you do not specify the zumo-api-version you will get a response and the body will tell you that you need to add this!

 

capture20161110114732831

Now the request is authenticated and you can test your backend without your client!

 

If you found this post useful, please drop me a note and let me know!

 

References

Authentication and authorization in Azure App Service

Client and server versioning in Mobile Apps and Mobile Services (zumo-api-version)

How to use Fiddler to Debug Azure App Service issues (with authentication)

$
0
0

Sometimes it is difficult to isolate Azure App Service issues to determine is the problem is the client or server.  You can remove the client easily using a tool like Fiddler or Postman however is you are using authentication there are some tricks you need to use.  I will demonstrate this with Azure Mobile Apps, but this will work with any Azure App Service using authentication.

Step 1 – Ensure authentication is set up correctly

This is easy to test:  Simply try to hit the /.auth/login/<provider> endpoint of your Azure App Service and see if this succeeds.

For example:  https://jsandersrockstest.azurewebsites.net/.auth/login/facebook to test if my facebook provider has been set up correctly.

capture20161110105813225

If there is an issue, you cannot proceed.  If you DO get an error, this method of using the /.auth/login/<provider> in the browser will tell you what the problem is, for examples:

URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.

Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

Fix these issues then proceed.

Step 2 – Get the x-zumo-auth token

This is the authentication token from Step 1.  It is actually part of the return URI in the address bar (starts at #token).  What I do is use Fiddler Text Wizard to help grab this.

Copy the entire address bar from the browser (you can use <ctrl><a> <ctrl><c>) open Fiddler, stop capturing (click on the bottom left corner of Fiddler) and go to Tools, Text Wizard.  As you see below the wizard will automatically to a URL Decode transform and you can see the JSON of the token.  What we want is the highlighted portion you see below which is the value of the “authenticationToken”.  Do NOT grab the enclosing quotes.  This will be the value we use for the x-zumo-auth token.

 

capture20161110113903465

Handy tip:  To see the JWT contents use the Text Wizard to perform a ‘From Base64’ transform or you can use a tool like https://jwt.io/ to troubleshoot, verify and decode the token, see the claims, verify the iss, aud and contents of this token.

Step 3 – Use the x-zumo-auth token to authenticate a request

 

Fiddler and Postman have the ability to construct a request.  I will use the Fiddler Composer tab and make an authenticated request to my Azure Mobile Apps backend.

Open the composer tab in Fiddler and create an HTTPS request to the endpoint.  In my case I am going after the /tables/todoitem endpoint.  I add the x-zumo-auth from the previous step to the headers section and since this is an Azure Mobile App I need to also add the zumo-api-version: 2.0.0 header.  If you do not specify the zumo-api-version you will get a response and the body will tell you that you need to add this!

 

capture20161110114732831

Now the request is authenticated and you can test your backend without your client!

 

If you found this post useful, please drop me a note and let me know!

 

References

Authentication and authorization in Azure App Service

Client and server versioning in Mobile Apps and Mobile Services (zumo-api-version)

https://jwt.io/ to troubleshoot, verify and decode the token

How to get a full memory dump in Azure App Services

$
0
0

There are a ton of blogs on getting full memory dumps but some get complicated.  Note then when you create a full memory dump it will have the effect of pausing your web app so use this judiciously!  Here is my simple version

Go to the Kudu site for your Azure Web App (or App Service)

You can do this from the portal for your app or simply use the azurewebsites.net url for your app and insert .scm after the name.  For example:

https://problemwebapp.scm.azurewebsites.net

Find the Process ID (pid) of the process you wish to get a dump for

Navigate to the Process Explorer by clicking on the Process explorer tab at the top of the page.

You will want the pid for the w3wp.exe process (in this case 5484) that is running your code.  This is NOT the SCM process.  That is the process running the Kudu site.

Note: .Net Core apps will be a sub process listed under the w3wp.exe process.  Java process would be a different process as well

capture20170202114609022

Go do the Debug console and capture the dump

Navigate by choosing the Debug console, then CMD pull down to get to the command line interface:

capture20170202115040673

Create a directory for the dumps and navigate there as pictured below using the commands: cd logfiles, md dumps, cd dumps

capture20170202115311981

Now you can create the full memory dump with this command:

d:\devtools\sysinternals\procdump -accepteula -ma 5484

And this will write a dump to the current directory:

capture20170202115903578

Note:  You can use several different procdump commands.  See this site for more options: ProcDump – technet.microsoft.com

Download Dumps for analysis

The easiest way is to navigate back to the log files directory and click on the download icon for the entire directory.  This will zip that folder and download it.

You can navigate through the directory structure by clicking on the icons at the top.  For instance click on the picture of the house, then the text LogFiles next to the folder icon.  Click on the down load icon for the dumps directory you created the dump in.

snip_20170202120509

 

capture20170202120545552

 

Alternatively you can zip files using the built in tools:

d:\7zip\7za a dumps.zip w3wp.exe_170202_165808.dmp

And download the zip by navigating to it in the Debug console and using the download console, or not zip the dump at all and download it!

Analyzing the dump

By far DebugDiag is the fasted way to analyze your dump.  You could also use Visual Studio.

Download Debug Diagnostic Tool v2 Update 2 from Official

 

Drop me a note if you thought this was useful!

Azure Traffic Manager probe degraded due to 401 from Azure Web App

$
0
0

Symptom

Your Azure Web App (or any Azure App Service) has authentication enabled but you want to use Traffic Manager.  Since the probe returns the HTTP status code 401, the endpoint is considered degraded.

Cause

Whatever you use for an endpoint in Azure Traffic Manager, it must return a 200.  Your site is locked down so any request returns 401

Solution

Use URL Authorization rules with a special Route to allow the ping to succeed.  Note:  This is in preview, so there may be updates as this matures.

  1. Create a directory in your application and call it whatever you wish (for this sample I am using TMStatus).
  2. Put an html file in it and call it something like status.html.
  3. Next add URL Authorization Rule to disable authentication for that directory and ensure you place this json file it in the wwwroot directory.  See: URL Authorization Rules  In this case All routes will be RedirectedToLogin, however the /TMStatus route will allow anonymous requests.

Your json would look something like this:

{
  “routes”: [{
      “path_prefix”: “/”,
      “policies”: { “unauthenticated_action”: “RedirectToLoginPage” }
    },{
      “path_prefix”: “/TMStatus”,
      “policies”: { “unauthenticated_action”: “AllowAnonymous” }
    }]
}

   4. Configure Authorization to Allow Anonymous requests in your Azure Portal:

snip_20170206104636

This should restart your web app and pickup the changes, then point traffic manager to your app/TMStatus/status.html  (or whatever you choose to call these from above).

Now when the ping from traffic manager hits this endpoint, it will return a 200 instead of a 401.


Cannot read property ‘listRegistrationsByTag’ of undefined’ (Azure App Services)

$
0
0

Situation:

You are creating a Mobile App or Azure App Services and setting up the push notifications for the first time

Problem:

Calling Register or RegisterAsync in the client code can result in a 400 status code coming back with an inner exception of: ‘Cannot read property ‘listRegistrationsByTag’ of undefined’

Cause:

The Portal blade does not set the Application Setting MS_NotificationHubName

Workaround:

Add MS_NotificationHubName in the Application settings.  The name will be the name of your Notification Hub.  It is the last item after the \ in the setting MS_NotificationHubId or you can get in from the notification Hub blade:

capture20170223080119644

 

capture20170223080212770

More information:

Once this is fixed the Portal Blade will set the MS_NotificationHubName for you when you walk through the Portal setup of Push notifications.  At that time I will update this Blog!  If you need further help, you can certainly open a support case through the Azure Portal.

Accessing Azure App Services using Azure AD Bearer token

$
0
0

Overview

Here are some simplified instructions on how to setup and use Azure Active Directory authentication for Azure App Services and code that will allow an application to use a Bearer Token to access that app.

Review

Simply put, the OAuth Bearer Token simply identifies the app that is calling an Azure Active Directory registered application.  The calling application requests a Token from AD by providing some information to include the Client Secret and Application ID of the app that will be calling the target app (the app that will use the token) as well as the Application ID of the application you wish to call.  The client secret is the key that you want to protect and keep ‘secret’.

Walkthrough

Register the target app you want to call in Azure AD and get the Application ID.  No client secret required.

Simply click on the application in the portal and enable Azure AD authentication (express) and save.

Copy the Application ID.  After the app is updated go back into the Azure Active Authentication and click on the Advanced button.  This will allow you to copy the Application ID:

snip_20170317080739

 

Register the client app you want to call from in Azure AD and get the Application ID, and generate a Client Secret Key

Simply click on the application in the portal and enable Azure AD authentication (express) and save.

You now need to go to the application registered in Azure AD and get the Application ID and generate a Client Secret.  Copy the Application ID and Client Secret of this client app to use later like you did in the previous step.

capture20170316102620455

Generate a client Secret by going to Azure Active Directory in the portal.  Search for the Client app:

capture20170316102812597

In Settings choose Keys:

capture20170316102831349

In Keys create a New Key (name it whatever you want) and Save:

capture20170316102907130

Important.  When you save you need to copy the Value for later as you cannot come back and get it.  This is the Client Secret.

capture20170316102930647

Note:  You can always generate a new secret if you forget or lose it.

Create code to get a Bearer token from Azure AD and use this token to call the Target app

Now you simply need to use the values from above to request a token and make a request using that token in the Authorization header.

Here is some sample code.  First the ServicePrinciple class is used to build and get the token.  I am using the latest ADAL library we provide (Microsoft.IdentityModel.Clients.ActiveDirectory ver 3.13.8:

capture20170317081758672

    public static class ServicePrincipal
    {
        /// <summary>
        /// The variables below are standard Azure AD terms from our various samples
        /// We set these in the Azure Portal for this app for security and to make it easy to change (you can reuse this code in other apps this way)
        /// You can name each of these what you want as long as you keep all of this straight
        /// </summary>
        static string authority = ConfigurationManager.AppSettings["ida:Authority"];  // the AD Authority used for login.  For example: https://login.microsoftonline.com/myadnamehere.onmicrosoft.com
        static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; // the Application ID of this app.  This is a guid you can get from the Advanced Settings of your Auth setup in the portal
        static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"]; // the key you generate in Azure Active Directory for this application
        static string resource = ConfigurationManager.AppSettings["ida:Resource"]; // the Application ID of the app you are going to call.  This is a guid you can get from the Advanced Settings of your Auth setup for the targetapp in the portal

        /// <summary>
        /// wrapper that passes the above variables
        /// </summary>
        /// <returns></returns>
        static public async Task<AuthenticationResult> GetS2SAccessTokenForProdMSAAsync()
        {
            return await GetS2SAccessToken(authority, resource, clientId, clientSecret);
        }

        static async Task<AuthenticationResult> GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
        {
            var clientCredential = new ClientCredential(clientId, clientSecret);
            AuthenticationContext context = new AuthenticationContext(authority, false);
            AuthenticationResult authenticationResult = await context.AcquireTokenAsync(
                resource,  // the resource (app) we are going to access with the token
                clientCredential);  // the client credentials
            return authenticationResult;
        }
    }

And then using this class my code to fetch data from the Target resource:

protected async void Page_Load(object sender, EventArgs e)
{
    // Normally you would use a single Global HttpClient per MS guidance
    // but for demo purposes... Just create one inline
    HttpClient client = new HttpClient();

    // This is an Aspx page so clearing anything already written in the buffer
    Response.Clear();

    try
    {
        // get the token
        var token = await ServicePrincipal.GetS2SAccessTokenForProdMSAAsync();

        // set the auth header with the aquired Bearer token
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer",token.AccessToken);

        // make the call to the resource requiring auth!
        var resp = await client.GetAsync("https://jsandersapicall.azurewebsites.net/");

        // do something with the response
        Response.Write(resp.StatusCode.ToString());
    }
    catch (Exception ex)
    {
        // important to log the exception if any because it will tell you what went wrong
        Response.Write(ex.Message);
    }

    // write page out
    Response.Flush();
}

 

Conclusion

This is a very compact sample that can be used as a checklist.  It eliminated a lot of the information in our documentation here: Service principal authentication for API Apps in Azure App Service 

Drop me a note if you found this useful!

Accessing Azure App Services using Azure AD Bearer token

$
0
0

Overview

Here are some simplified instructions on how to setup and use Azure Active Directory authentication for a client Azure App Services application and code that will allow a client application to use a Bearer Token to access a different target app.   In this scenario there are two web apps.  The client app is the app that has code to call to the target app.  Anyone can reach the client app without authentication and the client app then uses a Bearer token to access the target app which requires Active Directory Authentication.  This assumes you have already created both apps in the Azure Portal

Review

Simply put, the OAuth Bearer Token simply identifies the app that is calling an Azure Active Directory registered application.  The calling application requests a Token from AD by providing some information to include the Client Secret and Application ID of the app that will be calling the target app (the app that will use the token) as well as the Application ID of the application you wish to call.  The client secret is the key that you want to protect and keep ‘secret’.

Walkthrough

Register the target app you are calling from the client app in Azure AD and get the Application ID.  No client secret required.

My target app is https://jsandersapicall.azurewebsites.net.   Simply click on the application in the Azure Portal and enable Azure AD authentication (express) and save.

Copy the Client ID (which is also know as the Application ID).  After the app is updated go back into the Azure Active Authentication and click on the Advanced button.  This will allow you to copy the Application ID:

snip_20170317080739

Next Require the app to ‘Log in with Azure Active Directory’ and save.  This will ensure only calls that are authenticated can get to this server:

capture20170317103028578

Register the client app in Azure AD and get the Application ID, and generate a Client Secret Key

My client app is https://WebApplication420170316082455.azurewebsites.net (the one calling the protected target app).  Simply click on the client app in the portal and enable Azure AD authentication (express) and save.

You now need to go to the application registered in Azure AD and get the Client ID and generate a Client Secret.  Copy the Client ID and Client Secret of this client app to use later like you did in the previous step.

capture20170316102620455

Generate a client Secret by going to Azure Active Directory in the portal.  Search for the Client app:

capture20170316102812597

In Settings choose Keys:

capture20170316102831349

In Keys create a New Key (name it whatever you want) and Save:

capture20170316102907130

Important.  When you save you need to copy the Value for later as you cannot come back and get it.  This is the Client Secret.

capture20170316102930647

Note:  You can always generate a new secret if you forget or lose it.

Create code to get a Bearer token from Azure AD and use this token to call the Target app

Now you simply need to use the values from above to request a token and then make a request to the target app from the client app using that token in the Authorization header.

Here is some sample code.  First the ServicePrinciple class is used to build and get the token.  I am using the latest ADAL library we provide (Microsoft.IdentityModel.Clients.ActiveDirectory ver 3.13.8:

capture20170317081758672

    public static class ServicePrincipal
    {
        /// <summary>
        /// The variables below are standard Azure AD terms from our various samples
        /// We set these in the Azure Portal for this app for security and to make it easy to change (you can reuse this code in other apps this way)
        /// You can name each of these what you want as long as you keep all of this straight
        /// </summary>
        static string authority = ConfigurationManager.AppSettings["ida:Authority"];  // the AD Authority used for login.  For example: https://login.microsoftonline.com/myadnamehere.onmicrosoft.com
        static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; // the Application ID of this app.  This is a guid you can get from the Advanced Settings of your Auth setup in the portal
        static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"]; // the key you generate in Azure Active Directory for this application
        static string resource = ConfigurationManager.AppSettings["ida:Resource"]; // the Application ID of the app you are going to call.  This is a guid you can get from the Advanced Settings of your Auth setup for the targetapp in the portal

        /// <summary>
        /// wrapper that passes the above variables
        /// </summary>
        /// <returns></returns>
        static public async Task<AuthenticationResult> GetS2SAccessTokenForProdMSAAsync()
        {
            return await GetS2SAccessToken(authority, resource, clientId, clientSecret);
        }

        static async Task<AuthenticationResult> GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
        {
            var clientCredential = new ClientCredential(clientId, clientSecret);
            AuthenticationContext context = new AuthenticationContext(authority, false);
            AuthenticationResult authenticationResult = await context.AcquireTokenAsync(
                resource,  // the resource (app) we are going to access with the token
                clientCredential);  // the client credentials
            return authenticationResult;
        }
    }

And then using this class my code to fetch data from the Target resource:

protected async void Page_Load(object sender, EventArgs e)
{
    // Normally you would use a single Global HttpClient per MS guidance
    // but for demo purposes... Just create one inline
    HttpClient client = new HttpClient();

    // This is an Aspx page so clearing anything already written in the buffer
    Response.Clear();

    try
    {
        // get the token
        var token = await ServicePrincipal.GetS2SAccessTokenForProdMSAAsync();

        // set the auth header with the aquired Bearer token
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer",token.AccessToken);

        // make the call to the resource requiring auth!
        var resp = await client.GetAsync("https://jsandersapicall.azurewebsites.net/");

        // do something with the response
        Response.Write(resp.StatusCode.ToString());
    }
    catch (Exception ex)
    {
        // important to log the exception if any because it will tell you what went wrong
        Response.Write(ex.Message);
    }

    // write page out
    Response.Flush();
}

 

Conclusion

This is a very compact sample that can be used as a checklist.  It eliminated a lot of the information in our documentation here: Service principal authentication for API Apps in Azure App Service 

Drop me a note if you found this useful!

Problem adding Push Notification Hub to Azure App Service Slot

$
0
0

Overview

You can add Push Notification Hubs to your Azure Web App, Azure Api App etc… (all Azure App Services).  If you try to use the portal to add Push (a Notification Hub) to a Slot however this will fail.  You will see the portal will just sit there with the message: “Connecting Web App to Notification Hub” forever.

capture20170330144721190

Fix

The Push Notification Hub settings from the main site are inherited by the slots.  You cannot define a unique Push setting for the slots.  If you need different settings for testing for example, you need to simply create a new App Service and deploy to that.

More info

Drop me a note if you found this useful!

Azure Active Directory “Can’t access the account” Account Recovery–Where does the email contact come from?

$
0
0

Overview

If you are not using the Self-Serve option of Azure Active Directory premium, an email is sent to unblock the user account.  Where does that email come from?  I could not find it documented anywhere.

Solution

With the help of my friend Florin Chiva in Azure AD support he helped me understand this.

In Azure Active Directory/O365 only Password admins, User management admins and Global admins can receive the password reset request notification emails.  The priority for receiving the password reset request notification emails is:   Password admins > User management admins > Global admins.

For example:  If you have all the three types of admins in your organization, then only the Password admins will receive the notification emails.  If you only have User management admins and Global admins, then only the User management admins will receive the notification emails.  If you only have Global admins, then the Global admins or alternate email address of the Global Admins will receive the notification emails.

If you want to change the notification email, all you need to do is to create or use an existing account and assign the Password Administrator role or User Management role, set the email address that you need on this account, and the notifications will be redirected to this email instead of the Global Administrators (step by step procedure below).

Assign admin roles in Office 365

Conclusion

Although simple, this is not easy to find documented.  Again thanks to Florin for this information!

Drop us a note if you found this useful!

Viewing all 140 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>