Category Archives: .NET @en

Remove unused CSS out of an html template

How many times do you have to clean out HTML / CSS templates chosen for a given site you have to build?

If the answer to this question is yes, you are at the right place!

I have been facing this multiple times, especially with that so nice template that you need for only one page, which contains single-theme CSS files worth 600Kb or worse…

The solution I have been using has been working for me multiple times, and really helped reducing size of required files to be used.

First, create a node project, in which you can pre-create a package.json file (only to save development dependencies).

Then install the following packages :

npm install grunt --save-dev
npm install grunt-uncss --save-dev

grunt-unccs is a node package that will do for you the CSS cleaning, taking care of cleaning unused CSS classes for one or multiple html pages.

Now, create your gruntfile.js file, with the following content:

'use strict';

module.exports = function (grunt) {
  // Project Configuration

  // Project Configuration
  	uncss: {
	  dist: {
	    files: {
	      'dist/tidy.css': ['src/pages/index.html', 'src/pages/about.html']

Make sure your pages are accessible as per given entry under the files json object.

This will then let you run the following command:

C:\Projects\NodeTidyTest>grunt uncss
Running "uncss:dist" (uncss) task
File dist/tidy.css created: 888.72 kB → 32.98 kB

You are done!


  • This does not solve in-CSS file links such as images or font loading (e.g. Font-Awesome if loaded locally),
  • Complex CSS selectors are not managed by this plugin (could make it crash); once identified move them into a separated CSS file, not parsed by the lib to avoid issues.

Xamarin is acquired by Microsoft

What a story!

Microsoft has announced they are acquiring Xamarin.

This means a lot of things within the mobile/enterprise world now:

  • Microsoft is recognizing that the native platform targeting is a very valid point in today’s world; user are more into apps that target native user interface and native performance than only HTML containers (Safari is good for that!),
  • Integrated Dev environments (iOS dev with Visual Studio) as well are reusable language knowledge (C#) over multiple platforms are a thing; learning a new language in a way is not creating value, it’s what you do with it that does.

Know the next step is to see how all this will integrate into Microsoft licensing and offering for enterprise (part of Visual Studio?).

More should come at //BUILD next month, nearly in a month time!

Creating an Azure SQL Database+ using Entity Framework Code first

I have been talking about Azure SQL Database Elastic Pools a few times before, and using it now for self-registering and DB creation on the fly.

I came into an issue when using it along with code first to apply my model to a newly create database; the common message I was receiving was “Database does not exists“…

I figured out that, when SQL Database creation command gets executed, it doesn’t mean that the database is actually completely created, it’s status just after the creation command is “Creating”.

This then makes sense as from the error I am receiving from the API, which means I just need to wait a little bit before applying my Code First model 😀

var sqlMgmtClient = new SqlManagementClient(
    new CertificateCloudCredentials("subscriptionID",
    "your X509Certificate2 instance"));

// Generating a unique ID for the DB.
var dbId = Guid.NewGuid().ToString("N");

var dbParams = new DatabaseCreateParameters(dbId) { Edition = "Basic" };
var db = await sqlMgmtClient.Databases.CreateAsync(ServerName, dbParams);

// Waiting DB to be accessible before updating it.
var wait = true;
while (wait)
    var status = await _sqlMgmtClient.Databases.GetAsync(ServerName, dbId);
    if (status.Database.State == "Normal") // else is "Creating"
        wait = false;

// Updating DB to latest Code First version.
var connectionString = String.Format(this.dbConnectionTemplate,
    this.serverName, dbId, this.adminName, this.adminPassword);
var migratorConfig = new Configuration
    TargetDatabase = new DbConnectionInfo(connectionString, "System.Data.SqlClient")
var dbMigrator = new DbMigrator(migratorConfig);

Happy coding!

Swagger (Swashbuckle) with dotnet: real life implementation – part 2

Following my first article on how to use Swagger with .NET using Swashbuckle, I wanted to cover a last but very important point: dynamic entities.

I am sure that a lot of you are using dynamic object with document-orentied DBs, which bring the problem of giving a proper output to them with .NET documentation (and strongly type)

In any of these cases, what I usually do first is to never exposing my back-end objects directly through Swagger (which makes real sense with Entity Framework) to give all the flexibility to serialize or not certain properties, or even the way they need to.

1. Using SwashBuckle hooks

Which SwashBuckle we can hook into documentation creation to add/update object properties to set more custom properties. Have a look here in the current documentation.

2. Using string[] and Json.Net objects

What to do if you have complete dynamic objects that you what to show either as empty objects (on which you can add as many properties as you want) or an array of strings or properties ?

// property shown by Swashbuckle as empty object.
public JObject AppInstProperties { get; set; }

// property shown by Swashbuckle as an array.
public string[] EditableUserInAppProperties { get; set; }

In this cases, you could also replace string[] by YourObject[] 🙂

Happy coding!

Swagger (Swashbuckle) with dotnet: real life implementation – part 1

I have been roaming around the web for a while to try to find real hints to implement proper Swagger documentation on top of Web API, and I didn’t really find what I wanted.

I have then being doing myself investigations on the road, and I found very interesting points on how to (or not to!) do things with Swagger and dotnet.

1. Setup

To be able to use your method documentation on you assemblies, the first step is to enable then to be output, whether it’s coming from your main project or referenced libraries:

To do so, go to you build project Build settings, and check “XML documentation file” to specify the file name used to output the XML:


Then in your Swagger project go to your SwaggerConfig.cs in App_Start folder and use the following line of code to make Swashbuckle understand where to Get XML to enrich your methods and object definitions:

c.IncludeXmlComments(string.Format(@"{0}\bin\Gibberish.Api.xml", AppDomain.CurrentDomain.BaseDirectory));

2. Documenting

To document your entities refer to this table to know how xml tags are mapped to Swagger properties, have a look here (coming from the Swagger Github home page):

  • Action summary -> Operation.summar
  • Action remarks -> Operation.description
  • Parameter summary -> Parameter.description
  • Type summary -> Schema.descripton
  • Property summary -> Schema.description (i.e. on a property Schema)

Real example for these for methods:

/// <summary>
/// Updates the mobile entity
/// </summary>
/// <remarks>
/// entity need to be up to date
/// </remarks>
/// <param name="entity">Parameter description goes here</param>
[HttpPut, Route("update")]
public IHttpActionResult UpdateMobileEntity(RestMobileEntity entity)
    return Ok(base.mobileService.Update(entity));

And for types :

/// <summary>
/// Mobile entity
/// </summary>
public class RestMobileEntity 
    /// <summary>
    /// Entity Id
    /// </summary>
    public int entityId { get; set; }

    /// <summary>
    /// Entity content
    /// </summary>
    public string entityContent{ get; set; }

That’s a first round for Swagger and dotnet, let’s have a look next about Swagger with dynamic object, and custom theme use.

Back to basics : Generics in Action<T>!

Even if I have been using generics once in a while, it’s still quite interesting to see all scenarios you ca address with them.

To go back to basics, let’s see an old piece of code:

Hashtable d = new Hashtable();
d.Add("1", new User());
d.Add("1", new Group())

Then later in the code…

var user = d["2"] as User;

This does compile, but if you would have to run it… It would just crash.

What Generics avoid here is that it forces you to type (e.g. in case of collections) items in a list to a certain object :

var list = new List<User>();

This at least avoids us to try to cast incompatible types and to mix object types as it is possible for a hastable.

But this is just a very small value of what Generics can do.

You sure have seen so many methods used over LINQ or other parts of the .NET framework that uses SomethingOf<T>, which if the point I want to go to.

Here is a small example of what you can do in that matter:

public static T AsOb<T>(this string s) where T : new()
    if (String.IsNullOrEmpty(s))
    return new T();
    return JsonConvert.DeserializeObject<T>(s);

Which then gets called this way:

var user = strUser.AsOb<User>();

One single line of code then to de-serialize any string to any json objects (quite usual these days).

You can use additional selectors when using Generics on a methods:

  • class: if you want on ensure only object with are classes will be used,
  • specific class: for objects inheriting that class, letting you use its methods and properties,
  • interfaces: no need to explain 😀
  • finally the “new()” constraint e.g. (to ensure class is not sealed), to be able to instantiate it, as in above code

Now let’s do some more interesting things with it

Taking my code above for json deserialization, here is somehitg people do alllllllll the time:

var user = JsonConvert.DeserializeObject<User>(myObject.UserAsString);
user.LastModified = DateTime.UtcNow;
myObject.UserAsString = JsonConvert.SerializeObject(user);
// Do someting with the updated json (Db update...)

With the small piece of code above, we just change one line….
What if I just use then Action ???

Action if used here to wrap a method call (usually anonymous) to be done upon a given object.
Wait a minute, you can call a moethds passed as a parameter? (looks like JS isn’t it?)

So I can now redo my method like this:

public static string GetScopedJson<T>(this string s, Action<T> ssAction)
    var desserialized = JsonConvert.DeserializeObject<T>(s);
    return JsonConvert.SerializeObject(desserialized);

Which then makes my code looks like this:

myObject.UserAsString = myObject.UserAsString.GetScopedJson<User>(u =>
    u.LastModified = DateTime.UtcNow;

This then helps on simplifying very tedious pieces of code that could have been around for a while 🙂

Another example of code I have been using extensively, leveraging the same principle (for ADO.NET lovers):

public void ExecuteReader(string storedProcName, SqlParameter[] parameters, Action<SqlDataReader> action)
    using (SqlConnection connection = new SqlConnection(_conn))

        SqlCommand cmd = new SqlCommand(storedProcName);
        cmd.Connection = connection;
        cmd.CommandType = CommandType.StoredProcedure;

        using (SqlDataReader reader = cmd.ExecuteReader())

This way I can make my calls in ADO.NET pretty damn short:

Organization org = null;
var param = new SqlParameter("@IP", SqlDbType.NVarChar);
param.Value = orgKey;

    new SqlParameter[] { param }, reader =>
        org = DatabaseHelper.MapDataToEntity<Organization>(reader);

Back to basics : Difference between func and action

Generics are a really awesome feature of .NET; but what makes it even better are all what has been made out of it.

My preferred example her is to talk about Func and Action.

These two are a bit like the Tuple object : a way to give a general mean of a structure.

In the case of Action<T> and Func<T> here are what makes them special:

  • Action<T> is a way to pass a method with parameters (often anonymous) to another method.
  • Func<T> does the same, but also allows for a return type, which means your anonymous methods can then return a computed value used in matter of the method you have been calling.

An example of an Action<T> is (using Azure Table Storage):

public static T GetResult<T>(this TableResult result) where T : class
    if (result.Result != null)
        return result.Result as T;
    return null;

public T GetTenant<T>(string tableName, string pKey, string rKey) where T : TableEntity
    var tableClient = _storageAccount.CreateCloudTableClientWithRetries();
    var table = tableClient.GetTableReference(tableName);

    // Create a retrieve operation that takes a customer entity.
    var retrieveOperation = TableOperation.Retrieve<Tenant>(pKey, rKey);
    var result = table.Execute(retrieveOperation);
    return result.GetResult<Tenant>();

An example of a Func<T> is:

public void ExecuteReader(string storedProcName, Func<SqlParameter[]> parameters, Action<SqlDataReader> action)
    using (SqlConnection connection = new SqlConnection(_conn))
        SqlCommand cmd = new SqlCommand(storedProcName);
        cmd.Connection = connection;
        cmd.CommandType = CommandType.StoredProcedure;
        using (SqlDataReader reader = cmd.ExecuteReader())

Happy coding!

Announcing the new Azure App Service

Yesterday, Scotts (Guthrie and Hanselman) have been introduced a new AzurepPlatform offering called: Azure App Service.
A bit of renaming is to be done, but there is a LOT of new stuff behind all of this:

  • “Azure Websites” now become “Azure App Service – Web Apps”,
  • “Azure Mobile Service” is now “Azure App Service – Mobile Apps”,

Renaming stops here, with newcomers to the Platform:

  • “Azure App Service – Logic Apps”, which basically behaves like modeling processes using different API Apps,
  • “Azure App Service – API Apps”, which is actually for me the base of the new offfering.

So what about these API apps then?

To make long story short, API Apps are here to simplify most of the work of the 3 others (Web Apps, Moible Apps & Logic Apps) by:

  • providing a similar way of consuming API apps (JSON based with Swagger capabilities “”),
  • giving a way to make API apps to deal with authentication in a transparent manner,
    offer versioned and automatically updatable APIs to all 3 types of apps.

API Apps are based at core on ASPNET Web API stack, with few little twists for authentication.

To have a more concrete view of this, here is a little MS slide used to represent to common glue which is API Apps in that regard:

These API Apps is making a best use of some great tooling already available such as:

  • Swagger to repressent API methods and content (a “modern WSDL” I always say),
  • Swashbuckle, a tool to implement simply Swagger capabilities inside of ASP.NET Web API,
  • AutoRest, a Swagger “svcutil-like” to build up a proxy for REST Services.

As of with all these new offering, the best part is: you can get all of them hosted under the same pricing you has for only one Website or Mobile App: all of these can run inside a Shared or dedicated container that does all of this!

As a conclusion, this starts a real great new platofrm settlement for Azure, which we should all be looking into!

Introducing ASP.NET 5

For some of you who could have missed a bit about what is happening in the MS world these days, I am pretty sure that most didn’t miss all of the annoucements going around .Net…

The biggest part of it, is the annoucement of ASP.NET 5, which holds a lot of undelying changes and promises:

  • Build & run ASP.NET apps on Windows, Linux AND Mac.
  • .NET Core, which is the base of this capability, a new modular and versioning capable stack.

As .Net Core is for now more limited than the Full .Net frameowrk, this does not mean that you will have to migrate you code to benefit from all new ASP.NET 5 capbilities: these  will also be available on Full .NET stack 4.5.2 and above.

The BIGGEST point here is the fact that .Net Core is Open Source, and its code source is available on GitHub.

The promise that I see coming, is all the new block that could be coming along with it (Compiler…) would also end up as Open Source components!

These are great times to be working on MS tehcnologies!

VERY happy coding everyone!

Error “Compiler Error Message: CS0234” when running your ASP.NET MVC project

After trying to run a previously working ASP.NET MVC app, I suddendly got this error:

The type or namespace name 'Html' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)

Seems that “I just needed” to seet “System.Web.Mvc” reference “Copy Local” to true.

The thing was that it was already set to true…

The magic here has just been to set it to false, compile, THEN to set it again to “Copy Local” = true.

Happy coding!