European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET MVC 4 Mobile Tutorial - Part III

clock October 8, 2012 07:07 by author Scott

This final post will discuss the final piece; the UI and how it all comes together.

The User Interface

The default project uses the
jQuery mobile plugin to target mobile devices. The jQuery mobile plugin is touch-optimized for smartphones and tablets and it targets iOS, Android, Blackberry, Bada, Windows Phone, Palm WebOS, Symbian and MeeGo.

Lets start with the JavaScript logic, which will perform the interaction between the HTML UI and the JSON web service.


1. In the Scripts folder, add a folder called com then mobile underneath that and finally babyfeeding underneath that


2. In the final babyfeeding folder, add a JavaScript file and called it proxy.js


3. Copy and paste the following code into the js file


if
(mobile == undefined) var mobile;
if
(!mobile) mobile = {};

//Constructor

mobile.Proxy = function (siteBaseUrl) {

    // constructor
    mobile.Proxy.prototype.baseUrl = siteBaseUrl;
    mobile.Proxy.prototype.heartBeatUrl = siteBaseUrl + "/Services/BabyMonitorService.svc/HeartBeat";
    mobile.Proxy.prototype.FeeedingUrl = siteBaseUrl + "/Services/BabyMonitorService.svc/AddFeedingEntry"
    mobile.Proxy.prototype.DiaperingUrl = siteBaseUrl + "/Services/BabyMonitorService.svc/AddDiaperingEntry"
}


mobile.Proxy.prototype = {

    CallWebService: function (url, input, successCallBack, errorCallBack) {
        //Uncomment the next line to support JSONP
        //url = url + "?callback=?";      
        $.ajax({
            async: false,
            cache: false,
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: url,
            dataType: "json",
            data: input,
            success: successCallBack,
            error: errorCallBack
        });

    },

    HeartBeat: function (successFunction, failFunction) {
        this.CallWebService(this.heartBeatUrl, "", successFunction, failFunction);
    },
    AddFeeding: function (UserId, FeedType, FeedAmount, successFunction, failFunction) {
        var input = "UserId=" + UserId + "&FeedType=" + FeedType + "&FeedAmount=" + FeedAmount;
        this.CallWebService(this.FeeedingUrl, input, successFunction, failFunction);
    },
    AddDiapering: function (UserId, DiaperType, successFunction, failFunction) {
        var input = "UserId=" + UserId + "&DiaperType=" + DiaperType;
        this.CallWebService(this.DiaperingUrl, input, successFunction, failFunction);
    }
};


4. The JavaScript is structured using objects and namespaces. Every JavaScript object contains an inner class called Prototype. By defining methods on this inner class, we can encapsulate object variables and methods and share them across concrete instances of the class. In the code above, the Proxy object defines the following methods:


- CallWebService - helper method for invoking the JSON service

- HearBeat - invokes the Heat method call for diagnostics
- AddFeeding - creates a feed entry by taking input from the form and invoking the web service
- AddDiapering - creates an entry for a diaper change by taking input from the form and invoking the web service

Finally, we encapsulate the Proxy object inside the mobile object to create a namespace so that the proxy object can be referenced like so: mobile.Proxy


The Index.cshtml View

Copy and paste the following code for the Index page


@{
    ViewBag.Title = "Baby Log Home";
}

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnSubmit").click(function () {

            $("#txtLastEntry").val("Last: ");

            // Create the proxt class
            var proxy = new mobile.Proxy("@Request.Url.GetLeftPart(UriPartial.Authority)");
            // Add the feeding entry
            if ($("#chkFeed").attr("checked") != undefined && $("#chkFeed").attr("checked") == "checked") {
                proxy.AddFeeding("@Membership.GetUser().UserName", $("#drpType").val(), $("#drpAmount").val(),
                    function (result) {
                        // succeeded
                        $("#txtLastEntry").val($("#txtLastEntry").val() + $("#drpAmount option:selected").text() +
                        " of " + $("#drpType option:selected").text());
                    },
                    function (jqXHR, textStatus, errorThrown) {
                        // failed
                        var err = "Details: " + textStatus;
                        if (errorThrown != undefined) {
                            err += "\rMore details : " + errorThrown;
                        }
                        alert(err);
                    });
            }
            // Add the diapering entry
            if ($("#chkDiaper").attr("checked") != undefined && $("#chkDiaper").attr("checked") == "checked") {
                proxy.AddDiapering("@Membership.GetUser().UserName",
$("#drpDiaper").val(),

                    function (result) {
                        // succeeded
                        $("#txtLastEntry").val($("#txtLastEntry").val() + ", " +
                        $("#drpDiaper option:selected").text() + " diaper");
                    },
                    function (jqXHR, textStatus, errorThrown) {
                        // failed
                        var err = "Details: " + textStatus;
                        if (errorThrown != undefined) {
                            err += "\rMore details : " + errorThrown;
                        }
                        alert(err);
                    });
            }
        });
    });
</script>
<div data-role="fieldcontain" data-inset="true">
    <fieldset data-role="controlgroup">
        <legend>Feed Details</legend>
        <input id='chkFeed' name='chkFeed-1' type="checkbox" checked="checked" class="custom" />
        <label for="chkFeed">

            Log Feed</label>
    </fieldset>
    <fieldset data-role="controlgroup">
        <legend>Feed Type:</legend>
        @Html.DropDownList("drpType", new List<SelectListItem> {
            new SelectListItem { Text="Bottle", Value="Bottle", Selected=true },
            new SelectListItem { Text="Left", Value="Left" },
            new SelectListItem { Text="Right", Value="Right" },
        })
    </fieldset>
    <fieldset data-role="controlgroup">
        <legend>Amount:</legend>
        @Html.DropDownList("drpAmount", new List<SelectListItem> {
            new SelectListItem { Text="0.5 oz.", Value="0_5" },
            new SelectListItem { Text="1.0 oz.", Value="1_0" },
            new SelectListItem { Text="1.5 oz.", Value="1_5" },
            new SelectListItem { Text="2.0 oz.", Value="2_0" },
            new SelectListItem { Text="2.5 oz.", Value="2_5", Selected=true },
            new SelectListItem { Text="3.0 oz.", Value="3_0" },
            new SelectListItem { Text="3.5 oz.", Value="3_5" },
            new SelectListItem { Text="4.0 oz.", Value="4_0" },
            new SelectListItem { Text="4.5 oz.", Value="4_5" },
            new SelectListItem { Text="5.0 oz.", Value="5_0" },
            new SelectListItem { Text="5.5 oz.", Value="5_5" },
            new SelectListItem { Text="6.0 oz.", Value="6_0" },
            new SelectListItem { Text="6.5 oz.", Value="6_5" },
            new SelectListItem { Text="7.0 oz.", Value="7_0" },
            new SelectListItem { Text="7.5 oz.", Value="7_5" },
            new SelectListItem { Text="8.0 oz.", Value="8_0" },
            new SelectListItem { Text="8.5 oz.", Value="8_5" },
            new SelectListItem { Text="9.0 oz.", Value="9_0" }
        })
    </fieldset>
</div>
<div data-role="fieldcontain" data-inset="true">
    <fieldset data-role="controlgroup">
        <legend>Diaper Details</legend>
        <input id='chkDiaper' name='chkDiaper-1' type="checkbox" class="custom" />
        <label for="chkDiaper">
            Log Diaper</label>
    </fieldset>
    <fieldset data-role="controlgroup">
        <legend>Diaper:</legend>
        @Html.DropDownList("drpDiaper", new List<SelectListItem> {
            new SelectListItem { Text="Wet", Value="wet", Selected=true },
            new SelectListItem { Text="Dirty", Value="dirty" },
            new SelectListItem { Text="Both", Value="both" }
        })
    </fieldset>
</div>
<div data-role="fieldcontain" data-inset="true">
    <input id="btnSubmit" type="submit" value="Submit" data-role="button" />
    <fieldset data-role="controlgroup">
        <input id="txtLastEntry" readonly="readonly" type="text" />
    </fieldset>
</div>


The HTML code builds the input form for entering the feed and diaper change details and the Javascript code collects the input, creates the proxy class and calls its methods to invoke the web service.

Notice how the @ tag is used to inject runtime variables, such as the logged on user and the base url.



 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET MVC 4 Mobile Tutorial - Part II

clock October 5, 2012 08:13 by author Scott

In the last post, we covered the database design and the Entity model for the sample ASP.Net MVC4 Mobile application. We will continue with the Service layer in this post.

The Service Layer

We will define some methods in our service class to enter data into our SQL log tables.


-
Right-click the project, select Add->New Folder and call it Services
-
Right-click the Services folder, select Add, New Item and click on WCF service. Name the service



- Update the system.serviceModel section in the web.config file so that it looks like the following


<
system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="customWebHttpBinding">
          <security mode="None"></security>
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="JSLearning.Services.BabyMonitorServiceBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="DebugBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="JSLearning.Services.BabyMonitorService" behaviorConfiguration="DebugBehavior">
        <endpoint address="" behaviorConfiguration="JSLearning.Services.BabyMonitorServiceBehavior" binding="webHttpBinding" contract="JSLearning.Services.IBabyMonitorService" bindingConfiguration="customWebHttpBinding" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel
>

- In the Services folder, add a ServiceBase class and then copy and paste the following code to it. The ServiceBase class provides useful methods for interacting with the data Entity Model

public
class ServiceBase
    {
        private BabyLogEntities _context = null;
        private string _connectionString = string.Empty;

        protected ServiceBase()
        {
            RenewContext();
        }

         protected ServiceBase(string connectionString) {
             _connectionString = connectionString;
             _context = new BabyLogEntities(_connectionString);
        }

        protected BabyLogEntities Context

        {
            get
            {
                return _context;
            }
        }

        protected void RenewContext()
        {
             if (_connectionString == string.Empty)
             {
                 _connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BabyLogEntities"].ConnectionString;
             }
             _context = new BabyLogEntities(_connectionString);
            return;
        }

    }

- Edit the BabyMonitorService.svc.cs file and have it inherit from ServiceBase.cs

public class BabyMonitorService : ServiceBase, IBabyMonitorService

- Copy and paste the following into your IBabyMonitorService.cs interface


[ServiceContract]

    public interface IBabyMonitorService
    {
        [OperationContract]
        [WebMethod]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string HeartBeat();

        [OperationContract]
        [WebMethod]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string AddFeedingEntry(string UserId, string FeedType, string FeedAmount);

        [OperationContract]
        [WebMethod]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string AddDiaperingEntry(string UserId, string DiaperType);
    }

- Here is an explanation of the public methods:

1. HeartBeat - is a simple contract to verify that the service is responding

2. AddFeedingEntry - is used to make an entry for a feeding session
3. AddDiaperingEntry - is used to make an entry for a diaper change

- Open the BabyMonitorService.svc.cs file and add the following code:


public class BabyMonitorService : ServiceBase, IBabyMonitorService
    {
        public BabyMonitorService() : base()
        { }

        /// <summary>
        /// Check that the service is available
        /// </summary>
        /// <returns></returns>
        public string HeartBeat()
        {
            return "Service is alive";
        }

        /// <summary>
        /// Add a feed entry
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="FeedType"></param>
        /// <param name="FeedAmount"></param>
        /// <returns></returns>
        public string AddFeedingEntry(string UserId, string FeedType, string FeedAmount)
        {
            Models.WebServiceResponse response = new Models.WebServiceResponse();
            try
            {
                var log = new FeedingLog
                {
                    ID = Guid.NewGuid(),
                    DateCreated = DateTime.Now,
                    FeedType = FeedType,
                    // since IIS does not like the . character, we are passing decimals as x_y and converting to x.y
                    FeedAmount = Decimal.Parse(FeedAmount.Replace("_", ".")),
                    UserID = UserId
                };

                RenewContext();
                Context.AddToFeedingLogs(log);
                Context.SaveChanges();

                response.IsSuccess = true;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.ErrorMessage = ex.Message;
            }
            return SerializeAsJSON(response);
        }

        /// <summary>
        /// Add an entry for a diaper change
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="DiaperType"></param>
        /// <returns></returns>
        public string AddDiaperingEntry(string UserId, string DiaperType)
        {
            Models.WebServiceResponse response = new
Models.WebServiceResponse();

            try
            {
                var log = new DiaperLog
                {
                    ID = Guid.NewGuid(),
                    DateCreated = DateTime.Now,
                    DiaperType = DiaperType,
                    UserID = UserId
                };

                RenewContext();
                Context.AddToDiaperLogs(log);
                Context.SaveChanges();

                response.IsSuccess = true;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.ErrorMessage = ex.Message;
            }
            return SerializeAsJSON(response);
        }

        /// <summary>
        /// Serializes an object to JSON
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private string SerializeAsJSON(Models.WebServiceResponse response)
        {
            using (MemoryStream s = new MemoryStream())
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Models.WebServiceResponse));
                ser.WriteObject(s, response);
                s.Position = 0;
                using (StreamReader sr = new StreamReader(s))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }

- The code is quite simple, it uses the Entity Model to make an entry into the respective tables and returns the WebServiceResponse object in JSON format.
- In the Models folder, add a class called WebServiceResponse and add the following code. The WebServiceResponse is a nice way to return an object as the JSON response, and it can contain a lot of details from the service rather than a simple string error message. Check the service class to see how this object is built.

[DataContract]

    public class WebServiceResponse
    {
        /// <summary>
        /// Indicates if the web service call was successful
        /// </summary>
        [DataMember]
        public bool IsSuccess = false;
        /// <summary>
        /// Contains the response message from the service
        /// </summary>
        [DataMember]
        public object Payload = "Object not assigned";
        /// <summary>
        /// Contains a friendly error message if the service encountered an exception
        /// </summary>
        [DataMember]
        public string FriendlyErrorMessage = string.Empty;
        /// <summary>
        /// Contains the full text of the exception, if one occurred
        /// </summary>
        [DataMember]
        public string ErrorMessage = string.Empty;
        /// <summary>
        /// Contains the exception trace, if one occurred
        /// </summary>
        [DataMember]
        public string ErrorStackTrace = string.Empty;
        /// <summary>
        /// Contains the date and time of the service response in UTC format.
        /// </summary>
        [DataMember]
        public string UTC_DateOfResponse = DateTime.Now.ToUniversalTime().ToString("dd MMM yyyy hh:mm:ss tt");
    }


- At this point we should be able to compile the project and browse to the service. Go to http://yoursite/Services/BabyMonitorService.svc

- You can also invoke the HeartBeat method from earlier to see if your service is working correctly. Note, you will need to save the JSON response and then open it in notepad to see the results

 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.Net MVC4 Mobile Tutorial - Part I

clock October 4, 2012 06:27 by author Scott

In this posting I will show you how to build a new mobile web application based on my real world experience of tracking the feeding activities of my 4 month old baby.

The Design

We have a 4 month old baby and wanted to keep track of his feeding sessions so we do not wake each other up, especially late at night and to also make sure that the baby was feeding regularly. I have an iPhone, my wife has a HTC phone and we also own a Windows table (running Windows 8 Developer Preview), 2 laptops and a home server/multimedia system. I wanted to write an app for this, but it would be too difficult writing an maintaining an iPhone app, a Metro app and windows applications separately. That's why I decided to write a single web application leveraging the SQL Azure database.


Getting Started

You will need one of the following emulators to test the code:

-
Windows Phone Emulator (RC)
-
Opera Mobile Emulator
-
Apple Safari with the user agent set to iPhone. Click here for instructions.
-
FireFox with FireFox User Agent Switcher

Building the Solution

1. Install ASP.Net MVC 4 from here

2. Start Visual Studio 2010, choose new Project, then choose Web and select the "ASP.Net MVC 4 Web Application"



3. In the project template box, choose "Mobile Application", leave the View engine as Razor and leave the checkbox for HTML5 semantic markup




4. You will get a default mobile app with forms authentication ready to go


The Database

We will need to create a database and the schema for this demo next.


-
On your local instance, create a SQL Server 2008 R2 (SQL 2005+ will do) database and call it BabyLog

- We need two tables in the database for our application, one to hold records for feeding logs and the other for diaper changes. Run the following SQL to create those


CREATE TABLE [dbo].[FeedingLog](
    [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Log_ID]  DEFAULT (newid()),
    [UserID] [varchar](255) NOT NULL,
    [FeedType] [varchar](255) NOT NULL,
    [FeedAmount] [decimal](18, 1) NOT NULL,
    [DateCreated] [datetime] NOT NULL,
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
GO


CREATE
TABLE [dbo].[DiaperLog](
    [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_DiaperLog_ID]  DEFAULT (newid()),
    [UserID] [varchar](255) NOT NULL,
    [DiaperType] [varchar](255) NOT NULL,
    [DateCreated] [datetime] NOT NULL,
 CONSTRAINT [PK_DiaperLog] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
GO


- Next we need to create tables to support Forms authentication. Open the Visual Studio command prompt and type: aspnet_regsql




- Click next, select "Configure SQL Server for application services", provider the server name, credentials and the database name and click next.


- Once the wizard finishes, you will see your database tables




The Database Model

Next we will create the Entity Model for our database as well as the WCF uses that our website will use to enter data into the database.


- In the ASP.Net MVC project, right-click on the Models folder and select "Add New Item"


- Select the Data template and choose "ADO.Net Entity Data Model




- Select "Generate from Database", then click Next


- Supply the connection details for your database and name your connection string


- Select the FeedingLog and DiaperLog tables and leave the Model namespace as BabyLogModel




- You should now have a model with the required tables


 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in