TicketDesk 3 Dev Diary – Thoughts on Security

hunts point, the bronx, new yo... by andre dos santosIn this post, I’m brainstorming new approaches to handling security in TicketDesk 3, and reviewing the limitations of TicketDesk 2’s old approach.

Security in  TicketDesk 2:

TicketDesk 2 shipped with support for either active directory, or local security. Local security via the built-in membership providers worked reasonably well for most deployments, but the AD option has always been problematic.

Windows authentication, in conjunction with the WindowsTokenRoleProvider, works well enough for the basic question, “who are you?”, but windows authentication severely limits in the amount of information you can obtain about the user. You get the windows account name and a list of the user’s AD groups –and that’s pretty much all you get.

Some features in TD required more than that. It needed display names and email addresses, and it needed to list all users in some AD groups; information the built-in providers are incapable of obtaining.

To support these requirements, TicketDesk 2 used a complicated background processes for AD concerns. It maintains a local cache of AD data to reduce the number of queries, and moved AD query processing off of the user servicing request threads.

Even with the abstractions in System.DirectoryServices, querying AD is painfully obtuse. In addition, response times for AD queries are often measured in the tens of seconds –even in single domain environments. You can’t reasonably query AD in real-time without bringing the entire application to a standstill. The custom module alleviates these issues, but was a  complete nightmare to code and maintain.

The other significant problem has been the difficulty of extending the old system to support more features, such as custom roles and permissions. This is why TicketDesk still uses hard-coded roles with pre-defined permissions –I simply never had the time or energy to re-factor the AD side of the system.

Security technologies of the present:

I’ve played a bit with the SimpleMembership and Universal Providers, which have replaced the original SqlMembership providers. ASP.NET’s security system is still based on the same provider framework that shipped with .Net 2.0 back in 2005. Sadly, the framework is a fundamentally flawed system, and in need of a complete redesign.

In recent years, there have been two attempts to modernize the ASP.NET providers, but neither really addresses the underlying problems of the core framework itself. Both are just extensions layered on top of the original infrastructure.

Universal Providers are an evolutionary upgrade of the original SQL providers from ASP.NET 2.0. They mainly just move data access into Entity Framework, which allows them to work with any database back-end supported by EF. Otherwise, there isn’t a much of a difference between them.

SimpleMembership was created for ASP.NET WebPages, but has become the officially recommended replacement in MVC projects as well. This is the default security provider in the newer MVC project templates that come with Visual Studio 2012. As I wrote in another post though, this system has some deep design flaws of its own. You almost have to learn how to hack up a customized version of SimpleMembership just to make it useful in any real-world scenario.

The good news is that both SimpleMembership and Universal Providers include oAuth support backed by the popular DotNetOpenAuth libraries. So, while flawed and build on a shaky foundation, at least they have been modernized.

Traditional windows authentication itself has not changed in any significant way, and there have been no official replacements for the windows security providers that I know of. ASP.NET still uses the same windows provider options that shipped in .Net 2.0, all of which are spectacularly terrible.

The major action for Active Directory authentication has been with Active Directory Federation Services. This is an STS token server that exposes AD to clients that support WS-federation. The Windows Identity Foundation (WIF), originally introduced in WCF, was pulled directly into the core of the .Net framework with the 4.5 release. This provides the infrastructure ASP.NET needs to leverage federated authentication and authorization. So, if you setup federation in ASP.NET you can easily connect it to ADFS to authenticate your AD users. Best of all, ADFS can share any information stored in AD.

In Windows Azure land, you have the Access Control Service (ACS), which is also a WS-Federation token service. From ASP.NET, connecting to ACS is similar to connecting to ADFS. The real advantage of ACS is that it can act as an aggregator and proxy for any number of other external authentication sources. For example, you can connect your ACS to your domain’s ADFS service and to oAuth providers.

The new identity features in .NET 4.5 also incorporate claims based identity as a pervasive and normative feature used throughout the entire framework. You don’t have to use WS-federation in order to use claims based identities, since all identities are now claims based.

Ideas for TicketDesk 3:

For TicketDesk 3, I hope to support the following authentication options:

  • local user accounts (forms with user registration)
  • oAuth (sign-in with google, facebook, twitter, etc.)
  • Windows (AD or local system accounts)
  • WS-Federation (ADFS, Azure ACS, etc.)

My challenge is to find a way to bring all these pieces together in TicketDesk 3 in a sane way.

I want TicketDesk’s business logic to make use of claims based identity for its authorization decisions. Since claims are baked in, this seems to be the most sensible way of doing things. The key will be to map all users, regardless of how they are authenticated, to a common set of claims that TicketDesk understands. The business logic can then rely on having those claims attached to every user’s identity.

For authentication, I have little choice but to rely on existing mechanisms. I am not a crypto expert, and have no intention of rolling my own password and user verification code. But, to support multiple authentication sources, I will likely need to roll my own module to intercept user requests, and dynamically route them to the appropriate pre-built authentication mechanism as needed at runtime.

Each of the possible authentication systems will produce a ClaimsIndentity, but the structure and content of those claims varies. Some authentication generates very few usable claims, while others may contain all the claims TicketDesk could ever need. To bridge the gap, TicketDesk will need an identity transformer. This component will map incoming identities, obtained during authentication, to a TicketDesk identity with all the claims TicketDesk needs. Since some claims cannot be obtained during authentication, TicketDesk will need to obtain any missing data from the user, or an administrator, then store and manage that data locally.

As you can tell, this is all in the early conceptual stages. I’m doing a lot of experiments and research, but I’m at the point where I have a good grasp of most of the pieces that I’ll need to smash together.

I have several other projects with similar security requirements, and I’ve grown tired of approaching each new project with the question, “how much hacking will ASP.NET membership need this time?” So, no matter what I come up with, I hope to roll it into a re-usage package.

ASP.NET MVC SimpleMembership – Initilization and New Project Template Issues

The ASP.NET MVC new project templates have been upgraded in Visual Studio 2012. Among the many improvements, was the change to using SimpleMembershipProvider. Simple they may be named, but I’ve found using it to be anything but simple. There are some deep design flaws in the provider, as well as how it is used in the stock MVC project templates.

The issues start with web.config. If you have worked with asp.net in the past, the most obvious difference in new web.config files will be the lack of configuration elements related to security providers.

Old templates had something like this:

       ... stuff ...
            <add name=".... />
            <add name=".... />
            <add name=".... />
    ... stuff ...

The new templates have none of these elements. There is a default connection in web.config, called DefaultConnection, and the templates use this connection for membership as well application data by default.

So far, so simple.

If you need to change the default behavior of SimpleMembership though, where do you make those changes? For example, I don’t like the default password length requirements, so I’ve always changed that in config. You can explicitly add the SimpleMembership provider to web.config, but doing so is useless. SimpleMembership just ignores settings in web.config. If you want to change the behavior, you have to track down the entity classes SimpleMembership is using (models/AccountModels.cs in the stock templates), and manually change the attributes in code.

While modifying settings in code isn’t hard, it is a truly horrible design. Your security configuration is scattered all over your model classes, and the runtime security policy is buried deep within compiled code, instead of a centralized configuration file where your server admin can get at it. This design also eliminates the option of using config transformations during build, publish, or deployment to customize the security policy for different target environments.

If you want to change the connection used by SimpleMembership, you no longer do this through web.config either. Instead, you have to track down the code that initializes the security system, which is inconveniently located in the /Filters/InitializeSimpleMembershipAttribute.cs file. Here, you need to update the call to WebSecurity.InitializeDatabaseConnection to pass in the correct name of your connection string. Not very intuitive, but that’s not the truly weird part either…

The weird part is that initialization for SimpleMembership, in the stock project templates, is done from an ActionFilterAttribute. This attribute decorates the AccountController class, and only that class. The result is that none of the SimpleMembership system will be initialized until a real user physically visits one of your account pages; login, register, or whatever.

If you write code in a page that allows anonymous access, or in a background or start-up routine, and it tries to do something related to membership, roles, or profiles you will get bizzare behavior. You would think that the code would just fail –the providers haven’t been initialized right?

The truth is much, much worse.

If code tries to do security stuff before SimpleMembership is explicitly initialized, asp.net will initialize the default security providers automatically. Instead of the SimpleMembership provider that you expected, it will initialize a SqlMembershipProvider using a connection named “LocalSqlServer”. This stuff is configured in the machine.config file, which includes the default configuration settings for SqlMembership, and points it at the local SQLExpress instance.

So, lets say you open up your new MVC project, which you created from the VS 2012 default template. You go to the HomeController, and edit the Index action to call Membership.GetAllUsers(). That’s all. You don’t need to do anything with the users, just ask for a list of them.

Then you run your application.

What do you think happens?

If your system is setup like most, you probably have SQL express installed. So, suddenly a mysterious aspnet.mdf file shows up in your app_data folder, and gets attached to your SQLExpress instance… and this all probably happens without you noticing it. If you don’t have a SQLExpress instance, your application will hang on startup for a long while, then timeout with “The system cannot find the file specified”.

I don’t know about anyone else, but I REALLY hate when an application starts making new databases on SQL servers that it shouldn’t even know exist.

Overall, I am not impressed with SimpleMembership, nor how the stock templates implement it. The providers are prone to unexpected and unintended behavior unless you have deep knowledge about their internal workings. Customizing SimpleMembership is the opposite of simple. And for configuration, it is confusing that it plugs into a standard asp.net feature, then ignores the traditional means of configuring that feature. And to top it off, requiring basic security configuration to be handled in code is a severely deranged design choice.

TicketDesk 3 Dev Diary – EF Migrations & TD2 Upgrades – Part 3

dead-birdsIn this last installment, I’ll describe TicketDesk’s custom database initializers, which allow TicketDesk 3 to automatically choose which migration should run on startup. I’ll also confess to a major development blunder!

In my last post, I talked about creating the initial migration for new TicketDesk databases. I used the MigrateDatabaseToLatestVersion<T> initializer in global.asax.cs. This initializer works well for normal EF migration usage patterns, but TicketDesk needs initializers with a bit more spunk.

EF also ships with a feature called “automatic migrations”. I will NOT be talking about this feature here. Automatic migrations are, in my opinion, an abortion-in-progress for anything but the most trivial of applications. I advise you to read up on this feature, and then do your best to avoid it. What I will be talking about here is automatically executing a “code-based migration”.

Great primer on Automatic migrations here, and for Code-base migrations here.


A common technique for customizing database initialization is to write a custom initializer that inherits one of the standard initializers. Sadly, the MigrateDatabaseToLatestVersion initializer is ill-suited for inheritance. There are no overridable methods or extension points to plug into. Instead, I’ll roll my own initializers, implementing IDatabaseInitializer<T>, and take direct control over the migrations process. Fortunately, the EF APIs makes this pretty simple.

Initially, I built one big do-it-all initializer, but later switched to separate initializers that operate independently — in keeping with the SRP.

On Application_Start, TicketDesk will run both initializers. Here is how the process should go:

1) Legacy Initializer Runs
    1a) Check if there is a database
    1b) If a database exists, check the version number (stored in the dbo.settings table)
    1c) If version 2.0.2, run the legacy initial migration (else, do nothing)
2) Regular Initializer Runs
    2a) Run all standard migrations

While the initializers don’t need a mediator, or other coordinating object, the order in which they are invoked is relevant to achieve the desired behavior.

The trick to step 2 is that, if the DB was upgraded in step 1c, then the regular migration will think its own initial migration has already run (remember, both use the same ID and hash value). The regular initializer will still run all additional migrations added later, even if the legacy initializer did the initial migration.

The initializers themselves are rather simple. They instantiate EF’s DbMigrator, which is the code equivalent to using the Package Manager Console’s Update-Database command.

The regular initializer:
public class TicketDeskDatabaseInitializer : IDatabaseInitializer<TicketDeskContext>
    private string ConnectionName { get; set; }
    public TicketDeskDatabaseInitializer(string connectionName)
        ConnectionName = connectionName;

    public void InitializeDatabase(TicketDeskContext context)
        var config = new Configuration();
        config.TargetDatabase = new DbConnectionInfo(ConnectionName);
        var migrator = new DbMigrator(config);
        migrator.Update(); //run all migrations 
The legacy initializer:
public class LegacyDatabaseInitializer : IDatabaseInitializer<TicketDeskLegacyContext>

    private string ConnectionName { get; set; }

    public LegacyDatabaseInitializer(string connectionName)
        ConnectionName = connectionName;

    public void InitializeDatabase(TicketDeskLegacyContext context)
        //if existsing TD 2.x database, run upgrade; creates migration history table 
        if (context.Database.Exists() && IsLegacyDatabase(context))
            var upgradeConfig = new Configuration();
            upgradeConfig.TargetDatabase = new DbConnectionInfo(ConnectionName);

            //this will do nothing but add the migration history table 
            //  with the same migration ID as the standard migrator.
            var migrator = new DbMigrator(upgradeConfig);
            migrator.Update("Initial"); //run just the initial migration

    public static bool IsLegacyDatabase(TicketDeskLegacyContext context)
        // TicketDeskLegacyContext has no DbSets, directly execute select query
        var oldVersion = context.Database.SqlQuery<string>(
                  "select SettingValue from Settings where SettingName = 'Version'");
            oldVersion != null && 
            oldVersion.Count() > 0 && 

The Accidental Integration Test:

You will note that the constructor for both initializers requires an explicit connection name, which is used to set the target database for the migrator. This is the result of another oversight in how EF migrations were implemented internally –I consider it an oversight anyway.

The initialize method takes an instantiated DbContext as a parameter, but there is no way to pass that context to a DbMigrator. Instead, DbMigrator always creates a new instance of the DbContext, and it always uses the DbContext’s default constructor. So, in cases where you want to use non-default connections, you must explicitly pass that information into the DbMigrator, otherwise it will use whatever connection your DbContext’s default constructor uses.

I discovered this issue when trying unit test the legacy initializer. My unit test used a custom connection string when it instantiated the DbContext (pointing to a localdb file database in the unit test project). I would run the test, but the DB in the test project refused to change.

Eventually, I discovered that the migrator was making a new DbContext from the default constructor, which in this case was hard-coded to a default connection named “TicketDesk”. This connection string was present in my app.config file, but I had, unwisely, left it pointed at my production database server…  the real TicketDesk 2 database that my company’s IT staff uses!


The test was, indeed, migrating the crap out of my production database!

As a testament to the migrator’s effectiveness, and the similarity between the TD3 and TD2 schemas, TicketDesk 2 didn’t skip a beat. The users never knew their DB had been upgraded, and everything kept working. Later, I manually un-migrated the production database using the PM console commands, which also worked without a hitch.

Lesson learned! Again…

Planting Seeds

Another interesting facet to the design of EF Migrations is how it handles seed data. For migrations, seeding is done through an override method in the migration configuration class. The odd thing about this seed method is that it runs every time migrations are run, even if there are no pending migrations to apply to the database. In TicketDesk’s case, both seed methods will run (from legacy and regular configuration classes).

In my opinion, there are two kinds of “seed” data –there is “default data” which is data that should be pre-set when the DB is created, then there is “test data”, which is used for testing or just pre-loading some example data. EF uses “seed data” in the sense of “test data”.

As a practical example of the difference, TicketDesk has a bunch of default settings that are stored in its settings table. These values are required, or the application fails, but admins can change the default settings later if they choose. This is not, in the sense EF uses the term, “seed data”. It is “default data”, for which EF has no explicit support.

For default data, the best solution seems to be inserting the data during the migration itself –by adding insert operations to the migration class’s up and down methods. Unfortunately, there aren’t any convenient helper methods for doing inserts, so you have to issue raw SQL insert commands as strings.

For “test data”, you can rely on the seed method in configuration, as long as you are comfortable with your data being reset every time the application starts. At least you can use Linq helper methods and your strong-typed entities there.

At this point, I have working database initialization and full migrations support in TicketDesk 3, at least for the core model entities. Security, and security database support, may prove more challenging.

TicketDesk 2.1.1 – Official Release

TicketDesk 2.1 LogoTicketDesk 2.1.1 has been officially released at codeplex, and the source code has been merged and pushed to the public mercurial repository.

This is a platform refresh of the TicketDesk 2 project. The source code now supports development with Visual Studio 2012, and the application has been updated to target the .Net Framwork 4.5 and Asp.net MVC 4.

The databases have not been modified, but have been verified for compatibility with SQL 2012, including localdb.

There are no new user-facing features in this release.

TicketDesk 3 Dev Diary – EF Migrations & TD2 Upgrades – Part 2

Fixing MigrationsIn part 1, I outlined TicketDesk’s database management requirements, and how I hoped to use EF Migrations to meet them.

In this part, I will describe how I setup EF Migrations for new databases or TicketDesk 2 upgrades.

Migrations for a new TD3 database:

Ignoring TD2 upgrades, my first mission was to enable migrations for fresh TicketDesk 3 installations.

Bizarrely, Visual Studio 2012 did not include any tooling to support EF 5 migrations –odd since it has tooling for other EF 5 features. Developers interact with EF Migrations through the Package Manager Console; poor man’s tooling, but at least the commands are straight forward and well documented.

The Enable-Migrations command successfully created a migrations folder, generated the initial migration files, and added a migrations configuration class. As I mentioned before, there are database objects you can’t define with data annotations or the fluent API, so the next step was to edit the initial migration to include those pesky default constraints.

Once I had the initial migration finished, I was able to execute it from the PM console to produce the new database. The command line tools are fine for developers, but I also want the web application to initialize the database and run the migrations for me.

EF includes a migrations aware database initializer (MigrateDatabaseToLatestVersion), so I switched my app_start to use it. This also worked fine and the web application will make a fresh database on startup when it needs to.

Great! I’d be done if it weren’t for the need to support TicketDesk 2 databases upgrades.

Migration internals and limitations:

Before I get into how I Migrations work for TicketDesk 2 upgrades, I need to expalin a little about how migrations work internally, and point out some of its limitations.

From the developer’s viewpoint, EF Migrations are pretty simple. The initial migration is just a regular class that inherits from DbMigration. It has two method overrides, one for migrating up (containing create commands), and one for migrating down (containing drop commands). There are two other files associated with the initial migration. These track the parent/child relationships between migrations, but their main purpose is to manage the all-important model hash.


The hash is a compressed version of the entire code model at the time the migration was created. When the migration is run, the hash lands in the _MigrationHistory table in the database. This is how EF knows which migration was last used on the DB, and what the model looked like at that time.

The important thing to understand is that EF Migrations never look at your physical database schema. When EF generates a new migration, it does so by combobulating a model from the old hash value. Then it combobulates another model based on the hash of the current code. With before and after models in memory, it uses a complicated diff routine to figure out what needs to be changed to make the models match.

Since the real DB schema isn’t involved in migrations, you can modify the physical database manually, at your own peril, without migrations needing to know about it. In addition, you can modify the statements in the migration class in any way you want; EF will assume that whatever you changed will still result in a database that supports the storage needs of your EF model. Your physical database can also contain other tables and objects that are not related to the model being managed by EF.

The most glaring oversight in the design of EF 5 Migrations is that the _MigrationHistory table can only handle migrations for one model. If you have two different models and DbContexts, you cannot enable migrations on both unless they target different physical databases. If you try to share the same database, the migrations will overwrite each other’s records in the _MigrationsHistory table.

EF 6, currently an Alpha release, will fix this issue with a feature called “multi-tenant migrations”, but I’m not keen on using alpha bits just now.

TicketDesk 2 – Legacy Migration

While I’ve been careful to make sure the initial TD3 database is the same as a TD2 database, there are still minor differences. EF should run a different initial migration against an existing TD2 database. I will call this the “legacy migration” from here out. The legacy migration will just make a few alterations to eliminate the remaining schema differences.

I’ve already talked about how model hashes work, so here is why it matters… Each migration keeps track of its parent migration, which is how EF knows the correct order in which to run them. It is vital that both initial migrations use identical hashes, and have the same migration ID; otherwise, EF will get confused when I add new migrations later, and the linear migration path will be broken.

It took some experimentation to get two initial migrations to co-exist peacefully. Since both must share the same ID, class name, and hash value, it was simplest to put them in different assemblies –TicketDesk.Legacy for the legacy migrations, with regular migrations remaining in the TicketDesk.Domain project.

The legacy migration is a complete forgery, so I didn’t generate it with the PM console commands. Instead, I copied the initial migration files from TicketDesk.Domain into the legacy project. I then changed their namespaces, and gutted the up/down methods. This results in a legacy migration that does nothing, but when executed will add a _MigrationHistory table, and set the migration ID and hash values.

In order to run the legacy migration, EF will need a DbContext and migration configuration class. So, I made a LegacyDbContext. There is no actual model for this project, and we will never generate additional migrations for it, so the LegacyDbContext is empty, except for the constructors. It exists only so EF can open a connection to the database and run this one migration. I made a copy of the standard configuration file too, modifying its namespace and pointing it at the LegacyDbContext.


The last step was writing custom commands into the legacy migration class’s “up” method to take care of those last few schema differences. For completeness, I also added appropriate commands to the “down” method that restores the database to the stock TD2 schema.

At this point, I was able to use the PM console commands to run either the legacy migration, or the regular initial migration, and both work as expected. Looking at the databases with the schema compare tool, there were only cosmetic differences between a fresh DB and an upgraded one. Perfect!

In the next part of this series, I will setup an initializer to selectively run the appropriate initial migration at runtime, and explore a few more gotchas with the EF 5 migrations framework.

TicketDesk 3 Dev Diary – EF Migrations & TD2 Upgrades – Part 1

Sandhill Crane Migration by Serge MelkiTicketDesk 3 may be starting from a fresh code-base, but it is not a new application. There are organizations using TicketDesk in the real world. New releases of TicketDesk have always supported in-place database upgrades, and later versions automated them. I plan to continue this tradition in TicketDesk 3, but would rather not need to roll my own upgrade code, or rely on hacked up T-SQL scripts.

How Migrations Help:

EF code-first is highly capable of generating a well structured SQL database from a pure-code driven model –most of the time. But, EF’s standard database initializers only handle two operations; drop a database, and generate a new database. When you make a model change, EF can automatically drop the DB, and then create a new one that reflects the current model.

This is all fine when developing locally, and is acceptable when deploying a new installation to production. But once you have a production database that real people are using, it is a bad idea to drop and re-create it to deploy a new version of the code.

Customers often dislike having their production databases dropped.

This is where EF Migrations come in. The migrations framework allows EF to modify an existing database in-place, keeping existing data intact. Customers often prefer this approach.

EF make some assumptions about how you will use migrations. It expects a linear, ordered evolution of your database, starting from some “initial state” and ending with the “current state” of your model. The first migration creates a base-line database, then other migrations modify that base-line to reflect any model changes that come along later.

What TicketDesk needs from EF Migrations:

New TicketDesk 3 installations work fine with the normal linear pattern expected by EF migrations. The initial migration will create the database, and fill it with tables. Since I was careful to start with a model that closely resembles TicketDesk 2, the initial migration will create a complete, and reasonably mature, database schema. The TD3 model shouldn’t experience the kind of rapid churn you’d see when building a brand-new product. Still, some model changes will be necessary as work on TD3 progresses, and additional migrations will be needed. The standard design of EF Migrations fully supports this pattern of model evolution.

In my earlier post, I mentioned that there are some database objects that EF can’t automatically generate from data annotations, or the fluent API –default constraints being the main culprit. TicketDesk 3 could get by without default constraints, and the POCO classes could just handle setting defaults in code. But I want my DB to be as similar to the stock TD2 DB as possible. Fortunately EF Migrations does allow you to add real default constraints as part of the migration routine, though you have to manually edit the code to add them.

When upgrading from a TD2 database things gets more complicated. The linear pattern EF migrations expect is not sufficient for upgrades. EF should not attempt to run the regular kind of initial migration against an existing TD2 database. Such a migration would try to create DB objects that already exist, and would fail.

When upgrading, EF will need to run a different initial migration routine –one designed only to modify the DB where necessary to match the normal TD3 schema. Since I was careful to ensure that the two schemas are nearly identical, all the special migration has to do is clean up a few minor variations (e.g. mark an FK as “cascade on delete”, create a non-clustered index, etc).

In theory, once the special migration runs, the old database should be functionally identical to a regular TD3 database. No matter which initial migration routine runs, the same set of subsequent migrations will be able to upgrade the initial DB to reflect model changes that occur later in development.

So that’s what I want from EF Migrations. In the next post, I’ll try to make it happen.

TicketDesk 3 Dev Diary – EF Code-First Model

Nowhere to stand, nowhere to hide by Pete Wright Photography, on Flickr

It is often difficult to decide where to start when building a new application, but for TicketDesk 3 the obvious first step is to create the database and entity model.

Until now, the TicketDesk database has followed an unbroken evolution from the original TD1 database to TicketDesk 2.0.3. I built the original database by hand, then used it to generate a Linq to SQL model diagram. When I put TicketDesk 2 together, I just switched to EF 4 entity model diagrams; again, building the model from the existing database.

For TicketDesk 3, I’ll once again switch data access technologies, this time using EF 5’s DbContext with a code-first model (POCO). I could continue with *.edmx models, and generate the DbContext and POCO classes from the diagram, but Microsoft seems to be moving away from *.edmx, and I strongly prefer the code-first approach anyway.

Initially, I want to start TicketDesk 3 with a model as similar to the TicketDesk 2 database schema as possible. Due to the way EF generates T-SQL, there will be cosmetic differences, but I don’t want any significance structural variations –not yet.

To create the initial POCO classes, I was able to leverage the old entity model diagrams. The tooling in VS 2012 allowed me to open the old *.edmx files and add the “EF 5.x DbContext Generator”. This creates T4 templates, which in turn automatically produce generated DbContext and POCO classes based on the diagram. All I had to do was pluck out the generated class files and drop them into the TicketDesk 3 project.

Interestingly, the POCOs created by the generator include the model properties, but not the annotation attributes that identify key fields, required fields, and so on. Normally I’d have to annotate them all by hand, but I found a shortcut for this too. TicketDesk 2 originally used another T4 template, called AutoMetaData, which produces meta classes for all its entities; and those meta classes contain the data annotation attributes. The old EntityContext stuff doesn’t need those annotations, but generating them was useful to enable UI validations in the MVC front-end. So, all I had to do was copy the attributes from the TD2 meta classes, and drop them on the corresponding properties in the new TD3 model classes. Tedious, but easy.

TD 2 also included custom extensions (via partial classes) for a few entities. Mostly these just had a few non-persistent helper properties, and a custom method to two. I simply copied these into new POCOs too, and then made sure they were annotated correctly (adding the NotMapped attribute to most).

By leveraging the work I’d already done in TD 2, I was able to create a nearly complete EF code-first model for TD 3 without writing any code by hand. Sweet!

The last step was to test DB generation from the new model and DbContext.

My web project was created from the stock MVC SPA template that shipped with the “ASP.NET and Web Tools 2012.2 update“. I setup a new localdb connection string in web.config, configured EF to use the DropCreateDatabaseAlways initializer, and then called the Database.Initialize() method on my new DbContext during the application_startup event. Running the web application triggered the database creation without any problems.

I then used the schema compare tool in VS 2012 to compare the new DB against an unmodified copy of the TD2 database. There were a few differences, which I had expected, but structurally it was the same DB that TicketDesk 2 used. The only significant variation was the lack of default constraints in the new database.  EF 5 doesn’t support default constraint definitions via attributes, nor the fluent model builder APIs. Fortunately, EF migrations can handle defaults, so I will solve that problem later on.

The stock TD2 database also included SQL membership, role, and profile tables, which are not a part of  the new entity model. I’ll be addressing the security system pretty soon,  and then I can decide how best to handle the security DB objects.

And that is pretty much it for the initial TD 3 code-first entity model. As I develop TD 3, I will likely make changes, but I can rely on EF to manage the database schema going forward. I’ll need to setup EF migrations, deal with seed data, and add upgrade support for legacy TD2 databases… but those are topics for future posts.

TicketDesk 3 Dev Diary – Source Control and Source Hosting

source code hostingBefore any good project gets further than a mission statement, it needs source control. Typically, I don’t even create a project file without first creating a source repository in which to put it. But I’ve not been that happy with CodePlex, so I’ve decided to move the project to GitHub and switch to the Git source control system.

Source Control Systems

TicketDesk 1 and 2 were hosted at CodePlex using Microsoft’s Team Foundation source control system. After 5 years of trying, I eventually developed a deep and lasting hatred for all things TFS. When CodePlex added support for Mercurial, I had TicketDesk migrated as soon as I could.

I use both Mercurial and Git, but I tend to prefer Mercurial. Both are highly capable systems, but for windows development, the experience around Mercurial is much better. Mercurial installs easily, runs smoothly, is easy to learn, easy to use, and comes with a great GUI out of the box.

In contrast, running Git on windows requires installing a whole mess of junk to bridge the gap between Linux and Windows… and that just gets you to the command-line tools. There are several third party Git GUIs, but most of them are terrible. GitExtensions is the best, though still ugly and counter-intuitive compared to TortoiseHG.

Fortunately, there are great extensions available for Visual Studio no matter which system you go with.

About command lines… I love having the option of a command line, but I hate using a command line as my primary user interface. Command lines are fine for advanced scenarios, automation, or propping up a nice GUI… but for something I interact with as often as my source control system, I want a good GUI!

Repository Hosting

I like CodePlex, but it lags behind BitBucket and GitHub in both features and popularity. CodePlex’s release management features are way ahead of the competition, and the site makes a better end-to-end product hosting service than most of its competitors.

CodePlex elegantly handles product information, downloadable releases, source code, support forums, bug tracking, and documentation. I am completely comfortable sending an end-user to TicketDesk’s CodePlex site to submit bugs or ask questions. In contrast, I would never send an end-user to GitHub or BitBucket to get support for one of my products.

As much as I like CodePlex though, I’ve also had many bad experiences with them, particularly around support and reliability. As an example, my routine request to have TicketDesk converted to mercurial went unanswered for more than 3 months, and it wasn’t handled very well when they did get to it. CodePlex often doesn’t perform very well, though this seems to have improved some recently. CodePlex also isn’t very popular, which makes projects there less discoverable, and people less likely to fork or contribute.

I use Bitbucket extensively for my professional code. Bitbucket lagged behind GitHub for a long time, but in the last year it has improved rapidly. Now, it rivals or exceeds GitHub in most of the areas I care about most. They’ve added support for Git repositories too, though I’ve only used it with Mercurial. I like BitBucket’s pricing model, and it supports organizational team accounts, as well as individual users  –perfect for corporate projects where an individual doesn’t directly own the repositories.

GitHub is crazy popular, and for “social coding” popularity is everything. If you are using Git, and your project is public, then GitHub is the obvious choice. It has amazing features, and sets the bar by which everyone else is measured. The only major complaint I have is the lack of a release management system. GitHub doesn’t make the best full-service project hosting site, but it does a bang-up job with the core mission of source code collaboration. GitHub’s pricing is perfect for open source projects and private repositories, but awkward for some corporate scenarios.

Why Git and GitHub for TicketDesk 3?

    • Git
      • I use Git a lot when working with other peoples’ projects, but I have not used it extensively for my own. I could use more end-to-end experience with it.
      • The typical workflow with Git is perfect for public projects like TicketDesk. Private branches, history culling, and similar features all help keep the public repository clean, and focused only on commits that moved the project forward.
      • Even among the .Net developer community, Git is the more popular option. Using Git will hopefully encourage more people to contribute.
      • Git has better integration with Windows Azure, and I do hope to make TicketDesk 3 an Azure deployable application. This is a minor plus, but worth a mention.
    • GitHub
      • Since I’ve chosen Git, GitHub is the inevitable choice for hosting.
      • Hosting at GitHub should result in higher visibility for the project, which I hope translates into more people discovering TicketDesk.
      • GitHub’s best features are those designed to enable independent programmers to contribute and collaborate on public projects; something I’d like to see happen more frequently with TicketDesk.

What about the CodePlex project?

I do plan to keep the CodePlex project around. I will likely continue to push packaged releases there, especially since GitHub doesn’t do much for release management. I may push occasional source updates to CodePlex when the code reaches major milestones.

The TicketDesk 3 repository is already on GitHub, but is private for now. Once I have a good start, I’ll open it up to the public.

TicketDesk 3 Dev Diary – The development plan

TicketDesk3LogoTicketDesk 3 is mostly about re-architecting the core system for current asp.net webstack technologies. It will not be a feature heavy upgrade, though it will come with a completely new user interface on top of the existing feature set.

The following is an incomplete high-level feature list. Several aspects will change once I’ve done more research in certain areas.

New Features:

  • Ticket Subscribers: anyone can subscribe to a ticket’s notifications
  • Editable lists in TicketCenter: a TD1 feature that never got back into TD2
  • New Security System
    • Local users (forms)
    • oAuth support
    • Active Directory via ADFS
    • Legacy Account Migrations (TD2 upgrades)
  • New User Interface
  • Localization


  • Entity Framework 5
    • Code-First Model
    • EF Migrations
      • Legacy Migrations (TD2 upgrades)
  • SQL Server 2012
    • localdb, Express, and full editions
    • SQL Azure
    • SQL CE 4 (tentative)
  • MVC 4
  • SPA Based UI
    • HTML 5 & JavaScript
    • Responsive Design
    • Knockout.js & related
  • WebAPI
    • oData (tentative)
  • Windows Azure deployability
  • IoC
    • MEF 2 or Ninject (tentative)
  • Security
    • SimpleMemebership or Universal Providers (tentative)
    • oAuth
    • AD integration via ADFS
      • WIF (tentative)

Other Considerations:

Mobile is of course the hot-topic these days, and to a lesser extent so are native Windows 8 applications. I intend to design TicketDesk 3 around WebApi, which should go a long way towards enabling support for many different front-end clients. I’m looking at responsive design to enable the initial web application to scale around different screen sizes, but I’m not sure responsive design alone can bridge the gap all the way down to the small-screen devices (phones and mini-tablets).

After the initial TD3 release, I hope to build mobile specific HTML 5 views. These should enable a good experience on any modern smartphone, but I don’t want to get into building a native app for each phone platform.

I do hope to build a native Windows 8 metro (or whatever they call it this week) client app.

I plan to support upgrades for existing TicketDesk 2 installations, and the databases will continue to be self-initializing and self-upgrading.

Localization has also been a highly requested feature, much to my surprise. I’m monolingual, and have very little experience with localization, so don’t expect too much. I do plan to use localizable resource files for all the application’s various text, and will support localized date, time, and number formats.

TicketDesk 3 Dev Diary – Getting TicketDesk 2 back in shape

TicketDesk 2 LogoWhen developing a new version of an existing product, it really helps if you can run the old version and use it as a reference.

TicketDesk 2 works well, but it was designed for MVC 2 running on .Net 4, which would be fine if I still maintained a local development environment compatible with the old code. But I’ve ditched Visual Studio 2010 and 2008 entirely.

So, the first order of business is migrating TicketDesk 2 to the newer asp.net webstack.  I’d also like to update the source on codeplex so others can use it with current dev tools too.

I will not be upgrading the application to use MVC 4 or .Net 4.5 specific technologies or techniques; I’m not switching it to the razor view engine or upgrading to EF 5. The goal is to just get it running on current platforms with as few changes as possible.

The first step was finding the asp.net MVC 2 to MVC 3 project converter. Once I tracked that down, and did a bit of tweaking to get it to work, the conversion ran without a problem. This allowed the project to open  in VS 2012 at least, though it wouldn’t build or run.

Next I moved the web project up to MVC 4, and re-targeted both projects to compile against .Net 4.5. Re-targeting was just a matter of switching the setting in the project properties dialog. Then I just pulled down the asp.net MVC 4 NuGet packages, along with the three dependent packages. TicketDesk uses the old ASPX view engine, and doesn’t use WebApi or anything fancy, so I didn’t need most of the other NuGet packages that you’d see in most MVC 4 applications.

TicketDesk 2 used MEF 1. This was probably the riskiest decision I made when building it originally. MEF 1 was intended for Silverlight development, and I had a LOT of trouble getting it to work correctly for asp.Net MVC (I wrote about those issues at length here and here). Had my only need been dependency injection, I would have switched to Ninject. In the end though, I did get MEF to work for TicketDesk 2. But to be honest, the experience was not very inspiring. Since then, I’ve stuck with Ninject, and been the happier for it.

Now we have MEF 2, but it is nearly impossible to find coherent guidance on how to use it with web apps. There are tons of articles, blog posts, and discussions all over the net, but they all use different techniques, none of the examples actually work beyond demo land (most don’t work there either), and most of the info is based on obsolete pre-release versions. The MSDN docs are of particularly low quality, and frustratingly out of date too.

I’m sure MEF 2 is amazing, but if MS doesn’t do something serious about cleaning up the documentation and providing some coherent guidance appropriate for real world applications, then I doubt it’ll get much use among the asp.net developer community.

I spent several hours working with the best example of MEF 2 with MVC that I could find. In the end though, I still couldn’t get it to play nice with TicketDesk 2. But I got lucky and was able to get what I had built originally to work with very few changes. I’m sure the old pattern misses out of some nice MEF 2 specific improvements, but the goal here is to get TicketDesk 2 working again not optimize it for the new platforms.

I’ll probably take a deeper look at MEF 2 for TicketDesk 3 before I decide if I’ll switch to Ninject, or give the new MEF another shot.

I no longer have SQL Express installed locally. I am using SQL 2012 localdb, and have a full instance of SQL 2012 developer edition. So, I switched the TD 2 connection strings to localdb, and have had no problems with it. I’ll put them back to SQL express before I merge the code back into the default branch, and there are no databases changes for the new build.

This got me to up a working version of TicketDesk 2 that can run on MVC 4 using the .Net 4.5 framework. Mission accomplished!

Once I had it working though, I went ahead and upgraded the jQuery stuff. I just couldn’t resist. This required a tiny tweak to the corners plug-in to fix a compatibility problem with the newer jQuery releases; but overall it seems to work great.

At this point, I have what appears to be a fully functional update of TicketDesk 2. All that remains it to put it through some live testing, and update the documentation. Then I will merge the new code in source control, and push it up to codeplex along with a new downloadable release.

Best of all, I now have a working local copy I can use as a reference while I build TicketDesk 3.