Davos: Smart machines set to transform society

FT-Davos-Microsoft

Artificial intelligence will spur economic growth and create new wealth. Machines that “think” like humans will help solve huge problems, from curing cancer to climate change. Yet millions of human workers will need to retrain, as robots make their existing jobs redundant.

These are the contrasting messages provided by the world’s leading technologists during the World Economic Forum in Davos this week, as political and business leaders ponder how best to respond to the rise of smart machines.

Sebastian Thrun, the inventor of Google’s self-driving cars and an honorary professor at Delft University of Technology, told the Financial Times that “almost every established industry is not moving fast enough” to adapt their businesses to this change.

He suggested self-driving cars would make millions of taxi drivers redundant and planes running solely on autopilot would remove the need for thousands of human pilots.

One of the central themes of this year’s conference is the “Fourth Industrial Revolution,” referring to how technological breakthroughs are expected to transform industries across the world. Delegates argued that advances in robotics and artificial intelligence will have the transformative effect that steam power, electricity and ubiquitous computing achieved in previous centuries.

“[Artificially-intelligent machines] can look at a brainscan better than most radiologists, but they can also weld better than any human,” said Illah Nourbakhsh, a professor of robotics at Carnegie Mellon University, the institution which has a partnership with Uber to build driverless cars. “It’s affecting white-collar and blue-collar jobs. Nobody is inherently safe.”

But Mr Thrun was optimistic that redundant roles will quickly be replaced.

“With the advent of new technologies, we’ve always created new jobs,” he said. “I don’t know what these jobs will be, but I’m confident we will find them”

Satya Nadella, chief executive of Microsoft, said: “This challenge of displacement is a real one, [but] I feel the right emphasis is on skills, rather than worrying too much about the jobs [which] will be lost. We will have to spend the money to educate our people, not just children but also people mid-career so they can find new jobs.”

Creating a URL shortener using ASP.NET WepAPI and MVC

In this tutorial, I use several techniques and tools. I use Microsoft Visual Studio 2015 and the latest version of all components.

  • ASP.NET MVC: Microsoft’s modern web application framework. As the name says, it pushes you to use the MVC (model view controller) software design principle.
  • ASP.NET Web API: Web API and MVC are used together in many applications. With MVC, the HTML of the web pages are rendered on the server, and with Web API you can, like the name says, create an API. Web API also uses the MVC principle, but returns XML (or JSON, or YAML, or … whatever you want) instead of HTML.
  • Microsoft SQL: this is my primary database choice.
  • Entity Framework: this is my favourite ORM (object relational mapping) framework. With Entity Framework, you can create a database “code-first”, meaning that you can create classes (called entities) that represent the database and create the database based on those entities and its relations. When you’ve updated one of these entities, you can add a new migration, which means that the changes to your entities will be written to the database.
  • Unity: Unity is a dependency injection framework. You can read more on dependency injection and inversion of control later in this tutorial.

Basic project structure

If you didn’t know already, Visual Studio works with solutions. A solution can contain multiple projects. When a solution is compiled, a DLL (or EXE if it’s a WPF or Console application) is created. These DLLs, in case of an MVC application, are deployed to the server. A project can reference another project in the same solution, or assemblies compiled from another solution. A third way of adding references is using NuGet; this is a package manager for ASP.NET applications. Using this, you can add a connector to MySQL, Entity Framework, xUnit.net (testing framework) and many, many more to your solution. You can compare it to Composer (PHP) or npm (Node.js).

Once you’ve started Visual Studio, go to File | New | Project. I always select “ASP.NET Web Application”. In the following dialog, select “MVC”, but also select “Web API”. On the right hand, change authentication to “No Authentication”, since we’re not going to use that (not for this tutorial though, maybe later). In the bottom fields, you can fill in the name and location of your solution. I call it “PSC.Shorturl.Web” (but call it anything you want). You can uncheck “Host in the cloud”, although I’m not sure what the difference is (I never hosted anything in Azure). You can now click OK.

A basic MVC site is created now. Once you click the “Run” button at the top, you’ll already be able to browse the basic website. A local IIS web server is launched and your favourite browser will be opened with the MVC website.

ASPNET_MVC_FirstStart

As you can see, there are some files and folders created for you in this project. I’m going to explain what these folders and files are.

ASPNET_MVC_Solution

  • App_Data: This folder is empty for now, but if you ever want to enable uploads on your websites, it’s best if they are placed here.
  • App_Start: this folder contains some classes which are needed to start up MVC and Web API when the application is first run. If you add new frameworks which need something of a setup, this can be placed in this folder.
  • Content: this folder contains your CSS files and images.
  • Controllers: this folder contains the controller classes of the MVC application.
  • fonts: as the name says, this folder contains fonts.
  • Models: this folder contains models which will be used to pass data from the controllers to the views.
  • Scripts: this folder contains (Java)script files.
  • Views: this folder contains the views for the MVC application.
  • Global.asax: this file is loaded when the application is started. In this file, the classes in the “App_Start” folder are called.
  • packages.config: if you’re going to add packages from NuGet to your project, a reference to that project will be added to this file. When someone else receives your code and tries to build our code, Visual Studio first downloads all packages defined in this file (else the build would fail because these DLLs aren’t available).
  • Web.config: this file contains general configuration for your application. Think of database connection strings, SMTP server settings etc.

First, let’s open HomeController.cs in the folder Controllers. You’ll see this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PSC.Shorturl.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

This method contains three methods. When the application is started, RouteConfig (which is located in App_Start) is read and mapped to the existing controllers. In this application it means that when you go to http://yourapp/Home/About, the method About in the HomeController will be executed. This is called convention over configuration; you don’t have to explicitly tell the application that you have added a new controller. This means that when you add a new controller, say UrlController with a method Shorten, this will be called when you go to http://yourapp/Url/Shorten.

You also see that the methods in this class return a View(). For example, when you browse to /Home/About, the View() searches in the folder Views to the file About.cshtml (can be another extension, but the file should be called “About”). Again, this is “convention over configuration”.

Every method in this controller returns an ActionResult. An ActionResult can be a view, but can also be a redirect (which we’ll use later when redirecting a short URL).

This default behaviour can be fine tuned, but I think that’s not necessary for now; I think it works fine this way.

Now that’s explained, let’s create a new controller. Right click the Controllers folder and create a new controller (MVC 5 Controller – Empty). I call it UrlController.

ASPNET_MVC_AddController1

ASPNET_MVC_AddController2

By adding a new controller, a new folder is also added in the “Views” folder; “Url”. In this folder, create a new view called “Index.cshtml”. This is the code for the view:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

This is the main URL shortening view. Here, we'll show our form later on.

 

On the top of the view, you see a syntax you may have never seen before. This is MVC’s template syntax: Razor. The property “Title” of “ViewBag” is set to “URL shortener”. ViewBag is used to pass data from one view to another. In this case, the title will be rendered between the title tags of the master layout.

If you start the application now and head to /Url/Index (or just /Url, because Index is assumed if the second part isn’t set; see RouteConfig.cs), you’ll see our newly created view rendered. Later on, this view will contain the form where users can fill in their long URL to be shortened, so when the root URL is reached, we would like the user to see this page, we don’t want them to go to http://yourapp/Url. To accomplish this open RouteConfig.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace PSC.Shorturl.Web
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", 
                                id = UrlParameter.Optional }
            );
        }
    }
}

 

This is the default route configuration. You’ll see that by default the HomeController and Index action are selected. Change “Home” to “Url”. Now, when we go to the root URL, we’ll see our newly created view.

This view is a bit empty for now. First, add a new class called “Url” to the folder “Models”. Like I’ve said before, a model is responsible for passing data between a View and a Controller. Below, you’ll see the model I’ve created:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PSC.Shorturl.Web.Models
{
    public class Url
    {
        public string LongURL { get; set; }

        public string ShortURL { get; set; }
    }
}

 

The model will contain the long URL and the short URL for now. When the user has filled in the URL he / she would like to have shortened, the LongURL property will be set and it will be sent to the business layer (which we will create lateron). The business layer will validate the URL and will return a short URL. The short URL will be set and the model will be returned to the view.

Now, let’s add a form to Index.cshtml.

@model PSC.Shorturl.Web.Models.Url
@{
    ViewBag.Title = "URL shortener";
}

<h2>Shorten a URL</h2>

@using (Html.BeginForm())
{
    <div class="form-group">
        @Html.TextBoxFor(model => model.LongURL, 
                         new { placeholder = "URL you would like to have shortened", 
                         @class = "form-control" })
    </div>

    <input type="submit" class="btn btn-primary" value="Shorten" />
}

 

As you can see, I’ve added a “@model” reference at the top. The view now knows that it should use the class we’ve just created (you can call the model anywhere by using @Model in the view). Further on, you see we start a new HTML form. In this form we start a new TextBox, with a reference to the LongURL property in the class “Url”. The second parameter in this method is an anonymous object with several HTML attributes, like placeholder and class (class is prefixed with an “@” because it is a reserved keyword in ASP.NET, the application won’t work otherwise). The last line is a plain old HTML submit button.

ASPNET_MVC_FirstScreen

All very nice, but there is no logic at all at the moment. Let’s go back to UrlController.cs.

using PSC.Shorturl.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PSC.Shorturl.Web.Controllers
{
    public class UrlController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            Url url = new Url();
            return View(url);
        }

        public ActionResult Index(Url url)
        {
            url.ShortURL = "http://www.puresourcecode.com";
            return View(url);
        }
    }
}

 

You now see that I’ve created two methods with the same name. One which doesn’t have any parameters, one with a Url object as parameter. The first method will only be called when the user is first directed to the page. The second method is used when the user has pushed the submit button. MVC will serialize the data filled in on the form, place it in a URL object and pass it to that function. Here, we will be able read the original LongURL property and send it to the business layer. As of now, nothing happens with it and the ShortURL property is set to “http://www.google.com” hard coded. This is fine for now. The object with the ShortURL property set is being passed to the view, so we can read this property in the view now. If you place the snippet below in “Index.cshtml” underneath the textbox, you’ll see the shortened URL when you push the submit button.

if (!string.IsNullOrEmpty(Model.ShortURL))
{
    <div>
        lt;a href="@Model.ShortURL" target="_blank">@Model.ShortURL</a>
    </div>
}

 

It would be nice to have a little validation. For now, it’s enough to validate that the user has actually filled in anything as long URL. So go back to "Url.cs" and change LongURL to this:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace PSC.Shorturl.Web.Models
{
    public class Url
    {
        [Required]
        public string LongURL { get; set; }

        public string ShortURL { get; set; }
    }
}

 

By placing this attribute directly above this property, MVC knows that this property should be set. Next, change the second Index method in UrlController.cs to this:

public ActionResult Index(Url url)
{
    if (ModelState.IsValid)
    {
        url.ShortURL = "http://www.puresourcecode.com";
    }
    return View(url);
}

 

ModelState.IsValid checks if all validation requirements are met. If yes, set the ShortURL. Finally, we would like the user to get validation feedback. In “Index.cshtml”, place this piece of code anywhere you’d like (I place it directly beneath the H2 tags):

@Html.ValidationSummary()

At this point, I deleted the HomeController and Home folder in the Views folder; we don’t need it for the now.

Now, it’s time to set up the other projects. Right click the solution and add new projects. The project I’m describing should be of the type “Class Library”.

ShortUrl_NewProject

ShortUrl_ClassLibrary

  • PSC.Shorturl.Web.Business: this project will contain the interfaces and classes needed to execute numerous business actions; for example adding a new short URL to the database, searching a short URL etc.
  • PSC.Shorturl.Web.Data: this project will contain our data context for Entity Framework and the migrations will be saved in this project.
  • PSC.Shorturl.Web.Entities: this project will contain the entities (plain old classes) for our data structure.
  • PSC.Shorturl.Web.Exceptions: this project will contain custom exceptions. For example, when a specific URL isn’t found, an exception will be thrown and it will be caught by the MVC framework to show us a nice custom error page.

So, now we’ve created all project we’re going to need to add several NuGet packages to the projects.

ShortUrl_NuGet

Search and install the following packages. I’m going to describe in which projects every package has to be installed to.

Shorturl_Nuget_packages

  • EntityFramework: the ORM which we’re going to use.
    • Business
    • Data
    • Entities
    • Web
  • Newtonsoft.Json: a nice Json serializer for ASP.NET. This will be needed by Web API later on.
    • Business
    • Data
    • Entities
    • Web
  • Unity, Unity bootstrapper for ASP.NET MVC & Unity.WebAPI: this is an inversion of control (IoC) for ASP.NET. It is used for loose coupled web applications. I will explain this later on.
    • Web

The solution should be able to build now. If not, please leave a comment and maybe I can help you.

Dependency injection

Robust applications don’t have any hard coupling in their code. What I always like to do is constructor injection; whenever a controller (or any other class) is instantiated, you can fill in a few parameters in the constructor. These parameters are interfaces.

Unity, an inversion of control framework, finds out which implementation belongs to this interface, and injects it. With this framework, you don’t have hard coupling; there is only one place in your application where you fill in this interface/implementation mapping. Whenever you need to change the implementation (for example, you used Entity Framework, but want to switch to NHibernate), you just create a new class that implements that specific interface and you change the configuration for Unity. It might all sound a bit vague. Let’s try to setup Unity.

1. The web project should reference all other projects

Right click the web project and add a new reference.

ShortUrl_ReferencesMenu

ShortUrl_References

2. Add an interface IUrlManager and a class UrlManager (which implements IUrlManager)

IUrlManager
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Business
{
    public interface IUrlManager
    {
        Task<string> ShortenUrl(string longUrl);
    }
}
UrlManager

Create a folder named Implementations and under this folder create the following interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Business.Implementations
{
    public class UrlManager : IUrlManager
    {
        public Task<string> ShortenUrl(string longUrl)
        {
            return Task.Run(() =>
            {
                return "http://www.puresourcecode.com";
            });
        }
    }
}

We have to tell the application somehow that when an implementation for IUrlManager is desired, a UrlManager should be injected. The method RegisterTypes in the class UnityConfig will look like this now:

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using PSC.Shorturl.Web.Business;
using PSC.Shorturl.Web.Business.Implementations;

namespace PSC.Shorturl.Web.App_Start
{
    /// <summary>
    /// Specifies the Unity configuration for the main container.
    /// </summary>
    public class UnityConfig
    {
        #region Unity Container
        private static Lazy<iunitycontainer> container = new Lazy<iunitycontainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container" />The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your types here
            // container.RegisterType<iproductrepository productrepository ,>();
            container.RegisterType<iurlmanager urlmanager ,>();
        }
    }
}

3. Update the existing UrlController

Let’s take a look at the new UrlController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using PSC.Shorturl.Web.Business;
using PSC.Shorturl.Web.Models;

namespace PSC.Shorturl.Web.Controllers
{
    public class UrlController : Controller
    {
        private IUrlManager _urlManager;

        public UrlController(IUrlManager urlManager)
        {
            this._urlManager = urlManager;
        }

        [HttpGet]
        public ActionResult Index()
        {
            Url url = new Url();
            return View(url);
        }

        public async Task<actionresult> Index(Url url)
        {
            if (ModelState.IsValid)
            {
                url.ShortURL = await 
                    this._urlManager.ShortenUrl(url.LongURL);
            }
            return View(url);
        }
    }
}

As you see here, we’ve added a private field and a constructor. When the controller is selected, Unity knows that it should insert the UrlManager in the IUrlManager. We have no hard coupling on the implementation at the moment. The second Index method is now async, and returns a Task. This is because our final implementation of the UrlManager will call the database and check if the inserted URL actually exists. If this isn’t executed async, it will block the entire application until these actions are done; that’s something you don’t want.

Every new business manager you’re going to add, can be injected using Unity.

Entity Framework

As I’ve explained before, Entity Framework is a object relational mapping framework. You define a few classes with a few properties. These properties match the fields in the database. Before we can do anything with Entity Framework, we have to make set up the MySQL connection in the Web.config file. The code snippet below should be inserted in the configuration tag of Web.config:

  <connectionStrings>
    <add name="Shorturl"
        connectionString="Server=YourServer;Database=PSCShortUrl;Uid=youruser;Pwd=yourpassword;"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

Make sure you put in the correct server, username and password.

Let’s add two entities (so two tables) for the URL shortener application to the Entities project. These are just plain classes.

ShortUrl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Entities
{
    [Table("short_urls")]
    public class ShortUrl
    {
        [Key]
        [Column("id")]
        public int Id { get; set; }

        [Required]
        [Column("long_url")]
        [StringLength(1000)]
        public string LongUrl { get; set; }

        [Required]
        [Column("segment")]
        [StringLength(20)]
        public string Segment { get; set; }

        [Required]
        [Column("added")]
        public DateTime Added { get; set; }

        [Required]
        [Column("ip")]
        [StringLength(50)]
        public string Ip { get; set; }

        [Required]
        [Column("num_of_clicks")]
        public int NumOfClicks { get; set; }

        public Stat[] Stats { get; set; }
    }
}
Stat.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Entities
{
    [Table("stats")]
    public class Stat
    {
        [Key]
        [Column("id")]
        public int Id { get; set; }

        [Required]
        [Column("click_date")]
        public DateTime ClickDate { get; set; }

        [Required]
        [Column("ip")]
        [StringLength(50)]
        public string Ip { get; set; }

        [Column("referer")]
        [StringLength(500)]
        public string Referer { get; set; }

        public ShortUrl ShortUrl { get; set; }
    }
}

This is a very basic entity setup.

  • Table tells Entity Framework what the actual table name should be.
  • Key tells Entity Framework that this property is the primary key.
  • Column tells Entity Framework what the columns name is in the database.
  • StringLength tells Entity Framework what the maximum string length of a property is (only if the type is “string”).

This actually doesn’t do anything. We have to define a “data context”. The data context is the central piece in Entity Framework: it contains the relations between the different entities and contains the repositories. A repository is a collection of all records in a specific table mapped to a specific entity. Let’s add a ShortUrlContext to the Data project.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PSC.Shorturl.Web.Entities;

namespace PSC.Shorturl.Web.Data
{
    public class ShorturlContext : DbContext
    {
        public ShorturlContext()
            : base("name=Shorturl")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<stat>()
                .HasRequired(s => s.ShortUrl)
                .WithMany(u => u.Stats)
                .Map(m => m.MapKey("shortUrl_id"));
        }

        public virtual DbSet<shorturl> ShortUrls { get; set; }
        public virtual DbSet<stat> Stats { get; set; }
    }
}

The string "name=Shorturl" in the constructor refers to the connection string in the Web.config file. The method OnModelCreating is where all the relations between the entities are configured. At the moment, there is only one relation, so not much going on there. The latest two properties are the repositories. Entity Framework knows that these should be filled with the correct entities.

Now that we have the entities and the database configured, it’s time to set up our first migration. A migration is a change to the database. When you add a migration, Entity Framework compares the database with your current entity configuration and creates a new migration. This new migration can then be pushed to the database.

First, we have to open the package manager console.

ShortUrl_PackageConsole

Make sure the default project is “PSC.Shorturl.Web.Data”.

ShortUrl_PackageConsole_Data

Next, execute the command “enable-migrations”.

ShortUrl_PackageConsole_EnableMigration

If you have a Windows 10 Pro Insider Preview Build 11099, you can’t execute this command or other commands with Entity Framework. For updates see http://stackoverflow.com/questions/35060821/visual-studio-2015-entity-framework-and-enable-migrations-error

A migrations configuration file will be added to the Data project. From now on, it will be possible to add new migrations. Execute the following command:

add-migration "InitialCreate"

This will add an initial migration to your Data project. When you execute the following command:

update-database

The migration will actually be written to the database. If everything went right, you’ll now see the created (but empty) tables in the newly created database.

Next step is the implementation on business layer.

Throw vs Throw e

Some people asked me the different between those two following code:

Code 1

try
{
    ...
}
catch (Exception ex)
{
   throw ex;
}

Code 2

try
{
    ...
}
catch (Exception ex)
{
    throw;
}

I don't think there is ever a good reason to write catch (Exception e) { throw e; }. This loses the original stacktrace. When you use throw; the original stacktrace is preserved. This is good because it means that the cause of the error is easier to find.

Beware of the stopwatch

In my previous post I showed how to measure with stopwatch an execution time for a method. There are several mechanisms, I will explain 3 of them and point out their strengths and weaknesses.

DateTime.UtcNow

DateTime begin = DateTime.UtcNow;

...

DateTime end = DateTime.UtcNow;
Console.WriteLine("Measured time: " + (end-begin).TotalMilliseconds + 
                  " ms.");

This is the fastest mechanism because under the hood it only reads a counter from memory (the code above takes only 76 nanoseconds to execute on my machine). However the resolution is not so great: only 10 milliseconds on recent version of Windows. If you want to measure a piece of code that takes shorter to execute, you will have to execute it e.g. 1000 times and measure how long this takes, then divide the result by 1000.

Another disadvantage is that this is not reliable if the system-time changes. This should be a very rare situation, but could for instance happen through synchronization with a time server.

Stopwatch

Stopwatch watch = new Stopwatch();
watch.Start();

...

watch.Stop();
Console.WriteLine("Measured time: " + watch.Elapsed.TotalMilliseconds + 
                  " ms.");

This mechanism is a bit slower than the previous one (10 times slower on my machine) so for short intervals this may have an impact on the result. However there are some serious issues:

  • This can be unreliable on a PC with multiple processors. Due to a bug in the BIOS, Start() and Stop() must be executed on the same processor to get a correct result.
  • This is unreliable on processors that do not have a constant clock speed (most processors can reduce the clock speed to conserve energy). This is explained in detail here.

I suspect that you can get a reliable result if you run it on a single-processor machine and disable any power-saving options in the BIOS. I haven’t tested this though.

On the upside, it has the hightest possible resolution (which depends on the hardware it runs on).

Process.TotalProcessorTime

TimeSpan begin = Process.GetCurrentProcess().TotalProcessorTime;

...

TimeSpan end = Process.GetCurrentProcess().TotalProcessorTime;
Console.WriteLine("Measured time: " + (end - begin).TotalMilliseconds + 
                  " ms.");

This mechanism is different from the previous ones because it does not measure how much time has passed, but it measures how long your process has kept the CPU busy. This is great for performance measurements:

  • The timings are not distorted by other processes that consume a lot of CPU.
  • You can measure the impact that your code has on the overall performance of the system. On laptops, this also gives an indication towards the battery-power that is consumed by your process. This can be important for applications that run for a long time (such as services and other background tasks).

To interpret the measured time correctly, you should realize that time that is spent while your code is waiting (e.g. in a Sleep) will not be counted. On the other hand, if your process is keeping multiple processors busy, the time of each processor will be added (if a dual-core processor is kept 100% busy, the ‘TotalProcessorTime’ will increment with 2 each second!).

Note that this mechanism has the worst performance: the code above takes 19264 nanoseconds on my PC. This is 250 times slower than using DateTime.UtcNow!

So there is not one-size-fits-all solution to measure a time interval. Personally, if I want to measure how long a piece of code takes to execute, I run it in a loop (e.g. one million times) and measure it using DateTime.UtcNow.

C# Faster way to truncate a string

Very often I found this problem and now I got a solution!

I’ve compared some methods and I was decided which one. But I verified time (if you want to know how, read this post) of them and the final solutions are:

static string TruncateLongString(string str, int maxLength)
{
    return str.Substring(0, Math.Min(str.Length, maxLength));
}

or

string TruncateString(string str, int maxLength)
{
    return new string(str.Take(maxLength).ToArray());
}

The best solution than even is the second one!

TruncateString

Calculate the execution time of a method

I found a simple code to know the execution time of a method. First of all you have to import the following namespace:

using System.Diagnostics;

Then you use Stopwatch to know the execution time.

Stopwatch sw = Stopwatch.StartNew();
DoSomeWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

 

Happy coding!

String to Hex - Hex to String Convert

You can convert a string to hex or vice-versa with this methods. Example for real world; You want set / get some data from URL, but if your data has some special chars (like ^$ %) it'll be problem... In this case, you can use this methods and convert your data to hex.

public string ConvertStringToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}",
               (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}

public string ConvertHexToString(string HexValue)
{
    string StrValue = "";
    while (HexValue.Length > 0)
    {
        StrValue += System.Convert.ToChar(System.Convert.ToUInt32(
                        HexValue.Substring(0, 2), 16)).ToString();
        HexValue = HexValue.Substring(2, HexValue.Length - 2);
    }
    return StrValue;
}

 

Happy coding!

Regular expression for UK postcode

I'm looking for an answer to my regular expresssion problem in c#. I'm looking for a match on a specific postcode format and have run into problems. Here you can find my solution with the regex pattern.

C#

public bool IsPostCode (string postcode)
{
    return (
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][A-HJKS-UWa-hjks-uw][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][A-Za-z][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z{2}$)") ||
        Regex.IsMatch(postcode, "(^[Gg][Ii][Rr][]*0[Aa][Aa]$)")
        );
}

Visual Basic

Public Function IsPostCode(postcode As String) As Boolean
    Return (Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][A-HJKS-UWa-hjks-uw][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][A-Za-z][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[Gg][Ii][Rr][]*0[Aa][Aa]$)"))
End Function

Happy coding!

ChakraCore GitHub repository is now open

In a December 2015 talk at JSConf US, we announced that we would be open-sourcing the key components of the Chakra JavaScript engine that powers Microsoft Edge. Today, we are excited to share with you that we’ve just made the sources for ChakraCore available under the MIT License at the ChakraCore GitHub repository. Going forward, we’ll be developing the key components of Chakra in the open.

The ChakraCore repository provides a fully supported and open-source standalone JavaScript engine, with the same characteristics as the Microsoft Edge’s Chakra engine, to embed in projects, innovate on top of and contribute back to. We will be accepting community contributions and input to ChakraCore. Once the changes from any pull request have been vetted, our goal is to ensure that all changes find their way to be shipped as a part of the JavaScript engine powering Microsoft Edge and the Universal Windows Platform on Windows 10.

chakracore-1024x743

We are also publishing a roadmap for ChakraCore on our GitHub repository. With today’s release, you can build ChakraCore on Windows 7 SP1 or above with Visual Studio 2013 or 2015 with C++ support installed. In the future, we are committed to bringing it to other platforms, starting with Linux, and will keep the roadmap updated with details and status updates as we make progress. As a first step towards this goal, we have cleanly separated out Chakra’s JIT compiler, producing a build configuration that builds just the interpreter and runtime. This smaller build target is what we will initially enable cross platform porting. We also invite developers to help us in the pursuit either by letting us know which other platforms they’d like to see ChakraCore supported on, or even by helping port it to the platform of their choice.

In addition to cross platform support, some of the other  milestones on our roadmap include submitting a pull request to Node.js mainline to enable it to run with ChakraCore, continuing to make progress on JavaScript language innovation and standards, and improving the diagnostics support for ChakraCore. This includes advancing support for ECMAScript 2015 (aka ES6) and future ECMAScript proposals and making progress on Time Travel Debugging, which enables travelling back in time and across callbacks when debugging your app’s JavaScript code.

We look forward to seeing contributions from developers across the world and are eager to see what apps and solutions are built with this technology. Of course, we’d love to know where and how you use it, so keep sending us your feedback! You can reach us on Twitter at @ChakraCore or visit ChakraCore’s GitHub repo and leave us a note by opening an issue.

It’s an exciting day for the JavaScript community and everyone who’s been involved in this effort so far. We believe that developing in the open will allow the team to collaborate even more deeply with more developers around the world, resulting in better products for everyone.

OWIN and Facebook: the developers of this app have not set up this app properly for Facebook Login?

Facebook-error

Did you received this error when you try to login in your Owin app with Facebook?

App Not Set Up: This app is still in development mode, and you don't have access to it. Switch to a registered test user or ask an app admin for permissions.

Solution

  1. Go to https://developers.facebook.com/
  2. Click on the My Apps menu on the top bar and select your appFacebook-DeveloperThe circle next to your app name is not fully green. When you hover mouse on it, you'll see a popup saying, "Not available to all users because your app is not live." So next, you've to make it publicly available. Facebook-Developer_Dashboard
  3. Click on Setting at left panel Facebook-Developer_Settings
  4. In Basic tab add your "Contact Email" (a valid email address - I've added the one which I'm using with developers.facebook.com) and make "Save changes".
  5. Next click "Status & Review" at left panel
  6. Look for this, Do you want to make this app and all its live features available to the general public? and Turn ON the switch next to this. Facebook_Developer_Status_Review
  7. Confirm the question “Are you sure you want to make your app public? It will become available to everyone.”
  8. That's it! - App is now publicly available. See the fully green circle next to the app name.Facebook-Developer_AppPublish

Happy coding!

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  November 2017  >>
MonTueWedThuFriSatSun
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Month List