miércoles, 25 de abril de 2012

Consumiendo WCF con Web Client Software Factory

Anteriormente ya explicamos como implementar dicha arquitectura, y para este caso de ejemplo vamos a usar ASP.NET Web Application.

01

y busquemos tener esta estructura en la cual mas abajo explico como agregar las capas:

02

seguido, agreguemos una carpeta Solución a la Solución creada con el nombre Source y agregaremos las capas de datos, entidades, y logica (es decir agregamos proyectos)

 

03

 

de la misma manera agreguemos una carpeta solucion para los servicios WCF

04

la clase ICustomerServices va a contener la interfaz o el contrato que se va a exponer para el servicio

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Test.Entity;

namespace Test.WCFServices
{
    [ServiceContract]
    public interface ICustomerServices
    {
        [OperationContract]
        List<e_Customer> GetCustomer();
    }
}

donde e_customer es la entidad definida en nuestra capa Entity ubicada en Source

y el Servicio WCF:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Test.Entity;
using Test.BusinessLogic;

namespace Test.WCFServices
{
     public class CustomerServices : ICustomerServices
    {
        public List<e_Customer> GetCustomer()
        {
            List<e_Customer> objList = new List<e_Customer>();
            objList = new bl_Customer().GetCustomer();

            return objList;
        }
    }
}

Ahora tenemos que definir nuestro host, para levantar el servicio WCF, y esto lo creamos el la carpeta Host y agregamos una aplicación de tipo consola

05

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Test.WCFServices;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace ConsoleApplicationHost
{
    class Program
    {
        private static ServiceHost customerServices;

        static void Main(string[] args)
        {
            CreateServiceHost();
            OnStart();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\nPresione una tecla para finalizar el Service Host:");
            Console.ForegroundColor = ConsoleColor.White;
            Console.ReadKey();
            OnStop();
        }

        private static String GetEndpointAddresses(ServiceDescription svDescripcion)
        {
            StringBuilder ostringBuilder = new StringBuilder();
            foreach (System.ServiceModel.Description.ServiceEndpoint serviceEndPoint in svDescripcion.Endpoints)
                ostringBuilder.AppendFormat("\n\t{0}", serviceEndPoint.Address.ToString());

            return ostringBuilder.ToString();
        }

        private static void CreateServiceHost()
        {
            try
            {
                //variableServicio = new ServiceHost(typeof(nombreServicio_del_ServiceImplementation));
                customerServices = new ServiceHost(typeof(CustomerServices));


            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        private static void OnStart()
        {
            try
            {
                customerServices.Open();
                OutputServiceInformation(customerServices);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        private static void OnStop()
        {
            try
            {
                customerServices.Close();

            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        private static void OutputServiceInformation(ServiceHostBase serviceHost)
        {
            string endpointAddresses = GetEndpointAddresses(serviceHost.Description);
            Console.WriteLine(string.Format("\n\r El servicio {0} se está ejecutando en :{1}{2}", serviceHost.Description.Name, Environment.NewLine, endpointAddresses));
        }
    }
}

y asu vez tenemos que usar la herramienta de editar WCF o lo podemos hacer directamente editando el archivo app.config de la consola, donde definiremos los EndPoints, los binding (http y tcp)

<system.serviceModel>
      <behaviors>
        <serviceBehaviors>
          <behavior name="ServiceBehavior">
            <dataContractSerializer />
            <serviceDebug />
            <serviceMetadata httpGetEnabled="true" />
            <serviceTimeouts />
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <services>
        <service behaviorConfiguration="ServiceBehavior" name="Test.WCFServices.CustomerServices">
          <endpoint binding="basicHttpBinding" bindingConfiguration=""
            name="http_customer" contract="Test.WCFServices.ICustomerServices" />
          <endpoint binding="netTcpBinding" bindingConfiguration="" name="tcp_customer"
            contract="Test.WCFServices.ICustomerServices" />
          <host>
            <baseAddresses>
              <add baseAddress="
http://localhost:9015/WCF/service/CustomerServices" />
              <add baseAddress="net.tcp://localhost:9016/WCF/service/CustomerServices" />
            </baseAddresses>
          </host>
        </service>
      </services>

    </system.serviceModel>

probando que funcione el Host: solo ejecutamos nuestra aplicación de consola en modo administrador y si todo esta correcto veremos la siguiente pantalla la cual quiere decir que nuestro servicio esta listo para consumirlo

06

Para consumir el servicio tenemos que referenciarlo al Module de la arquirectura que estamos WCSF usando y la ruta a usar es la de http:// ……..

07

Para consumir el Servicio, lo hacemos en la clase presentadora de la vista que queremos ejecutar, para este caso usaremos la pagina Default.aspx

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeWeb;
using Test.SolWCSF.Shell.SrvCustomer;


namespace Test.SolWCSF.Shell.Views
{
    public class DefaultViewPresenter : Presenter<IDefaultView>
    {
        public DefaultViewPresenter()
        {

        }

        public List<e_Customer> Get()
        {
            List<e_Customer> obje = new List<e_Customer>();
            using (CustomerServicesClient oProxy = new CustomerServicesClient("tcp_customer"))
            {

                obje = oProxy.GetCustomer();
            }
            return obje;
        }  
    }
}

como podrán observar creamos un proxy, en la cual le pasamos el nombre del EndPoint que definimos en el app.config

al hacer esto en la clase presentadora, ya lo tenemos referenciado en nustra pagina aspx, y poderlo utilizar, y con esta clase podemos pintar una grilla

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Test.SolWCSF.Shell.Views;
using Microsoft.Practices.ObjectBuilder;

using System.Collections.Generic;

public partial class ShellDefault : Microsoft.Practices.CompositeWeb.Web.UI.Page, IDefaultView
{
    private DefaultViewPresenter _presenter;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this._presenter.OnViewInitialized();
        }
        this._presenter.OnViewLoaded();

        this.GridView1.DataSource = _presenter.Get();
        this.GridView1.DataBind();
       
       
    }

[CreateNew]
    public DefaultViewPresenter Presenter
    {
        get
        {
            return this._presenter;
        }
        set
        {
            if (value == null)
                throw new ArgumentNullException("value");

            this._presenter = value;
            this._presenter.View = this;
        }
    }
}

El resultado se veria asi:

08

1 comentario: