DotNetCurry Logo

Using Windows Azure Mobile Services in ASP.NET MVC

Posted by: Mahesh Sabnis , on 2/22/2015, in Category ASP.NET MVC
Views: 19370
Abstract: Explore the use of Windows Azure Mobile Services in an ASP.NET MVC application.

Windows Azure provides various features like Cloud Services, Sql Azure, Web Sites, Virtual Machine, Mobile Services, etc. Each of these features has its own advantages. In this article we will explore the use of Windows Azure Mobile Services in an ASP.NET MVC application.

Windows Azure mobile services are designed to develop highly functional mobile apps. These are designed for enabling back-end capabilities for the application. Mobile Services provides various features and some of them are as follows:

  • Easy management of tables for storing data of Apps
  • Support for push notifications
  • Notification services integration used for PUSH notifications

Windows Azure mobile services client libraries can be used in Windows Store Apps, Windows Phone, HTML, iOS and Android. Since Mobile Services client libraries are available across various device platforms, we can develop applications which can be used by a large number of end-users. The feature of data store using tables in Mobile services can be used to save data by one client and made available to other clients.

 

In this application we will be creating Mobile Service for Storing Appointment for the user. The Mobile Service will create the Appointment table and will help to store appointments by using MVC client application.

To create a Mobile service we need a Windows Azure subscription. Please visit to http://azure.microsoft.com/en-us/ and create a free trial subscription.

Step 1: Open the Windows Azure Portal using http://manage.windowsazure.com. Log in with your subscription credentials. On the portal, select Mobile Services. In the lower left section of the portal, select New and create Mobile Service with the following option:

create-mobile-service

On clicking on Create, the following window will be displayed where we need to enter some information about the Mobile Service:

portal_createserv

The options for database in the Dropdown are Create a new SQL instance and use the Existing Database. The BACKEND dropdown has the following options for runtime:

azure-backend-options

These options generate APIs for performing operation on the backend table data. After entering Mobile Service details, click on the Next arrow and specify the Database Settings as shown in the following figure:

azure-db-settings

After entering the necessary information, click on the OK (tick sign) and the Mobile Service will be created as shown in the following figure:

portal_mob_service_created

Step 2: Once the Mobile service is created, click on it and the following page will get displayed:

mobile-service-details

This page provides information about the platform for consuming the Mobile service. We have options like Windows, iOS, Android, HTML/JavaScript, etc. The portal provides a ready App for guiding us through the use of Mobile Services. On the top of the page, we have options to create DATA Store Table, Scheduler, PUSH configuration, the Host configuration, etc.

Step 3: To create a Data Table, click on DATA. This will show the Page which contains List of tables for the Mobile Service. Click on Create at the bottom of the page and the Create New Table window will be displayed. In this window, Enter Table information as shown in the following figure:

create-new-table

Create an Appointments table. Here we need to define permissions for performing CRUD operations on the table.

Step 4: Once the table is created, click on the table name. A new page will be displayed with options such as BROWSE, SCRIPT COLUMNS and PERMISSIONS. Click on the COLUMNS option to view the default columns of the table as shown in the following figure:

default-coumns

To add new columns, click on the Add Column link at the bottom of the page. The Add Column dialog gets displayed:

create-column

For the table, create the following columns:

  • Persontomeet
  • Meetinglocation
  • Meetingdate
  • Meetingstatus
  • Createdby
  • Description

The final definition of the table will be as follows:

table-definition

Creating ASP.NET MVC Client Application for Windows Azure Mobile Services

In this section, we will develop an ASP.NET MVC 5 client for consuming Mobile Service. This client will make use of the Mobile Service URL and the associated key to perform Operations with Mobile Service.

Step 1: Open Visual Studio 2013 and create a new ASP.NET MVC application. Make sure that you select the MVC project which will provide ready controllers for Account, used for Authentication.

Step 2: In the controller’s folder, add a new AppointmentsController with the Index method implemented as follows:

[Authorize]
public ActionResult Index()
{
    //var uSplit = User.Identity.Name.Split('@');
    ViewBag.UserName = User.Identity.Name;
    return View();
}

The Index Action method is applied with the [Authorize] filter, this means that the end-user must log-In before accessing Appoint Index View.

Step 3: Run the application and create two users for the application using Register View under AccountsController. The current application uses ‘user1@user.com’ and ‘user2@user.com’.

Step 4: In this MVC project using NuGet package manager add references to the latest jQuery, knockout library and bootstrap 3.3.2 library.

Step 5: Scaffold an empty Index view form the Index action method of the AppointmentsController.

Step 6: In the Index.cshtml, add the following code:

<html>
<head>
    <title>The Mobile Servive App</title>
    <style type="text/css">
        table, td {
          border:double;
        }
        .c1{
            width:200px;
        }
        #dvappointments {
         height:400px;
         width:1000px;
         overflow:visible;
        }
    </style>


    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/themes/base/all.css" rel="stylesheet" />
    <link href="~/Content/Site.css" rel="stylesheet" />

    <script src="http://ajax.aspnetcdn.com/ajax/mobileservices/MobileServices.Web-1.2.5.min.js"></script>

   

</head>
<body>
    <form class="form-horizontal" role="form">
        <h1>The Meeting Planner</h1>
        <div>
                 <div>
            <table>
                <tr>
                        <td>
                            <label for="persontomeet" class="control-label">Person To Meet</label>
                        </td>
                        <td>
                            <input type="text" id="persontomeet" class="form-control c1" 
                                    data-bind="value:PersonToMeet"/>
                        </td>
                </tr>
                <tr>
                        <td>
                            <label for="meetinglocation" class="control-label">Meeting Location</label>
                        </td>
                        <td>
                            <input type="text" id="meetinglocation" class="form-control c1"
                                   data-bind="value:MeetingLocation" />
                        </td>

                </tr>
                <tr>
                        <td>
                            <label for="meetingdate" class="control-label">Meeting Date</label>
                        </td>
                        <td>

                            <div class="controls">
                                <input id="meetingdate" type="text"
                                       class="date-picker form-control c1"
                                       data-bind="value:MeetingDate" />
                            </div>

                        </td>
                </tr>
                <tr>
                    <td>
                        <label for="lstmeetststus">Meeting For</label>
                    </td>
                    <td>
                        <select id="lstmeetststus" class="form-control c1"
                                data-bind="options:MeetingType,optionsCaption:'Select Meeting Type',value:SelectedMeetingType"></select>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="description">Meeting For</label>
                    </td>
                    <td>
                        <textarea id="description" class="form-control c1"
                                  data-bind="value:Description"></textarea>
                    </td>
                </tr>
            </table>
        </div>        </div>
        <input type="button" id="btnsave" value="Save" class="btn btn-primary"
               data-bind="click:$root.save" />
        <div id="dvappointments">
            <table>
                <thead>
                    <tr>
                        <td>Person To Meet</td>
                        <td>Person Location</td>
                        <td>Meeting Date</td>
                        <td>Purpose</td>    
                        <td>Description</td>
                    </tr>
                </thead>
                <tbody data-bind="foreach:Appointments">
                    <tr>
                        <td>
                            <span data-bind="text:persontomeet"></span>
                        </td>
                        <td>
                            <span data-bind="text:meetinglocation"></span>
                        </td>
                        <td>
                            <span data-bind="text:meetingdate"></span>
                        </td>
                        <td>
                            <span data-bind="text:meetingstatus"></span>
                        </td>   
                        <td>
                            <span data-bind="text:description"></span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </form>
     


    <script src="~/Scripts/jquery-2.1.3.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.11.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/knockout-3.2.0.js"></script>

    <script type="text/javascript">
        //The variable used to read the current login user

        var user = '@ViewBag.UserName';

         $(document).ready(function () {
             //Set the Style for data
            $(".date-picker").datepicker({ minDate: 0, maxDate: "+1M +10D" });
         });


         var appointmentVM = function () {
             //The mobile service client object
             var client = new WindowsAzure.MobileServiceClient(
                   "https://appointmentserv.azure-mobile.net/",
                 "<Your key here>");
             //The Mobile Service Table object
             var appointmentTable = client.getTable("Appointments");

             //Observables for Accessing data from end-user
             var self = this;
             self.PersonToMeet = ko.observable("");
             self.MeetingLocation = ko.observable("");
             self.MeetingDate = ko.observable();
             self.MeetingStatus = ko.observable();
             self.Description = ko.observable("");

             self.Appointments = ko.observableArray([]);

             self.MeetingType = ko.observableArray(["Official", "Personal"]);

             self.SelMeetingType = ko.observable();
             self.SelectedMeetingType = ko.observable();

             //Logic to Select the Meeting status
             self.SelectedMeetingType.subscribe(function (text) {
                 if (text !== 'undefined') {
                     self.SelectedMeetingType(text);
                 }
             });

             //Function to Save Appointment 
             self.save = function () {

                 var appointment = {
                    persontomeet: self.PersonToMeet(),
                      meetinglocation: self.MeetingLocation(),
                     meetingdate: self.MeetingDate(),
                      meetingstatus: self.SelectedMeetingType(),
                      createdby: user,
                      description: self.Description()
                 };
                 //Insert the Appoint Information
                 appointmentTable.insert(appointment).done(function (res) {
                     getMeetings();
                 }, function (err) {
                     alert("Error " + err.request + "   " + err.request.status);
                 });
             };



             getMeetings();

             //Function to Get All Appointments for the login user
             function getMeetings() {
                 var query = appointmentTable.where({createdby:user});

                 query.read().done(function (appointments) {
                     self.Appointments(appointments);
                 }, function (err) {
                     alert("Error " + err.request + "   " + err.request.status);
                 });
             };
         };
            ko.applyBindings(new appointmentVM());

    </script>


</body>
</html>

The above code performs the following operations:

  • The knockout ViewModel, appointmentVM creates a client object of the Mobile service based on the URL and the access key associated with it.
  • The, <script src="http://ajax.aspnetcdn.com/ajax/mobileservices/MobileServices.Web-1.2.5.min.js"></script> provides access to the MobileServiceClient object. Using getTable() function of this object, we can access references of the Mobile Service Table; in our case Appointment.
  • The code defines observables for data-binding with the HTML UI. Using these observables, we can access data entered by the end-user.
  • The save() function contains code for inserting the appointment data entered by the end-user. This function calls insert() function of the MobileServiceClient to insert data in the table.
  • The getMeetings() function queries the Table and receives data for a current login user.

Run the application, Login with the credentials (user1@user.com) and the following page will get displayed.

meeting-planner

Enter Appointment details. After clicking the Save button, you should see the following appointment details:

appointment-details

The Table in the above figure displays only appoints saved by the current logged in user.

The inserted data can be viewed in the portal for the Appointments table:

appointments

This is the MVC client application, in short a web application used by the end-user to save his appointments information using Mobile Services on the cloud. The advantages of this approach are the same. The end-user can access his appointments information from any device having the client-application on it, and by consuming the same mobile service. Mobile services provide client-libraries to build application on any client-device.

Deploying the MVC Client Application

The Mobile service by default is accessible to the localhost, but what if we want to deploy the current MVC application on the cloud using a Web Site? In that case it will have a different domain. This must be configured in the Cross-Origin resource sharing configuration section of the Mobile service.

Deploy the MVC application. If you haven’t deployed an MVC application to the cloud, here’s a step-by-step getting started guide for you - Deploying ASP.NET MVC Web Site on Windows Azure. In the portal, open the AppointmentServ mobile service by double clicking on it. Open the Configure Tab and locate the Cross-Origin resource sharing (cors). Provide the host name. For e.g. as *. azurewebsites.net cloudapp.net:

cors

Browse the website and try to register an appointment. See you at cloud 9!

Conclusion: Windows Azure Mobile is a great feature for developing applications which can be accessible across all devices and application. This can be used for building highly personalized applications e.g. Appointment Management, Task Scheduler, etc.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!