Avançar para o conteúdo principal

C# Web Service

After the last post on PHP web service now we develop a web service with Visual Studio 2013 in C#.

Let's start by creating a ASP.NET project.




In the next screen wee choose an Empty application.

Now in we add a new item to our project.


And next choose Web Service


By now the Visual Studio have created the basic structure of our web service with one method called HelloWorld as an example.

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

namespace WebApplication2
{
    /// <summary>
    /// Summary description for WebService1
    /// </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 WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

In this post were going to create a new method call listUsers that will receive one parameter indicating the type of output to be generated, XML or JSON.

        [WebMethod]
        public string listUsers(string op)
        {
            if(op=="json"||op=="JSON")
                return devolveRegistosJSON();

            return devolveRegistosXML();
        }

As is easy to see in the code there are two function that get called, one return a JSON string and the other a XML string. Let's look at that code.

Starting with de JSON.

        public string devolveRegistosJSON()
        {
            var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string registos = "";
            string strligacao = "Database=database;Server=server;UID=user;PWD=password;";
            MySqlConnection ligacao = new MySqlConnection(strligacao);
            ligacao.Open();
            string strSQL = "SELECT * FROM test_users;";
            MySqlCommand comando = new MySqlCommand(strSQL, ligacao);
            MySqlDataReader dados = comando.ExecuteReader();
            List<Registo> lDados = new List<Registo>();
            while (dados.Read())
            {
                lDados.Add(new Registo(int.Parse(dados[0].ToString()), dados[1].ToString(), dados[2].ToString()));
            }
            registos = jsonSerializer.Serialize(lDados);
            lDados.Clear();
            dados.Dispose();
            comando.Dispose();
            ligacao.Close();
            ligacao.Dispose();
            return registos;
        }

This functions uses a serializer to generate the JSON string from a list of objects with the data.
Each object is an instance of the class Registo.

        [Serializable]
        public class Registo
        {
            public int id { get; set; }
            public string name { get; set; }
            public string country { get; set; }
            public Registo(int id, string name, string country)
            {
                this.id = id;
                this.name = name;
                this.country = country;
            }
        }

Next the XML version.

public string devolveRegistosXML()
        {
            string registos = "";
            string strligacao = "Database=database;Server=server;UID=user;PWD=password;";
            MySqlConnection ligacao = new MySqlConnection(strligacao);
            ligacao.Open();
            string strSQL="SELECT * FROM test_users;";
            MySqlCommand comando = new MySqlCommand(strSQL,ligacao);
            MySqlDataReader dados = comando.ExecuteReader();
            while (dados.Read())
            {
                string registo = "";
                registo=adicionarTag("id", dados[0].ToString());
                registo += adicionarTag("name", dados[1].ToString());
                registo += adicionarTag("country", dados[2].ToString());
                registos += adicionarTag("registo", registo);
            }
            registos = adicionarTag("registos", registos);
            dados.Dispose();
            comando.Dispose();
            ligacao.Close();
            ligacao.Dispose();
            return registos;
        }

This functions makes use of a helper function to generate the xml tags.

        public string adicionarTag(string tag, string texto)
        {
            string temp = "<" + tag + ">" + texto + "</" + tag + ">";
            return temp;
        }

When testing the service this is the page presented.


If we choose the new method the browser shows us a form with a field for the parameter of the service.

By choosing XML we get.
If the choice is JSON.
Get the project here.

Comentários

Mensagens populares deste blogue

New Unity 3D Project

Today I will present a new project that I started. From the post about the car I am building a game with cars, or transportation. The idea is very simple: the player starts with a car and a mission, when he is done with the mission he gets some cash that can be spent buying a new vehicle. Here are some pics: - the car in Unity - the car in Blender - working in the texture - looks great - a wheel - the texture in Gimp - back in Unity testing different materials  like water - and code

Let's make a car in Unity 3D

In this post we will make a simple car in Unity 3D. The Unity 3D physics engine is used in order to give the car a real behavior. This are the steps: [1] - Create a new Project

Single Page App with C# WPF/XAML

 In this post we are going to create a single page app. The app will have multiple pages that get rendered in the main window. We will be using Visual Studio, C#, WPF and XAML. Let's start by creating a new project in Visual Studio of this type: Next, in the MainWindow, we define the interface structure. On the left side we place a menu and on the right side a DockPanel with a Frame in it. The Frame is the element that is used to render de pages content. Now let's add the new pages. In this example I will add two pages. Click in the Solution Explorer with the mouse right button, then choose Add and Page. The project looks like this. The app content goes on the recently create pages. Because this is just an example I will just change the background color and add a small text. Page1 Page2 Finally the code. Back to the MainWindow we need to create the click events on the menu items. So, in the MenuItem line add the click event and pick New Event Handler. If that option doesn't...