Category Archives: Web @en

Azure Directory Library & TokenCache persistance – upgrade issue

When using the Microsoft.IdentityModel.Clients.ActiveDirectory nuget package to deal with ADAL token cache, you can ctaully serialize the state of your cache to use it at a later point:

public class RefreshTokenCache : TokenCache
    private void AfterAccessNotification(TokenCacheNotificationArgs args)
        if (this.HasStateChanged)
            var data = Convert.ToBase64String(this.Serialize());

When migrating from 2.x to 3.x versions of the library, I encountered some issues trying to serialize back my token cache to its initial state:

var tc = new RefreshTokenCache();

The problem was that serialized data obtained on v2.x was not de-serialized properly when using 3.x versions.

I that case, I am forcing the token to be asked again to the end-user, so that I can serialize it back to the 3.x format.

Happy coding!

Kicking System.Web out of your code – part 3: utilities

Last part of my blog posts about getting rid of System.Web.

We are going to look into some pretty gluing parts of System.Web now.

1. HtmlEncode & UrlEncode

This one is pretty easy, System.Net is actually coming with System.Web equivalents methods here.

2. Querystring value access

Same for easiness here, based on Rick Strahl’s extensions found here.

3. MachineKey

This one gets a litle more tricky, but looking around can bring you a replacement, as the one below:

public class LogrrMachineKey
    private static string _decryption = "AES";

    private static byte[] _cryptKey;
    private static string _decryptionKey;

    public static string DecryptionKey
            _decryptionKey = value;
            var key = HexStringToByteArray(_decryptionKey);
            _cryptKey = key;

    public static byte[] Encrypt(byte[] inputBuffer)
        SymmetricAlgorithm algorithm;
        byte[] outputBuffer;

        if (inputBuffer == null)
            throw new ArgumentNullException("inputBuffer");

        algorithm = GetCryptAlgorithm();

        using (var ms = new MemoryStream())
            ms.Write(algorithm.IV, 0, algorithm.IV.Length);

            using (var cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
                cs.Write(inputBuffer, 0, inputBuffer.Length);
            outputBuffer = ms.ToArray();
        return outputBuffer;

    public static byte[] Decrypt(byte[] inputBuffer)
        SymmetricAlgorithm algorithm;
        byte[] inputVectorBuffer, outputBuffer;

        if (inputBuffer == null)
            throw new ArgumentNullException("inputBuffer");

        algorithm = GetCryptAlgorithm();
        outputBuffer = null;

            inputVectorBuffer = new byte[algorithm.IV.Length];
            Array.Copy(inputBuffer, inputVectorBuffer, inputVectorBuffer.Length);
            algorithm.IV = inputVectorBuffer;

            using (var ms = new MemoryStream())
                using (var cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
                    cs.Write(inputBuffer, inputVectorBuffer.Length, inputBuffer.Length - inputVectorBuffer.Length);
                outputBuffer = ms.ToArray();
        catch (FormatException e)
            throw new CryptographicException("The string could not be decoded.", e);
        return outputBuffer;

    private static SymmetricAlgorithm GetCryptAlgorithm()
        SymmetricAlgorithm algorithm;
        string algorithmName;

        algorithmName = _decryption;
        if (algorithmName == "Auto")
            throw new Exception("Explicit algorithm is required");

        switch (algorithmName)
            case "AES":
                algorithm = new RijndaelManaged();
            case "3DES":
                algorithm = new TripleDESCryptoServiceProvider();
            case "DES":
                algorithm = new DESCryptoServiceProvider();
                throw new Exception($"Algorithm {algorithmName} is not recognized");

        algorithm.Key = _cryptKey;

        return algorithm;

    private static byte[] HexStringToByteArray(string str)
        byte[] buffer;

        if (str == null)
            throw new ArgumentNullException("str");

        if (str.Length % 2 == 1)
            str = '0' + str;

        buffer = new byte[str.Length / 2];

        for (int i = 0; i < buffer.Length; ++i)
            buffer[i] = byte.Parse(str.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
        return buffer;

This class is not a one-to-one replacement of the existing MachineKey classes found in System.Web, so please make sure you migrate/ reset your values first.

Happy coding!

Kicking System.Web out of your code – part 2: HttpBrowserCapabilities object

Second part of my blog posts about getting rid of System.Web.

I will cover 2 part fo this object that I usually use: browser info & mobile device detection

1. Web browser information

We will he make use of the UAParser-csharp (c-sharp equivalent or the UAParser.js) which provides us a parsing mechanism of the User Agent string.

After installing the lib using Nuget, just a simple extension make the day (here returning “Windows 10 using Chrome“):

public static string GetBrowserName(this HttpRequestMessage request)
    var ua = request.Headers.UserAgent.ToString();
    var uaParser = Parser.GetDefault();
    var c = uaParser.Parse(ua);
    return $"{c.OS.Family} using {c.UA.Family}";

2. Mobile device detection

As far as you want to make sure you are rendering the web page for a mobile device or not, you can just use this extension method (inspired by this SO answer):

public static bool IsMobileDevice(this HttpRequestMessage request)
    string u = request.Headers.UserAgent.ToString();
    var b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
    var v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
    var returnVal = b.IsMatch(u) || v.IsMatch(u.Substring(0, 4));
    return returnVal;

Last step, will be removing MachineKey and utilities dependencies.

Happy coding!

Kicking System.Web out of your code – part 1: ASPNET MVC

Being doing some .NET code for a while now, you sure saw how much dependencies your code has on it.

With .NET core coming in sight, but also for optimizing you existing ASP.NET code base, you probably would want to start lowering your dependencies on it…

The first step (but not the smallest) for me is to kick out ASP.NET MVC.

DISCLAIMER: don’t get me wrong, ASP.NET MVC is a great framework for some use cases, but in my search for boot time optimization and lower memory footprint, this is not exactly what I need.

  1. Replacing ASPNET.MVC by RazorEngine

Not having much linked to it anyway, I replaced it with Razor Engine, a decoupled open source version for the MVC Razor engine (that you can also use to render other things than pages: emails, documents…)

Here is a piece of code to end up using the Razor Engine to render html views and use it the way you alwazs used ASP.NET MVC:

HttpRequestMessage extensions first:

public static class HttpRequestMessageExtensions
    public static TemplateServiceConfiguration TemplateConfig = new TemplateServiceConfiguration
        TemplateManager = new EmbeddedResourceTemplateManager(typeof(Startup))

    public static IHttpActionResult View&amp;lt;T&amp;gt;(this ApiController controller, string viewName, T model)
        return GetResponseView(controller.Request, viewName, model);

    public static IHttpActionResult GetResponseView&amp;lt;T&amp;gt;(this HttpRequestMessage request, string viewName, T model)
        var service = RazorEngineService.Create(TemplateConfig);

        var result = service.RunCompile($"Views.{viewName}", typeof(T), model);

        return new HtmlActionResult(request, result);

Using the extension in a controller:

public IHttpActionResult Index()
    var model = new AppModel();
    // filling the model accordingly.
    return this.View("Index", model);

Warning: this does not handle partial views, so this has to be managed additionally.

  1. Replace ASPNET.MVC with SPAs

The ultimate goal is to only have service-side code running as services (leveraging ASP.NET Web API), then to build your UI using a front-end stack for that (Angular. React, whichever suits you).

Next step, will be removing Browser HttpBrowserCapabilities dependencies.

Happy coding!

Build desktop apps using Electron

Working with web technology about he part years, you surely heard about Nodejs (who wouldn’t?).

So where Nodejs is about reusing the same JavaScript skills on the server-side, Electron is about reusing those skills for desktop apps.

I have been working for a while with Electron.

Let’s look again at what’s Nodejs:

  • based on chromium for JavaScript execution engine
  • Added feature to interact with filesystem access, ports (e.g. http server)
  • No UI (it is an execution engine to just run code!)

So what about Electron?

Well, basically you can think of Electron being Nodejs + UI, UI being here proper windows and not just HTML/CSS rendering.

What makes Electron interesting in that regard is that:

  • Electron runs as Nodejs for all server-side frameworks you want to use: web-sockets, queuing….
  • Electron provides a way to spawn “windows”, which can embed their own execution logic
  • Electron has one main process (aka the “server-side”) and a thread for each opened window
  • More interestingly, those processes can communicate together (using buit-in IPC capabilities)

Here is a drawn example of channel creation & subscription to close windows from the main process:

The bests things about Electron are:

  1. All this is that Electron offers a way to bundle your app to run independently on MAcOS, Windows & Linux!
  2. You can keep all your JavaScript development habits on frameworks you use with Nodejs, and the same applies to front-end, as you can embed Angular, React an build SPAs just like you were doing for an existing site; you can actually port an exiting website as an Electron app without that much efforts!
  3. As the UI you build is based on Chromium as the rendering engine, you don’t have to make any compat choices because of old or previous browsers not supporting Xor Y, you always get the top notch features available in Chrome engine!

Go and try it out here, happy coding!


Why I prefer PaaS over IaaS

A small digression on my techy blog mostly on a subjective aspect of what I like a bout Cloud services in General: PaaS.

I am not going to enter into a complete explanation to differentiate IaaS over PaaS, so I just chose to reuse a couple of well know picture around the subject to highlight my view:

AzureServicesOverview PaaSPizza

The point of these 2 pictures is to show that PaaS offers more managed components than IaaS does.

It is true that PaaS, dues to offered services costs more than traditional IaaS does…

Price/Cost is a thing for sure, but having your team losing time on infrastructure building/patching/deployment/reboots is in today’s world not something you wanna do for multiple reasons:

  • When you teams do these tedious things, they aren’t producing value; neither for you of for your customers,
  • Doing these activities is not something that will make your team happy on the long run, better having it off your plate to let them work on things they like and that will make them learn,
  • Building software these days in more about playing with Legos, and it’s a good thing; building your infrastructure should be the same (of course you still need to know what’s in those boxes, and what are their limitations in what you wanna do with it).


Happy legoing!


“Invalid service definition or service configuration” when accessing a Windows Azure role definition.

This happened to me recently, when accessing roles configured inside one of my project after adding a new Worker role into it.


It then has automatically something to do with this, but I did this operation a lot of times… Then Is remebered that I did had some extra Nestwork configuration inside of on of my cloud CSCFG files…

Solution: Roles need to be next to each other in the Solution definition, which makes the Role designer to work again; just move the “NetworkConfiguration” section at the bottom of the CSCFG file.


Happy coding!

Windows 8.1: Here it is!

Build is gone, lots new things have been showed up during the MS mass.

So far from all sessions I saw/watched over Channel9, a lot of good things hasve been coming out of Build 2013, and consequently a lot of good things have been coming up for Windows 8!

As a result, here is the set of videos I encourage you to watch from my development perspective to get a great dev insight on Windows 8.1 and other MS tech stuff:

Continue reading Windows 8.1: Here it is!

How to deal with different environments in Windows Azure

Hi everyone,

For those of you who are working with Windows Azure and looking for flexibility in their different environments, here are a couple of points I have been using during my projects to help being flexible and fast.

Web.config transformations:

Since Visual Studio 2010, one can use XML transformations on web.config, to help getting different file versions when you build your app in Debug or in Release.

Here is a small example on how to do it for the SessionState:

In file Web.Debug.config:

<sessionState xdt:Transform="Replace" mode="InProc" />

In file Web.Release.config:

<sessionState xdt:Transform="Replace"
mode="SQLServer" allowCustomSqlDatabase="true"
sqlConnectionString=";Database=MyDB;User ID=admin;Password=password;Trusted_Connection=False;Encrypt=True; MultipleActiveResultSets=True;" />

You can then do the same for the DB connection you use to you SQL Azure back end when using Entity Framework.

The problem here is that transformations only apply to “built” config files (stored in bin or debug folders), so this doesn’t apply when debbuging locally your Web project!!

To do this, leave DEV related entries in the Web.config directly, so that transformations will only apply when building the Azure packages in Release using the Web.Release.config:

In file Web.config:

<add name="RMOPEntities" connectionString="metadata=res://*/Data.RMOP.csdl|res://*/Data.RMOP.ssdl|res://*/Data.RMOP.msl;provider=System.Data.SqlClient;provider connection string=&quot;data\galatea;initial catalog=RMOP;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

In file Web.Release.config (to transform it when building package):

<add name="RMOPEntities"
connectionString="metadata=res://*/Data.RMOP.csdl|res://*/Data.RMOP.ssdl|res://*/Data.RMOP.msl;provider=System.Data.SqlClient;provider connection string=&quot;data;initial catalog=RMOP;;User ID=ctpadmin;Password=pass@word1;multipleactiveresultsets=True;App=EntityFramework&quot;"
providerName="System.Data.EntityClient" />

Conditional Symbols:

You certainly know already DEBUG and RELEASE constants (used with “#if DEBUG” in code).

You can also build you own, to address specific purposes; you can eevn build your own build configurations to include these conditional symbols or not.

Here is a sample of a Project properties set to use conditional symbols:

In that case I created a “NOAUTH” symbol to bypass user having to log in the application for debug purposes.

Verifying if you are  REALLY in Azure:

In certain cases (e.g. layout modifications) , you are not forced to run your whole project using the DevFabric.

To avoid this you can just run the WebApp project, but of course you won’t be able to leverage anything from Azure APIs like Storage.

You can then do it using Dummy Data to return through your layers to test more rapidly your application and keep on having it to work without Azure.

A small sample here:

if (RoleEnvironment.IsAvailable)
    return AzureBlobMaganer.GetDataItems();
    return new List<DataItem>() {new DataItem() {Label = "Test", Value = 12}};

Config Items in Roles:

The last point here is to play a bit with Azure connections; which on will we connect to: DevFavric or Azure ?

Here is a sample of an Azure project configuration:

The simple solution here is:

var account = CloudStorageAccount.FromConfigurationSetting("StorageDev");
var account = CloudStorageAccount.FromConfigurationSetting("Storage");

A clever way would be to encapsulate this in a method to return the right storage account, or even a static property set to different variables depending on constant definition:

public const string CloudAccountName = "StorageDev";
public const string CloudAccountName = "Storage";

Thanks for reading, and don’t hesitate to give me feedback!