Showing posts with label C Sharp. Show all posts
Showing posts with label C Sharp. Show all posts

Wednesday, January 22, 2014

Pass Complex JavaScript Object to MVC Controller

In this tutorial I'm going to illustrate how we can pass complex javascript objects to MVC controller.

I have two Model objects called Project and Employee as below.

    public class Project
    {
        public long ProjectID { get; set; }
        public string ProjectName { get; set; }
    }

    public class Employee
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

And I have view-model called "ProjectViewModel" which contains above models as below.

    public class ProjectViewModel
    {
        public Project Project { get; set; }
        public IList<Employee> EmployeeList { get; set; }
    }
Now I'm going to pass instance of ProjectViewModel and an Employee object to my MVC controller. Here is the controller method.
        [HttpPost]
        public ActionResult Create(ProjectViewModel projectViewModel, Employee anotherEmployee)
        {
            return Content("done");
        }
This is the JavaScript code that we can use to call the controller method.
        var projectViewModel = {};

        var project = {};
        project.ProjectID = 1234;
        project.ProjectName = "Test Project";

        projectViewModel.Project = project;

        var employeeList = [];

        var employee1 = {};
        employee1.Code = "1111";
        employee1.Name = "Saranga";

        var employee2 = {};
        employee2.Code = "2222";
        employee2.Name = "Rathnayaka";

        employeeList.push(employee1);
        employeeList.push(employee2);

        projectViewModel.EmployeeList = employeeList;

        var employee3 = {};
        employee3.Code = "3333";
        employee3.Name = "Test User";

        $.ajax(
  {
      url: 'Project/Create',
      data: JSON.stringify({projectViewModel : projectViewModel, anotherEmployee : employee3}),
      contentType: 'application/json',
      dataType: 'json',
      type: 'POST',
      success: function (data) {
          alert("success");
      },
      error: function () { alert('error'); }
  });

Wednesday, September 29, 2010

Create Simple Web Service with Visual Studio

This tutorial explains how we can create simple Web Services using Visual Studio.

1. Create the Web Service

First create new project and select "New ASP.NET Web Service Application" and I'm giving the name "MyFirstWebService" to it, you can give any name to your project.

Now you can see auto generated code that you can add methods to create your web service. You can see simple method "HelloWorld" and in this sample code I have removed it.

I'm going to add simple method called "simpleMethod" which takes a string as an input and add "Hello" to beginning of that string. Now the code will appear like bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace MyFirstWebService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string simpleMethod(String srt)
        {
            return "Hello "+srt;
        }

        [WebMethod]
        public int anotherSimpleMethod(int firstNum, int secondNum)
        {
            return firstNum + secondNum;
        }

    }
}

Then you can run your code and you can see the resulting page as bellow.

2. Create the Client Program

We have created our simple web service and we have to create small client program to use this web service. There you can open another instant of Visual Studio and create new "Console Application" project.

Then you have to add Service Reference so that you can access your web service. Here are the screen-shots.



Here you have to give the URL of the web service we created earlier. As I said before previously created web service application should be running on another instant of Visual Studio.

Note that I have set the "Web reference name" as "TestWeb".

Now you can update your client program using following code. Note the line 5 "using WebServiceTest.TestWeb;".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebServiceTest.TestWeb;

namespace WebServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1 webservice = new Service1();
            string srt = webservice.simpleMethod("Saranga Rathnayake");
            Console.WriteLine(srt);
            Console.WriteLine(webservice .anotherSimpleMethod(4,3));
        }
    }
}

Now you can run the client program to see the result.

3. Publish Our Web Service in Internet Information Service (IIS)

Let's see how we can publish our web service in IIS. Otherwise you always need to run your web service application in separate VS instant. There first stop the web service application and go to the Solution Explore and Right Click on the project. Then select "Publish...".

Then the following window will appear and there you can directly publish to the IIS by selecting "Web Deploy" as the publishing method. But here I'm going to use the "File System as the publishing method. There you have to provide the target location. I have created new folder called "MyApp" in my D drive and selected it.

Now click "Publish" and check the "MyApp" folder. There you will be able to see Service1.asmx file, Web.config file and bin folder which contains the DLL file has been generated. Then copy this "MyApp" folder to "wwwroot" folder. You may find it in "C:\inetpub\wwwroot".

Now enable IIS in your computer and open IIS Manager. I'm going to add my service to Default Web Site. There Right Click on the "Default Web Site" and click "Add Application...".

There you will get following window. Now you can provide appropriate Alias (I have given testservice) and select the physical path of your application. There you can provide the path to the folder we copied previously as following figure and click Ok.

You have to make sure that the application pool identity has Read access to the physical path. So it is better if you copy your files to the "wwwroot" folder other than keep it in separate partition. Please check the following screen-shot

Now restart the IIS and goto http://localhost/testservice/Service1.asmx. You will be able to see the Web Service running.

Now you have published your web service in IIS and you can update the Client Program by giving the new Web Reference URL using Properties Window.

If you are interested in creating web services in java, please follow my post Create Web Service in Java Using Apache Axis2 and Eclipse

Wednesday, October 14, 2009

Sort Object ArrayList in C#

You can easily sort an arraylist using its "sort()" method, but how can you sort an ArrayList of Objects? You can get this task done very easily with "IComparer" Interface.

As an example let’s get a "Person" object which contains two attributes called "ID" and "Name". Now we need to sort these objects by "ID" or "Name". By looking at the following picture, you can get very clear idea about what we are going to do now.

You may notice in "Sort 2" first I have sort by "ID" and then by "Name". I’ll give you the C# code for the above task using simple console application.

Create new class called "Person" and paste this code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SortArrayList
{
    class Person
    {
        private int id;
        public int ID
        {
            get { return id; }
            set { id = value; }
        }
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public int CompareTo(Person psn2, ObjCompare.ComparisonType comparisonType, Person psn1)
        {
            int returnValue;
            if (comparisonType == ObjCompare.ComparisonType.ID)
            {
                if (psn1.ID == psn2.ID)
                {
                    returnValue = Name.CompareTo(psn2.Name);
                }
                else
                {
                    returnValue = ID.CompareTo(psn2.ID);
                }
            }
            else if (comparisonType == ObjCompare.ComparisonType.Name)
            {
                returnValue = Name.CompareTo(psn2.Name);
            }
            else
            {
                returnValue = ID.CompareTo(psn2.ID);
            }
            return returnValue;
        }
    }
}

Create new class called "ObjCompare" and paste this code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SortArrayList
{
    class ObjCompare : IComparer
    {
        public enum ComparisonType
        {
            ID, Name
        }
        private ComparisonType compMethod;
        public ComparisonType ComparisonMethod
        {
            get { return compMethod; }
            set { compMethod = value; }
        }
        public int Compare(object x, object y)
        {
            Person psn1 = (Person)x;
            Person psn2 = (Person)y;
            return psn1.CompareTo(psn2, ComparisonMethod, psn1);
        }
    }
}

Now update your "Programme.cs" as bellow;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SortArrayList
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList lst = new ArrayList();

            Person psn = new Person();
            psn.Name = "Jack"; psn.ID = 15;
            lst.Add(psn);

            Person psn1 = new Person();
            psn1.Name = "David"; psn1.ID = 18;
            lst.Add(psn1);

            Person psn2 = new Person();
            psn2.Name = "Daniel"; psn2.ID = 12;
            lst.Add(psn2);

            Person psn3 = new Person();
            psn3.Name = "Owen"; psn3.ID = 20;
            lst.Add(psn3);

            Person psn4 = new Person();
            psn4.Name = "Colin"; psn4.ID = 16;
            lst.Add(psn4);

            Person psn5 = new Person();
            psn5.Name = "Aiden"; psn5.ID = 18;
            lst.Add(psn5);

            Console.Write(" ---before sort --- \n");
            foreach (Person item in lst)
            {
                int id = item.ID;
                string ttl = item.Name;
                Console.Write(id + " " + ttl + "\n");
            }
            /* sorting */
            ObjCompare objcom = new ObjCompare();
            objcom.ComparisonMethod = ObjCompare.ComparisonType.ID;
            lst.Sort(objcom);

            Console.Write(" ---after sort -- \n");
            foreach (Person item in lst)
            {
                int id = item.ID;
                string ttl = item.Name;
                Console.Write(id + " " + ttl + "\n");
            }
        }
    }
}

You will get the output as "Sort 2" in the picture. If you don't want to sort by "Name" you can do it by editing "Person" class. There I have check whether "psn1.ID == psn2.ID", by commenting that part you can get the result as "Sort 1".