Export (0) Print
Expand All

Walkthrough: Publishing an F#/C# MVC Application to Windows Azure

Visual Studio 2012

In this walkthrough and its accompanying sample, you’ll use C# and F# to start developing web applications and cloud services that are hosted in Windows Azure. By following this walkthrough, you’ll get a web application, the WordGrid sample, running in Windows Azure as a cloud service. You can use that sample to explore how to integrate F# with a C# web application and, in general, how to use the power of F# in Windows Azure. The sample uses the ASP.NET Model View Controller (MVC) 4 framework, which provides a powerful and versatile library for web applications. By using this framework, you can separate the application’s layout and UI (the "View" in MVC) from its program logic (the "Model"). MVC applications also include controllers that handle and route incoming requests. For each request, the controllers determine which view to render with which model.

When you write a web application in F#, it’s helpful to use C# for the part of the application that depends on MVC because the framework supports C# by design. By using the Razor engine for the views, you can write C# code to control the view layout. The Razor engine is the newer of two rendering engines that are available in ASP.NET, and this engine offers more flexibility than the the Web Forms engine. This sample shows two ways to integrate F# into a C# web application. Windows Azure cloud services contain one or more roles. This sample includes web roles, which provide the web pages that make up the web application, and worker roles, which have no user interface but perform background processing. This sample uses an F# worker role and an F# library in a C# web role.

The WordGrid sample is a turn-based crossword game that users can play over the Internet. The application is a cloud service that uses a web role (written in C#) to display the game board as a web page and an F# library to handle the game logic. An F# worker role provides dictionary lookup services. The worker role and the web role communicate by using Windows Azure queues, which provide a lightweight message-passing mechanism that you can use to communicate between roles in a cloud service. The web role uses the SimpleMembership database to manage users, and the same database also contains game data. Users can start games with any other user and play multiple games simultaneously. A view page provides the game board layout and UI elements, and JavaScript functions define logic during play, including HTML dragging, scoring and validation, and tile management.

You’ll also learn how to migrate a local SQL Server database to a database that's hosted in Windows Azure. This migration is often the most complicated part of getting a cloud service running in Windows Azure.

This walkthrough depends on the following prerequisites:

The WordGrid sample is an implementation of a popular type of word game. When the game is played, it resembles the following illustration:

WordGrid Sample

The following illustration shows the architecture of the WordGrid sample.

WordGrid App Architecture

The MVC application contains controllers, views, and models, but it also contains JavaScript code that handles game play in the client’s web browser and CSS style sheets that determine the colors, fonts, and details of the layout. The application also includes MVC infrastructure, such as the contents of the App_Start folder. These files are unchanged from the Internet application template for MVC web roles. Unless specifically mentioned in this section, files are unchanged from the template.

The parts of the app that are closest to the user interface and the MVC-specific technologies are written in C#. The game logic layer, WordGridGame, is written in F# and is referenced as a library from the MVC portion of the app. Another F# library, FsAzureHelper, provides F#-friendly wrappers for Windows Azure APIs.

Controllers handle incoming HTTP requests, determine which page to display, and respond to URL parameters and values that users submit in forms. In the WordGrid app, the controllers are divided into three files: AccountController.cs, BoardController.cs, and HomeController.cs. The controllers are written in C#. AccountController.cs and HomeController.cs are included when you create a web role and then choose the Internet Application template. They have been customized slightly for the WordGrid app. BoardController.cs contains all the WordGrid-specific logic and handles requests that occur when users set up and play the game.

The views control the layout of the web pages. Views contain HTML and embedded C# code that creates more HTML that’s based on application logic. The board that’s in memory for the WordGrid game is used to generate an HTML table. You can find this code in the Play.cshtml view. In the Shared folder, you’ll find layouts that are common to many pages. These contain sections that are filled in by the more specific pages. In this way, you can ensure that your pages have a common header and navigation.

The models represent the objects that are behind the pages. In the WordGrid game, the model layer is in C# and forms a layer between the UI and the game logic in the F# WordGrid project.

JavaScript on the client handles client-side behavior, such as tile management and placement, in addition to validation and scoring of plays.

The game logic for WordGrid is in the WordGrid project, in the WordGrid.fs code file. This code uses type providers to interact with the database.

When you download the WordGrid sample, it uses a LocalDB database in an .mdf file in the App_Data folder of the project for the web role. Connection strings for this database appear in two web.config files: one in the WordGrid project and the other in the project for the web role.

By default, the WordGrid sample’s word validation code is disabled because the sample doesn’t include a dictionary. To play the WordGrid game and verify whether a word is valid, you must hook up a dictionary, which can be a text file, with each valid word listed on a separate line. You can easily find a variety of such dictionaries online, with varying licensing restrictions. If you have Microsoft Office installed, you can also configure WordGrid to use the spell checker in Word as a dictionary. To set up either dictionary option, see instructions in code comments in the file WorkerRole.fs.

To Build, Test, and Deploy the Sample in the Compute Emulator

  1. In Visual Studio, open a Windows Azure solution, and then choose the F5 key.

    As an alternative, you can, on menu bar, choose Debug, Start Debugging.

    The solution starts in the compute emulator, and the WordGrid logon page appears in your browser.

  2. Choose the Register link, and then enter a username and password.

    To test the sample, you’ll need to create a second user to play a game.

  3. Choose the Log Out link to log the first user out, and then repeat step 2 to create a username for the second player.

  4. Choose the New Game link, and then choose the other player from the list of possible opponents.

    A game starts and shows on the screen.

  5. Place tiles on the board to make a valid word, and then choose the Submit Play button.

    If you’re playing both players, choose the browser’s Back button to return to the logon page, and then log out and log on again as the other user to continue play.

  6. To monitor the status of your local deployment in the compute emulator, choose the Windows Azure Emulator icon in the task bar, and then choose Show Compute Emulator UI.

  7. Under Service Deployments, expand the node for WordGrid, and then choose an instance of MvcWebRole1.

    The logs appear in real-time for each instance. For more information about the compute emulator and other tools that are available on the local machine, see Windows Azure SDK Tools.

To set up a Storage Account

  1. Log on to the Windows Azure Management Portal, and then choose the New button.

  2. On the menu that appears, choose Data Services, Storage, Quick Create, and then enter a name for the storage account.

    The name of the storage account must contain only lowercase alphanumeric characters without spaces or special characters. The URL for the account will be mystorageaccountname.core.windows.net.

  3. In the list of regions or affinity groups, choose the one that's closest to you, and then select the Enable Geo-Replication check box.

    At no additional cost, this option stores your data in more than one redundant physical location within the same region.

  4. Choose the Create Storage Account link to finalize your settings and create the storage account.

    In Visual Studio, you can now set up the WordGrid project to use the newly created storage account when you deploy the project to Windows Azure.

  5. In the Windows Azure project, open the shortcut menu for MvcWebRole1, and then choose Properties.

    The role designer appears.

  6. Choose the Settings page, and then, in the Service Configuration list, choose Cloud.

    If you choose the Cloud service configuration, you can use a connection string for your storage account when you deploy to Windows Azure but still use the compute emulator when you are running and debugging on your local machine.

  7. Choose the button next to the StorageConnectionString item in the data grid.

    The Create Storage Connection String dialog box appears.

  8. Under Connect using, choose the My subscription option button.

  9. If you’ve never downloaded a .publishsettings file before for your Windows Azure subscription, choose the Download Publish Settings link, and then log on to the Management Portal.

    A .publishsettings file is downloaded. This file contains your subscription and storage account credentials, which should appear in the dialog box.

  10. In the list of storage accounts, choose the one that you want to use for the WordGrid sample, and then choose the OK button.

Migrate the Database to Windows Azure

  1. If you haven’t created a database, choose the New button in the Windows Azure Management Portal, and then, on the menu that appears, choose Database Services, SQL Database, Quick Create.

    A database is created so that you can connect to a database server. You won’t be using the database because you’ll create another one when you import the WordGrid data. If you already have a database server, you can skip this step

  2. Create a username and password as prompted.

    You’ll use this username and password in the database connection string.

  3. Choose the Allow the connection in firewall rules link.

    The Allowed IP Addresses page appears. On this page, you can set the firewall to allow ingoing connections to the database server.

  4. Perform one of the following steps:

    • If your development computer uses a dynamic IP address, find out the range of addresses that your computer uses, and then enter these values in the Start IP Address and End IP Address text boxes.

      If you don’t know your IP address range, contact your network administrator.

    • If your development computer has a static IP address, enter it in both the Start IP Address text box and the End IP Address text box.

  5. Under Allowed Services, make sure that the Windows Azure Services element is set to Yes.

  6. Open SQL Server Management Studio

    You must transfer the local database to Windows Azure. The local database is included as an .mdf file in the App_Data subfolder of the MvcWebRole1 project.

    Connect to the LocalDB server for Visual Studio 2012, (localdb)\v11.0.

  7. Open the local WordGrid database.

    Its name begins with "aspnet-MvcWebRole1." If multiple databases have similar names, make sure that the database matches the .mdf filename in the WordGrid MvcWebRole1 project.

  8. Open the shortcut menu for the local WordGrid database node, choose Tasks, choose Deploy Database to SQL Azure, and then choose Next.

  9. On the Deployment Settings page, choose the Connect button.

  10. In the Server name box, enter the address of the database server that you created in step 1.

    For example, enter servername.database.windows.net.

  11. Enter the username and password that you created in step 1.

    Note Note

    If you created other database users, don’t use those credentials here unless they have permissions to create a database on the server.

  12. In the New database name text box, enter wordgrid as the name of the new database, and then choose the Next button.

    A page that summarizes the proposed database deployment appears.

  13. Verify that all the information is correct, and then choose the Finish button.

    The database is created on the server, with all the schema and data copied from the local database.

  14. Open the Management Portal, choose the New button, and then, on the menu that appears, choose Database Services, SQL Database, Import.

  15. Specify wordgrid as the database name, and then choose or create a server.

    A database is created and added to the list of resources that are available with your subscription.

  16. In the list of resources, choose the database that you just created.

    The page for the database appears.

  17. (optional) Windows Azure SQL Database does not support Windows Authentication. Therefore, you must use SQL Server usernames and passwords. You can use the username and password that you created in step 1, but that user also has access to other databases on the same server. If you want to restrict access, you can create a username and password only for the wordgrid database. These credentials can differ from the username and password for the database server. To create credentials that have restricted access, follow these steps:

    1. Choose the Manage button, and then enter the username and password for the database server that you created in step 1.

    2. Choose the Select Database button, and then choose master from the list of databases.

    3. Choose the New Query button, and then enter the following SQL code, with a newly created username and password:

      CREATE LOGIN loginname WITH PASSWORD='myPassword'
      

      You can now create a database user for this login to grant access to the wordgrid database.

    4. Choose the button that shows the database to which you are connected (currently master).

    5. In the choices that appear, choose the wordgrid database that you just imported, choose the New Query button, and then enter the following code:

      CREATE USER username FOR LOGIN loginname
      
    6. Choose the Run button, and then close the tab.

  18. On the page for the wordgrid database, choose the Show Connection Strings link, and then copy the ADO.NET connection string to the Clipboard.

    Paste the connection string into the top-level web.config file in the MVC project, as the following code shows.

    <connectionStrings>
        <add name="DefaultConnection" connectionString="<Paste here>" providerName="System.Data.SqlClient" />
        </connectionStrings>
    

    You can leave the connection string unchanged in the web.config file in the WordGrid F# project. That string is used only for the F# type provider at compile time.

  19. Choose the F5 key to build and debug the app in the compute emulator, which is now using Windows Azure SQL Database instead of your LocalDB database.

    For more information about LocalDB, see SQL Server 2012 Express LocalDB. For more information about databases in Windows Azure, see Windows Azure SQL Database.

Publish the Application as a Cloud Service

  1. Open the shortcut menu for the Windows Azure project, and then choose Publish.

    The Publish Windows Azure Application Wizard appears.

  2. If you haven't run the Publish Windows Azure Application Wizard before and you have not yet downloaded a .publishsettings file, choose the Sign In to Download Credentials link on the Sign In page, and then enter your credentials.

    A .publishsettings file is downloaded.

  3. Choose the Import button to populate the subscription list.

  4. In the Choose your subscription list, choose the subscription to use for this deployment.

    You can now publish the application or modify any setting for this deployment.

  5. Choose the Next button.

    The Settings page appears.

  6. In the Environment list, choose Staging.

  7. In the Build Configuration list, choose Debug.

    The staging environment is a deployment location that is fully accessible on the Internet, except that instead of publishing the cloud service to a public URL, the service is published to a URL that contains a computer-generated string of characters. This environment is useful for testing and verification prior to final publishing. When you want to promote your cloud service in the staging environment to your public URL, you can swap the staging environment for the production environment.

  8. Choose the Advanced Settings tab, and in the Storage Account list, choose the storage account that you created. Also, make sure that the Enable IntelliTrace check box is selected.

  9. Choose Next, review the settings, and then choose Publish when you are ready to deploy the application as a cloud service.

    Use the Windows Azure Activity Log window in Visual Studio to monitor the progress of the deployment.

    For more information about how to publish a cloud service, see Publishing a Windows Azure Application from Visual Studio.

Use IntelliTrace Logs to Debug the Application

  1. In Server Explorer, open the shortcut menu for the Windows Azure Compute node, and then choose Add Deployment Environment….

    The Add Deployment Environment dialog box appears.

  2. Under Choose a Deployment Environment, expand the node for your subscription, expand the node for the WordGrid cloud service, choose the WordGrid - Staging deployment environment. and then choose the OK button.

  3. In Server Explorer, expand the MvcWebRole1 role, open the shortcut menu for the Instance 0 node, and then choose View IntelliTrace logs.

    The progress of this action appears in the Windows Azure Activity Log window. After some time, the logs open in Visual Studio. A list of exceptions, threads, requests, and other information about this instance appears. You can also reconstruct the state of a thread in the Visual Studio debugger. Note that the IntelliTrace debug session is quite limited compared to debugging locally, so the best practice is to do as much debugging in the compute emulator before you deploy your application. For more information, see Debugging a Published Hosted Service with IntelliTrace and Visual Studio.

For an overview of the code for the WordGrid game, see Walkthrough: Creating an Internet Game with F#, C#, and Windows Azure.

Show:
© 2014 Microsoft