Entity Framework: Database first or code first? Some non-conceptual, very practical differences in real life scenarios

In the last years, Microsoft has promoted Code First as a very comfortable way to make your web (or even client-server) application communicate with your database (I am not talking only about Sql Server. I have had good experience of Entity Framework with Oracle databases as well).

Code First, in contrast with Database first.

Database first is how it has always worked in the IT world:

  1. first you create a DB
  2. then you create objects in your application that are a representation of your DB, and modify the DB contents through the objects.

Code First works the other way around:

  1. first you create (business?) classes in your application
  2. then Entity framework creates the DB tables to hold those objects and keep track of the DB modifications.

There is a third approach (Model First), but I have never really given it a chance because the other two were really sufficient for what I do.

What is better? the Practical Approach

Let us see how the DB-classes link is created in Database First and how this changes in Code First.

The problem:

I am a tie salesperson. I have two entities that are linked:

  1. ties
  2. racks

A tie can be linked to one rack. Racks can hold many ties.

Managing Related Tables in Entity Framework Database First

These are my Racks

CREATE TABLE [dbo].[Rack] (
[Id] INT NOT NULL IDENTITY,
[RackPosition] NVARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

These are my Ties (linked to my Racks via the RackId, that is a foreign key)

CREATE TABLE [dbo].[Tie] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TieSerial] INT NULL,
[RackId] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

ALTER TABLE [dbo].[Tie] WITH CHECK ADD CONSTRAINT [FK_Tie_Rack] FOREIGN KEY([RackId])
REFERENCES [dbo].[Rack] ([Id])
GO

These are the tables as you see them in Sql Management Studio:

Image of the two DB tables

The two tables created in the DB

In order to create the classes out of this Database, in Visual Studio we:

  1. Add or update the entity framework package to our web project (why not via NuGet, and why not 6.1, at the beginning of November 2014?)
  2. Add the ADO.NET Entity object to our project (we choose the option “EF Designer from DB”)
  3. We specify the connection string and finally import the DB objects

In Sql Management studio, we add some data to the Rack table, so that – when we create new ties – they can be hung on something!

Racks in the Rack table, Database first

Let us add some racks

Database first: choose what tables you want to import

DB Object to import in database first

We build the solution. At the end, the EF scripts create these class files we take good care of, because we will reuse them in Code First approach:

namespace DatabaseFirst
{
using System;
using System.Collections.Generic;

public partial class Tie
{
public int Id { get; set; }
public Nullable<int> TieSerial { get; set; }
public int RackId { get; set; }

public virtual Rack Rack { get; set; }
}
}

and

namespace DatabaseFirst
{
using System;
using System.Collections.Generic;

public partial class Rack
{
public Rack()
{
this.Ties = new HashSet<Tie>();
}

public int Id { get; set; }
public string RackPosition { get; set; }

public virtual ICollection<Tie> Ties { get; set; }
}
}

Please note: since the foreign key is on the Tie, this means a Tie has a Rack. A Rack has multiple Ties (thus, the ICollection of Ties) in the Rack object

Now, let us see what happens when we create an MVC controller and “scaffold” views

Let us create the views to edit these objects

MVC scaffolding of Database first objects

Below, the code we get for the Ties Controller. Note the bold statements: the scaffolding templates have recognized that, when we create or show a Tie, we also create or show the Rack it is bound to.

Note also that the templates makes use of the RackId field to create and modify the link between the Tie and the Rack.

public class TiesController : Controller
{
private DatabaseFirstDBEntities db = new DatabaseFirstDBEntities();

// GET: Ties
public ActionResult Index()
{
var ties = db.Ties.Include(t => t.Rack);
return View(ties.ToList());
}

// GET: Ties/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tie tie = db.Ties.Find(id);
if (tie == null)
{
return HttpNotFound();
}
return View(tie);
}

// GET: Ties/Create
public ActionResult Create()
{
ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”);
return View();
}

// POST: Ties/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = “Id,TieSerial,RackId”)] Tie tie)
{
if (ModelState.IsValid)
{
db.Ties.Add(tie);
db.SaveChanges();
return RedirectToAction(“Index”);
}

ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”, tie.RackId);
return View(tie);
}

// GET: Ties/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tie tie = db.Ties.Find(id);
if (tie == null)
{
return HttpNotFound();
}
ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”, tie.RackId);
return View(tie);
}

// POST: Ties/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = “Id,TieSerial,RackId”)] Tie tie)
{
if (ModelState.IsValid)
{
db.Entry(tie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction(“Index”);
}
ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”, tie.RackId);
return View(tie);
}

// GET: Ties/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tie tie = db.Ties.Find(id);
if (tie == null)
{
return HttpNotFound();
}
return View(tie);
}

// POST: Ties/Delete/5
[HttpPost, ActionName(“Delete”)]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Tie tie = db.Ties.Find(id);
db.Ties.Remove(tie);
db.SaveChanges();
return RedirectToAction(“Index”);
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}

The scaffolding creates not only the controller, but also the views.

This is the Create view (you will notice the creation of a dropdown list that allows us to choose the rack the tie is hung on)

DB First: creation of a new record

Creation of a new record with Entity Framework DB first

And last the index page, which shows what we just created

Tie Table in database first

The ties in our table

Noteworthy:

When the model is sent from the view to the controller, the rack object that is linked to the tie is null (see the breakpoint screenshot). However, the RackId key is not. This allows the DB to keep the link between the new tie and the chosen rack.

model of tie table entry

screenshot of the tie model

Managing Related Tables in Entity Framework Code First

To test how all of this works in the “Code First” world, I will do so:

Create a new Visual Studio project (web application, MVC)

  1. Upgrade EF to 6.1
  2. Prepare a new DB, called CodeFirst
  3. Create model classes from the same classes that were generated automatically by EF in Database First
  4. Add to the project an “Entity framework Code First” ADO.net object. This doesn’t do a lot: basically, it creates a new connection string for you [that you will have to change to make it point to your real DB].
  5. The ADO.net object also adds a DbContext class where you have to specify what classes will be written to the DB (this is another difference from Database First: naturally, Database first asks you where to read data from and what data it should read. Code First does not ask where it should write data and what it should write. You have to write additional code for that. But it’s not a lot.)

This is how the DbContext class looks like after our intervention. In bold, the code we added.

public class CodeFirstModel : DbContext
{
// Your context has been configured to use a ‘CodeFirstModel’ connection string from your application’s
// configuration file (App.config or Web.config). By default, this connection string targets the
// ‘CodeFirst.CodeFirstModel’ database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the ‘CodeFirstModel’
// connection string in the application configuration file.
public CodeFirstModel()
: base(“name=DefaultConnection”)
{
}

// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.

// public virtual DbSet<MyEntity> MyEntities { get; set; }

public virtual DbSet<Tie> Ties { get; set; }
public virtual DbSet<Rack> Racks { get; set; }
}

Now, we ask the scaffolding engine to generate the controller exactly as we did with Database first

Code first in Entity framework: code creation

Code First Controller creation

The created controller is exactly like that of the Database first controller.

public class TiesController : Controller

{
private CodeFirstModel db = new CodeFirstModel();

// GET: Ties
public ActionResult Index()
{
var ties = db.Ties.Include(t => t.Rack);
return View(ties.ToList());
}

// GET: Ties/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tie tie = db.Ties.Find(id);
if (tie == null)
{
return HttpNotFound();
}
return View(tie);
}

// GET: Ties/Create
public ActionResult Create()
{
ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”);
return View();
}

// POST: Ties/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = “Id,TieSerial,RackId”)] Tie tie)
{
if (ModelState.IsValid)
{
db.Ties.Add(tie);
db.SaveChanges();
return RedirectToAction(“Index”);
}

ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”, tie.RackId);
return View(tie);
}

// GET: Ties/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tie tie = db.Ties.Find(id);
if (tie == null)
{
return HttpNotFound();
}
ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”, tie.RackId);
return View(tie);
}

// POST: Ties/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = “Id,TieSerial,RackId”)] Tie tie)
{
if (ModelState.IsValid)
{
db.Entry(tie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction(“Index”);
}
ViewBag.RackId = new SelectList(db.Racks, “Id”, “RackPosition”, tie.RackId);
return View(tie);
}

// GET: Ties/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tie tie = db.Ties.Find(id);
if (tie == null)
{
return HttpNotFound();
}
return View(tie);
}

// POST: Ties/Delete/5
[HttpPost, ActionName(“Delete”)]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Tie tie = db.Ties.Find(id);
db.Ties.Remove(tie);
db.SaveChanges();
return RedirectToAction(“Index”);
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}

The database is not created, yet.

To create it, either you enable Migrations (in Package console), or – more simply – you launch the application and, via the automatically generated views, create a DB entry that does not depend on other objects (you might as well seed some objects in the database via code, but we want to keep this example as simple as possible),

So, we create new Racks with a Racks controller (we do not start creating Ties because you cannot have a Tie without a Rack). The DB is automatically created. After we create some racks, we can add ties to them.

filling db items in code first

Create racks in Code first

Db created by code first approach

Codefirst database

How does the “automatic” DB look like? Well, it does look identical to the DB first approach: entity framework has indeed created two tables (with a plural name, but there is an option to specify it should remain singular) and the foreign keys.

Now we create our Ties

Tie table creation

We create Ties in CodeFirst now

We have obtained exactly the same result as with Database First.

Bottom line: what is better?

Rarely as in this occasion have I felt entitled to say: it’s the same, it depends on your inclinations and what you have at hand.

Database First is better if you have large databases you need your code to mirror (for smaller DBs, there is the opportunity to do Codefirst importing a part of the DB and creating the rest via .net classes)

Code First is better if you have an empty DB and don’t want to spend too much time switching between two different environments (the code IDE and the DB IDE).

With Code First, you have to learn some new attributes that you will use in your code to specify DB-related attributes as: a certain column has an index, a certain column should not go to the DB at all, and so on.

What do I prefer?

Lately I have gone with Code First because I have always been repaid by investments in technologies that automate certain processes even if at the beginning they seem to confront problems in a simplistic way.

Usually, these technologies improve and take away a lot of programming hassles. Take ORMs: how many developers would have bet they would almost totally replace field-level programming one day? Code First  gives you a more centralized view of your application, with potentially fewer bug to take care of in the future. That did the trick for me.

C# 5 polymorphism notes: interface implementations at subclass level

When we want to show how polymorphism works, we often use the superclass -> subclass example and verify how overridden methods of the subclass are dynamically invoked when the subclass is created using the superclass’s type (in this fashion: SuperClassType x = new SubClassType() )

Here I would like to show something a bit different: how dynamic invocation of methods works when we create objects using the type of an interface they implement, and what changes if the subclasses inherit from a superclass and implement the interface itself.

The interface and objects we’ll use are very simple.

We have an interface called IAreaOrVolume, which contains a “blueprint” method AreaOrVolumeSize.

We have a “Quad” class that implements this interface.

Quad gives back the Area by multiplying its own width by its own height.

Then, we have a PossibleSquare that subclasses Quad. We call it “PossibleSquare” because we will see that, given the inheritance mechanisms, at times it is a Square but works as a Quad.

We have a PossibleCube that subclasses PossibleSquare. We call it “PossibleCube” because it is a Cube BUT its volume is at times (we will see exactly when) calculated as a Square’s or even any Quad’s area. Probably the idea that a “Cube” is a subclass of a “Square” is logically flawed, as a Square is a “slice” of a Cube, but for the time let us forget about the Aristotelic Ideas and let us see just what they mean in C#.

All objects have a constructor that accepts width, height and depth. Even if a Square does not have a height different from its width, we pass the constructor a width different from the height to show how unexpected results can stem from different implementations of inheritance.

In this first example, the “AreaOrVolumeSize” method is declared as “virtual” in the superclass “Quad” and overridden in the subclasses. See, in bold, the modifiers “virtual” and “override”.

namespace TestInheritanceWithInterfaces
{

interface IAreaOrVolume
{
double AreaOrVolumeSize();
//whatever object implements this interface will have to define its own AreaOrVolumeSize metod
}

class Quad : IAreaOrVolume
{
protected double _width;
protected double _height;
protected double _depth;

public Quad(double width, double height, double depth)
{
_width = width;
_height = height;
_depth = depth;

}

public virtual double AreaOrVolumeSize() // virtual means: go on, you can override me
{
return _width * _height * 1;
// this is a Quad. In calculating “Area or Volume”, we disregard the depth of the object, as a Quad has an area, not a volume
}

}

class PossibleSquare : Quad
{
public PossibleSquare(double width, double height, double depth) : base(width, height, depth) { }

public override double AreaOrVolumeSize()
{
return _width * _width * 1;
// this is a Square. In calculating “Area or Volume”, we disregard the depth of the object,
// as a Square has an area, not a volume
// we also disregard the height as it is equal to the width
}
}

class PossibleCube : PossibleSquare
{
public PossibleCube(double width, double height, double depth) : base(width, height, depth) { }

public override double AreaOrVolumeSize()
{
return _width * _width * _width;
// this is a Cube.
// In calculating the volume, we disregard depth and height as they are both equal to the width
}
}

class Program
{
static void Main(string[] args)
{
IAreaOrVolume thisShape;
// typing our variable with the interface implemented by classes and subclasses allows
// polymorphism

thisShape = new Quad(5,6,1);
Debug.WriteLine(“Shape’s area or volume: {0}”,thisShape.AreaOrVolumeSize());

thisShape = new PossibleSquare(5,6,1);
Debug.WriteLine(“Shape’s area or volume: {0}”, thisShape.AreaOrVolumeSize());

thisShape = new PossibleCube (5,6,2);
Debug.WriteLine(“Shape’s area or volume: {0}”, thisShape.AreaOrVolumeSize());
}

}

}

The results are what we expected:

Quad’s area or volume: 30
Square’s area or volume: 25 (height is ignored in the overridden method; the area is a Square’s area = width squared)
Cubes’s area or volume: 125 (height is ignored in the overridden method; volume is the cube’s volume = width to the power of three)

What happens, instead, if we declare the AreaOrVolumeSize as “new” methods, which do not inherit from their superclass?

In this following example, the AreaOrVolumeSize method is not overridden, but marked as “new” suggesting that we want to hide the superclass’s method.

namespace TestInheritanceWithInterfaces
{

interface IAreaOrVolume
{
double AreaOrVolumeSize();
//whatever object implements this interface will have to define its own AreaOrVolumeSize metod
}

class Quad : IAreaOrVolume
{
protected double _width;
protected double _height;
protected double _depth;

public Quad(double width, double height, double depth)
{
_width = width;
_height = height;
_depth = depth;

}

public double AreaOrVolumeSize()
{
return _width * _height * 1;
// this is a Quad. We disregard the depth of the object, as a Quad has an area, not a volume
}

}

class PossibleSquare : Quad
{
public PossibleSquare(double width, double height, double depth) : base(width, height, depth) { }

public new double AreaOrVolumeSize() // new hides the superclass’s implementation
{
return _width * _width * 1;
// this is a Square. We disregard the depth of the object,
// as a Square has an area, not a volume
// we also disregard the height as it is equal to the width
}
}

class PossibleCube : PossibleSquare
{
public PossibleCube(double width, double height, double depth) : base(width, height, depth) { }

public new double AreaOrVolumeSize()
{
return _width * _width * _width;
// this is a Cube.
// we disregard depth and height as they are both equal to the width
}
}

class Program
{
static void Main(string[] args)
{
IAreaOrVolume thisShape;
// typing our variable with the interface implemented by classes and subclasses allows
// polymorphism

thisShape = new Quad(5,6,1);
Debug.WriteLine(“Quad’s area or volume: {0}”,thisShape.AreaOrVolumeSize());

thisShape = new PossibleSquare(5,6,1);
Debug.WriteLine(“Square’s area or volume: {0}”, thisShape.AreaOrVolumeSize());

thisShape = new PossibleCube (5,6,2);
Debug.WriteLine(“Cubes’s area or volume: {0}”, thisShape.AreaOrVolumeSize());
}
}
}

The result is what we expected, and a bit funny:

Quad’s area or volume: 30
Square’s area or volume: 30
Cubes’s area or volume: 30

What happened here is: since we declared the AreaOrVolumeSize as new in the subclasses, C# supposes we want to break the polymorphism mechanism and invoke the method of the superclass, not the “new” implementation in the subclass.

There is another possibility, though: if our subclasses implement the interface along with inheriting from the superclass, the runtime behavior is again that of invoking the specific class’s implementation, not the superclass’s.

In the following code, our subclasses (PossibleSquare and PossibleCube) inherit from Quad and they hide its AreaOrVolumeSize method, but they also implement the interface directly. In this way, even if they have hidden the superclass’s method, .Net knows that it is their method implementation it has to call, not the superclass’s:

namespace TestInheritanceWithInterfaces

{

interface IAreaOrVolume
{
double AreaOrVolumeSize();
//whatever object implements this interface will have to define its own AreaOrVolumeSize metod
}

class Quad : IAreaOrVolume
{
protected double _width;
protected double _height;
protected double _depth;

public Quad(double width, double height, double depth)
{
_width = width;
_height = height;
_depth = depth;

}

public double AreaOrVolumeSize()
{
return _width * _height * 1;
// this is a Quad. We disregard the depth of the object, as a Quad has an area, not a volume
}

}

class PossibleSquare : Quad, IAreaOrVolume // implementing directly IAreaOrVolume
{
public PossibleSquare(double width, double height, double depth) : base(width, height, depth) { }

public new double AreaOrVolumeSize()
{
return _width * _width * 1;
// this is a Square. We disregard the depth of the object,
// as a Square has an area, not a volume
// we also disregard the height as it is equal to the width
}
}

class PossibleCube : PossibleSquare, IAreaOrVolume // implementing directly IAreaOrVolume
{
public PossibleCube(double width, double height, double depth) : base(width, height, depth) { }

public new double AreaOrVolumeSize()
{
return _width * _width * _width;
// this is a Cube.
// we disregard depth and height as they are both equal to the width
}
}

class Program
{
static void Main(string[] args)
{
IAreaOrVolume thisShape;
// typing our variable with the interface implemented by classes and subclasses allows
// polymorphism

thisShape = new Quad(5,6,1);
Debug.WriteLine(“Quad’s area or volume: {0}”,thisShape.AreaOrVolumeSize());

thisShape = new PossibleSquare(5,6,1);
Debug.WriteLine(“Square’s area or volume: {0}”, thisShape.AreaOrVolumeSize());

thisShape = new PossibleCube (5,6,2);
Debug.WriteLine(“Cubes’s area or volume: {0}”, thisShape.AreaOrVolumeSize());
}
}
}

The result?

This time, more logic:

Quad’s area or volume: 30
Square’s area or volume: 25
Cubes’s area or volume: 125

Alternatives:

Below, we declare PossibleCube as a subclass of PossibleSquare, but do not specify it implements IAreaOrVolume.

class PossibleCube : PossibleSquare // NOT implementing directly IAreaOrVolume

Result?

Quad’s area or volume: 30
Square’s area or volume: 25 (its own implementation)
Cubes’s area or volume: 25 (again, the superclass’s implementation)

Here below, instead, it is PossibleSquare that hides the method’s implementation, and does not implement the interface directly

class PossibleSquare : Quad // NOT implementing directly IAreaOrVolume

class PossibleCube : PossibleSquare, IAreaOrVolume // again implementing directly IAreaOrVolume

The obvious result:

Quad’s area or volume: 30
Square’s area or volume: 30 (again, the superclass’s implementation)
Cubes’s area or volume: 125 (its own implementation)

Static IP addresses for Azure websites that are not hosted as “cloud services” or “VM”s: still impossible for outbound, but workarounds possible

I hope this article is not valid for long and that static IPs will also soon also applicable for Azure websites. At this moment (October 2014), this is not the case.

Microsoft announced at the end of July that you can finally have reserved IPs for VMs and cloud services. Cloud services CAN host websites (the “web” role) but they’re not as easy to deploy as Azure website services (which are elementary).

The details of the procedure to obtain the static IP (for inbound AND outbound traffic) are in this MSDN article here.

The procedure is not very friendly yet: you have to use powershell or Azure’s API. I haven’t seen a graphic interface yet. Moreover, static IPs can – today – only be assigned to newly deployed stuff, not to already-deployed services.

What happens if you still have an Azure “website”, that is the most simple (and agile) way to deploy your own website to the Azure cloud?

Inbound traffic

You CAN have an static IP address for inbound traffic. Here, in an MSDN blog entry, Benjamin Perkins shows how to do it with the help of SSL certificates.

Outbound traffic: there’s the rub

Why would you want your outbound traffic IP to be static? Because there are cases in which your website, in the background, has to call web services which only accept calls from whitelisted IPs. When is this the case?
– financial services (for instance: online payment)
– other paid web services

Should we give up Azure if we need outbound static IP? Not really. There are two ways to overcome the issue of outbound traffic not being static in Azure websites.

1. Azure websites’s IP addresses are not totally dynamic. There IS a range of IPs that your outbound traffic can use. The list is here. If your remote web server needs to know what IP address you’re going to use to make the calls, you can give them the Azure datacenter IP ranges.

What is the problem with this approach? the list is long, whereas web service providers may accept only a few IP addresses.

In October 2014, the West Europe Data Center IP list is long tens of lines. Chances are your web service provider gives you… say ten IPs you can communicate them?

2. You use a static-IP proxy for your websites calls. I have tested this British service called Quotaguard, that I pay for and with whom I have no affiliation whatsoever. It works.

What do they do? they provide you with a proxy server that does have two static IPs you can communicate to your provider as your “whitelisted” IPs. Your Azure traffic that needs whitelisting can pass via Quotaguard.

They have a lot of implementation examples. For .NET, they focus on web forms and http requests that have a proxy property. In case you are using (as it was my case) objects that have no “proxy” porperties, you can create a Proxy object yourself and link it to the .NET framework object “WebRequest”, like this:

using System.Net;

var proxy = new WebProxy(“http://quotaguard_THE_CODE_QUOTAGUARD_GIVES_YOU@eu-west-1-babbage.quotaguard.com:9293“); // you may want to store this URI in the application’s config page in Azure, rather than hardcoding it
            proxy.Credentials = new NetworkCredential(“YourQuotaGuardAccount”, “yourQuotaguardpassword”); // you may want to store credentials in secure config files rather than hardcoding them
            WebRequest.DefaultWebProxy = proxy; // we set the “global” proxy here
            Now you can use your whitelisted webservice call…
Another version of the same code can be found here:
Enjoy!

Opening a mobile app from a link: the Xamarin way (URL-Schemes)

Launching an app from within another app, from a mail link or from a link in a web page can be a very useful feature.

Social networks use this function a lot. However, all apps which have some “sharing” feature can benefit from it.

How to implement the URL schemes in Xamarin? We have to use two different methods for Android and iOS.

This is the task at hand:

– We have an app called superduperapp that should be opened whenever, on a user’s device, a URL as “superduperapp://my_code_is_here” is clicked by the user on their iPhone or Android phone (or: opened by another app on the same device);

– The data following the URL “protocol” (the string “my_code_is_here” in this example) is read by the app, which creates its data context based on that code.

This is one of those times in which Xamarin iOS and Xamarin Android implementations have little in common, since we’re touching the foundations of how the device operating system communicates and deals with the apps.

Xamarin for iOS URL Schemes:

As a first thing, we have to “decorate” the iOS app with the new URL scheme. We do this in the Info.plist file.

Xamarin Studio has a good editor for this file. You have to go to the “advanced tab” and add a “URL Type”. The URL scheme should contain the URL type you want to link your application to. In our case, since we would like superduperapp to be opened by URLs as “superduperapp://my_code_is_here”, our URL scheme will be “superduperapp”.

Xamarin Studio for iOS screenshot

How to edit Info.plist in Xamarin Studio

The “role” field is apparently ignored by iOS, but it’s supposed to mean:

Editor=app can read and write the type of files individuated by the URL
Viewer=can only view that file type;
None=cannot use it (I guess this option is used when an app is updated and we want to delete the file association)

As a second thing, we have to override the OpenUrl method of the Application delegate class:

public override bool OpenUrl (UIApplication application, NSUrl url,
string sourceApplication, NSObject annotation)
{
Console.WriteLine (url);
/* now store the url somewhere in the app’s context. The url is in the url NSUrl object. The data is in url.Host if the link as a scheme as superduperapp://something_interesting */
return true;
}

That’s it. If you store the url data in a persistent object, you can then use it in your ViewControllers. It is not very elegant, but it could be just sufficient to grab the code passed to the app with the “Host” property of the url, like this:

PersistantClass.CodeEntered=url.Host; //PersistantClass would be your custom class to hold data

To test, we create a web page with a link as this:

<a href=”superduperapp://my_code_is_here”>superduperapp_link</a>

which visually translates into this:

Link with custom URL schema to open our app

A link with a custom URL looks exactly as any link. In it, we might have a personal URL scheme, as superduperapp in our case

When we click on the link on the simulator, the iOS app opens (well, of course we must have installed it first). The app delegate reads the URL in the OpenUrl overridden method. Later, we display – as a test – the code extracted from the link:

this is how the code shows once we open the app via the custom URL

iPhone or iPad app done in Xamarin, opened by custom URL

Please note:

The application name does NOT have to be the same of the URL scheme. You can register your app “uncommonApp” to deal with any URL: BeautifulThings://, http:// (if you’re making a browser), whatever://

Xamarin for Android

In Android, the procedure to register an app to deal with a type of URL is (you figured that out already) completely different from that of iOS. We have to work on the AndroidManifest.xml file (contained in the /properties folder).

A typical AndroidManifest.xml file will look like a bit this (depending on the permissions and features the app needs):

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221; android:versionCode=”1″ android:versionName=”1.0″ package=”superduperapp.superduperapp”>
<uses-sdk android:minSdkVersion=”19″ android:targetSdkVersion=”19″ />
<application android:label=”superduperapp”></application>
<uses-permission android:name=”android.permission.CAMERA” />
</manifest>

Our task here is to tell the operating system that a certain activity of the superduper app will be able to deal with the links that have a URL scheme as, for instance, superduper://my_code_is_here .

In the application tag, we have to add an indication to the activity and to the associated URL type.

The activity name goes in the android:name attribute of the application tag. The URL scheme name goes in the android:scheme attribute of the data tag inside the intent-filter, inside the activity, inside the application… like so:

<application android:label=”superduperapp”>
<activity android:icon=”@drawable/Icon” android:label=”superduperapp” android:name=”superduperapp.urlentryclass”>
<intent-filter>
<action android:name=”android.intent.action.VIEW” />
<category android:name=”android.intent.category.DEFAULT” />
<category android:name=”android.intent.category.BROWSABLE” />
<data android:scheme=”superduperapp” />
</intent-filter>
</activity>
</application>

We install the app on the device (it works also on the emulator).

As we did with iOS, we open our emulator and navigate to the address that contains the link

<a href=”superduperapp://my_code_is_here”>superduperapp_link</a>

Link in android device

Link to open android app from custom link

When we click, our app opens on the Activity we indicated on the AndroidManifest.xml file (superduperapp.urlentryclass).

The class reads the code that is after the superduperapp:// “protocol” string in the Intent object, with this code:

[Activity (Label = “urlentryclass”)]
public class urlentryclass : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);

Intent outsideIntent = Intent;
AlertDialog.Builder CodeAD = new AlertDialog.Builder (this);

CodeAD.SetTitle (“Superduperapp”);
CodeAD.SetMessage (“Code: ” + Intent.Data.EncodedAuthority);
CodeAD.Show ();
}
}

This is the result:

this is the screenshot of the Android app opened by the custom URL scheme

the Android app opened by our custom URL

Please note four things:

1 – in Xamarin Android, it is better to keep solution, project and class name in lowercase. I have had lots of issues when this wasn’t the case and I’m not entirely sure I was typing the names wrong. I think something may work incorrectly when you use class names LiKe_tHiS.

2 – the application name does NOT have to be the same of the URL scheme. You can register your app “uncommonApp” to deal with any URL: BeautifulThings://, http:// (if you’re making a browser), whatever://

3 – you don’t have to run the app to register the new association. Installation is enough.

4 – the URL association won’t work if you type the URL in a browser. It has to be a link in a web page or in an email.

A simple redirection mechanism using MVC 5 [and IIS8], including “Legacy” URLs

For some hours, I have been looking for good ideas on how to manage redirections in MVC without necessarily configuring IIS (which is not always available to the programmer, unfortunately).

However, very few of the walkthroughs found on the web take into account dealing with “legacy” URLs; primarily, those who have the “.html” extension.

How do I, in MVC, redirect a URL like “oldfolder/oldfilename.html” to a new MVC URL as “/newfolder/beautifulpeople” ?

The answer is not the simplest, because MVC doesn’t manage all that is asked to it by the browser:

A client request is handled, summarily, like this:

– MVC manages the “MVC” routes (as “/area/controller/action”)

– IIS8 manages the static files, which *presumably* don’t need MVC’s intervention.

If we want to manage all the redirections via MVC, we have to tell MVC that it has to take care of BOTH MVC routes AND static files (unless, of course, the latter don’t exist as such. If the static file exists, let IIS transfer it to the user).

The following is a very basic mechanism which uses MVC and a DB table to store redirections. It can be extended to use caching and OR XML files to be faster. It is also true that redirections should be an exception rather than the norm.

The idea is:

– We create a DB table holding old URLs and corresponding new URLs, along with the code we want to use for the redirection (301 is permanent) and an “active” flag.

– We create a set of MVC “catchall” routes (in the RouteConfig file) which will prevent 404 (“not found”) and will call a new controller that does the “redirection” job

– This new controller checks if the DB has an entry equal to the originating URL. If there is, it redirects  the flow to the new URL (permanenty or temporarily, depending on what we wrote in the DB entry); otherwise, it generates a custom 404 page.

– We tell MVC (in web.config) that it has to also take care of the routes that look like files, unless (of course) they are actual static files.

RouteConfig

In our MVC application’s RouteConfig, we create, AFTER the standard routes, a set of “catchall” routes which will direct to a new controller and action (“Error”/”NotFound”) all the requests that could not be routed to an existing controller.

Like this:

//Default, Real route

routes.MapRoute(

name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional },
constraints: new { controller=”Home|Search|Account|Show|Other_Controllers|Error”} // CONSTRAINTS are VERY IMPORTANT
);

//catchAll routes to grab the URLs we want to redirect

routes.MapRoute(
name: “Redirect_OrError”,
url: “{*CatchAll1*}”,
defaults: new { controller = “Error”, action = “NotFound” }
);

routes.MapRoute(
name: “Redirect_OrError_two_levels”,
url: “{CatchAll1*}/{CatchAll2*}”,
defaults: new { controller = “Error”, action = “NotFound” }
);

routes.MapRoute(
name: “Redirect_OrError_three_levels”,
url: “{CatchAll1*}/{CatchAll2*}/{CatchAll3*}”,
defaults: new { controller = “Error”, action = “NotFound” }
);
routes.MapRoute(
name: “Redirect_OrError_four_levels”,
url: “{CatchAll1*}/{CatchAll2*}/{CatchAll3*}/{CatchAll4*}”,
defaults: new { controller = “Error”, action = “NotFound” }
);

Attention: The “default, real” MapRoute method must be called with Constraints (Controller=”Home|…. all the controllers you have). If you don’t do so, MVC will not fall through to our “catchall” controllers. It will stop at the default and will give a “404”.

The “Error” Controller

The “Error” Controller does three things:

1. It checks if the request is actually found in the Redirections table as a URL we consider as “old”

2. If it is there, we redirect to the new URL (if 301, “RedirectPermanent”; if others, “Redirect”)

3. If it doesn’t, it generates a custom error page with a 404 status code

public class ErrorController:Controller
{

[HttpGet]
public ActionResult NotFound()
{

string UrlToTest = Request.Url.AbsolutePath.Trim(‘/’);
Redirections redirect = RedirectManager.GetRedirectFromDB(UrlToTest);
if (redirect != null)
{
if (redirect.RedirectType==”301″)
{
return RedirectPermanent(redirect.NewURL);
}
else
{
return Redirect(redirect.NewURL);
}
}
Response.StatusCode = 404;
ViewBag.UrlToTest = UrlToTest;
return View();
}

public ErrorController()
{

}

}

Now what is the RedirectManager we just found in the code?

Very simply, it is a class which contains some helper classes and methods that allow us to examine the DB and look for the URL we want to redirect from.

public class RedirectManager

{

public RedirectManager()

{

}

public class RedirectionsDTO
{

public int Id { get; set; }
public string OldURL { get; set; }
public string NewURL { get; set; }
public string RedirectType { get; set; }
public Nullable<bool> Active { get; set; }

}

public static Redirections GetRedirectFromDB(string OldUrl)
{
RedirectionsDTO redirects;
using (var db = new OurEntitiesDB()) // this is the name of your Entity Framework
{
string URLWithoutSlash = OldUrl;
if (!URLWithoutSlash.StartsWith(“/”))
{
URLWithoutSlash = “/” + URLWithoutSlash;
}

redirects = (from e in db.Redirections
where (e.Active == true && (e.OldURL == URLWithoutSlash))
select new RedirectionsDTO
{
OldURL = e.OldURL,
NewURL = e.NewURL,
RedirectType=e.RedirectType,
Active=e.Active
}).FirstOrDefault();
if (redirects != null)
{
return new Redirections { OldURL = redirects.OldURL, NewURL = redirects.NewURL, Active=redirects.Active, RedirectType=redirects.RedirectType };
}
else
{
return null;
}

}

}

}

}

How is the Redirect table created? It is created by Entity Framework Database first, based on a table maybe similar to this…

MVC redirection storage table

Table which holds redirection data

There should be an index on the OldURL column because we will include it in our queries.

The generated code could be something like this:

namespace YourPreferredNameSpace

{
using System;
using System.Collections.Generic;

public partial class Redirections
{
public int Id { get; set; }
public string OldURL { get; set; }
public string NewURL { get; set; }
public string RedirectType { get; set; }
public Nullable<bool> Active { get; set; }
}
}

Of course, you have to fill this table with the needed redirections! I suggest you create a controller and allow scaffolding templates to automatically generate the CRUD actions and views for these “Redirections” objects.

Web.Config

What we did so far does not help us if we want to redirect *.html files (or *.pdf files, for that matter). This is beacuse IIS will think that the *.html file should not be a part of an MVC route and it will look for it as a static file. To allow MVC to see the *.html URL as a possible MVC route (and redirect it, if needed), we have to allow MVC to examine all the file requests. To do so, we have three suggested paths. There are: an easy+smart way, a smart way and a semi-silly way. The easy+smart way didn’t work for me. The “smart way” did. It happens.

The easy+smart way is to patch the IIS as this article suggests: http://support.microsoft.com/kb/980368

It didn’t work for me because I had no access to IIS.

The “smart one” is suggested by Colin Farr in this old but powerful article:

http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html

he suggests that in System.webServers you add

<system.webServer>
<modules >
<remove name=”UrlRoutingModule-4.0″ />
<add name=”UrlRoutingModule-4.0″ type=”System.Web.Routing.UrlRoutingModule” preCondition=”” />

… other modules…

</module>

Now the silly solution instead:

add the runAllManagedModulesForAllRequests=”true” attribute to the “module” section. Colin Farr already explains why this is silly, so I will not.

<modules runAllManagedModulesForAllRequests=”true”>

Using Google and LinkedIn Accounts for Your .net MVC 5 Site’s Authentication: Tips and Tricks and the error externalLoginCallback?error=access_denied

Some months ago, Rick Anderson and Erik Reitan wrote a very good article in the asp.net website (http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on)  to show how the ASP.NET Identity authentication / authorization framework can leverage external authentication providers as Google, Facebook, Twitter and LinkedIn.

These providers do frequent changes to their interfaces. I am writing this post to underline a couple of tricky errors that the Google / LinkedIn authentications can present to you even if you seemingly do everything by the books.

Authentication with Google: tricks

Google can give you: “externalLoginCallback?error=access_denied” if you don’t allow your application to use certain – not so intuituive – APIs. In particular, the API that must be checked so that Google gives the green light for authentication is the Google+ API, which is not pre-authorized.

This is documented in MSDN: http://blogs.msdn.com/b/webdev/archive/2014/07/02/changes-to-google-oauth-2-0-and-updates-in-google-middleware-for-3-0-0-rc-release.aspx, however, i thought it was a good idea to replicate the same concept on this site in order to make it easier to find it with a search on the redirect URI error.

Another error one can get for the Google authentication is that the Google “project” has to have a PRODUCT_NAME (however, this is easy to spot because it is Google’s page itself to tell you where the problem lies).

All in all, these are the steps to enable the Google + authentication in MVC 5 (highly suggested to use Visual Studio 2013 Release 2 or superior)

Steps in Visual Studio

Create a new MVC project with “Individual user” authentication

From Nuget, download the Microsoft.Owin.Security.Google package

Google authentication package in NuGet

Google authentication package in NuGet

Enable https for your site (project – properties – set SSL enabled to true)

Copy the location of the SSL site (https://localhost:port_number/, for instance: https://localhost:44302/)

Steps in Google Developer Console

Go to https://console.developers.google.com/project. Click on “Create Project”.

Click on the project name, click on APIs in the left menu and select “Google+ API”. Set it to ON (default is OFF)

Screenshot of the Google+ API we have to check to authenticate users in an MVC project

The Google+ API to enable if you want external authentication to work

Click on “Credentials” – oAuth.

Set the “Authorized Javascript origins” to the localhost SSL root (https://localhost:your_port_number). Set the “authorized redirect URLs” to localhost SSL root + /signin-google: for instance, https://localhost:43202/signin-google. No slash at the end of the URL!

Once you do this step, you have a ClientID and a Secret. You will need those for the Visual Studio application.

Configuring the ClientID in Google

Configuring the ClientID in Google

In the Consent screen, choose a contact email and give the PRODUCT a name!

Google Authentication: Consent screen

Google Authentication: Consent screen

Back to Visual Studio

In the folder App_Start, there is a file Startup.Auth.cs. 

Un-comment the lines releted to the Google authentication and fill the ClientId and ClientSecret fields with those given out by Google (these below are examples, they don’t work.

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = “xyzsdusidui2uo2380r787285780457284057804.apps.googleusercontent.com”,
ClientSecret = “Uhjhkjhk189r_iGAsMZdHz”
});

Now you should be good to use Google to register and authenticate your users.

 

Authentication with LinkedIn: tricks

Rick and Erik mention this good tutorial for authentication with Yahoo and LinkedIn (+ a set of other OAuth 2.0 providers)

http://www.beabigrockstar.com/blog/introducing-the-yahoo-linkedin-oauth-security-providers-for-owin/

The LinkedIn tutorial is a bit simplified: it does not take into consideration the Redirection URI for localhost.

How to work with Localhost?

As with Google, you need to write down the httpS address of your localhost, for instance: https://localhost:44302/

Beware: for the authentication to work, the OAuth 2.0 redirection URLs must be set to https://localhost:44302/signin-linkedin (or your port of course). 

You have to set this address here:

Linkedin-no-signin-error

In case you don’t append /signin-linkedin, you’ll end up with an “invalid redirect_uri” error:

invalid-redirect-uri-linkedin

URL routing in Microsoft MVC 5 when Areas are present: potential pitfalls

The “convention over configuration” philosophy of Microsoft’s MVC engine is very useful, as it automates a lot of “wiring” among the different components of a web application.

However, when the “going gets tough”, you have be careful how to circumvent certain convention-based automations that may bring undesired results.

One very important aspect to consider is routing, which technically is not part of MVC (it is a separate component of .net, as you can also use it with web forms) but plays an incredibly important role in the functioning of MVC. Routing is the mechanism that calls a certain object (in MVC, it is usually a controller) based on the URL the user typed or clicked on.

In MVC’s views based on Razor 3, we have a very user HTML helper which creates a URL based on:

– the controller we need

– the action we need.

Its syntax is the following:

@Html.ActionLink(“link text”, “action name”, “controller name”)

When you divide the application in Areas, you have to be extra-careful, as the overload that allows you to specify the Area you need has five arguments rather than four as you might wonder (since the Area is the fourth argument.)

So, in case you need a link that should call a controller inside an Area, it should read:

@Html.ActionLink(“link text”, “action name”, “controller name”, new {Area=”Area Name”}, new {})

The last new{} parameter is in lieu of html attributes. Without that specification, the compiler will think we’re calling the four-parameter overload, which has as fourth parameter… exactly the html attributes, not the Routing object and we would be wrong.

Is that all? No. There is another consideration related to the priority that the routing mechanism uses when you register more than one route in an Area route registration class (or any registration class, for that matter.)

When you create an area, in fact, an additional route AreaRegistration subclass is created for you.

For instance: if you create an area called “Particularities”, Visual Studio will create a class with this code (could not reproduce the indentation correctly here):
using System.Web.Mvc;
namespace RMTestSite.Areas.Particularities
{
public class ParticularitiesAreaRegistration : AreaRegistration
{
public override string AreaName
{
  get
{
  return "Particularities";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
  context.MapRoute(
  "Particularities_default",
  "Particularities/{controller}/{action}/{id}",
   new { action = "Index", id = UrlParameter.Optional }
 );
}
}
}

So, if you want to point to the new Area controller from a page called by a controller that is in another Area, you would have to code:

@Html.ActionLink("Particularities","Index", "Home", new{Area="Particularities"}, new {})

The result of this link is an reference to:
http://localhost:53869/Particularities/Home, which is OK.

Now let us imagine we add another route to the Particularities Area.

For instance, let us add this route before our default route (as a rule, specialized routes should precede general routing rules):

context.MapRoute(
"Particularities_AdditionalParticularitiesdefault",
"Particularities/AdditionalParticularities/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);

What happens now if I use again my Html.ActionLink? I mean: if I use exactly again,
@Html.ActionLink("Particularities","Index", "Home", new{Area="Particularities"}, new {})

The result is different. The address becomes
http://localhost:53869/Particularities/AdditionalParticularities/Home

Why is this? Because the routing mechanism found the first (in terms of: how the code is ordered) pattern in the route series which is matched by our controller/action ActionLink request. It does not choose the “simplest” one.

How can we continue to point to the previous controller/page?

We can specify the route itself when we build our link.

We can do this very easily by using RouteLink rather than the ActionLink. Some say this is in general a preferred routing habit: you can have thusly a list of what routes should do regardless where you want to implement the controllers and you are safer (well, in this case we would have been safe.)

Following our example, our code should have been
@Html.RouteLink("Particularities!", "Particularities_default", new { controller = "home", action = "index" }, new { })

We added the route name to the link, rather than the Area name, and we know we won’t get the wrong controller.

All in all, MVC’s routing mechanism (I specify, again, that is not a part of MVC per se) is a great thing, but we never have to give for granted that it will work in the way we guess a convention should work: it is the .net framework developer’s convention, not necessarily the one we think it is.