Custom error pages with ASP.NET MVC 5

So you created an ASP.NET application, hit a 404 Not Found error, and now you want to show something else other than the ugly default ASP.NET / IIS error pages, right? Well, sit back, because it’s rather annoying to setup properly. I strongly suggest reading the details that encouraged me to write this article. While that article definitely provides a majority of the setup required to make sure all cases and edge cases are handled when errors occur, there are some things that I had to do in order to make it all work properly.

Create a .html file and .aspx file for each error you want to handle. For example, 404.html and 404.aspx.

In the .aspx page, add this line below the “<%@ Page %>” directive where “xxx” is the error code you are handling such as 404 or 500.

In web.config, add this to your system.web section where each <error> section relates to whatever codes you are handling.

In web.config add this to your system.webServer section where each <remove> and <error> section relates to whatever codes you are handling.

Be sure to read through the originally linked blog to understand why you have to do certain things. I will say, however, that I had to fix a few things:

  • There was a missing semi-colon in the .aspx line for “Response.StatusCode”.
Read more

Customizing ApplicationDbContext in ASP.NET MVC 5 and ASP.NET Identity 2.0

As of Visual Studio 2013 Update 1, the ASP.NET MVC 5 templates with Authentication enabled will create a project that contains a class named ApplicationDbContext. This is the Entity Framework DbContext that is used by the ASP.NET Identity libraries to manage user records.

By default, here is the generated class:

You’ll notice that it inherits from IdentityDbContext with a generic type of ApplicationUser. The base DbContext handles whatever is needed by the ASP.NET Identity libraries, and the ApplicationUser is the model that describes the authenticated user. If you’re like me, and you don’t want to create a ton of separate DbContext classes for different repositories, you can just mash it all together into ApplicationDbContext like so.

At a glance, it seems weird that a DbContext which is inherited from a very specific library contains other non-related DbSet objects, but it gets the job done. If you’re more into separation of concerns and don’t want a huge explosion of fluent API in a single class, look into creating separate DbContext classes as appropriate. Just remember that you need to maintain a connection string per DbContext in your web.config.… Read more

Upgrading an Existing Project from ASP.NET Identity 1.0 to 2.0

I have recently been playing around with ASP.NET MVC 5 via Visual Studio 2013 and the new ASP.NET Identity libraries. While the project templates mostly help you get to where you need to go when starting a brand new application, upgrading from the first Identity package (1.0) to the latest stable (2.0) wasn’t quite as smooth as I expected. For reference, Visual Studio 2013 Update 1 project templates use the 1.0 version of the ASP.NET Identity libraries. Visual Studio 2013 Update 2 RC (at the time of this writing), uses the 2.0 version.

By default, the project templates will set you up with a database schema that is accessible via EntityFramework and Code First. Since the templates utilize Code First, you will need to manage database migrations. And that’s where the trouble came in when upgrading from 1.0 to 2.0. The database schema changed (and will require code migrations) as a result of upgrading since the library supports new features like email confirmation, phone numbers, new primary keys, new indexes, and more. Attempting to run the application after simply upgrading all the libraries through NuGet gave me this essay of an error:

The model backing the ‘ApplicationDbContext’ context has changed since the database was created. This could have happened because the model used by ASP.NET Identity Framework has changed or the model being used in your application has changed. To resolve this issue, you need to update your database. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=301867). Before you update your database using Code First Migrations, please disable the schema consistency check for ASP.NET Identity by setting throwIfV1Schema = false in the constructor of your ApplicationDbContext in your application.
public ApplicationDbContext() : base(“ApplicationServices”, throwIfV1Schema:false)

Fortunately, the error message itself and a blog post gets you a good portion closer to finishing the upgrade process. By changing the constructor of ApplicationDbContext to pass in false to its base class for throwIfV1Schema, you can avoid this exception and force your way through the migration steps. So, in brief:

  1. Open the Package Manager Console
  2. If you haven’t for this project, type Enable-Migrations to allow code migrations to be used in your project
  3. Type Add-Migration IdentityUpdate to create a migration script so the database schema can be brought up to speed to match the new model that was updated as a result of moving from 1.0 to 2.0. Note that the name of the migration can be anything.

Step 3 should fail if you have the same scenario as I did. You’ll probably see this error (which isn’t mentioned in the above linked blog post):

System.Data.Entity.Core.MetadataException: Schema specified is not valid. Errors:
(0,0) : error 0004: Could not load file or assembly ‘Microsoft.AspNet.Identity.EntityFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I actually got lucky and saw this error message in an issue on the ASP.NET Identity CodePlex page. Specifically, there is a workaround mentioned on this issue.… Read more

Resolution Independent 2D Rendering in SDL2

A little over a year ago, I wrote a post about how to render to a fixed, virtual resolution so that we can render independently of the actual window size resolution. That approach utilized the XNA framework to perform what we needed. Since Microsoft effectively killed XNA by pushing forward with DirectX / WinRT, myself and others have moved on to other libraries. In this post, I will show you how to do the same thing but with SDL2. Honestly, this approach is even easier (as long as you are using SDL2 that is!)

The concept of rendering to a virtually sized target is labeled as “Logical Size” in SDL2. Rendering a game to a logical size makes the scaling of that game to match different window sizes much easier. Imagine that we created our game under the assumption of 800×600 (an old school, 4:3 aspect ratio). On a user’s machine that has their system resolution set to 1920×1080, we have two choices: 1) show the game in a tiny window or 2) stretch the picture to fit the full screen. Both of these options are pretty terrible. In the first, the window will be too small to see anything useful (depending on the textures and fonts used in the game). In the second, the stretched picture will look awful because the aspect ratios do not even match. This is where SDL2’s logical rendering comes into play.

After establishing your renderer, all you really need to do is call the SDL_RenderSetLogicalSize function with the appropriate parameters. For example, the below code will set the logical rendering size to 800×600.

Now whenever we use our renderer to render textures, they will be appropriately scaled to fit the window size and letter-boxed to avoid the ugly stretched look of different aspect ratios. You can see this in action in the picture below. In this example, I am rendering to a logical size of 800×600 in a window of size 1400×900. Note the letter boxes that SDL2 added to the left and right to avoid stretching.

LogicalRenderingRead more

Using SDL2-C# to Capture Text Input

A common feature of applications and video games is to allow the player to input text for various reasons. Maybe we want to allow the player to input their character’s name in an RPG, name a city in SimCity, or type a chat message to a friend in online. Using SDL2, we can take advantage of its built-in text processing system which abstracts much of the operating system event handles and character encoding mechanisms.

On consoles such as Xbox and Playstation, text input is rather simplistic and limited to visual keypads that you select via the controller. On a PC, we have the full range of widely varying keyboards from English and Spanish to Russian and Japanese. If we want our game or application to attract users on an international scale, it’s probably in your best interest to learn here and now how to use SDL2 to accomplish this goal.

At first glance, it probably seems simple to process text input. If the user presses the ‘A’ key on the keyboard, the OS will send an event that the keyboard was just pressed, the key was ‘A’, and no modifier keys were pressed (CAPS, SHIFT, CTRL, ALT, etc…). That’s it, right? Unfortunately, there are a ton of languages on this planet, and some of them have thousands of characters in them. People who type in those languages most certainly do not have thousand-letter keyboards or entire walls of their houses dedicated as a giant keyboard. This basically means that some characters will require multiple key presses just to process. Fortunately, SDL2 handles all of this for us and simply sends us a byte array with the results.

Among SDL2’s event processing, the structure we are interested in is SDL_TextInputEvent. This event is sent through the SDL2 event processing chain whenever text is input. I have personally seen this trigger from both physical keyboards and the Windows virtual on-screen keyboard. I am sure that there are other ways to trigger this event as well. Using this event, we can get the character information that was input by the user. Here are the fields of the C-style structure that we can use:

After determining that this is an SDL_TextInputEvent by checking the type field, we are most interested in the text field. That field is a pointer to a character array which is encoded using the UTF-8 scheme. In my most recent cases, I was using a C# wrapper around the SDL2 library named SDL2-CS. Because C# runs in a managed, garbage collected runtime, it’s a bit tricky to get the text input from C into C# through the .NET marshaller, but here’s how to do it.… Read more

How to load a map from Tiled Map Editor and render it with SDL2

I recently created a library named SharpTiles that is heavily based on Nick Gravelyn’s TiledLib. Both libraries will allow developers to load maps from Tiled Map Editor. However, TiledLib is based around XNA while SharpTiles is based around SharpDL (an XNA-like game framework for SDL2). I will discuss more about SharpDL in another post, but you can refer to the simple code in this post to learn how to render a map with a small subset of the library.

Load a Map

  • Window is a SharpDL object that represents a SDL_Window
  • Renderer is a SharpDL object that represents a SDL_Renderer
  • TiledMap is the main object that you will use to load a map file

Draw a Map

You can draw a map by looping through all TileLayers (layers which containd textured tiles) and all Tiles within the layers. Make sure to check if the tile is empty before drawing it. Tiled Map Editor will create empty tiles in spots that contain no textured tiles within the layer.

  • Texture is the tileset that contains the tile’s texture
  • Position.X is the X position of the tile to draw
  • Position.Y is the Y position of the tile to draw
  • SourceTextureBounds is a rectangle that indicates where in the tileset the tile’s actual texture is contained

Read more

Setting Up SDL2 with Visual Studio 2012 and 2013

I have confirmed that everything below works for Visual Studio 2013.
Links updated to the latest release (2.0.3).

The Simple DirectMedia Library (SDL) version 2 has been released after a long time in development. It seems that the author has more time on his hands and more corporate backing from his new position at Valve Software. I’ve heard that they use SDL for various small time projects that don’t require heavy rendering. Even so, SDL does a formidable job at making things easy.

I wrote this guide under the following setup, but I’m sure that it can be applied to other version of Windows (and maybe even Visual Studio).


Anyway, try your setup and let me know how it goes. Follow these steps to get all setup and ready to code:

  1. Download the development libraries
  2. Download the 32-bit binary or the 64-bit binary
  3. Extract both zips to a convenient location
  4. Open Visual Studio and create an empty C++ project
  5. Right click the created project in the Solution Explorer, go to Properties
  6. Click VC++ Directories under Configuration Properties
  7. In the “Include Directorires” line, add the include directory from the extracted development library
  8. In the “Library Directories” line, add the libx86 directory from the extracted development library
  9. Click Linker –> Input under Configuration Properties
  10. In the “Additional Dependencies” line, add “SDL2.lib” and “SDL2main.lib” strings
  11. Click Linker –> System under Configuration Properties
  12. In the “SubSystem” line, change the selection to WINDOWS(/SUBSYSTEM: WINDOWS)
  13. Finally, copy the SDL2.dll file from the extracted 32-bit binary folder to your project’s output directory alongside the executable

OK, the ugly project setup is finished. Now we can have some fun with coding. Now add a new cpp file with this code.

Compile and run the application to see if any errors are generated. All we did in this code was initialize SDL and immediately quit. If you saw any strange errors, then something is either wrong with the project properties described above, or you’re missing some SDL dependencies.… Read more

Resolving the problem where “WADLogsTable” is not created in Windows Azure Diagnostics

I’ve been using Windows Azure to host a Worker Role in a Cloud Service for an in-development version of my new app, Steam Community Viewer. This service will allow users to be notified of when their friends come online or start playing a game through Windows 8 Toast Notifications. Additionally, it will push updates to Live Tiles for new Steam deals.

During my tests, I tried to turn diagnostics on, but failed to save them to a permanent storage because the table that gets created when you enable basic logging wasn’t actually being created! Windows Azure Basic Logs will be saved in Azure Storage Tables under “WADLogsTable” based on a logging level (error, critical, verbose, etc…). This table is supposed to be automatically created when the service is uploaded and deployed with tracing enabled. If you find that the official Windows Azure documentation on using diagnostics is not helping you with this task, try the code below in your service OnStart() overload.

Read more

Some Useful git Commands

git status
shows pending changes that can be added to repo

git add -A
adds all pending changed files to pending commit list

git commit -a -m “Message”
commits all pending additions to the current branch with a message of “Message”

git push
pushes current branch to default remote

git push {branch name} {remote repo name}
pushes {branch name} changes to {remote repo name}

git reset {file name}
resets a file back to previous state after adding to pending commit list

git branch {branch name}
creates a branch named {branch name}

git checkout {branch name}
switches to a branch named {branch name}

git checkout -b {branch name}
creates and switches to a branch named {branch name}

git remote add {remote repo name} {remote repo uri}
adds a reference to a remote repo that can be pushed to… Read more

Steam Community Viewer Privacy Policy

The Steam Community Viewer allows users to search for Steam Community profiles to view profile details, game lists, game statistics, achievements, friend lists, group lists, and more. All data is obtained through public and Valve supplied methods. This application is not associated with Valve Software.

All data is made available through Valve provided interfaces. I do not own any of the data provided through this application. Except for your Steam ID, this application does not store, collect, or share any data that you enter or retrieve through its use. Data is not tampered with between retrieval and display except for formatting purposes. Your Steam ID is only stored if you enable “Friend Notifications” in the “Notifications” tab of the “Settings Flyout”. When you disable “Friend Notifications”, your Steam ID is immediately removed from storage.

This application does not provide any means of managing the your profile data because your profile data is not owned by the developers of this application. The only way to modify your profile data presented in this application is to modify your profile through the official Steam application or website.… Read more