Thursday, 7 January 2016

Working with JSON using Json.NET by Newtonsoft 3 (Passing data from form to the server using JSON and JQuery and accessing via C# action)

Sometimes when we have a single page application or semi single page application, we have to pass data to the server without reloading the page.
For this purpose, we can use JQuery, JSON and a simple view in ASP.NET MVC.


First lets create a view with some validation

<!-- this is a button to show create employee modal -->
<button class="btn btn-primary" onclick="return createEmployeeShowModal()">
    Create New Employee
</button>

<!-- this is the create employee modal-->
<div class="modal fade" id="createEmployeeDialog" tabindex="-1" role="dialog" aria-labelledby="createEmployeeDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="createEmployeeDialogLabel">Create New Employee</h4>
            </div>
            <input id="selectedDelete" type="hidden" value="-1" />
            <div class="modal-body">
                <div class="panel panel-body">
                    <div id="errorDiv" name="errorDiv" style="text-align:center; color:red">
                    </div>
                    <form>
                        <p>
                            <label for="firstName" class="control-label">First Name : </label>
                            <input type="text" id="firstName" name="firstName" class="form-control" />
                        </p>
                        <p>
                            <label for="middleName" class="control-label">Middle Name : </label>
                            <input type="text" id="middleName" name="middleName" class="form-control" />
                        </p>
                        <p>
                            <label for="lastName" class="control-label">Last Name : </label>
                            <input type="text" id="lastName" name="lastName" class="form-control" />
                        </p>
                        <p>
                            <label for="departmentSelect">Department : </label>
                            <select id="departmentSelect" name="departmentSelect" class="form-control"></select>
                        </p>
                        <p>
                            <label for="dateofBirth">Date of Birth (Use DD-MM-YYYY format) : </label>
                            <input type="text" id="dateofBirth" name="dateofBirth" class="form-control" />
                        </p>
                        <br />
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="return validateEmployee()" class="btn btn-primary">Add New Employee</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>


<!-- this is the create employee confirmation modal-->
<div class="modal fade" id="createEmployeeConfirmDialog" tabindex="-1" role="dialog" aria-labelledby="createEmployeeConfirmDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="createEmployeeConfirmDialogLabel">Confirmation</h4>
            </div>
            <div class="modal-body">
                Are you sure you want to create this employee ?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="addNewEmployee()">Yes</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>


In the JavaScript add the following

//show the create employee modal
function createEmployeeShowModal() {
    $('#createEmployeeDialog').modal('show');
}



//validate employee
function validateEmployee() {

    var errorText = "";
    var hasErrors = false;

    var firstName = $("#firstName").val();
    var middleName = $("#middleName").val();
    var lastName = $("#lastName").val();
    var dateofBirth = $("#dateofBirth").val();
    var departmentID = $("#departmentSelect").val();

    if (firstName.trim() === "") {
        errorText = errorText + "<br/>First Name cannot be empty"
        hasErrors = true;
    }

    if (lastName.trim() === "") {
        errorText = errorText + "<br/>Last Name cannot be empty"
        hasErrors = true;
    }

    if (dateofBirth.trim() === "") {
        errorText = errorText + "<br/>Date of birth cannot be empty"
        hasErrors = true;
    } else if (dateofBirth.trim().length != 10) {
        errorText = errorText + "<br/>Incorrect date format"
        hasErrors = true;
    }
    else if ((dateofBirth.trim().split("-").length - 1) != 2) {
        errorText = errorText + "<br/>Incorrect date format"
        hasErrors = true;
    }

    if (hasErrors == true) {
        $('#errorDiv').html("<b>" + errorText + "</b><br/><br/>");
        $('#errorDiv').show();
        return false;
    }
    else {
        $('#errorDiv').html("");
        $('#errorDiv').hide();
        $('#createEmployeeConfirmDialog').modal('show');
    }

    return false;
}

//adding the employee (posting data to the server(Note the data part here)
function addNewEmployee() {
    var firstName = $("#firstName").val();
    var middleName = $("#middleName").val();
    var lastName = $("#lastName").val();
    var dateofBirth = $("#dateofBirth").val();
    var departmentID = $("#departmentSelect").val();


    var url = '/Home/AddNewEmployeeJSON';
    var data = {
        FirstName: firstName,
        MiddleName: middleName,
        LastName: lastName,
        DateofBirth: dateofBirth,
        DepartmentID: departmentID
    };

    $.post(
        url,
        data,
        function (result) {
            if (!$.isEmptyObject(result)) {
                if (result.errorCode === 1) {
                    location.assign('/Home/Retrieve');
                }
                else {
                    //there are errors
                    alert("faliure");
                }
            }
            else {
                alert("Unexpected Error, Returned Result is Empty.");
            }
        });

    return false;
}

//heres the code inside server /Home/AddNewEmployeeJSON

        public ActionResult AddNewEmployeeJSON(FormCollection fc)
        {      
            string firstName = fc["firstName"];
            string middleName = fc["middleName"];
            string lastName = fc["lastName"];
            string dateofBirth = fc["dateofBirth"];
            int departmentID = Convert.ToInt32(fc["departmentID"]);

//send data to BLL to create employee...
            int retVal = new BLLEmployeeManager().addNewEmployee(firstName, middleName, lastName, departmentID, dateofBirth);
            var camelCaseFormatter = new JsonSerializerSettings();
            camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

            var jsonResult = new ContentResult
            {
                Content = JsonConvert.SerializeObject(
                new { errorCode = 1 }
                ,
                camelCaseFormatter
                ),
                ContentType = "application/json"
            };

            return jsonResult;
        }






Tuesday, 5 January 2016

Working with JSON using Json.NET by Newtonsoft 2 (Consume JSON with JQuery)

In the previous example, we discussed about how to return JSON with the use of JSON.NET.
Here, we consume the returned data and display it in the view, using JQuery.

In JQuery, there are 3 main ways to make ajax calls.

$.ajax();
$.get();
$.post();

In this tutorial, lets add some code to consume the JSON from the previous tutorial

since we want to show the data when the page loads, lets put the call inside the document.ready function

** please note that, I have 2 buttons inside this table with onclick functions they will open up modal dialogues to do relevant actions.
** for the 2 buttons, on the onClick methods, I pass in the relevant employeeID and with that, I am able to edit a particular employee...
**note that the table body in the view has a tbody with the id="tbodyEmp", which is used to append data into

Table in the view

      <div style="text-align:center">
         <table style="width:100%" class="table table-striped table-responsive table-bordered">
                        <tr>
                            <th>Employee ID</th>
                            <th>Employee Name</th>
                            <th>Edit Employee</th>
                            <th>Delete Employee</th>
                        </tr>  
                        <tbody id="tbodyEmp">
                        </tbody>                

            </table>
         </div>


Calling from the Javascript

$(document).ready(function () {
    //load employees
    var url = '/Home/GetAllEmployeesJSON';
 
//when we execute the ajax call, the script will continue to execute without waiting for the data
//to return, this will stop that
$.ajaxSetup({ async: false });

    $.post(
    url,
    function (result) {
        if (!$.isEmptyObject(result)) {
            var empListCount = result.length;
            for (var i = 0; i < empListCount; i++) {
                $("#tbodyEmp").append(
                            "<tr>" +
                                "<td>" + result[i].employeeID + "</td>" +
                                "<td>" + result[i].employeeName + "</td>" +
                                "<td>" +
                                    "<button onclick='return showEditEmployee(" + result[i].employeeID + ")'>" +
                                        "Edit" +
                                    "</button>" +
                                "</td>" +
                                "<td>" +
                                    "<button onclick='return showDeleteEmployee(" + result[i].employeeID + ")'>" +
                                        "Delete" +
                                    "</button>" +
                                "</td>" +
                            "</tr>"
                    );
            }
        }
        else {
            $('#empDisplayDiv').append(
                    "<div>Employee list not available</div>"
                );
        }
    });


    $.ajaxSetup({ async: true});   //this will resume the async....
});


//delete employee modal show
function showDeleteEmployee(empID) {
    $('#selectedDelete').val(empID);//this is how you assign a value using id
    $('#deleteEmployeeConfirmDialog').modal('show');
    return false;
}

delete employee modal in the view
<div class="modal fade" id="deleteEmployeeConfirmDialog" tabindex="-1" role="dialog" aria-labelledby="deleteEmployeeConfirmDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="deleteEmployeeConfirmDialogLabel">Confirmation</h4>
            </div>
            <input id="selectedDelete" type="hidden" value="-1"/>
            <div class="modal-body">
                Are you sure you want to delete this employee ?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="deleteEmployee()">Yes</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>




//edit employee modal show
function showEditEmployee(empID) {
    $('#editEmployeeDialog').modal('show');

  //this is how you get values using id
   //var firstName = $("#editFirstName").val();

}

edit employee dialog
<div class="modal fade" id="editEmployeeDialog" tabindex="-1" role="dialog" aria-labelledby="editEmployeeDialogLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="editEmployeeDialogLabel">Edit Employee</h4>
            </div>
            <input id="selectedDelete" type="hidden" value="-1" />
            <div class="modal-body">
                <div class="panel panel-body">
                    <div id="editErrorDiv" name="editErrorDiv" style="text-align:center; color:red">
                    </div>
                    <form>
                        <p>
                            <label for="editFirstName" class="control-label">First Name : </label>
                            <input type="text" id="editFirstName" name="editFirstName" class="form-control" />
                        </p>
                        <p>
                            <label for="editMiddleName" class="control-label">Middle Name : </label>
                            <input type="text" id="editMiddleName" name="editMiddleName" class="form-control" />
                        </p>
                        <p>
                            <label for="editLastName" class="control-label">Last Name : </label>
                            <input type="text" id="editLastName" name="editLastName" class="form-control" />
                        </p>
                        <p>
                            <label for="editDepartmentSelect">Department : </label>
                            <select id="editDepartmentSelect" name="editDepartmentSelect" class="form-control"></select>
                        </p>
                        <p>
                            <label for="editDateofBirth">Date of Birth (Use DD-MM-YYYY format) : </label>
                            <input type="text" id="editDateofBirth" name="editDateofBirth" class="form-control" />
                        </p>
                        <input type="hidden" id="editCurrentID" value="-1"/>
                        <br />
                    </form>
                </div>
            </div>
            <div class="modal-footer">              
                <button onclick="return editValidateEmployee()" class="btn btn-primary">Edit Employee</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>



Sunday, 3 January 2016

Working with JSON using Json.NET by Newtonsoft 1 (Returning JSON)

In ASP.NET MVC application development, controller actions can be used to return content.
When you go in to a particular url, you will be pointed to a view (most of the time).

With Newtonsoft's JSON.NET, those urls can be used to retrieve JSON.

Before we start, you should create a simple MVC application, in that application,
right click and go to the nuget package manager (right click -> manage nuget packages).

in there search for 
Newtonsoft.Json

install it to your application.

in order for us to use the JSON.NET, we have to import the following in to our code (here I am putting them in the controller)

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;


now that we have the relevant imports, lets see some sample code to return json,

use the following code to make the relevant JSON comply with the camel case notation

var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

now lets create a ContentResult object that we can return.

            var jsonResult = new ContentResult
            {
                Content = JsonConvert.SerializeObject(
               <<this will have the returning object>>
                ,
                camelCaseFormatter
                ),
                ContentType = "application/json"
            };

            return jsonResult;



Heres a complete example.

in models we can create,

    public class EmployeeDisplayModel
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
    }

in the controller add the following action

public class HomeController : Controller
{

        public ActionResult GetAllEmployeesJSON()
        {
            List<EmployeeDisplayModel> empDisplayList = new List<EmployeeDisplayModel>();
            empDisplayList.Add(new EmployeeDisplayModel() {
                EmployeeID = 1,
                EmployeeName = "emp1"
            });
            empDisplayList.Add(new EmployeeDisplayModel()
            {
                EmployeeID = 2,
                EmployeeName = "emp2"
            });
            empDisplayList.Add(new EmployeeDisplayModel()
            {
                EmployeeID = 3,
                EmployeeName = "emp3"
            });

            var camelCaseFormatter = new JsonSerializerSettings();
   camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

            var jsonResult = new ContentResult
            {
                Content = JsonConvert.SerializeObject(
                empDisplayList
                ,
                camelCaseFormatter
                ),
                ContentType = "application/json"
            };

            return jsonResult;
         }
}


when you can access them by going to the relavent /<<controller>>/<<action>> link,




Friday, 30 October 2015

The Design of The iPhone


screen-shot-iphone-5-6-blog-post.png


The iPhone is considered as a prestigious device among the smartphone enthusiast around the world. Apple became popular with the introduction of the iPhone than from their mackintosh business. Steve jobs, founder and the CEO of apple personally involved in the process of creating the iPhone. The latest iPhone model is cost around $1200.
When compared with other phones in the market, iPhones is a very expensive choice for a smartphone. Why iPhone is priced so higher? What does an iPhone have that other phones don’t? These questions can be answered simply. There are two main aspect of an iPhone that make it one of the most prestigious devices in the world.
1.     Physical Design
2.     iOS
Physical Design
The physical design of an iPhone is considered having the best build quality that is in a smart phone. The design and development of iPhone is mostly done in the United States, especially in California, where the Apple headquarters is located.
When iPhone first released back in 2007 it had the minimalistic metallic finish design that made it very popular. There were no smartphones in the market to compete with design of iPhone and this single phone made apple billions. Then apple released its second wave of apple phones (iPhone 4 & 4S). When they released iPhone 4 it was clear that they were after a simplistic design rather than a bulky one.
The 3rd generations of iPhones were released in 2012 and the design was awesome. They had it made thinner while securing the unibody concept. The colors and button architectures were perfect to use. They had considered that fact that, the phone should be able to use with a single hand.
The same concepts and more upgrades were visible in the iPhone version 6 and 6 plus released this year. It can be named as the most advanced iPhone ever made yet. The design of the phone can be considered as a huge win for apple. iPhone 6 was made ultra-thinner and the edges were curved. The whole body was made with aluminum.
The metallic finish of the iPhone makes it rich and durable to the fell overs and unexpected shocks. One person has claimed that his iPhone fell down accidentally when he was sky diving with his friend and he managed to find it on the ground with only a cracked screen. According to him it was still working and he could answer calls with it.



IOS – iPhone Operating System
Apart from the physical design, iOS is the most elegant entity that makes an iPhone superior. iOS made iPhone better looking than ever. iOS is the single most powerful reason for people to buy an iPhone. iOS is said to be crash free and faster. iOS was designed to be easy to understand Above all the design concept of iOS is awesome.
Back in 2007 when the first iPhone was introduced, the iOS had a 3D UI with attractive app icons with a glittering shine. This UI continued through iOS version 4,5 and 6. The iPhone fans started buying apps for the store and developers started contributing more and more beautiful apps store. The key factor was the design for these apps to be bought by users.
iOS evolved through years and today it has become a phenomenon mobile operating system that serves a top end device. Apple developed iOS 7 deviating from their current design ethics. They introduced a flat design model with iPhone 5. This was backward compatible with the iPhone 4 as well. The iOS 7 was remarkably attractive and with the design new icon packs were introduced as well.
The iPhone 6 & 6 plus were shipped with the latest apple iOS, 8. This is the most amazing design brought by apple ever. With an easy-to-use interface, amazing features, iOS 8 became the foundation of iPhone, iPad, and iPod touch. It’s designed to look beautiful and work beautifully, so even the simplest tasks were more engaging. The simple-yet-beautiful home screen in iOS 8 invites you to discover each of the built-in apps. And no matter what you’re doing or what app you’re using, everything feels easy, intuitive, and even fun.
Above are some UI mockups of iPhone and iOS made by an iphone mockup tool online. You can see the design changes accordingly as you go through them. There many apps in the iTunes store having beautiful app icons of iOS 8. You can use these mockups and templates. Just click on the mockup and select use as a template. Enjoy!

Wednesday, 9 September 2015

Creating a Simple iPhone Application


Creating an iPhone app is considered as a time consuming task. The main reason for this is the different stages in the development process of a mobile application.  Creating an iPhone application may need the knowledge of programming, designing (implementation) and testing as well.  We take an iPhone app example for this particular article. iPhone applications became popular as many developers started working on the platform with the evolution of the smartphone industry.

Before creating an iPhone app you need to have the basic idea about what you are going to create and how it will be implemented. For this you need to have a prototype of the application created from iPhone mockup software. Actual implementation of the application may seem hard. But creating the initial prototype is easy when you can illustrate it with a wire-frame or mockups. We’re taking a sample application idea for the sake of this article and I will be describing how you can take it forward to make a prototype from an iPhone mockup.

The App Idea

We’re taking this simple example of an alarm clock to set the alarm to get up every day. With this clock you will be able to set a time to wake up and control the desired time along the week.

Functions

Main function of the alarm is to set a specific time and to trigger the alarm when that time is reached. Other than that, below functions are included in the app.

1.      User specific alarms
2.      Customize the time along the week
3.      Selecting alarm tones.

When creating the prototype for this application first you will need a login. This alarm application can be used by desired number of people. Since, you need to have a registration form as well. The first phase of the iPhone prototype is the welcome screen with the login. An illustration of step one is given in the fig 1.1 below.

1.png
For this screen I have used two buttons and two input text fields.

Thereafter you need to illustrate the screen after logging in. This screen usually shows the name of the person that is using the application with a nice greeting. This screen also shows information user needs to operate the application including controls to assign an alarm and change setting. You can see this screen in the figure 2.0 below.

2.png

As you can see the user is logged in and the last alarm time is shown at the top right side of the screen. The 3 main icons on the screen represent the corresponding functions in the app.

Now you can create the next screen which is the setup screen. The user should be able to setup the alarm at a desired time. The alarm should also be able to set on all 7 days of the week. This is a very interesting screen and the most important one as well. In this screen I have used a foreign object to illustrate seven days of the week. You need to be able to navigate to the specific screens within the app. A back button will be included to this page to return to the previous page.  See figure 3.0 for alarm setup screen.

3.png

Another important function would be to setup the alarm sound. In this screen you need a list to pick a sound to set the alarm. By using the web picker you can do this as it was done for the alarm picker. Figure 4 illustrates the sound picker.

4.png

The final screen is the history screen to show the history of alarms that a user had used. For this I’m going to use a list object in the prototyping tool to illustrate. I have also put a button to clear up the history in the list as well. You can see the final screen in figure 6 below.

5.png

It is not that hard to create a mockup of the prototype when you have a clear idea of what you are doing. You can develop your app idea into a usable prototype using an iphone mockup tool. Your mockup can be understood by anyone to develop a working prototype.

Thursday, 14 November 2013

Introduction to Data Flow Diagrams


Data flow diagrams are very important to structured programming. So I decided to do a little article about DFD’s. Data flow diagrams are also known as bubble charts. It is a visual representation of a system via input data to a system, the number of processes carried out to these data and the final output from the system. Data flow diagrams are so popular because of the simplicity and the clearness of the diagrams. Otherwise you can say they are very formal and easy to understand. Data flow diagrams use specific number of easy symbols to depict the functions and processes with the inputs and outputs of the system. Data flow diagrams are a hierarchical diagram type where representing from the set of most high level functions of the system to the sub level function. Any hierarchical model is easy to understand by the humans because hierarchical models starts very simple with abstract model of a system and different details of the system are introduced slowly. There are simple set of rules when drawing data flow diagrams followed by conceptual techniques. Below are the different symbols that represent and used to construct data flow diagrams. Just have a look and see how simple they are.



I’m going to explain each one of these symbols briefly. Try and understand what each of these means and how to use them in a data flow diagram correctly.

External Entity

External entities are represented by a rectangle and the better examples for external entities are librarian, library member, etc. These external entities represent those physical entities in the real world that interacts with the system. As you can see these external entities are outside to the software system and interacting with the system by inputting data by consuming the data created by the software system.

Process

Functions are represented by a circle. These symbols are called as process or bubbles. This term is derived from the bubble chart terminology. Bubbles are connected with the corresponding functions. 

Data Flow Symbol (Arrow)

An arrow is used to represent the connectors or a data flow symbol. This arrow can be a straight directed arrow as well as a curve arrow according to the structure of the diagram. There are three things that a data flow symbol can represent.

1. Data flow between two processes
2. Between external entity and a process
3. Process in a direction of the data flow arrow

Data flow symbols are usually represented with corresponding data names.

Data Store Symbol

Data stores are where data is basically stores and it is represented by an open box. There for an open box can represent a logical file, data structure or a physical file on disk. Each data source is connected with a process obviously with an arrow or a data flow symbol. The direction of the arrow can represent whether the data is read or write from the disk or into a data source. An arrow flowing in or out of a data store implicitly represents the entire data of the data store and hence arrows connecting to a data source need not be annotated with the name of the corresponding data item. 

Above symbols are created with Creately Org Chart Software.