martes, 21 de abril de 2020

WCF C# CRUD

Vamos a crear un WCF en C#
Creamos la base de datos bdagenda y la tabla tblagenda
Usaremos Visual Studio 2017 y SQL Server 2008

IService1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
    // NOTA: puede usar el comando "Rename" del menú "Refactorizar" para cambiar el nombre de interfaz "IService1" en el código y en el archivo de configuración a la vez.
    [DataContract]
    public class myAgenda
    {
        int _Id;
        string _Nombre;
        string _Apellidos;
        string _Telefono;
        string _Correo;
        [DataMember]
        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }
        [DataMember]
        public string Nombre
        {
            get { return _Nombre; }
            set { _Nombre = value; }
        }
        [DataMember]
        public string Apellidos
        {
            get { return _Apellidos; }
            set { _Apellidos = value; }
        }
        [DataMember]
        public string Telefono
        {
            get { return _Telefono; }
            set { _Telefono = value; }
        }
        [DataMember]
        public string Correo
        {
            get { return _Correo; }
            set { _Correo = value; }
        }
    }
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
        [OperationContract]
        int NuevoContacto(myAgenda agenda);
        [OperationContract]
        int EditarContacto(myAgenda agenda);
        [OperationContract]
        int EliminarContacto(int idContacto);
        [OperationContract]
        myAgenda buscarContacto(int idContacto);
        [OperationContract]
        List<myAgenda> mostrarContactos();
        // TODO: agregue aquí sus operaciones de servicio
    }
    // Utilice un contrato de datos, como se ilustra en el ejemplo siguiente, para agregar tipos compuestos a las operaciones de servicio.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";
        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }
        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}
--------------------------------------------------------------------------------
Service1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WcfService1
{
    // NOTA: puede usar el comando "Rename" del menú "Refactorizar" para cambiar el nombre de clase "Service1" en el código, en svc y en el archivo de configuración.
    // NOTE: para iniciar el Cliente de prueba WCF para probar este servicio, seleccione Service1.svc o Service1.svc.cs en el Explorador de soluciones e inicie la depuración.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
        string cadenaConexion = ConfigurationManager.ConnectionStrings["myConexion"].ConnectionString;
        //    /*
        //CREATE PROCEDURE _spIAContacto(
        // @operacion varchar(1),
        // @dId int,
        // @dNombre varchar(50),
        // @dApellidos varchar(100),
        // @dTelefono varchar(15),
        // @dCorreo varchar(100)
        //)
        //AS
        //  if @operacion='I'/* Insertar */
        // insert into tblAgenda(Nombre,Apellidos,Telefono,Correo)values(@dNombre,@dApellidos,@dTelefono,@dCorreo)
        //else if @operacion='A'/* Insertar */
        // update tblAgenda set Nombre=@dNombre, Apellidos=@dApellidos, Telefono=@dTelefono,Correo=@dCorreo) Where Id=@Id
        public int NuevoContacto(myAgenda agenda)
        {
            int res = 0;
            try
            {
                SqlConnection cnn = new SqlConnection(cadenaConexion);
                cnn.Open();
                SqlCommand cmd = new SqlCommand("_spIAContacto", cnn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@operacion", "I");
                cmd.Parameters.AddWithValue("@dId", 0);
                cmd.Parameters.AddWithValue("@dNombre", agenda.Nombre);
                cmd.Parameters.AddWithValue("@dApellidos", agenda.Apellidos);
                cmd.Parameters.AddWithValue("@dTelefono", agenda.Telefono);
                cmd.Parameters.AddWithValue("@dCorreo", agenda.Correo);
                res = cmd.ExecuteNonQuery();
                cnn.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Error al insertar", ex);
            }
            return res;
        }
        public int EditarContacto(myAgenda agenda)
        {
            int res = 0;
            try
            {
                SqlConnection cnn = new SqlConnection(cadenaConexion);
                cnn.Open();
                SqlCommand cmd = new SqlCommand("_spIAContacto", cnn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@operacion", "A");
                cmd.Parameters.AddWithValue("@dId", agenda.Id);
                cmd.Parameters.AddWithValue("@dNombre", agenda.Nombre);
                cmd.Parameters.AddWithValue("@dApellidos", agenda.Apellidos);
                cmd.Parameters.AddWithValue("@dTelefono", agenda.Telefono);
                cmd.Parameters.AddWithValue("@dCorreo", agenda.Correo);
                res = cmd.ExecuteNonQuery();
                cnn.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Error al modificar", ex);
            }
            return res;
        }
        // CREATE PROCEDURE -spContactoSE(
        // @operacion varchar(1),
        // @dId int
        //)as
        //if @operacion ='S' /*Seleccionar un Registro*/
        //select * from tblAgenda where Id=@dId
        //else
        //if @operacion ='E' /* Eliminar */
        // delete from tblAgenda where Id=@dId
        //else
        // select * from TblAgenda
        public int EliminarContacto(int idContacto)
        {
            int res = 0;
            try
            {
                SqlConnection cnn = new SqlConnection(cadenaConexion);
                cnn.Open();
                SqlCommand cmd = new SqlCommand("spContactoSE", cnn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@operacion", "E");
                cmd.Parameters.AddWithValue("@dId", idContacto);
                res = cmd.ExecuteNonQuery();
                cnn.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Error al eliminar", ex);
            }
            return res;
        }

        public myAgenda buscarContacto(int idContacto)
        {
            myAgenda newAgenda = new myAgenda();
            try
            {
                SqlConnection cnn = new SqlConnection(cadenaConexion);
                cnn.Open();
                SqlCommand cmd = new SqlCommand("spContactoSE", cnn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@operacion", "S");
                cmd.Parameters.AddWithValue("@dId", idContacto);
                SqlDataReader rd = cmd.ExecuteReader();
                if (rd.HasRows)
                {
                    if (rd.Read())
                    {
                        newAgenda.Id = rd.GetInt32(0);
                        newAgenda.Nombre = rd.GetString(1);
                        newAgenda.Apellidos = rd.GetString(2);
                        newAgenda.Telefono = rd.GetString(3);
                        newAgenda.Correo = rd.GetString(4);
                    }
                }
                else
                {
                    return newAgenda;
                    throw new Exception("No hay Registros");
                }
                cnn.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Error al buscar contacto", ex);
            }
            return newAgenda;
        }
        public List<myAgenda> mostrarContactos()
        {
            List<myAgenda> lista = new List<myAgenda>();
            try
            {
                SqlConnection cnn = new SqlConnection(cadenaConexion);
                cnn.Open();
                SqlCommand cmd = new SqlCommand("spContactoSE", cnn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@operacion", "");
                cmd.Parameters.AddWithValue("@dId", "");
                SqlDataReader rd = cmd.ExecuteReader();
                if (rd.HasRows)
                {
                    while (rd.Read())
                    {
                        lista.Add(new myAgenda
                        {
                            Id = rd.GetInt32(0),
                            Nombre = rd.GetString(1),
                            Apellidos = rd.GetString(2),
                            Telefono = rd.GetString(3),
                            Correo = rd.GetString(4),
                        });
                    }
                }
                else
                {
                    return lista;
                    throw new Exception("No hay Registros");
                   
                }
                cnn.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Error al buscar contacto", ex);
            }
            return lista;
        }
        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

}

Ahora configuramos la conexion en el archivo Web.config


 <connectionStrings>
    <add name="myconexion" connectionString="data source=CHARLY-PC\SQLEXPRESS;initial catalog =bdagenda;integrated security =true;"/>
  </connectionStrings>

Escriba el ID del contacto  txtid  btnbuscar
lblmensaje
Nombre txtnombre.Text
Apellidos txtapellidos.Text
Telefono txttelefono.Text
Correo txtcorreo.Text
btnnuevo btneditar btneliminar
btnmostrartodos



 <EmptyDataTemplate>No hay datos disponibles</EmptyDataTemplate>


y por ultimo ponemos los metodos dentro de cada boton

 protected void btnbuscar_Click(object sender, EventArgs e)
        {
            Service1 cliente = new Service1();
            myAgenda agenda = new myAgenda();
            int id;
            id = Convert.ToInt32(this.txtid.Text);
            if (txtid.Text.Trim() != "")
            {
                agenda = cliente.buscarContacto(id);
                if (agenda.Nombre == null) {
                    this.lblmensaje.Text = "No existe el id";
                    txtnombre.Text = "";
                    txtapellidos.Text = "";
                    txttelefono.Text = "";
                    txtcorreo.Text = "";
                }
               
                else {
                    txtnombre.Text = agenda.Nombre;
                    txtapellidos.Text = agenda.Apellidos;
                    txttelefono.Text = agenda.Telefono;
                    txtcorreo.Text = agenda.Correo;
                }
            }
            else {
                lblmensaje.Text = "Escriba el id";
            }
           
        }
        protected void btnmostrartodos_Click(object sender, EventArgs e)
        {
            Service1 cliente = new Service1();
            GridView1.DataSource = cliente.mostrarContactos();
            GridView1.DataBind();
        }
        protected void btnnuevo_Click(object sender, EventArgs e)
        {
            Service1 cliente = new Service1();
            myAgenda agenda = new myAgenda();
            agenda.Nombre = this.txtnombre.Text;
            agenda.Apellidos = this.txtapellidos.Text;
            agenda.Correo = this.txtcorreo.Text;
            agenda.Telefono = this.txttelefono.Text;
           
            if (cliente.NuevoContacto(agenda) > 0)
            {
                lblmensaje.Text = "Los datos se guardaron con exito";
            }
        }
        protected void btneditar_Click(object sender, EventArgs e)
        {
            Service1 cliente = new Service1();
            myAgenda agenda = new myAgenda();
            agenda.Id = Convert.ToInt32(this.txtid.Text);
            agenda.Nombre = this.txtnombre.Text;
            agenda.Apellidos = this.txtapellidos.Text;
            agenda.Correo = this.txtcorreo.Text;
            agenda.Telefono = this.txttelefono.Text;
            if (cliente.EditarContacto(agenda) > 0)
            {
                lblmensaje.Text = "Contacto actualizado con exito";
            }
        }
        protected void btneliminar_Click(object sender, EventArgs e)
        {
            Service1 cliente = new Service1();
            myAgenda agenda = new myAgenda();
            agenda.Id = Convert.ToInt32(this.txtid.Text);
            if (cliente.EliminarContacto(agenda.Id) > 0)
            {
                lblmensaje.Text = "Se elimino con exito";
            }
        }













No hay comentarios:

Publicar un comentario