Azure AD and Azure Functions authentication 401 problems with access tokens

This is a very annoying thing since most documentation describing Azure AD user authentication is not very clear about using access tokens to authenticate a user.

If you follow the example on Microsoft page you will be doing the all right things but if you intend to use access token to authenticate you will likely encounter 401 even if you pass a proper access token. Especially if you are using Postman.

So this is because you are using the wrong version of the authenticate API URLs for Azure AD.

The fix is to use the v2.0 of the login URLs and scopes.

Auth URL:{tenant}/oauth2/v2.0/authorize

Access Token URL:{tenant}/oauth2/v2.0/token



Found the fix finally in stackoverflow after alot of searching. It’s hard to find the exact documentation that you need:

For postman if you Authorization tab in your request you can ask Azure AD to generate you a new access token:

My Kubernetes Cheat Sheet, things I find useful everyday


Here is a list of my personal most used and useful commands with Kubernetes.

kubectl config current-context # Get the Kuberneste context where you are operating

kubectl get services # List all services in the namespace
kubectl get pods # Get all pods
kubectl get pods –all-namespaces # List all pods in all namespaces
kubectl get pods -o wide # List all pods in the namespace, with more details
kubectl get deployment my-dep # List a particular deployment
kubectl get pods –include-uninitialized # List all pods in the namespace, including uninitialized ones

kubectl describe nodes my-node
kubectl describe pods my-pod
kubectl describe my-dep

kubectl scale –replicas=0 my-dep # roll down a deployment to zore instances
kubectl scale –replicas=1 my-dep # roll up a deployment to desired instaces number

kubectl set image my-dep my-containers=my-image –record # Update the image of the diven deployment containers

kubectl apply -f my-file.yaml # apply a kubernetes specific conifiguration, secrets file, deployment file

kubectl logs -f –tail=1 my-pod # Attach to the pods output and print one line of at a time

kubectl exec my-podf — printenv | sort # print all environmental variables from a pod and sort them

kubectl get my-dep –output=yaml # Print a deployment yaml file the deployment is using

kubectl get pod my-pod –output=yaml # Print the pod related configurations it is using

kubectl logs -p my-pod # Print the logs of the previous container instance, you can use this if there was a crash

kubectl run -i –tty busybox –image=busybox –restart=Never — sh # run a busybox pod for troubleshooting

More useful commands:

Azure AD Integration

This year I’ve been working a lot more with Azure. On of my tasks has been to integrate other application to each other using Azure AD. Here are some of my finding and good to know things in case someone else runs into them:

  • Create a new MVC Application in Visual Studio
  • When this is done, press the second mouse button on the project and go to “Add” > “Connected Services”. This will allow you to create an O365 connection.
  • Select Office 365 API Services.
  • In the new Window select or type in your domain.
  • Next, create new Azure AD application configuration or use an existing one by providing the GUID for the application.
    • Make sure you select the “Configure Single Sign-On using Azure AD” option
    • Make sure that your application is multi-tenant:
      • This works so that you register your app with you own Azure AD domain, then after that external Azure AD tenants and their users are registered through an “onboarding” process. The process will the user or admin user for privileges to use certain information from the AD or other resources. These are defined in the Azure AD application settings.
      • Notice you are using an application ID and key to connect to your own organization Azure AD then the users are only onboarding using the multi-tenant option in the Azure AD application configuration.
    • Next select what kind of privileges your application needs from the Azure AD and O365.
    • You need onboarding functionality from here:
    • In Global.asax.cs application_start function add the following: AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
      • If this is missing, then you claim will not work properly.
    • If you are using a SQL Server database and Entity Framework remember to update you model from the database and remember primary key connections. If the Entity Framework update does not work then removing and adding the database tables should force an update. Also remember to clean and build your project if nothing else helps.
    • If you get this error: Error: {“error”:”invalid_grant”,”error_description”:”AADSTS70002: Error validating credentials. AADSTS70000: The provided access grant is invalid or malformed…..
    • Doing a redirect the proper way in an MVC apllication using the following piece of code in your contoller: return Redirect(returnUrl);
      • If you use the normal way in ASP .NET: Response.Redirect(returnUrl); you will run into trouble. The error message might look something like this:
        • Server Cannot Append Header After HTTP headers have been sent Exception at @Html.AntiForgery
        • You could set the AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in the Application_start, but this will lower your security and not advisable.


How to use: Azure Service Bus – Notification hub, Azure hosted SignalR Hub with .NET clients, Android clients and web JavaScript clients

Huh that is a looong title for a blog post :). It is easier for me to write these all in one post since they are related the code in this case. So here I go, bear with me, it’s going to be alot of stuff and code.

The codes and examples here are from the own personal technology workbench project hosted in Azure. More code and examples how these features and functionality work can be found here.

I will go in the following order with the topics covered in this post:

  • Notification Hub
    • Setting up the Azure Service Bus – Notification Hub
    • Connecting with a .NET Client and sending messages
    • Connecting and listening to messages with an Android device client
  • SignalR Hub
    • Setting up a Azure hosted SignalR hub
    • Connecting and listening to activities with the following clients:
      • Connecting with the .NET Client
      • Connecting with the JavaScript client
      • Connecting with the Android client

Notification Hub

Some links to get you started:

Setting up the Azure Service Bus – Notification Hub

I wont go into much details here. Microsoft has done a great job documenting these steps, I recommend you go to the following link and follow the first part of these instructions:

What you will need for my code example is a Google Developer account and a API Key from google to be able to send and receive GCM messages to Android devices. Of course you will also need a Azure account to be able to create the notification hub.

Add the following Nugget package:

Microsoft Azure Service Bus

Connecting with a .NET Client and sending messages

The code below will connect from a .NET Client to the Notification Hub. This is done in the class constructor. At the moment this code can only send GCM messages to Android devices. Note that these operations are asynchronous.

But you could use a "central" hub from where to send these messages which will handle sending messages to different devices through a WebAPI:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Notifications;

namespace MyFitnessTrackerLibrary.ServiceBus
    // TODO: Replace this with a connection to the notification central hub, do not sent message directly from here in the future!!!!
    public class NotificationGateway
        private NotificationHubClient hub = null;
        private static NotificationGateway _notificationGateway;
        public NotificationGateway()

            hub = NotificationHubClient.CreateClientFromConnectionString(MyFitnessTrackerLibrary.Globals.MyFitAppSettings.NotificationHubConnectionString, MyFitnessTrackerLibrary.Globals.MyFitAppSettings.NotificationHubName);




        public async Task<NotificationOutcome> SendMessage(string message)
            var toast = "{ \"data\" : {\"message\":\"" + "From : " + message + "\"}}";
            return await hub.SendGcmNativeNotificationAsync(toast);

        public static NotificationGateway GetInstance()
            if(_notificationGateway == null)
                _notificationGateway = new NotificationGateway();

            return _notificationGateway;

Connecting and listening to messages with an Android device client

The Android side is a bit more complicated and annoying. You have to do more work here.

At the first you need two Microsoft java libraries to be able to connect to a notification hub:

After this you need to add them to your Android Studio gradle file:

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 compile ''
 compile ''
 compile ''
 compile files('libs/signalr-client-sdk.jar')
compile files('libs/notifications-1.0.1.jar')
compile files('libs/notification-hubs-0.4.jar')
 compile files('libs/Java-WebSocket-1.3.0.jar')
 compile project(':signalr-client-sdk-android-release')

 Please remember to follow these instructions to setup your Android Studio project in a correct manner, more details here:

The most important piece of code is the class named MyHandler in this case which will handle your notifications once your device is registered to the notification hub:

package com.example.adriansimionescu.myfitnessandroidapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class MyHandler extends NotificationsHandler {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context ctx;

    static public MainActivity mainActivity;

    public void onReceive(Context context, Bundle bundle) {
        ctx = context;
        String nhMessage = bundle.getString("message");

        mainActivity.DialogNotify("Received Notification",nhMessage);

    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)

        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                new Intent(ctx, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
                        .setContentTitle("Notification Hub Demo")
                        .setStyle(new NotificationCompat.BigTextStyle()


You also need a class that will register you device to the notification hub:


package com.example.adriansimionescu.myfitnessandroidapp;

import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

public class RegisterClient {
    private static final String PREFS_NAME = "ANHSettings";
    private static final String REGID_SETTING_NAME = "ANHRegistrationId";
    private String Backend_Endpoint;
    SharedPreferences settings;
    protected HttpClient httpClient;
    private String authorizationHeader;

    public RegisterClient(Context context, String backendEnpoint) {
        this.settings = context.getSharedPreferences(PREFS_NAME, 0);
        httpClient =  new DefaultHttpClient();
        Backend_Endpoint = backendEnpoint + "/api/register";

    public String getAuthorizationHeader() {
        return authorizationHeader;

    public void setAuthorizationHeader(String authorizationHeader) {
        this.authorizationHeader = authorizationHeader;

    public void register(String handle, Set<String> tags) throws ClientProtocolException, IOException, JSONException {
        String registrationId = retrieveRegistrationIdOrRequestNewOne(handle);

        JSONObject deviceInfo = new JSONObject();
        deviceInfo.put("Platform", "gcm");
        deviceInfo.put("Handle", handle);
        deviceInfo.put("Tags", new JSONArray(tags));

        int statusCode = upsertRegistration(registrationId, deviceInfo);

        if (statusCode == HttpStatus.SC_OK) {
        } else if (statusCode == HttpStatus.SC_GONE){
            registrationId = retrieveRegistrationIdOrRequestNewOne(handle);
            statusCode = upsertRegistration(registrationId, deviceInfo);
            if (statusCode != HttpStatus.SC_OK) {
                Log.e("RegisterClient", "Error upserting registration: " + statusCode);
                throw new RuntimeException("Error upserting registration");
        } else {
            Log.e("RegisterClient", "Error upserting registration: " + statusCode);
            throw new RuntimeException("Error upserting registration");

    private int upsertRegistration(String registrationId, JSONObject deviceInfo)
            throws UnsupportedEncodingException, IOException,
            ClientProtocolException {
        HttpPut request = new HttpPut(Backend_Endpoint+"/"+registrationId);
        request.setEntity(new StringEntity(deviceInfo.toString()));
        request.addHeader("Authorization", "Basic "+authorizationHeader);
        request.addHeader("Content-Type", "application/json");
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode;

    private String retrieveRegistrationIdOrRequestNewOne(String handle) throws ClientProtocolException, IOException {
        if (settings.contains(REGID_SETTING_NAME))
            return settings.getString(REGID_SETTING_NAME, null);

        HttpUriRequest request = new HttpPost(Backend_Endpoint+"?handle="+handle);
        request.addHeader("Authorization", "Basic "+authorizationHeader);
        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Log.e("RegisterClient", "Error creating registrationId: " + response.getStatusLine().getStatusCode());
            throw new RuntimeException("Error creating Notification Hubs registrationId");
        String registrationId = EntityUtils.toString(response.getEntity());
        registrationId = registrationId.substring(1, registrationId.length()-1);

        settings.edit().putString(REGID_SETTING_NAME, registrationId).commit();

        return registrationId;

After all these steps and setups you can finally go to your activity and add the following pieces of codes to fire up the connection and start listening to messages:


// Define this properties in you activity class</pre>
<pre>private RegisterClient registerClient;
private String SENDER_ID = "";
private GoogleCloudMessaging gcm;
private NotificationHub hub;
private String HubName = "fittracker";
private String HubListenConnectionString = "";</pre>
private void registerWithNotificationHubs() {
 new AsyncTask() {
 protected Object doInBackground(Object... params) {
 try {
 String regid = gcm.register(SENDER_ID);
 DialogNotify("Registered Successfully", "RegId : " +
 } catch (Exception e) {
 return e;
 return null;
 }.execute(null, null, null);

 * A modal AlertDialog for displaying a message on the UI thread
 * when theres an exception or message to report.
 * @param title Title for the AlertDialog box.
 * @param message The message displayed for the AlertDialog box.
public void DialogNotify(final String title,final String message)
 final AlertDialog.Builder dlg;
 dlg = new AlertDialog.Builder(this);

 runOnUiThread(new Runnable() {
 public void run() {
 AlertDialog dlgAlert = dlg.create();
 (CharSequence) "OK",
 new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int which) {

So the first function will register you device and the next one will create a notification with a message in your device. Next you create the connection with this piece of code:

<pre>MyHandler.mainActivity = this;
NotificationsManager.handleNotifications(this, SENDER_ID, MyHandler.class);
gcm = GoogleCloudMessaging.getInstance(this);
hub = new NotificationHub(HubName, HubListenConnectionString, this);

Notice how you pass your activity instance you the myhandler class. This is important.

And that’s it :D. Simple yet alot of work. Luckily Microsoft has made a good job documenting these steps. If in trouble don’t hesitate to look up on some documentation.

SignalR Hub

Implementing SignalR on the .NET side is rather easy BUT there is so much automation that it simply feel weird :). Everything seems to work if you just follow the instuctions but as I noticed one you poke around custom authentication and authorization you can really mess thing up. For example I wanted to add to my SignalR hun web project EDM mapping to a database or a custom authentication, well I made the mistake of choosing to use Entity Framework version 6.0 which uses a different version of Newtonsoft.json library which caused all sorts of problems. Another issue which I ran into was that I create a connection identification by client ID to be able to notify the client devices and services of changes within my system. At one point I did a simple mistake of forgeting to pass on the identification information which lead to weird errors on the client side browser such as IE and Chrome. The errors had nothing to do with the fact that the connection failed on the server side because the user ID was missing. The browsers expressed errors related to CORS which made no sense since I configured CORS support. So just be careful.Setting up a

Azure hosted SignalR hub

Start by looking at this source:

To host my SignalR hub in Azure I simply created an empty web application and followed the instructions in the link above. Sample code:

Also include the following SignalR nuget package:

Microsoft ASP .NET SignalR (to be able to host)

Microsoft ASP .NET Cross-Origin Support

Windows Azure Storage

Lets look at bit more closely at the ChartHub:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using SignalRGateway.AzureTableStorage;
using System.Configuration;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using MyFitnessTrackerLibrary.Globals;

namespace SignalRGateway
 public class ChatHub : Hub

 public void Send(string name, string message)
 // Call the broadcastMessage method to update clients.
 var queryResult = this.SendMessageTo(name, message);
 foreach (var entity in queryResult)
 Clients.Client(entity.RowKey).broadcastMessage(name, message);

 public void IsDataUpdateRequiredForWeb(string name, bool isRequired, string message)
 var queryResult = this.SendMessageTo(name, message);
 foreach (var entity in queryResult)
 Clients.Client(entity.RowKey).isDataUpdateRequiredForWeb(name, isRequired, message);
 Clients.All.isDataUpdateRequiredForWeb(name, isRequired, message);

 public void IsDataUpdateRequiredForMobileClient(string name, bool isRequired, string message)
 var queryResult = this.SendMessageTo(name, message);
 foreach (var entity in queryResult)
 Clients.Client(entity.RowKey).isDataUpdateRequiredForMobileClient(name, isRequired, message);

 private List<ConnectionEntity> SendMessageTo(String who, String message)
 //var name = Context.User.Identity.Name;
 var name = this.GetConnectionUser();

 if (!String.IsNullOrEmpty(name))
 var table = GetConnectionTable();

 // Notice that the partition keys are stored in azure storage as lower case
 var query = new TableQuery<ConnectionEntity>()

 var queryResult = table.ExecuteQuery(query).ToList();
 if (queryResult.Count == 0)
 Clients.Caller.showErrorMessage("The user is no longer connected.");
 // Load only once the host application connections to display the data there
 if(queryResult.Count(o=>o.PartitionKey.Equals(Constants.SignalR_HostApplicationUserName.ToLowerInvariant())) <= 0)
 queryResult.AddRange(this.SendMessageTo(Constants.SignalR_HostApplicationUserName, message));

 return queryResult;

 return new List<ConnectionEntity>();

 // This assumes that "normmaly" all others clients than the host SignalR web application (this app) will use header named as username for user identification. The SignalR web app will user querystring.
 private String GetConnectionUser()
 var name = Context.Headers[Constants.SignalR_HeaderID_Username];

 if (String.IsNullOrEmpty(name))
 name = Context.QueryString[Constants.SignalR_HeaderID_Username];
 if (String.IsNullOrEmpty(name))
 return null;

 // Notice that the partition keys are stored in azure storage as lower case
 return name.ToLowerInvariant();

 public override Task OnConnected()
 //var name = Context.User.Identity.Name;
 var name = this.GetConnectionUser();

 var table = GetConnectionTable();
 var created = table.CreateIfNotExists();

 var entity = new ConnectionEntity(
 var insertOperation = TableOperation.InsertOrReplace(entity);

 return base.OnConnected();

 public override Task OnDisconnected(bool stopCalled)
 //var name = Context.User.Identity.Name;
 var name = this.GetConnectionUser();

 if (!String.IsNullOrEmpty(name))
 var table = GetConnectionTable();

 var deleteOperation = TableOperation.Delete(
 new ConnectionEntity(name, Context.ConnectionId) { ETag = "*" });

 return base.OnDisconnected(stopCalled);

 private CloudTable GetConnectionTable()

 var storageAccount =
 var tableClient = storageAccount.CreateCloudTableClient();
 var table = tableClient.GetTableReference("connection");

 return table;

In my code example connections are stored and managed in Azure Table Storage(check the link below how to create one):

When you connect to the hub you will enter the OnConnected() function. Here my implementation seeks for the username header value or QueryString username value(this is to just go around a problem in JavaScript client which I did not want to spend to much time on). After this we connect to the Azure Table Storage and add a new connection to the table.

When disconnecting the reverse is done to the Azure Storage Table.

The GetConnectionTable() function will open a connection to the storage table(check from azure management web console for your connection data).

The SignlarR has threee function which will send information to listening clients based on connection IDs:

  • Send
  • IsDataUpdateRequiredForWeb
  • IsDataUpdateRequiredForMobileClient

The SendMessageTo() function is used to get all of the connection for a user name which needs to be notified of updates.

The code is pretty simple an easy. Microsoft has done a great job documenting this:

Last thing which I recommend to do is to configure CORS support:

// Branch the pipeline here for requests that start with "/signalr"
 app.Map("/signalr", map =>
 // Setup the CORS middleware to run before SignalR.
 // By default this will allow all origins. You can
 // configure the set of origins and/or http verbs by
 // providing a cors options with a different policy.
 var hubConfiguration = new HubConfiguration
 // You can enable JSONP by uncommenting line below.
 // JSONP requests are insecure but some older browsers (and some
 // versions of IE) require JSONP to work cross domain
 // EnableJSONP = true
 // Run the SignalR pipeline. We're not using MapSignalR
 // since this branch already runs under the "/signalr"
 // path.

Simply copy&paste the code above to get it to work but notice that it will allow requests from all possible connections.

Connecting and listening to activities with the following clients:

You will need to import the following libraries in Visual Studio to get you clients to work on SignalR:

Microsoft ASP .NET SignalR .NET Client

Microsoft ASP .NET SignalR JavaScript Client

Connecting with the .NET Client

The .NET Client code is pretty easy to understand:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR.Client;
using System.Threading.Tasks;
using MyFitnessTrackerLibrary.ServiceBus;
using MyFitnessTrackerLibrary.Globals;

namespace MyFitnessTrackerLibrary.SignalRLogic
 public class HubGateway

 private String hubLocation = MyFitAppSettings.SignalRHubHostLocation;
 private static HubGateway _hubGateway = null;
 private String hubProxyName = MyFitAppSettings.SignalRHubProxy;
 private IHubProxy hubProxy = null;
 private HubConnection hubConnection = null;
 private String sourceID = "NO ID";

 public IHubProxy HubProxyPoint
 get { return this.hubProxy; }

 public String SourceID
 return this.sourceID;


 this.sourceID = value;

 public HubGateway()
 hubConnection = new HubConnection(this.hubLocation);
 hubProxy = hubConnection.CreateHubProxy(hubProxyName);


 public async Task SendNormalMessage(String name, String message)
 await this.Start(name);
 await this.HubProxyPoint.Invoke("Send", name, message + " #Source ID: " + this.sourceID);

 public async Task IsDataUpdateRequiredForWeb(String name, bool isRequired, String message)
 await this.Start(name);
 await this.HubProxyPoint.Invoke("IsDataUpdateRequiredForWeb", name, isRequired, message + " #Source ID: " + this.sourceID);
 await NotificationGateway.GetInstance().SendMessage("New data was added. Your UI is updated/updating.");

 public async Task IsDataUpdateRequiredForMobileClient(String name, bool isRequired, String message)
 await this.Start(name);
 await this.HubProxyPoint.Invoke("IsDataUpdateRequiredForMobileClient", name, isRequired, message + " #Source ID: " + this.sourceID);
 await NotificationGateway.GetInstance().SendMessage("New data was added. Your UI is updated/updating.");

 public static HubGateway GetInstance()
 if( _hubGateway == null)
 _hubGateway = new HubGateway();

 return _hubGateway;

 public async Task Start(String userName)
 if (hubConnection.State == ConnectionState.Disconnected)
 this.hubConnection.Headers.Add(new KeyValuePair<string, string>(Constants.SignalR_HeaderID_Username, userName));

 await hubConnection.Start();

 public void Stop()

The important part in this code in when you call the Invoke() function to invoke in the SignalR hub the needed function and notify registered clients of updates.

The second important part is the Start() function. We add the username data in the connection, this way the hub knows where to send the messages/updates requests. Yes I know there is a bug in the code above, only one user will receive messages from this piece of code. I haven’t got around to fix this in my original project but it’s a simple matter.

Connecting with the JavaScript client

var connection = $.hubConnection(Constants.SignalRGatewayLocation);
 connection.qs = { "username": CookieHelper.UserName };
 var contosoChatHubProxy = connection.createHubProxy(Constants.SignalRHubProxyName);

 contosoChatHubProxy.on(Constants.SignalRHubMethod_IsDataUpdateRequiredForWeb, function (name, isRequired, message) {
 // Html encode display name and message.
 var encodedName = $('<div />').text(name).html();
 //var encodedMsg = $('<div />').text("isDataUpdateRequiredForWeb is Update Required: " + isRequired + " Message: " + message).html();
 var encodedMsg = $('<div />').text("Updating UI. New data from the mobile app.").html();
 // Add the message to the page.
 $('#notifications').append('<ul><li><strong>' + encodedName
 + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li></ul>');

 .done(function () {
 console.log('Now connected, connection ID=' +
 .fail(function () {
 console.log('Could not connect');

The code above is rather simple. You create a connection, define the hub name, register to a function on the SignalR hub and start the connection.
The only “weird” part is that the username is passed in the QueryString and not in the header. This was due to a problem which I could not fix and had to go around. There might be a better solution out there.

Connecting with the Android client

Now here comes the hard part. Getting SignalR to work on android was a pain in the but :). Lots of weird problems and lack or proper documentation.

To start with you will need this library downloaded and compiled in Android Studio(or some other Java development tool you are using).

You also might need the following library:

Then a good place to go next would be:

BUT the example above did not work for me as it was stated in the example. Here what I had to do:

Add to your Android project these libraries:




The following libraries can be added from Android Studio UI: File -> Project Structure. Then add a new library from the plus icon and in the new popup select the “import .JAR or .AAR Package”.

Your gradle file should look something like this:

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 compile ''
 compile ''
 compile ''
 compile files('libs/signalr-client-sdk.jar')
compile files('libs/notifications-1.0.1.jar')
compile files('libs/notification-hubs-0.4.jar')
 compile files('libs/Java-WebSocket-1.3.0.jar')
 compile project(':signalr-client-sdk-android-release')

The next step is to start to create a background service in Android that will be able to communicate with your desired activity.

We Start this by defining a interface which is implemented in the activity:

package com.example.adriansimionescu.myfitnessandroidapp;

public interface ServiceCallbacks {
    void updateUI();
<pre>// To implement it in your activity:</pre>
<pre>public class MainActivity extends ActionBarActivity implements ServiceCallbacks {

Next we create the background service:

package com.example.adriansimionescu.myfitnessandroidapp;

import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import java.util.concurrent.ExecutionException;

import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler3;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;

public class SignalRService extends Service {

    // Binder given to clients
    private final IBinder binder = new LocalBinder();
    // Registered callbacks
    private ServiceCallbacks serviceCallbacks;

    // Class used for the client Binder.
    public class LocalBinder extends Binder {
        SignalRService getService() {
            // Return this instance of MyService so clients can call public methods
            return SignalRService.this;

    public IBinder onBind(Intent intent) {
        return binder;

    public void onCreate() {

    public void setCallbacks(ServiceCallbacks callbacks) {
        this.serviceCallbacks = callbacks;

    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this, "Service Start", Toast.LENGTH_LONG).show();

        String server = Constants.SignalRGateway;
        HubConnection connection = new HubConnection(server);
        connection.getHeaders().put("username", UserDataContainer.LoginData.userName);
        HubProxy proxy = connection.createHubProxy(Constants.SignalRHubName);

        //SignalRFuture<Void> awaitConnection = connection.start();

// This was added to get around a websocket problem with Android devices to the SignalR hub hosted in Azure
        ClientTransport transport = new ServerSentEventsTransport(connection.getLogger());

        SignalRFuture<Void> awaitConnection = connection.start(transport);
        try {
            proxy.subscribe(this );
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block


    public void Send( String name, String message )
        final String fmessage = message;
        final String fname = name;


    public void IsDataUpdateRequiredForMobileClient( String name, boolean isRequired, String message ) {
        final String fmessage = message;
        final String fname = name;
        final boolean fisrequired = isRequired;
        if (serviceCallbacks != null) {

    public void onDestroy() {


There are a few important function.

onBind() => Use this to bind the actual instance of the service from your activity
setCallbacks() => use this to create a connection to the activity class interface so that we can call a desired method in the activity when a singalr message is received.

To bind to the SignalR function and message you need to define methods that use the same names as in the hub.
IsDataUpdateRequiredForMobileClient() and Send()

After the connection in made you need to call the subscribe method in the proxy class and pass the service class as a parameter. This will allow the binding between the defined methods above with the one in the SignalR hub.

The last part of the puzzle is that we call the interface function updateUI() which will trigger the same function in the activity to trigger and allow you to perform something in the activity.

Then all you have to do is to create the service instance in the activity, bind it and start it:

private SignalRService signalRService;</pre>
protected void onStart() {
    // Bind to LocalService

        Intent intent = new Intent(this, SignalRService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    // Do this to avoid starting multiple service, only one is needed
    if(this.signalRService == null) {

protected void onStop() {

    // Unbind from service
    if (bound) {
        this.signalRService.setCallbacks(null); // unregister
        bound = false;

/** Callbacks for service binding, passed to bindService() */
private ServiceConnection serviceConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        // cast the IBinder and get MyService instance
        SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service;
        signalRService = binder.getService();
        bound = true;
        signalRService.setCallbacks(MainActivity.this); // register

    public void onServiceDisconnected(ComponentName arg0) {
        bound = false;

/* Defined by ServiceCallbacks interface */
public void updateUI() {
// update your UI here

In the OnStart() and OnStop() functions we bind and start the service.

In the serviceConnection class instance we do the actual binding and notice how the code maps the activity to the service to be able to call the updateUI() function below.


The End

Huh, a long post but I hope you got the idea how to use notification hub, azure table storage and singnalr to communicate between different service and devices in different manner. SignalR is pretty cool what you can do with it. Especially with games and backend stuff. Cool 🙂

Lessons learned from WebAPI and MVC Implementations

My Notes on a painful journey to learn, make and publish a Azure hosted MVC, Sinlge-Page application, Android client app and a WebAPI working with-one another. Software technology can be real pain in the ass!!!

JSON and Self referencing loop

If you get the following error:

Self referencing loop detected for property ‘your model’ with type ‘System.Data.Entity.DynamicProxies


Loop Reference handling in Web API

My Solution:

I used [JsonIgnore] attribute to tell the proper inheritance to JSON serialization.

using Newtonsoft.Json;

public partial class Set
public Set()
this.Exercises = new HashSet<Exercise>();

public long Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }

public virtual ICollection<Exercise> Exercises { get; set; }

public partial class ExerciseRecord
public long Id { get; set; }
public double Record { get; set; }
public System.DateTime Date { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public long ExerciseId { get; set; }

public virtual Exercise Exercise { get; set; }

public partial class Exercise
public Exercise()
this.ExerciseAttributes = new HashSet<ExerciseAttribute>();
this.ExerciseRecords = new HashSet<ExerciseRecord>();

public long Id { get; set; }
public string Name { get; set; }
public double Target { get; set; }
public long SetId { get; set; }
public virtual Set Set { get; set; }
public virtual ICollection<ExerciseAttribute> ExerciseAttributes { get; set; }
public virtual ICollection<ExerciseRecord> ExerciseRecords { get; set; }


MVC loads older script files

This is due to browser script caching. The easiest solution for this is to set the browser which you are using to debug to retrieve the newest versions of web page content on each time you visit a webpage.

Missing Key definition from Model when creating a controller

You might get an error like this: EntityType ‘your type’ has no key defined. Define the key for this EntityType.

To fix such problems simply add this namespace definitions:

using System.ComponentModel.DataAnnotations;

And then define in your data model a key like this:

public class ColumnDataHighChart
public int ID { get; set; }
public String Title { get; set; }
public String SubTitle { get; set; }
public IList<String> xAxisCategories { get; set; }
public String yAxisTitle { get; set; }
public IList<SeriesDataHighChart> Series { get; set; }



Intercepting web requests


I have two ways of doing this:

  1. A delegation handler
  2. Or an action filter for a controller.

Delegation handler

DelegatingHandler Class

Sample code:

public class AuthHandler : DelegatingHandler
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
return response;

Action filter for a controlle

Notice that for MVC and Web API there are two different sets of action filter definitions:

MVC Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext filterContext)
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);


WebAPI Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

public override System.Threading.Tasks.Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, System.Threading.CancellationToken cancellationToken)
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);

public override void OnActionExecuting(HttpActionContext actionContext)
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);

public override System.Threading.Tasks.Task OnActionExecutingAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
return base.OnActionExecutingAsync(actionContext, cancellationToken);


Lambda Expression “Magic” 🙂

Retrieve distinct parent from child elements

As the title suggests I needed to retrieve the parent from a multilevel data set:


First I needed to get the child elements and in this exmaple it is assumed that you have the child elements retrieved.

Once you have the child elements it is time to get the distinct parent elements. for this I needed a way to group the distinct parent from the child elements. Here are my steps:

  • Get child elements:

ExerciseRecordsController exerciseRecordsController = new ExerciseRecordsController();
var exerciseRecordsData = exerciseRecordsController.GetExerciseRecords().Where(er => er.Date > startDate && er.Date < endDate && er.Exercise.Set.UserId.ToLower().CompareTo(this.user.Id.ToLower()) == 0);

  • Define a custom extension named “DistinctBy”

public static class LambdaExtensions
public static IEnumerable<t> DistinctBy<t>(this IEnumerable<t> list, Func<t, object> propertySelector)
return list.GroupBy(propertySelector).Select(x => x.First());
} Original code from:

  • Apply the new extension on the data set

var setsData = exerciseRecordsData.DistinctBy(o => o.Exercise.SetId).Select( o => o.Exercise.Set);

How to create/populate a collection with data with an unknown data type

You may ask yourself why would anyone needs this? Well I do not why would others needs this but I came into a situation where I needed this.

I had a solution where I needed to be able to create data from a back-end server WebAPI to a JS HighCharts JS library without knowing what kind of data I would be processing, also I wanted to have the possibility to extend the back-end code so that it can return any kind of data to the client and let the client figure out what to do with the data.

So how to do this?

In a human language it goes something like this: Use LINQ in your code to go through the data set, select your data and return it as and array of objects, then create a new collection by passing to the constructor your processed data as an array of objects. Ofcourse your collection must store objects as well. The data type information is going to be stored because every class in C# is a descendant of the Object class.

public class SeriesDataHighChart
public long ID { get; set; }
public String Name { get; set; }
public IList<object> Data { get; set; }


// One series corresponds to one set and data for each month
SeriesDataHighChart seriesData = new SeriesDataHighChart();

seriesData.ID = chartSet.Id;
seriesData.Name = chartSet.Name;
var seriesMonthsActivityCountData = (from monthActivityCount in chartSet.ChartSetMonthsData
select new object[] { monthActivityCount.ActivityCount as object });
seriesData.Data = new List<object>(seriesMonthsActivityCountData.ToArray());



You could also return an array of more complex object such as a key value pairs:

var sd = from d in unparsedData
select new object[] { d.Key as object, d.Value as object };

newSeries.Data = new Data(sd.ToArray());

Avoiding “Sequence contains no elements” exception in object initializers

If you have something like this in your code:

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Average(a => a.Record)



The Average lambda expression will throw the above exception error message because the Where clause may return Zero elements back(Notice that for example the Count expression will not throw a similar exception).

To fix(go around the problem, yes there might be other solutions but this was mine at the moment 🙂 ) I created an anonymous function that checks if there are elements returned by the clause and only then perform the Average operation on the elements. The solution is highlighted with the green color.

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = new Func<double>(() => {
double averageRecord = 0;
var exerciseRecordByDateRange = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate);
if (exerciseRecordByDateRange.Count() > 0)
averageRecord = exerciseRecordByDateRange.Average(a => a.Record);

return (averageRecord);

 Get the count for a complex data structure/hierarchy, tree like

A rather simple implementation, choose to retrieve any records inside your main records set with a where:

set.Exercises.Where(o => o.ExerciseRecords.Any(m => m.Date.Month == month)).Count()

Update Azure SQL Database via SQL Server management studio and Generated scripts

  1. Mouse second button on database > Taskas > Generate Scripts > Choose your objects (Chose objects view) > Select “Advanced” button, then in the “Script for the database engine type” select option Windows Azure SQL Database
  2. Next open the database connection with management studio to your Azure SQL Database.
  3. Create a new empty database
  4. Open a new query windows and simply add the generated script to this window and run the script against the new empty database. This will create the structure and data if you selected so.

After deploying your WebAPI you get a following error when accessing your database data “There is already an open DataReader associated with this Command which must be closed first.”

To fix this error simply add the following to your connection strings used in your web api in Azure MultipleActiveResultSets=true.

Enable WebAPI Cross-Origin Resource Sharing (CORS)

You might run into problems after deploying your WebAPI to Azure and trying to access your api from different origins. Here is a solution:

Summary of the article above: Install the following nuget package in your WebAPI project: Microsoft.AspNet.WebApi.Cors

In your webapiconfig add the following(in green):

public static class WebApiConfig
public static void Register(HttpConfiguration config)
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

var cors = new EnableCorsAttribute(“*”, “*”, “*”);

// Web API routes

name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }

config.MessageHandlers.Add(new Handler.AuthHandler());

Next add the following to your ApplicationOAuthProvider.GrantResourceOwnerCredentials function:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
context.OwinContext.Response.Headers.Add(“Access-Control-Allow-Origin”, new[] { “*” });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(user.Id);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, user.UserName);
if (user == null)
context.SetError(“invalid_grant”, “The user name or password is incorrect.”);

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,

AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);


Notice that these changes may have undesired effects. Find out if these are suitable to your needs.

Good to Know: Windows Azure and Web Services functionality


Here is my knowledge source listing for Windows Azure and Web Services functionality. Hope it helps someone:

Accessing Data
.NET Framework Data Providers
ADO.NET Entity Data Model Designer
ADO.NET Entity Data Model Designer
ADO.NET Entity Data Model Tools
Advanced using OData in .NET: WCF Data Services
ASP.NET Application State Overview
ASP.NET Session State Overview
CacheDependency Class
CacheItemPolicy Class
CacheItemPriority Enumeration
ChangeMonitor Class
Code First to an Existing Database
CommandType Enumeration
Configuring Parameters and Parameter Data Types
Create Database Wizard (Master Data Services Configuration Manager)
DataAdapter Class
DataAdapter.AcceptChangesDuringFill Property
DataContractAttribute Class
DataSet Class
DataSet Class
DataTable Class
DbContext Class
DBContext vs ObjectContexts
DbContext.SaveChanges Method
DbContext.Set<TEntity> Method
DbDataAdapter.Fill Method (DataSet)
DbDataAdapter.Update Method (DataSet)
Demystifying Entity Framework Strategies: Loading Related Data (Eager Loading,  Lazy Loading, Explicitly Loading)
EdmEntityTypeAttribute Class
EF Designer TPT Inheritance
Entity Data Model Wizard
Entity Framework
Entity Framework – Database First
Entity Framework (EF) Documentation
Entity Framework 5: Controlling automatic query compilation
Entity Framework- Code First to a New Database
EntityCommand Class
EntityConnection Class
EntityObject Class
EntityTransaction Class
How to: Use Lazy Loading to Load Related Objects
HttpContext.Cache Property
Improve Performance with Entity Framework 5
IsolationLevel Enumeration
LINQ (Language-Integrated Query)
LINQ to Entities: Basic Concepts and Features
LINQ to Objects
LINQ to XML [from BPUEDev11]
LINQ to XML Overview
Loading Related Entities (Eager Loading,  Lazy Loading, Explicitly Loading)
Model-First in the Entity Framework 4
ObjectCache Class
ObjectContext Class
ObjectContext management
ObjectQuery Class
ObjectQuery.ToTraceString Method
ObjectQuery<T> Class
Object-relational impedance mismatch
OData protocol
Open Data Protocol by Example
Plain Old CLR Object(POCO)
Precompiling LINQ Queries
Queries in LINQ to Entities
Relational database management system
Retrieving Data Using a DataReader
SerializableAttribute Class
SQL Server Connection Pooling (ADO.NET)
SqlCommand Class
SqlCommand.CommandText Property
SqlCommand.ExecuteReader Method
SqlCommand.ExecuteScalar Method
SqlConnection Class
SqlConnectionStringBuilder Class
SqlDataAdapter Class
SqlDataReader Class
SqlDataReader.Read Method
SqlParameter Class
SqlTransaction Class
System.Data.EntityClient Namespace
System.Data.SqlClient Namespace
System.Transactions Namespace
System.Xml Namespaces
Table-per-Type vs Table-per-Hierarchy Inheritance
The ADO.NET Entity Framework Overview
TransactionScope Class
Understanding ASP.NET View State
Understanding Service-Oriented Architecture
Update Model Wizard (Entity Data Model Tools)
Using the DbContext API
Using the REST Interface
Walkthrough: Mapping Table-per-Hierarchy Inheritance in Dynamic Data
WCF Data Services 4.5
WCF Data Services Overview
Working with Datasets in Visual Studio
Working with POCO Entities
XElement Class
XML Documents and Data
XmlDocument Class
XmlReader Class
XmlWriter Class
XPath Examples
Designing and implementing WCF Services – Create, Configure, Secure, Consume
Accessing Services Using a WCF Client
Azure Service Bus
Basic [WCF Samples]
BasicHttpBinding Class
BinaryMessageEncodingBindingElement Class
Binding [WCF Samples]
Chapter 7: Message and Transport Security
Choosing a Message Exchange Pattern
CompositeDuplexBindingElement Class
Configuration Editor Tool (SvcConfigEditor.exe)
Configuring Services Using Configuration Files
Creating the Web Service Proxy
Custom Binding Samples
Custom Bindings
Data Contract Known Types
DataContractAttribute Class
DataMemberAttribute Class
Difference between BasicHttpBinding and WsHttpBinding
Endpoints: Addresses, Bindings, and Contracts
EnumMemberAttribute Class
Extending Dispatchers
Extensibility [WCF Samples]
Fault Contract
Fault Contract – Handling Errors in WCF and A Very Simple WCF Service Implementation
Getting Started Tutorial
Host WCF in an Azure worker role (CSAzureWCFWorkerRole)
Hosting WCF Services
How to: Create a Transactional Service
How to: Create a Windows Communication Foundation Client
How to: Expose a Metadata Endpoint
How to: Implement a Windows Communication Foundation Service Contract
How to: Inspect or Modify Messages on the Client
How to: Set the Security Mode
How to: Use the ChannelFactory
IClientMessageInspector Interface
IDispatchMessageInspector Interface
KnownTypeAttribute Class
Message Inspectors
Message Patterns in WCF Services
Message Security in WCF
MetadataExchangeBindings Class
MtomMessageEncodingBindingElement Class
NetMsmqBinding Class
NetNamedPipeBinding Class
OneWayBindingElement Class
OperationBehaviorAttribute Class
OperationContractAttribute Class
Programming WCF Security
Publishing Metadata
Reliable Sessions Overview
ReliableSessionBindingElement Class
Scenario [WCF Samples]
Securing and Authenticating a Service Bus Connection
SecurityBindingElement Class
Service Bus Bindings
Service Bus Queues, Topics, and Subscriptions
ServiceBehaviorAttribute Class
ServiceContractAttribute Class
ServiceHost Class
ServiceModel Metadata Utility Tool (Svcutil.exe)
Sessions, Instancing, and Concurrency
Simplified Configuration
Simplified Configuration for WCF Services
SslStreamSecurityBindingElement Class
Status codes
System-Provided Bindings
TextMessageEncodingBindingElement Class
TransactionFlowBindingElement Class
Transactions in WCF Services
Types Supported by the Data Contract Serializer
Using Data Contracts
WCF Configuration Tools
WCF Extensibility – IParameterInspector
WCF Extensibility: Parameter Inspectors
Versioning Strategies
Windows Communication Foundation Endpoints
Windows Communication Foundation Tools
WindowsStreamSecurityBindingElement Class
WSHttpBinding Class
Creating and consuming Web API-based services – Design, Implement, Secure, Host and Manage, Consume
A WebAPI Basic Authentication Authorization Filter
AcceptVerbsAttribute Class
ActionFilterAttribute Class
Add Models and Controllers
Async Streaming in ASP.NET Web API
Asynchronous Programming with Async and Await (C# and Visual Basic)
Authentication and Authorization in ASP.NET Web API
Basic Authentication in ASP.NET Web API
Content Negotiation in ASP.NET Web API
Cross-Site Request Forgery (CSRF)
Dependency Injection in ASP.NET Web API 2
Enabling Cross-Origin Requests in ASP.NET Web API 2
Enabling CRUD Operations in ASP.NET Web API 1
Forms Authentication in ASP.NET Web API
Getting Started with ASP.NET Web API 2 (C#)
How to host your web API.
HTTP Authentication: Basic and Digest Access Authentication
HttpClient Class
HttpClient.GetAsync Method (String)
HttpMessageHandler Class
HttpResponseException Class
HttpResponseMessage Class
Integrated Windows Authentication
JSON and XML Serialization in ASP.NET Web API
Makecert.exe (Certificate Creation Tool)
Media Formatters in ASP.NET Web API 2
Media Formatters in ASP.NET Web API 2
Parameter Binding in ASP.NET Web API
Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET Web API
Preventing CSRF Hacks in ASP.NET WebAPI
Routing Service
Routing Services [WCF Samples]
synchronous Streaming in ASP.NET WebApi
Using Asynchronous Methods in ASP.NET MVC 4
Working with SSL in Web API
Deploying web applications and services
Azure Guest OS Releases and SDK Compatibility Matrix
Azure Service Definition Schema (.csdef File)
Configuring a Web Server for Web Deploy Publishing (Remote Agent)
Configuring Parameters for Web Package Deployment
Configuring Step 1: Install IIS and ASP.NET Modules
Continuous Delivery for Cloud Services in Azure
Continuous delivery to Azure using Visual Studio Online
Export a Package through IIS Manager
Get Started with Azure Cmdlets
Get started with Azure Websites and ASP.NET
How to Configure Cloud Services
How to Deploy an Azure Website
IIS Information
Installing and Configuring Web Deploy on IIS 7
Installing NuGet
Manage Deployments in Azure
NetworkConfiguration Schema
Nuspec Reference
Package Manager Console Powershell Reference
Reference for the Web Application Package
Shadow Copying Assemblies
Step 1: Examining the Configuration Files
Swap Deployment
Team Build + Web Deployment + Web Deploy + VS 2010 = Goodness
Web Deploy Command Line Syntax
Web Deployment Overview for Visual Studio and ASP.NET
Web.config Transformation Syntax for Web Project Deployment Using Visual Studio

Good To Know: ASP .NET MVC Reference Guide


This is my collection of sources of the most “relevant” information on ASP .NET MVC. Hope this helps you if you need information on MVC and web development with Microsoft Tools.

Design the application architecture – Application Layers, Azure, State Management, Caching, WebSocket, HTTPModules
ASP.NET MVC 4 Content Map
.NET On-Premises/Cloud Hybrid Application Using Service Bus Relay
A Beginner’s Guide to HTTP Cache Headers
ASP.NET MVC Views Overview
ASP.NET Routing
ASP.NET State Management Overview
Beginners guide to HTML5 Application Cache API
Caching in .NET Framework Applications
Controllers and Action Methods in ASP.NET MVC Applications
Differences Between ASMX and WCF Services
Distributed Cache
Donut Caching and Donut Hole Caching with Asp.Net MVC 4
Donut Caching with ASP.NET MVC 4
Entity Framework
Extending ASP.NET Processing with HTTP Modules
Getting Started with ASP.NET Web API 2
Global.asax File
HOW TO: Write a Simple Web Service by Using Visual C# .NET
HTML5 Web Storage
HTTP Handlers and HTTP Modules Overview
IHttpModule Interface
Improving Performance with Output Caching (C#)
INFO: ASP.NET Configuration Overview
Introducing “Razor” – a new view engine for ASP.NET
Introducing WebSocket HTML5
Introducing Windows Azure
Introducing Windows Azure AppFabric Applications
Introduction to HTTP Modules
Learn About ASP.NET Web API
patterns & practices: Data Access Guidance
Run Startup Tasks in Windows Azure
The WebSocket API
Two Ways of Passing HTML5 Web Storage Data to ASP.NET
Use AppCmd.exe to Configure IIS at Startup
Using an Asynchronous Controller in ASP.NET MVC
WCF Web HTTP Programming Model
Windows Azure Execution Models
Windows Azure Jump Start (03): Windows Azure Lifecycle, Part 1
Windows Azure Jump Start (04): Windows Azure Lifecycle, Part 2
Design the user experience – User Interface Design and Implementation
About Font Embedding
AjaxExtensions.BeginForm Method
ASP.NET MVC 4 Content Map
Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers.
CSS Media Types
CSS Reference
DisplayModeProvider Class
EditorExtensions.EditorFor Method
How To Test ModelState.IsValid In ASP.NET MVC
How to: Implement Remote Validation in ASP.NET MVC
How to: Validate Model Data Using DataAnnotations Attributes
HTML DOM innerHTML Property
Html.BeginForm() vs Ajax.BeginForm() in MVC3
HTML5 New Input Types
HtmlHelper Class
JavaScript prototype Property
JavaScript Tutorial
jQuery Documentation
jQuery Mobile
jQuery Mobile Framework
jQuery UI
JsonRequestBehavior Enumeration
JsonResult Class
Kendo UI Mobile
LinkExtensions.ActionLink Method
ModelStateDictionary.IsValid Property
Partial View in ASP.NET MVC 4
Rendering a Form in ASP.NET MVC Using HTML Helpers
Sencha Touch
Simplifying HTML generation in code using Razor templates
Styles.Render Method
System.Web.Mvc.Ajax Namespace
System.Web.Mvc.Html Namespace
Understanding JavaScript Prototypes.
Using the viewport meta tag to control layout on mobile browsers
ValidationExtensions.ValidationMessageFor Method
ValidationMessageFor HTML Helper in MVC3 Razor
Vendor-specific Properties
Views and UI Rendering in ASP.NET MVC Applications
Develop User Experience – Search Engine Optimization, Globalization and Localization, Routes, Application Behaviour, Network Optimization
13 ASP.NET MVC extensibility points you have to know
Action Filtering in ASP.NET MVC Applications
ActionResult Class
ActionResult.ExecuteResult Method
An Introduction to ASP.NET MVC Extensibility
ASP.NET Globalization and Localization
ASP.NET MVC – Basic overview of different view engines
ASP.NET MVC Custom Model Binder
ASP.NET MVC Model Binding and Data Annotation
ASP.NET MVC Routing Overview (C#)
ASP.NET Routing
Attribute Usage Guidelines
BindAttribute Class
Bundling and Minification
Configuring HTTP Compression in IIS 7
CultureInfo Class
Custom Controller Factory in ASP.NET MVC
FilterAttribute Class
HandleErrorAttribute Class
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
HTML 5: The Markup Language (ARIA Edition)
Mage.exe (Manifest Generation and Editing Tool)
Microsoft Ajax Content Delivery Network
MVC 4 Part 4 – Bundles and Optimisation
MvcRouteHandler and MvcHandler in ASP.NET MVC Framework
ResourceManager Class
Search Engine Optimization Toolkit
Subscriber Locale Codes
The Features and Foibles of ASP.NET MVC Model Binding
Thread.CurrentUICulture Property
Using CDN for Windows Azure
Using Value Providers in ASP.NET 4.5
Walkthrough: Organizing an ASP.NET MVC Application using Areas
WebPart.AuthorizationFilter Property
What’s the Difference Between a Value Provider and Model Binder?
ViewResultBase Class
VirtualPathProviderViewEngine Class
Troubleshoot and debug web applications – Runtime issues, Exception handling, Testing, Debuging
AppDomain.FirstChanceException Event
Assert Class
Beginners Guide to Performance Profiling
Code Contracts
Code Contracts
Code Contracts for .NET
Collect Logging Data by Using Windows Azure Diagnostics
Configuring Performance Sessions for Profiling Tools
Configuring Windows Azure Diagnostics
Controller.OnException Method
Create and Use Performance Counters in a Windows Azure Application
customErrors Element (ASP.NET Settings Schema)
Debugging a Cloud Service in Visual Studio
Debugging Cloud Services
HandleErrorAttribute Class
How To Put Your Toe Into ASP.NET MVC Integration Testing
How to: Break When an Exception is Thrown
How to: Handle Application-Level Errors
How to: Receive First-Chance Exception Notifications
Integration Testing Your ASP.NET MVC Application
Invariants and Inheritance in Code Contracts
Isolating Code Under Test with Microsoft Fakes
Logging Error Details with ASP.NET Health Monitoring (C#)
MVC: Error Page implementation
Performance and Diagnostics Hub in Visual Studio 2013
Performance Profiler in Visual Studio 2012
Quick Start: Test Driven Development with Test Explorer
Record and run a web performance test
Remote Debugging a Window Azure Web Site with Visual Studio 2013
System.Diagnostics.Contracts Namespace
TraceListener Class
Tracing in ASP.NET MVC Razor Views
Understanding Web Tests
Unit Testing in ASP.NET MVC Applications
Use the Windows Azure Diagnostics Configuration File
Walkthrough: Using TDD with ASP.NET MVC
What is a First Chance Exception?
Windows Performance Monitor
Working with Web Tests
Design And Implement Security – Authentication, Authorization, Data Integrity, Hacks and Security, Communication
A Beginner’s Tutorial on Custom Forms Authentication in ASP.NET MVC Application
A Custom SqlRoleProvider for “Authenticated Users”
Anti-Cross Site Scripting Library
Apple Secure Coding Guide
ASP.NET Impersonation
ASP.NET MVC Authentication – Global Authentication and Allow Anonymous
Asp.Net MVC With the ValidateAntiForgeryToken For Cross Site Request Forgeries
ASP.NET Web Application Security
Authenticating Users with Windows Authentication (C#)
AuthorizeAttribute Class
Basic Security Practices for Web Applications
Client Certificates vs. Server Certificates – What’s the Difference?
Configure ASP.NET Impersonation Authentication (IIS 7)
Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on (C#)
CryptoStream Class
Custom Authentication and Authorization in ASP.NET MVC
Custom Authentication with MVC 3.0
Custom Membership Providers
Custom Membership Providers – Task Manager
Custom Role Providers
DpapiProtectedConfigurationProvider Class
FormsIdentity Class
How to Authenticate Web Users with Windows Azure Active Directory Access Control
How to configure Custom Membership and Role Provider using ASP.NET MVC4
How to Create an Intranet Site Using ASP.NET MVC
How to: Create a WindowsPrincipal Object
How to: Create GenericPrincipal and GenericIdentity Objects
How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA
How To: Use Membership in ASP.NET 2.0
HtmlHelper.AntiForgeryToken Method
HttpEncoder Class
Microsoft Web Protection Library
OAuthWebSecurity.Login Method
OAuthWebSecurity.VerifyAuthentication Method
patterns & practices Improving Web Services Security – Now Released
Programming WCF Security
Provider Model Design Pattern and Specification, Part 1
RequireHttpsAttribute Class
Role-Based Authorization (C#)
RSACryptoServiceProvider Class
RsaProtectedConfigurationProvider Class
SAML 2.0 tokens and WIF – bridging the divide
Securing Your ASP.NET Applications
Security Practices: ASP.NET Security Practices at a Glance
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
SqlMembershipProvider Class
SqlRoleProvider Class
System.Security.Cryptography Namespace
System.Threading.Thread.CurrentPrincipal vs. System.Web.HttpContext.Current.User or why FormsAuthentication can be subtle
Thread.CurrentPrincipal Property
Understanding and Using Simple Membership Provider in ASP.NET MVC 4.0
Understanding the Forms Authentication Ticket and Cookie
Understanding Windows Identity Foundation (WIF) 4.5
Using IIS Authentication with ASP.NET Impersonation
Using OAuth Providers with MVC 4
Walkthrough: Using Forms Authentication in ASP.NET MVC
WCF Security Fundamentals
WCF Using Windows Authentication and SqlRoleProvider over basicHttp
WebSecurity Class
Windows Communication Foundation Security
WindowsIdentity Class
WS-Trust 1.3 OASIS Standard