LightSwitch for Games Part 1: Introduction to Building your Game Data Network with LightSwitch
NOTE: Although this series is aimed at small game developers, it is equally applicable to anyone wishing to learn how to use LightSwitch.
Most modern video games have an online component nowadays. For games with online leaderboards, stats tracking, world-viewable awards and achievements, online virtual currency and distributed non-real-time turn-based games (for a very simple example, play-by-mail chess), a server is required with a database to store the information, and some way of retrieving and updating the data in a secure manner.
A typical and traditional way to achieve this is by using PHP and MySQL: you merely create tables in the MySQL database for the information required, and provide a series of PHP scripts or endpoints which can be passed data via HTTP GET queries (standard browser URLs with no additional data except that in the query string), and return the results – typically either the requested data, or a flag indicating whether the data was updated successfully or not. Your game code calls these endpoints as required to query and update the server-side data.
The PHP/MySQL solution has the upside that it is free (if you have a server), and quick to implement in the initial stages. Downsides are numerous:
- if your game becomes popular, you will have to handle scaleability issues (such as creating server farms or CDNs – Content Delivery Networks, and replicating the database) yourself
- a potentially huge amount of boilerplate code is required to validate input data, and this code will have to be repeated for each project and in many cases, for every endpoint
- security is a major burden. Hackers love to manipulate game server data, and in some cases it can be financially beneficial to them (and detrimental to the game studio or publisher) to do so, so the incentives are large
- speed of development. A lot of game server data management is just a question of doing the same tasks over and over again: validate the input data, store the input data, filter the output data, return the output data. The PHP solution requires you to copy and modify code or write lots of similar code every time you add a new database table or field.
- deployment. You have to manage the server yourself.
Visual Studio LightSwitch is a turnkey solution to creating so-called line-of-business (LOB) or forms-over-data applications. You can, at the simplest level, simply create your database tables and relationships with a visual designer, to a certain extent automatically generate a desktop (EXE) or web-based interface (Silverlight or, as we will prefer since Silverlight is mostly a dead technology at this point, plain HTML), deploy the project onto a server and everything else is taken care of for you. LightSwitch deals with application security (not server security, see below) almost automatically for you, and contains many built-in validation functions and other automated niceties. Adding new data fields and tables is a breeze that takes literally seconds.
If you don’t want a web-based interface to the data (because you’re only going to be accessing it from within your game code), you can publish the database only with no client interface. All of the database tables are exposed as web services using a standardized CRUD (create, read, update, delete) interface to access each one. For the majority of simple applications, little or no code needs to be written at all, but you are not locked in as your LightSwitch applications can be extended and hooked in to any .NET language code you wish.
LightSwitch therefore deals with the speed of development, boilerplate code (including input validation) and application security problems for us nicely. What about the other problems?
Enter Windows Azure
LightSwitch applications have to be deployed to IIS servers running Microsoft SQL Server, which as we all know is an expensive pain in the ass complex maintenance nightmare. Fortunately, there is a solution in the form of Windows Azure, a relative newcomer on the cloud computing block and probably the main competitor to Amazon Web Services (with among other things, Amazon’s EC2 compute cloud). Windows Azure provides you with a cloud service which allows you to provision web sites, databases and general computing power (CPU, memory, storage, bandwidth etc.) on demand. You pay only for what you use, which in many cases will be nothing since your resource allocation is automatically scaled down when your site is not experiencing high traffic.
When you provision a web site on Windows Azure, you get a ready-configured IIS server with all the .NET (and PHP and MySQL!) gubbins set up for you, and a Microsoft SQL Server, both pre-configured in a secure manner and ready to go.
In summary, Windows Azure solves the problems of scaleability, ease of deployment, server-side security and needing to manage your own server at a low level.
You are pitching Microsoft as a secure and easy-to-use solution, really?
Now if you’re used to UNIX/Linux-based server-side development as many of us are, the idea of using Microsoft-based solutions may leave you with a sense of unease. To some of you, it may be anathema. If you’re used to the customizability that a UNIX environment brings, you may feel queasy about using any turnkey solution.
I understand this point of view. I have been using Amazon EC2 happily for a couple of years, and coding with the LAMP architecture (Linux, Apache, MySQL and PHP) for many years longer. However I like to remain vendor-agnostic, and when I was researching the available systems and tools for what I wanted to accomplish with a game server, and how to do it in the shortest possible time, LightSwitch seemed like a natural fit. I experimented with it for a while, and although jumping from Apache/PHP to IIS/ASP.NET development is jumping in at the deep end at first, the effort does pay off with time.
If you’re still skeptical, keep reading and try to keep an open mind. Hopefully you will be able to see the benefits of this approach!
Windows Azure is optional
In this series, I will assume your projects will be hosted on a Windows Azure server and show how to set it up. However, this is entirely optional: you are free to use your own or a rented IIS server instead. This requires a bit of configuration but it is very simple; see How to: Configure a Server to Host LightSwitch-Based Applications on MSDN for the details if you aren’t planning to use Windows Azure.
What you’ll need
- A copy of Visual Studio 2012 Professional or better. Make sure to tick the box to install LightSwitch when you install Visual Studio 2012 (or modify your existing installation via Control Panel)
- Visual Studio 2012 Update 2. This update adds the latest features to LightSwitch which you can read about at Visual Studio LightSwitch Team Blog: A New User Experience. You will need this update to accomplish some of the tasks in this series.
- A little bit of knowledge in C#, but not too much.
- No ASP.NET or IIS web development skills are needed!. I’ll walk you through it from scratch.
- If you plan to use Windows Azure, you’ll also need a Windows Azure account. If you don’t have one, head on over to Windows Azure and create one. At this time, 90-day free trials are available which include more than enough free resources to get going.
Once you have everything in place, proceed on to the next section!
Provision a web site and database
Go to your Windows Azure Portal, sign in if needed, then follow these steps to provision a web site and database to use for your gaming network:
- Click New -> Compute -> Web Site -> Custom Create (Figure 1) (note, if you don’t want a web-based user interface you can choose Cloud Service instead which gives greater flexibility over scaling, however the setup instructions will be different to those below)
- Enter a URL for your web site (Figure 2); I’ve used gamenetwork here. If you want to map a custom domain to your Windows Azure web site, you have to upgrade to a paid service subscription so we’ll just use the azurewebsites.net domain for now.
- Select the region closest to you.
- Choose Create a new SQL database (note, not a MySQL database; this is also an option but is not compatible with LightSwitch).
- Leave the rest of the settings at their defaults and move to the next page.
- Enter a name for the database (Figure 3). Again I’ve gone with gamenetwork. Choose New SQL database server from the drop-down list, enter an administrator username and password, leave the rest of the settings at their defaults and click the tick box to finish.
Your web site and database will now be created. This may take a few minutes; you can check the progress on your portal home page.
Allow your development PC to connect to the database through the Windows Azure server’s firewall
Failure to enable firewall access to the database from the machine on which you are developing your LightSwitch application will cause an error like this when you try to publish:
4>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\LightSwitch\v3.0\Publish\v1.8\Microsoft.LightSwitch.Publish.targets(1435,9): error : An exception occurred when deploying the database for the application.
4>Cannot open server ‘***********’ requested by the login. Client with IP address ‘**.***.***.*’ is not allowed to access the server. To enable access, use the SQL Azure Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.
You can enable access as follows:
- Go to your Windows Azure Portal and choose SQL Databases in the left-hand pane
- Click on your database
- Click the Dashboard tab at the top
- Click Manage allowed IP addresses in the quick glance pane on the right
- Your PC’s external IP address will be shown in the allowed IP addresses section. Click the arrow to add it to the list of allowed IP addresses. If you want to add a different IP address, use the edit boxes below this to add allowed ranges as you wish.
- Click Save in the command bar at the bottom when you are finished
Create a LightSwitch Project
Open Visual Studio and create a new LightSwitch HTML Application (Visual C#) project from the File -> New -> Project… menu. I called mine GameNetwork. The project may take a few minutes to create if it’s the first time you have made a LightSwitch application.
You should now see something like the display in Figure 4 in Solution Explorer.
Understanding the organization of a LightSwitch application
Full-blown LightSwitch applications are split into 3 tiers:
Server-side data storage – this is where all the data is stored, in a database on the server. LightSwitch applications use Microsoft SQL Server for this as we mentioned earlier. Each set of data goes in a database table as you probably know already, and tables are created under the Server folder in Solution Explorer for a LightSwitch project.
Middle-tier (business logic) – all of the queries and updates to the database are handled here. The data is validated and processed, any special so-called business rules you have created are applied and so on. By way of example, a business rule could be as simple as, don’t let the user submit a high score lower than zero, so don’t be scared by the terminology. LightSwitch will allow you to use a whole host of pre-made business rules (including validation rules) without writing any code, and if you do want to add special rules, you can insert code as we shall see later.
The middle tier also exposes the functionality of your application programmatically across the world wide web via a protocol called OData. This is crucial for us, as our games need to be able to send and receive data from the LightSwitch application remotely, and we will use OData to accomplish this. Note that OData is an open standard, so you do not need to be using any particular language or development environment for your game to take advantage of it.
Presentation tier – this is the HTML (or Silverlight) client. It can also be our client application (ie. game) itself, but as far as the LightSwitch project is concerned, it is the HTML or Silverlight client. The user interface of a LightSwitch application is realized as a series of Screens, which are simply forms on a web page that the user can fill out to query or change data in the database. Screens are added under the HTMLClient (or DesktopClient for a Silverlight application) in Solution Explorer.
To summarize, Tables store all of the data of the application on the server, and Screens provide browseable or editable views of this data in the web browser. OData is a protocol which allows us to bypass the Screens and access the Tables in our project programmatically from another application (our games).
Create a home screen
- Right-click the HTMLClient folder and choose Add Screen… from the menu.
- Choose Browse Data Screen from the left-hand pane and change the screen name to Welcome on the right. Click OK to create the screen.
Since this is the first screen you created, it is automatically set as the home screen, which is the screen that will be displayed when you browse to the application’s home page on the web. We don’t really care about the web-based interface right now as we are going to mainly use the application to manage data remotely, so we just leave it blank. Note that Visual Studio shows the layout of the screen as a tree rather than how it will actually appear in the running application (see Figure 5).
Set up authentication
Later when we add sensitive data like user’s names, email addresses and passwords, we don’t want people snooping around in it – only authenticated users (ie. logged in users) should be able to access the application (we can further define which parts of the data each individual user can access later).
- Right-click your project in Solution Explorer and choose Properties…
- Choose Access Control from the left-hand pane (Figure 6)
- Choose Use Forms authentication from the main window
- Close the properties window
Forms authentication is a method of access control which maintains a list of usernames and passwords in a database, and only allows the application to be accessed once a user has logged on with one of these.
Technical side note: forms authentication uses HTTP Basic authentication on an HTML client; the data is stored as ASP.NET users in the database using the standard ASP.NET Membership Provider model (don’t worry if you don’t understand this)
Relaxing the password complexity requirements
By default, all passwords in a LightSwitch application must have at least 8 characters including 1 non-alphanumeric character (ie. one symbol or item of punctuation). This catches a lot of people out. If you want to simplify the requirements, you can edit Web.config in the project as follows:
- In Solution Explorer, click the View icon drop-down and choose File View. You’ll see something similar to Figure 7.
- Double-click on Web.config. Its XML code appears in the code editor.
- Find this line:
<add name="AspNetMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="_IntrinsicData" applicationName="GameNetwork" requiresUniqueEmail="false" requiresQuestionAndAnswer="false" />
- Edit the tags at the end to change the requirements as you wish. For example, to remove the requirement that at least one non-alphanumeric character is included in the password, change the line to:
<add name="AspNetMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="_IntrinsicData" applicationName="GameNetwork" requiresUniqueEmail="false" requiresQuestionAndAnswer="false" minRequiredNonalphanumericCharacters="0" />
minRequiredPasswordLength attribute can be changed to adjust the minimum password length. The full list of allowed attributes can be found in the class properties list at MembershipProvider Class on MSDN.
Publish the application
- Change the solution build configuration from Debug to Release in the toolbar drop-down near the top of the Visual Studio window. Don’t deploy Debug builds of your project to a live web server that is accessible via the internet.
- Choose Publish GameNetwork from Visual Studio’s Build menu, or right-click the project in Solution Explorer and choose Publish…. Since this is the first time we are publishing the project, we have to configure quite a few options. On subsequent publishes, the settings are remembered and you just need to click Publish to confirm.
- Choose Complete application and click Next (if you don’t want any web-based interface at all, you can choose Web service only instead, but we are going to use the web-based interface for administration later so we choose to publish everything at this time).
- Choose the appropriate server type (Windows Azure or IIS Server) and click Next. The following steps assume you are publishing to Windows Azure. Instructions for IIS will be different.
- You’ll now be asked to sign in and provide your Windows Azure subscription credentials. This is a file that you download to your PC from your Azure account and can then re-use in all future LightSwitch projects. Download your publishing profile here. Follow the steps on the page and set the drop-down box to use the desired subscription, then click Next.
- Choose Web Site if you made an Azure web site, or Cloud Service if you made a cloud service (in our example we made a web site) and click Next.
- You will now be asked which web site to publish to. After a few moments the drop-down box should be populated with all the Windows Azure web sites you have created. Here I select gamenetwork to publish to the site we provisioned above. Choose the URL you want to publish to and click Next.
- Now choose a username, full name and password for the site administrator. This gal or guy will have permission to do everything, so make sure you choose a strong password. The password complexity will be subject to the settings in Web.config, which you may or may not have edited above.
- On the HTTPS tab of the same page, select No, HTTPS is not required for now. Note that you should use HTTPS (SSL) normally when communicating with the server from your game code to prevent MITM (man-in-the-middle) attacks where the transmissions are intercepted and repeated or modified by a 3rd party. However, this requires the creation of an SSL certificate, which is beyond the scope of this article. If you do happen to have an SSL certificate configured on your server, by all means select Yes, users must connect using HTTPS instead. Click Next when you’re done.
- Next you have to provide the connection string for the database. A Connection String describes how to connect to a database, typically including the server name, database name, login credentials etc. If you provisioned a database at the same time you provisioned the web site on Windows Azure, these strings will already be filled in for you. Otherwise, you can get it by going to the Windows Azure Portal, clicking on your web site, clicking the Dashboard tab and clicking View connection strings on the Quick glance pane on the right. Copy the connection string and paste it into both boxes in the publish wizard window. Then click Next.
- Finally, you’ll see a Summary (and on future publishes, this is the only window you’ll see). Check the details are correct and click Publish. The process of first-time publishing takes several minutes so feel free to grab a coffee at this point! (if you get an error about your client not being allowed access to the database server, see the section about firewall rules above)
Running the application
Go to the URL of your web site and append /HTMLClient/ to launch the LightSwitch application, for example in the example above you would browse to http://gamenetwork.azurewebsites.net/HTMLClient/. If all is well, you should be presented with a log in screen. This is the screen that all users will see if they visit the site without being logged in. Enter the administrator username and password you created in step 8 above and after the login completes you should see a blank page with the word Welcome at the top left and a logout icon at the top-right.
If you have reached this stage, congratulations! You now have a server-secure, application-secure 3-tier database and logic infrastructure deployed. There’s not much to show for it yet though, but “all” that’s left now is to plug in the data.
In Part 2, we’ll look at the first task of any online connected game: allowing the players to create their user accounts. Until next time!