banner



How To Create Windows Mobile Application In Visual Studio 2012

At present, the most important trend in the software development world is Mobile application development, especially with the rise of smartphones and tablets. Mobile applications have become must-haves for both businesses and consumers. The impressive growth of mobile platforms like Android, iOS, Windows Phone etc. have had a transformational impact of how we entertain, work and communicate.

Consumers may prefer any mobile device of their choice from time to time, however once they get accustomed to using a certain mobile application, they want to use the same application with the same feature, on all these platforms. This a real challenge with the ever changing and evolving mobile platform and landscape.

Now there are numerous open source and commercial products that can potentially simplify the process of cross platform mobile application development. Some of them are jQuery Mobile, PhoneGap, VsNomad by RedGate, Icenium by Telerik, MonoTouch and Mono by Xamarin etc.

Amongst these toolkits, the one that we explore lately is the Icenium Toolkit which enables developers to use HTML5, CSS and JavaScript/jQuery to develop cross-platform mobile applications. These applications run natively on iOS and Android.

For .NET Developers, Icenium also provides a Visual Studio Extension (currently in beta and with a free trial but quite stable) which enhances Visual Studio by adding cloud services, device simulator and mobile app templates.  Once you install these extensions (available for VS 2012), you can see an additional menu item in Visual Studio as shown here:

icenium-menu

The options in this menu item allows you to Run the application in Simulator and also on the Cloud as below:

icenium-menu-options

You can now create a mobile application using a Project Template as shown below:

mobile-project-templ

In the subsequent steps, we will see how to develop a mobile application which will make use of on device database (Database on client side).

Step 1: Open Visual Studio 2012 (I am assuming you have the Icenium Visual Studio Extensions downloaded). Create a new Icenium Blank project, name it as 'jQM_SampleApp'. The project structure will be as shown below:

project-structure

Observe that the project has references to the jQuery Mobile and jQuery libraries.

Step 2: We will create a simple application which will store Person information like PersonId, PersonName, Address, Gender, Age, BloodGroup in a client side database store. To provide the necessary user interface, add the following HTML in the Index.html inside the <body> tag:

<body>

<div id="pagePersonList" data-role="page" >
    <div  data-role="header">
        <h2>List of Persons</h2>
    </div>
    <div data-role="content">
        <div id="dvdata"></div>
    </div>
    <div data-role="footer">
        <input type="button" value="To Manage Persons Click here"   id="btnpersonmanager"/>
        <div><span>Tap on the Person Id to Change (Update or Delete)</span></div>
    </div>
</div>
<div data-role="page" id="pagePersonManager" data-add-back-btn="true">
  <table>
      <tr>
          <td><span>Person Id:</span></td>
           <td><span><input type="text" id="txtpersonid" /></span></td>
      </tr>

            <tr>
          <td><span>Name:</span></td>
           <td><span><input type="text" id="txtpername" /></span></td>
      </tr>

            <tr>
          <td><span>Gender:</span></td>
           <td><span>
                 <select data-role="listview" id="lstgender">
                      <option value="Male">Male</option>
                        <option value="Feale">Female</option>
                 </select>
              </span>
          </td>
      </tr>

            <tr>
            <td><span>Address:</span></td>
            <td><span><input type="text" id="txtaddr"/></span></td>
      </tr>

              <tr>
          <td><span>Blood Group:</span></td>
          <td><span><input type="text" id="txtbloodgrp" /></span></td>
      </tr>

            <tr>
          <td><span>Age:</span></td>
           <td><span><input type="text" id="txtage" /></span></td>
      </tr>

            <tr>
         <td><input type="button" value="New" id="btnnew"  data-icon="home" data-iconpos="notext"/></td>
         <td><input type="button" value="Add" id="btnadd" data-icon="add" data-iconpos="notext"/></td>
         <td><input type="button" value="Delete" id="btndelete" data-icon="delete" data-iconpos="notext"/>/td>
      </tr>

            <tr>
          <td><input type="button" value="Back to Details" id="btnback"  data-icon="home"/></td>
      </tr>
  </table>
</div>
</body>

The above HTML code has two major <div>'s - 'pagePersonList' and 'pagePersonManager'. Both these div's are set to data-role as 'page'. This means that these are the containers to display specific UI and across these UI, navigation is possible. The 'pagePersonList' contains <div> 'dvdata' which will be used to display the person details in a tabular form. The 'pagePersonManager' has textboxes and buttons for accepting the Person information and performing operations for New, Add, Delete and Back respectively. The Mobile Icons are assigned to these buttons using 'data-icon' property.

Step 3: In the Index.html, add a <script> tag for JavaScript and write the following code. Add these code segments in the jQuery $(document).ready(function(){…}); for creating and managing the database

var PersonInfoDB = {};
PersonInfoDB.init = {};
PersonInfoDB.init.db = {};

Add the following script to create a Database of name 'Persons'

//Method to Create Database
PersonInfoDB.init.open = function () {
    PersonInfoDB.init.db = window.openDatabase("Persons", "1.0", "Persons", 5000000); //The Size of DB is 5 MB
};

The above code creates a database of size 5 MB.

Now add  some code to create a table of the name 'PersonInfo'

//Function to Create Table
PersonInfoDB.init.createTable = function () {

         var database = PersonInfoDB.init.db;
    database.transaction(function (txn) {
        var query = "CREATE TABLE IF NOT EXISTS PersonInfo (PersonId INTEGER PRIMARY KEY," +
           "PersonName TEXT, Gender TEXT," +
           "Address TEXT, BloodGroup  TEXT,Age INTEGER)";


        txn.executeSql(query, []);
    });
};

The above code creates a table if it does not already exist with columns representing Person Info.

The following method will check if the database is already available or if not supported, this method will be called in $(document).ready ();

///Initialize the Database and Table
function InitializeDBandTable() {
     alert("In Init");
    if (typeof (openDatabase) !== 'undefined') {

        PersonInfoDB.init.open();
        PersonInfoDB.init.createTable();

        alert("Db and Table Created");
    }
    else {
        alert("DB Not Supported");
    }
}
InitializeDBandTable();

Add the below function to clear all TextBoxes

//Method to Create All TextBoxes
function newPerson() {
    $("#pagePersonManager input").val('');
}

Add the following method to load Person Information:

//Method to Load Order
function loadPersons() {
personTable = "";
var database = PersonInfoDB.init.db;
personTable = "<table id='tblpersons' border='1'><tr><th>PersonId</th><th>PersonName</th><th>Gender</th><th>Address</th><th>BloodGroup</th><th>Age</th></tr>";
database.transaction(function (tx) {
tx.executeSql("SELECT * from PersonInfo", [], function (tx, result) {

    for (var i = 0; i < result.rows.length; i++) {
         Perid = result.rows.item(i).PersonId;
         Pername = result.rows.item(i).PersonName;
         Pergender = result.rows.item(i).Gender;
         Peraddr = result.rows.item(i).Address;
         Perbloodgrp = result.rows.item(i).BloodGroup;
         Perage = result.rows.item(i).Age;

        personTable += "<tr><td class='cid'>" + Perid + "</td><td>" + Pername + "</td><td>" +
         Pergender + "</td><td>" + Peraddr  + "</td><td>" + Perbloodgrp +
         "</td><td>" + Perage+ "</td></tr>";


    }
    personTable+= "</table>";

        $("#dvdata").html(personTable);
});
})
};


The above method sets the transaction on the table and executes the 'Select' statement to read all rows from the Table. Then it generates the HTML table of name 'tblpersons' dynamically with rows from the PersonInfo table and adds this table in the <div> of id 'dvdata'.

Note: If you have a large number of rows, make use of Array.join (for slight performance benefit) to add the dynamically created string instead of concatenating it as we see above

Add the following method to add a new row in the PersonInfo table:

//Method to Create Order
function createPerson() {
    var database = PersonInfoDB.init.db;

    var perid  =    $("#txtpersonid").val();
  var pername = $("#txtpername").val();
  var pergender = $("#lstgender").find(":selected").text();
  var peraddr = $("#txtaddr").val();
  var perbdgp = $("#txtbloodgrp").val();
  var perage = $("#txtage").val();

database.transaction(function (tx) {
     tx.executeSql("Insert into PersonInfo (PersonId,PersonName,Gender,Address,BloodGroup,Age)values(?,?,?,?,?,?)", [perid, pername, pergender, peraddr, perbdgp, perage]);
     alert("Inserted Successfully");
});
$.mobile.changePage($("#pagePersonList"));
loadPersons();
}

The above code executes the Insert query on the PersonInfo table by accepting values from the textboxes. Once the record is inserted in the table, the page 'pagePersonList' will be displayed with person information in it.

Add the following method to select the Person row from the table:

//Method to Get the PersonId on clicking on the Table

$("#dvdata").on('click', $("#tblpersons"), function () {
     var id = 0;
    $("#tblpersons tr").filter(":not(:has(table,th))").each(function () {
        $(this).on('click', function () {
            id = $(this).closest('tr').children('td.cid').text();
            if (id > 0) {
                loadPerson(id);
                alert("Selected Id = " + id);
                $.mobile.changePage("#pagePersonManager");
                return false;
            }
        });
    });
});

The above code, iterate through all the rows of the table and read the cell value containing PersonId. The selected PersonId will be passed to 'loadPerson' method to display the selected Person information in the TextBoxes, this information can be Updated or Deleted.

Add the LoadPerson method:

//Method to Load Order By Id
function loadPerson(id) {
  alert("In Load " + id);

var database = PersonInfoDB.init.db;
database.transaction(function (tx) {
    tx.executeSql("SELECT * from PersonInfo where PersonId=?", [id], function (tx, result) {

           if (result.rows.length > 0) {
            $("#txtpersonid").val(result.rows.item(0).PersonId);
            $("#txtpername").val(result.rows.item(0).PersonName);
            $("#txtaddr").val(result.rows.item(0).Address);
            $("#txtbloodgrp").val(result.rows.item(0).BloodGroup);
            $("#txtage").val(result.rows.item(0).Age);
        }

    })
});

Add the following method to delete the Person record:

//Method to Delete Order
function deletePerson(id) {
   var database = PersonInfoDB.init.db;
    database.transaction(function (tx) {
        tx.executeSql("DELETE FROM PersonInfo WHERE PersonId=?", [id], function () {
            alert("Delete Successful");
        },error);
    });
    $.mobile.changePage($("#pagePersonList"));
    loadPersons();
}
function error()
{
    alert("Error");
}

The above code fires Delete command on the PersonInfo table to delete the record based upon the PersonId. Add Click events for each button to execute the functionality for Create, Delete etc:

$("#btnpersonmanager").on('click', function () {
    newPerson();
    $.mobile.changePage("#pagePersonManager");
});

$("#btnnew").on('click', function () {
    newPerson();
});

$("#btnadd").on('click', function () {
    //alert ("Add Called")
    createPerson();
});

$("#btndelete").on('click', function () {
    deletePerson($("#txtpersonid").val());
});

$("#btnback").on('click', function () {
    $.mobile.changePage("#pagePersonList");
});

Note: I have chosen code clarity over code brevity here.

Step 4: To test the application in the Simulator from the Icenium menu, select 'Run in Simulator'. To use it you must Login using your Facebook, Gmail, Live, credentials. This step is for the 30 day trial.

icenium-login

Once the Application is loaded in the Simulator, the View will be as shown below:

simulator-view

By default the iPhone simulator will be displayed. Click (Tap on actual device) on > To Manage Persons Click here button which brings up the UI for entering the Person information as below:


person-view

Enter Person Details as below:

enter-person-detail

Click on the '+' button to navigate to page 'PersonListpage' where information will be displayed in tables as below:

phone-table-display

Again on clicking on To Manage Persons Click here button, you can now go to the PersonManager page and enter person details. To Delete the Record, click on the person Id in the Table and you will get the person details loaded in the textboxes which you can delete.

Step 5: By clicking the iPhone icon on top left of the window (shown below), you can select different Simulators:

different-simulators

Now you can test the application on the other simulators too for a cross platform mobile experience.

Step 6: To test the application on the device, you need to get the package file. To do that, from the Icenium menu of Visual Studio, select 'Run in Cloud' option and you will get the Build Window as shown below:

run-in-cloud-mobile

Click on Build for Android and the progress of build will be as shown below:

build-for-android

Once the Build is completed, it will allow you to download the 'apk' file for Android as shown below:

android-apk

Now you can Transfer this file on your Android device and test the application. After transferring the .apk file, it gets installed on the Android Device and the application looks as below:

When the application is loaded, tap on the 'To Manage Person Click Here' button and the Person Data entry page will be displayed as below:

android-device-shot

Conclusion:

Using Icenium makes it very easy to build cross-platform mobile native applications. You can make use of your existing JavaScript & HTML5 knowledge. The Visual Studio Plugin helps to easily develop and test the applications in the shortest possible time

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there's always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!


Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades 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), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

How To Create Windows Mobile Application In Visual Studio 2012

Source: https://www.dotnetcurry.com/visualstudio/950/cross-platform-mobile-app-visual-studio-html5-javascript

Posted by: ramergoope1995.blogspot.com

0 Response to "How To Create Windows Mobile Application In Visual Studio 2012"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel