The required anti-forgery cookie “__RequestVerificationToken” is not present.

In your ASP.NET MVC adventures, you may come across the following error when loading a view.

The required anti-forgery cookie “__RequestVerificationToken” is not present.

After searching Google for awhile, you might become desperate with the many different solutions presented. Normally, the solution to this issue is related to the ValidateAntiForgeryToken attribute on actions. When accessing a GET action, you don’t need to use the anti-forgery token.

However, this is not the only solution. In my case, my web.config had this entry:

Checking the project settings in Visual Studio revealed that my project was not set to use SSL which caused a conflict. Either comment out the above line or set the project to always use SSL.

See more solutions to this issue on this StackOverflow answer..… Read more

Fixing Error 5: Access Denied when Starting a Windows Service

After creating your own Windows Service, you may encounter the following error:
53rgc

Sounds serious, but it’s not. It’s complaining that executable can’t be started because the account under which the service is running does not have access. When you installed the Windows Service, you had to choose a context like Local System, Local User, Network User, or something custom. In order to fix this issue, you need to give execute permissions to the user you chose. For example, NETWORK SERVICE account may need permission if that’s the context you chose to run the service.

Even after that hard work, you might still see an error like below:
Fp6Zq

This is a more generic error which indicates that something threw an exception during the OnStart method of the service. Since it’s so generic, there’s not really one solution to the problem. You need to check the Application Log in the Windows Event Viewer to understand what faulted the service. In some cases, it could be a bad application configuration (as one example).… Read more

Installing XNA 4 on Windows 8 / 8.1

Microsoft has long since abandoned XNA improvements, but that doesn’t mean you have to stop using the framework entirely. If you’re interested in installing the XNA framework on Windows 8 and 8.1, it can be a little tricky. Follow these steps.

Option 1

Source: http://blogs.msdn.com/b/astebner/archive/2012/02/29/10274694.aspx

  1. Download and install the latest version of the Games for Windows – LIVE Redistributable from http://www.xbox.com/en-US/LIVE/PC/DownloadClient
  2. If you are installing the Windows Phone SDK 7.1, re-run setup and choose to repair it. This will re-run the previously failing XNA Game Studio installers and they should install correctly this time.
  3. If you are install a standalone XNA Game Studio product, re-run setup and it should install correctly this time.
  4. If you are planning to do Windows Phone development, you should also install the Windows Phone SDK 7.1.1 Update after installing the Windows Phone SDK 7.1. This update fixes an issue that prevents the emulator in the Windows Phone SDK 7.1 from working correctly on Windows 8.

If you are installing the Windows Phone SDK 7.1, you can use the log collection tool to gather your setup log files. This log collection tool will create a file named %temp%\vslogs.cab.

If you are installing XNA Game Studio, you can find log files at the following locations:

  • XNA Game Studio 4.0 Refresh – %temp%\XNA Game Studio 4.0 Setup\Logs
  • XNA Game Studio 4.0 – %temp%\XNA Game Studio 4.0 Setup\Logs
  • XNA Game Studio 3.1 – %temp%\XNA Game Studio 3.1 Setup\Logs
  • XNA Game Studio 3.0 – %temp%\XNA Game Studio 3.0 Setup\Logs
  • XNA Game Studio 2.0 – %ProgramFiles%\Microsoft XNA\XNA Game Studio\v2.0\Setup\Logs

Option 2

This method may not be entirely legal, so only try it at your own discretion.

Use the download for VS2012 and VS2013 at this link: https://msxna.codeplex.com/releases. I have no idea of the legality on that project (the developers seem to have decompiled XNA), but it did help me ease the pain of needing VS2010 in order to utilize the content pipeline.… Read more

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

Setting up a custom domain with Namecheap and Azure Websites

There are a ton of domain name registrars and hosts out there. Finding specific instructions to match the two together is something a bit of a challenge. To make things tougher, instructions aren’t always updated when user interfaces and processes are changed in the tools provided by these services. Hopefully, this article will provide simple instructions.

  1. Log in to your Azure account and go to the management portal.
    • Your website must be set to “Shared”, “Basic” or “Standard” tiers in order to use custom domains.
    • If you want to eventually setup SSL on your custom domain, you will need to set the website to “Basic” or “Standard” tier.
    • Read more on pricing.
  2. Navigate to the dashboard of the Azure Website you are working with.
  3. In the bottom toolbar, click “Manage Domains”.
  4. Make note of the IP address listed at the bottom of the popup.
  5. Log in to your Namecheap account.
  6. Under “account information”, click to view your domains.
  7. On the left sidebar, click “Your Domains”.
  8. Click the domain you want to connect with Azure from the middle section.
  9. On the left sidebar, click “All Host Records”.
  10. Copy the IP address from step 4 to the IP Address / URL of the root host name “@”. Change that record type to “A Record”.
  11. Copy the “xxx.azurewebsites.net” domain name to the IP Address / URL of the host name “www” where “xxx” is your website name. Change that record type to “CNAME”.
  12. Under the subdomains section, add “awverify” and “awverify.www” subdomains. Set both IP Address / URL to awverify.xxx.azurewebsites.net where “xxx” is your website name. Change those record types to “CNAME”.
  13. Save your changes. Wait until the DNS records propogate. Sometimes this takes awhile (over 24 hours). In my case, it took about an hour.
  14. Go back to your Azure dashboard, add the domain and any subdomains to the popup from step 4. For example, “xxx.com” and “www.xxx.com” where “xxx” is your domain name.
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