jueves, 25 de febrero de 2016

BibliotecaDeClases_BaseDatos

/*CLiente

using Biblioteca;
using System.Globalization;
using System.Data.Sql;
using System.Data.SqlClient;



namespace Cliente
{
    public partial class Frm_Cliente : Form
    {
        public Frm_Cliente()
        {
            InitializeComponent();
        }

        private void Frm_Cliente_Load(object sender, EventArgs e)
        {
            this.setModos("INICIO");
        }

        private void btn_Nuevo_Click(object sender, EventArgs e)
        {
            this.setModos("NUEVO");
            btn_Actualizar.Enabled = false;
            btn_Eliminar.Enabled = false;
            btn_Nuevo.Enabled = true;
        }

        public void setModos(String modo)
        {
            if (modo == "INICIO")
            {
                btn_Agregar.Enabled = false;
                btn_Actualizar.Enabled = false;
                btn_Eliminar.Enabled = false;

                txt_Codigo.Clear();
                txt_Nombre.Clear();
                txt_DireccionMac.Clear();
                txt_Puerto.Clear();
                txt_Modelo.Clear();
                txt_Marca.Clear();
                txt_Precio.Clear();
            }
            if (modo == "NUEVO")
            {
                txt_Codigo.Enabled = true;
                txt_Nombre.Enabled = true;
                txt_DireccionMac.Enabled = true;
                txt_Puerto.Enabled = true;
                txt_Modelo.Enabled = true;
                txt_Marca.Enabled = true;
                txt_Precio.Enabled = true;
                btn_Agregar.Enabled = true;
                btn_Actualizar.Enabled = true;
                btn_Eliminar.Enabled = true;

                txt_Codigo.Clear();
                txt_Nombre.Clear();
                txt_DireccionMac.Clear();
                txt_Puerto.Clear();
                txt_Modelo.Clear();
                txt_Marca.Clear();
                txt_Precio.Clear();
            }
            if (modo == "UDATE")
            {
                txt_Codigo.Enabled = true;
                txt_Nombre.Enabled = true;
                txt_DireccionMac.Enabled = true;
                txt_Puerto.Enabled = true;
                txt_Modelo.Enabled = true;
                txt_Marca.Enabled = true;
                txt_Precio.Enabled = true;
            }
        }

        private void btn_Agregar_Click(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrWhiteSpace(txt_Codigo.Text) || String.IsNullOrWhiteSpace(txt_Nombre.Text) ||
                    String.IsNullOrWhiteSpace(txt_DireccionMac.Text) || String.IsNullOrWhiteSpace(txt_Puerto.Text) ||
                    String.IsNullOrWhiteSpace(txt_Modelo.Text) || String.IsNullOrWhiteSpace(txt_Marca.Text) ||
                    String.IsNullOrWhiteSpace(txt_Precio.Text))
                {
                    MessageBox.Show("Existe uno o más campos vacios. Llene todos los campos.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    EquiposRed equipo = new EquiposRed();

                    equipo.Codigo = txt_Codigo.Text;
                    equipo.Nombre = txt_Nombre.Text;
                    equipo.Direc_mac = txt_DireccionMac.Text;
                    equipo.Puerto =Convert.ToInt32(txt_Puerto.Text);
                    equipo.Modelo = txt_Modelo.Text;
                    equipo.Marca = txt_Marca.Text;
                    equipo.Fecha_Ingreso = DateTime.Now.ToString();
                    equipo.Precio =float.Parse(txt_Precio.Text);
                    this.setModos("INICIO");

                    int resultado = EquipoDB.agregarEquipo(equipo);
                    if (resultado > 0)
                    {
                        MessageBox.Show("Equipo ingresado exitosamente.", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.setModos("INICIO");
                    }
                }
            }
            catch (System.NullReferenceException)
            {
                MessageBox.Show("No se pudo ingresar los datos del Equipo.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btn_Actualizar_Click(object sender, EventArgs e)
        {
            this.setModos("UPDATE");
            try
            {
                if (String.IsNullOrWhiteSpace(txt_Codigo.Text) || String.IsNullOrWhiteSpace(txt_Nombre.Text) ||
                    String.IsNullOrWhiteSpace(txt_DireccionMac.Text) || String.IsNullOrWhiteSpace(txt_Puerto.Text) ||
                    String.IsNullOrWhiteSpace(txt_Modelo.Text) || String.IsNullOrWhiteSpace(txt_Marca.Text) ||
                    String.IsNullOrWhiteSpace(txt_Precio.Text))
                {
                    MessageBox.Show("Existe uno o más campos vacios. Llene todos los campos.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    EquiposRed equipo = new EquiposRed();
                    equipo.Codigo = txt_Codigo.Text;
                    equipo.Nombre = txt_Nombre.Text;
                    equipo.Direc_mac = txt_DireccionMac.Text;
                    equipo.Puerto = Convert.ToInt32(txt_Puerto.Text);
                    equipo.Modelo = txt_Modelo.Text;
                    equipo.Marca = txt_Marca.Text;
                    equipo.Fecha_Ingreso = DateTime.Now.ToString();
                    equipo.Precio = float.Parse(txt_Precio.Text);

                    int resultado = EquipoDB.actualizarEquipo(equipo);
                    if (resultado > 0)
                    {
                        MessageBox.Show("Equipo "+equipo.Nombre+" actualizado exitosamente.", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.setModos("INICIO");
                    }
                }
            }
            catch (System.NullReferenceException)
            {
                MessageBox.Show("No se pudo ingresar los datos del Equipo.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btn_Eliminar_Click(object sender, EventArgs e)
        {
            try
            {
                ListView.SelectedListViewItemCollection seleccion = this.listView_Despliegue.SelectedItems;
                foreach (ListViewItem item in seleccion)
                {
                    int id;
                    id =Convert.ToInt32(item.SubItems[0].Text);
                    var resultado = MessageBox.Show("Desea eliminar el Equipo de la lista?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (resultado == DialogResult.Yes)
                    {
                        int a = 0;
                        SqlCommand comando = new SqlCommand("DELETE FROM Equipo WHERE Id = "+id+"", EquipoDB.ObtenerConexion());
                        a = comando.ExecuteNonQuery();
                        MessageBox.Show("Equipo eliminado.");
                    }
                }
            }
            catch (SystemException)
            {
                MessageBox.Show("No se pudo eliminar el Equipo de su lista.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btn_BuscarTodos_Click(object sender, EventArgs e)
        {
            this.setModos("INICIO");
            listView_Despliegue.Items.Clear();
            try
            {
                SqlCommand comando = new SqlCommand("SELECT *FROM Equipo WHERE Id > 0", EquipoDB.ObtenerConexion());
                SqlDataReader dr = comando.ExecuteReader();
                while (dr.Read())
                {
                    ListViewItem item = new ListViewItem(dr["Id"].ToString());
                    item.SubItems.Add(dr["Codigo"].ToString());
                    item.SubItems.Add(dr["Nombre"].ToString());
                    item.SubItems.Add(dr["Direccion_MAC"].ToString());
                    item.SubItems.Add(dr["Puerto"].ToString());
                    item.SubItems.Add(dr["Modelo"].ToString());
                    item.SubItems.Add(dr["Marca"].ToString());
                    item.SubItems.Add(dr["Fecha_Ingreso"].ToString());
                    item.SubItems.Add(dr["Precio"].ToString());
                    listView_Despliegue.Items.Add(item);
                }
            }
            catch (System.NullReferenceException)
            {

            }

        }

        private void btn_Buscar_Click(object sender, EventArgs e)
        {
            this.setModos("INICIO");
            listView_Despliegue.Items.Clear();
            try
            {
                SqlCommand comando = new SqlCommand("SELECT *FROM Equipo WHERE Codigo = '"+txt_Buscar.Text+"'", EquipoDB.ObtenerConexion());
                SqlDataReader dr = comando.ExecuteReader();
                while (dr.Read())
                {
                    ListViewItem item = new ListViewItem(dr["Id"].ToString());
                    item.SubItems.Add(dr["Codigo"].ToString());
                    item.SubItems.Add(dr["Nombre"].ToString());
                    item.SubItems.Add(dr["Direccion_MAC"].ToString());
                    item.SubItems.Add(dr["Puerto"].ToString());
                    item.SubItems.Add(dr["Modelo"].ToString());
                    item.SubItems.Add(dr["Marca"].ToString());
                    item.SubItems.Add(dr["Fecha_Ingreso"].ToString());
                    item.SubItems.Add(dr["Precio"].ToString());
                    listView_Despliegue.Items.Add(item);
                }
            }
            catch(System.NullReferenceException)
            {

            }
        }


        private void btn_Salir_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void listView_Despliegue_SelectedIndexChanged(object sender, EventArgs e)
        {

            ListView.SelectedListViewItemCollection seleccionar = this.listView_Despliegue.SelectedItems;
            foreach (ListViewItem item in seleccionar)
            {
                txt_Codigo.Text = item.SubItems[1].Text;
                txt_Nombre.Text = item.SubItems[2].Text;
                txt_DireccionMac.Text = item.SubItems[3].Text;
                txt_Puerto.Text = item.SubItems[4].Text;
                txt_Modelo.Text = item.SubItems[5].Text;
                txt_Marca.Text = item.SubItems[6].Text;
                txt_Precio.Text = item.SubItems[8].Text;
                btn_Actualizar.Enabled = true;
                btn_Eliminar.Enabled = true;
            }
        }
    }
}

*/
====================================================================
/*Bibliote
//Agregar
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Biblioteca
{
    public class EquipoDB
    {
        public static SqlConnection ObtenerConexion()
        {
            try
            {
                SqlConnection conectar = new SqlConnection(Properties.Settings.Default.CadenaConexion);
                conectar.Open();
                return conectar;
            }
            catch(System.NullReferenceException)
            {
                MessageBox.Show("Error al intentar conectar a la Base de Datos.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return ObtenerConexion();
        }

        public static int agregarEquipo(EquiposRed addEquipo)
        {
            int retorno = 0;
            using (SqlConnection conexion = EquipoDB.ObtenerConexion())
            {
                SqlCommand comando = new SqlCommand(String.Format("INSERT INTO Equipo(Codigo, Nombre, Direccion_MAC, Puerto, Modelo, Marca, Fecha_Ingreso, Precio) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", addEquipo.Codigo, addEquipo.Nombre, addEquipo.Direc_mac, addEquipo.Puerto, addEquipo.Modelo, addEquipo.Marca, addEquipo.Fecha_Ingreso, addEquipo.Precio), conexion);
                retorno = comando.ExecuteNonQuery();
                conexion.Close();
            } return retorno;
        }

        public static int actualizarEquipo(EquiposRed upEquipo)
        {
            int retorno = 0;
            using (SqlConnection conexion = EquipoDB.ObtenerConexion())
            {
                SqlCommand comando = new SqlCommand(String.Format(
                    "UPDATE Equipo SET Codigo='{0}', Nombre='{1}', Direccion_MAC='{2}', Puerto='{3}', Modelo='{4}', Marca='{5}', Fecha_Ingreso='{6}', Precio='{7}'", upEquipo.Codigo, upEquipo.Nombre, upEquipo.Direc_mac, upEquipo.Puerto, upEquipo.Modelo, upEquipo.Marca, upEquipo.Fecha_Ingreso, upEquipo.Precio), conexion);
                retorno = comando.ExecuteNonQuery();
                conexion.Close();
            }return retorno;
        }
    }
}

*********************************************************************************namespace Biblioteca
{
    //Serializamos para que la clase figure y pueda ser enviada la informacion
    [Serializable]
    public class EquiposRed
    {
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private String codigo;

        public String Codigo
        {
            get { return codigo; }
            set { codigo = value; }
        }
        private String nombre;

        public String Nombre
        {
            get { return nombre; }
            set { nombre = value; }
        }
        private String direc_mac;

        public String Direc_mac
        {
            get { return direc_mac; }
            set { direc_mac = value; }
        }
        private int puerto;

        public int Puerto
        {
            get { return puerto; }
            set { puerto = value; }
        }
        private String marca;

        public String Marca
        {
            get { return marca; }
            set { marca = value; }
        }
        private String modelo;

        public String Modelo
        {
            get { return modelo; }
            set { modelo = value; }
        }
        private String fecha_Ingreso;

        public String Fecha_Ingreso
        {
            get { return fecha_Ingreso; }
            set { fecha_Ingreso = value; }
        }

        private float precio;

        public float Precio
        {
            get { return precio; }
            set { precio = value; }
        }

        public EquiposRed(){}

        public EquiposRed(int pId, String pCodigo, String pNombre, String pDirecMac, int pPuerto,
            String pMarca, String pModelo, String pFechaIngreso, float pPrecio)
        {
            Id = pId;
            Codigo = pCodigo;
            Nombre = pNombre;
            Direc_mac = pDirecMac;
            Puerto = pPuerto;
            Marca = pMarca;
            Modelo = pModelo;
            Fecha_Ingreso = pFechaIngreso;
            Precio = pPrecio;
        }

    }
}

*/

Form_TCP_Client_ExplorarArchivos

/*CLinte
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Cliente_TCP
{
    public partial class FrmClienteTcp : Form
    {
        public FrmClienteTcp()
        {
            InitializeComponent();
        }

        private void FrmClienteTcp_Load(object sender, EventArgs e)
        {

        }

        private void btnExplorar_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialogo = new OpenFileDialog();
           
            if (dialogo.ShowDialog() == DialogResult.OK)
            {
                txtNombreArchivo.Text = dialogo.FileName;
                btnEnviar.Enabled = true;
            }
        }

        private void btnEnviar_Click(object sender, EventArgs e)
        {
            Stream flujoArchivo = File.OpenRead(txtNombreArchivo.Text);

            byte[] bufferEnvio = new byte[flujoArchivo.Length];
            flujoArchivo.Read(bufferEnvio, 0, (int)flujoArchivo.Length);
           
            TcpClient cliente = new TcpClient(txtServidor.Text, 12345);

            NetworkStream flujoRed = cliente.GetStream();

            flujoRed.Write(bufferEnvio, 0, bufferEnvio.GetLength(0));

            flujoRed.Close();
        }
    }
}
*/
========================================================================
/*Servidor
//Agregar
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;


namespace Servidor_TCP
{
    public partial class FrmServidorTcp : Form
    {
        private ArrayList clientes;

        private IPAddress[] informacionIP;
        private IPAddress ipReal;

        private delegate void ActualizarListBox(string texto);

        public FrmServidorTcp()
        {
            InitializeComponent();
        }

        private void FrmServidorTcp_Load(object sender, EventArgs e)
        {
            //guarda todas las direcciones IP que tiene el hostname.
            informacionIP = Dns.GetHostAddresses(Dns.GetHostName());

            foreach (IPAddress ip in informacionIP)
            {
                if (ip.AddressFamily.ToString() == ProtocolFamily.InterNetwork.ToString())
                    if (!ip.Equals("127.0.0.1"))
                        ipReal = ip;
            }

            lblInfo.Text = "Mi dirección IP es: " + ipReal.ToString();

            clientes = new ArrayList();

            //Inicio del hilo
            Thread hiloEscucha = new Thread(new ThreadStart(TareaEscucha));
            hiloEscucha.Start();
        }

        public void TareaEscucha()
        {
            TcpListener socketEscucha = new TcpListener(ipReal, 12345);
            socketEscucha.Start();

            while (true)
            {
                Socket socketCliente = socketEscucha.AcceptSocket();
               
                if (socketCliente.Connected)
                {
                    lsbClientes.Invoke(new ActualizarListBox(ActualizarInformacionEnListBox), new object[] { socketCliente.RemoteEndPoint.ToString() + " conectado..." });
                   
                    lock (this)
                    {
                        clientes.Add(socketCliente);
                    }
           
                    ThreadStart iniciadorHiloCliente = new ThreadStart(TareaCliente);
                    Thread hiloCliente = new Thread(iniciadorHiloCliente);
                    hiloCliente.Start();
                }
            }
        }

        public void TareaCliente()
        {
            Socket cliente = (Socket)clientes[clientes.Count - 1];

            NetworkStream flujoRed = new NetworkStream(cliente);
           
            int indicadorLectura = 0;

            int tamanioBloque = 1024;
           
            int numero = 1;
            IPEndPoint ipRemoto = cliente.RemoteEndPoint as IPEndPoint;
            DateTime hora = DateTime.Now;

            string nombreFichero = "Archivos" + numero++ +"_"+ ipRemoto.Address +"_" +hora.Hour.ToString() + "." + hora.Minute.ToString() + "." + hora.Second.ToString() +".txt";

            Byte[] datosRx = new Byte[tamanioBloque];

            lock(this)
            {
                Stream flujoArchivo = File.OpenWrite("B:\\Repaso\\Form_TCP_Client_ExplorarArchivos"+nombreFichero);
               
                while(true)
                {
                    indicadorLectura = flujoRed.Read(datosRx, 0, tamanioBloque);
                    flujoArchivo.Write(datosRx, 0, indicadorLectura);
                   
                    if (indicadorLectura == 0)
                        break;
                }
                flujoArchivo.Close();
            }

            lsbClientes.Invoke(new ActualizarListBox(ActualizarInformacionEnListBox), new  object[] { "Archivo guardado exitosamente..." });

            cliente = null;
        }

        public void ActualizarInformacionEnListBox(string texto)
        {
            lsbClientes.Items.Add(texto);
        }
    }
}
*/

Form_UDP_Client

/*Cliente
//Agreagr
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace Frm_ClienteUDP
{
    public partial class Frm_ClienteUDP : Form
    {
        public Frm_ClienteUDP()
        {
            InitializeComponent();
        }

        private delegate void ActualizarInformacion(string texto);
        byte[] bufferTx;
        byte[] bufferRx;
        string datosRx = "";
        bool terminado = false;

        private void btn_Enviar_Click(object sender, EventArgs e)
        {
            int puerto = Convert.ToInt32(txt_PuertoEquipoRemoto.Text);
            string direccionIp = txt_EquipoRemoto.Text;

            UdpClient cliente = new UdpClient();
            cliente.Connect(direccionIp, puerto);

            bufferTx = Encoding.ASCII.GetBytes(txt_Mensaje.Text);
            cliente.Send(bufferTx, bufferTx.Length);

            //creacion de hilos.
            Thread hiloComunicacion = new Thread(()=> Comunicaciones(cliente));
            hiloComunicacion.Start();
            txt_Mensaje.Clear();
        }

        public void Comunicaciones(object ack)
        {
            UdpClient cliente = (UdpClient)ack;
            while (!terminado)
            {
                IPEndPoint equipoRemoto = new IPEndPoint(IPAddress.Any, 0);
                bufferRx = cliente.Receive(ref equipoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx);

                lsb_AckServidor.Invoke(new ActualizarInformacion(ActualizarItemsEnsbConexion),
                    new object [] {datosRx});
            }
        }

        public void ActualizarItemsEnsbConexion(string texto)
        {
            lsb_AckServidor.Items.Add(texto);
        }
    }
}

*/
========================================================================
/*Servidor
//Agregar
using System.Configuration;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace ServidorUDP
{
    public partial class Form_ServidorUDP : Form
    {
        public Form_ServidorUDP()
        {
            InitializeComponent();
        }

        private delegate void ActualizarElemento(string texto);
        private delegate void ActualizarInformacion();
        bool terminado;
        byte[] bufferRx = new byte[1024];
        byte[] bufferTx;
        string datosRx = "";

        private void Form_ServidorUDP_Load(object sender, EventArgs e)
        {
            Thread hiloComunicaciones = new Thread(new ThreadStart(Comunicaciones));
            hiloComunicaciones.Start();
        }

        public void Comunicaciones()
        {
            string direccionIp= ConfigurationManager.AppSettings["IP"];
            string puerto = ConfigurationManager.AppSettings["puerto"];

            IPEndPoint equipoConexion = new IPEndPoint(IPAddress.Parse(direccionIp), Convert.ToInt32(puerto));

            UdpClient servidor = new UdpClient(equipoConexion);
           

            while (!terminado)
            {
                IPEndPoint equipoRemoto = new IPEndPoint(IPAddress.Any, 0);
                bufferRx = servidor.Receive(ref equipoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx);

                string texto = equipoRemoto.Address.ToString() + "; Mensaje: " + datosRx;

                lsbConexiones.Invoke(new ActualizarInformacion(InformarDelCliente));
                lsbConexiones.Invoke(new ActualizarElemento(ActualizarItemsEnlsbConexion),
                    new object[] {texto});

                bufferTx = Encoding.ASCII.GetBytes("Datos recibidos por el servidor de la IP: "+equipoRemoto.Address.ToString());
                servidor.Send(bufferTx, bufferTx.Length, equipoRemoto);

            }
        }

        public void ActualizarItemsEnlsbConexion(string texto)
        {
            lsbConexiones.Items.Add(texto);
        }

        public void InformarDelCliente()
        {
            lsbConexiones.Items.Add("Transmision recibida a las: " + DateTime.Now.ToString());
        }
       
    }
}

*/

TCP_Eco

/*CLiente
//Agregar
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ClienteTCPTipoEco
{
    class Program
    {
        static void Main(string[] args)
        {
             Console.WriteLine("CLIENTE TCP TIPO ECO");

            string datos = "##--##--##----***----##--##--##";

            IPEndPoint remoto = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
           
            TcpClient cliente = new TcpClient();

            byte[] bufferRx = new byte[512];
            int indicador;
           
            cliente.Connect(remoto);

            if(cliente.Connected)
            {
                NetworkStream flujo = cliente.GetStream();
                byte[] bufferTx = Encoding.ASCII.GetBytes(datos);
                flujo.Write(bufferTx, 0, bufferTx.Length);
               
                do
                {
                    indicador = flujo.Read(bufferRx, 0, bufferRx.Length);

                    if(indicador>0)
                    {
                        datos = Encoding.ASCII.GetString(bufferRx);
                       
                        Console.WriteLine("Mensaje Recibido");
                        Console.WriteLine("Se recibio: \n{0}", datos);
                    }
                }while(indicador>0);
                cliente.Close();
            }
            Console.ReadLine();
        }
    }
}

*/
=======================================================================
/*Servidor
//Agregar
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ServidorTCPTipoEco
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("SERVIDOR TCP TIPO ECO");
           
            TcpClient manejoCliente;

            TcpListener servidor;

            byte[] bufferRx = new byte[512];
            byte[] bufferTx;
            int datosLeidos;
            string datos;

            IPEndPoint puntoLocal = new IPEndPoint(IPAddress.Any, 11000);
            servidor = new TcpListener(puntoLocal);

            Console.WriteLine("El servidor está escuchando...");
            servidor.Start(5);

            while(true)
            {
                manejoCliente = servidor.AcceptTcpClient();

                Console.WriteLine("El servidor ha aceptado a un cliente...");

                NetworkStream flujo = manejoCliente.GetStream();

                do
                {
                    datosLeidos = flujo.Read(bufferRx, 0, bufferRx.Length);

                    if(datosLeidos>0)
                    {
                        datos = Encoding.ASCII.GetString(bufferRx);

                        Console.WriteLine("Mensaje Recibido");
                        Console.WriteLine("Se recibio: \n{0}", datos);

                        Console.WriteLine("Mensaje Enviado");
                       
                        bufferTx = Encoding.ASCII.GetBytes(datos);
                        flujo.Write(bufferTx, 0, bufferTx.Length);
                    }
                }while(datosLeidos>0);
            }
        }
    }
}
*/

TCPSocket

/*TCP_Cleinte
namespace ClientePrueba
{
    public partial class Form1 : Form
    {
        byte[] datosTx = new byte[2048];
        string mensaje;
        Socket socketCliente = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        public Form1()
        {
            InitializeComponent();
        }

        private void btnConectar_Click(object sender, EventArgs e)
        {
            socketCliente.Connect(txtDireccion.Text, Convert.ToInt16(txtPuerto.Text));

            try
            {
                mensaje = "$Conectado";
                datosTx = System.Text.Encoding.ASCII.GetBytes(mensaje);

                socketCliente.Send(datosTx,
                    System.Text.Encoding.ASCII.GetByteCount(mensaje),
                    SocketFlags.None);

                int cuenta = socketCliente.Receive(datosTx);
                mensaje = System.Text.Encoding.ASCII.GetString(datosTx, 0, cuenta);
                Console.WriteLine(mensaje);

                txtServidor.Text = mensaje;
            }
            catch (SocketException Error)
            {
                MessageBox.Show("Excepcion" + Error.Message);
            }
        }


        private void btnHello_Click(object sender, EventArgs e)
        {
            mensaje = "$Hello$" + txtNombre.Text;
            datosTx = System.Text.Encoding.ASCII.GetBytes(mensaje);
            socketCliente.Send(datosTx,
                System.Text.Encoding.ASCII.GetByteCount(mensaje),
                SocketFlags.None);
            datosTx = new byte[1024];
            int cuenta = socketCliente.Receive(datosTx);

            mensaje = System.Text.Encoding.ASCII.GetString(datosTx, 0, cuenta);
            string[] cadena = mensaje.Split('$');
            txtServidor.Text = cadena[2];

        }

        private void btnEcho_Click(object sender, EventArgs e)
        {
            mensaje = "$Echo$" + txtRepetir.Text;
            datosTx = System.Text.Encoding.ASCII.GetBytes(mensaje);
            socketCliente.Send(datosTx,
                System.Text.Encoding.ASCII.GetByteCount(mensaje),
                SocketFlags.None);
            datosTx = new byte[1024];
            int cuenta = socketCliente.Receive(datosTx);

            mensaje = System.Text.Encoding.ASCII.GetString(datosTx, 0, cuenta);
            string[] cadena = mensaje.Split('$');
            txtServidor.Text = cadena[2];
        }

        private void btnDate_Click(object sender, EventArgs e)
        {
            mensaje = "$Date";
            datosTx = System.Text.Encoding.ASCII.GetBytes(mensaje);
            socketCliente.Send(datosTx,
                System.Text.Encoding.ASCII.GetByteCount(mensaje),
                SocketFlags.None);
            datosTx = new byte[1024];
            int cuenta = socketCliente.Receive(datosTx);

            mensaje = System.Text.Encoding.ASCII.GetString(datosTx, 0, cuenta);
            string[] cadena = mensaje.Split('$');
            txtServidor.Text = cadena[2];
        }

        private void btnRandom_Click(object sender, EventArgs e)
        {
            mensaje = "$Random";
            datosTx = System.Text.Encoding.ASCII.GetBytes(mensaje);
            socketCliente.Send(datosTx,
                System.Text.Encoding.ASCII.GetByteCount(mensaje),
                SocketFlags.None);
            datosTx = new byte[1024];
            int cuenta = socketCliente.Receive(datosTx);

            mensaje = System.Text.Encoding.ASCII.GetString(datosTx, 0, cuenta);
            string[] cadena = mensaje.Split('$');
            txtServidor.Text = cadena[2];
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            mensaje = "$Salir";
            datosTx = System.Text.Encoding.ASCII.GetBytes(mensaje);
            socketCliente.Send(datosTx,
                System.Text.Encoding.ASCII.GetByteCount(mensaje),
                SocketFlags.None);
            string [] cadena = mensaje.Split('$');

            txtServidor.Text = cadena[1];
            socketCliente.Close();
            Application.Exit();
        }
    }
}

*/
=======================================================================
/*TCP_Servidor
namespace ServidorPrueba
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Uso del servidor...");
            byte[] bytes = new byte[1024];
            int cuenta;
            String data = " ";

            IPAddress direccionIP = IPAddress.Parse("127.0.0.1");

            IPEndPoint puntoFinal = new IPEndPoint(direccionIP, 12345);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(puntoFinal);

            //-1 para q acepte una unica conexion.
            socket.Listen(-1);

            Socket manipuladorCliente = socket.Accept();
            Console.WriteLine("El servidor enlazó el socket...");
            try
            {
                do
                {
                    cuenta = manipuladorCliente.Receive(bytes);
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, cuenta);
                   
                    Console.WriteLine("Mensaje recibido: "+data);
                    string[] cadena = data.Split('$');
                    string respuesta = " ";

                    if (cadena[1] == "Conectado")
                    {
                        respuesta = "$Servidor";
                        Console.WriteLine("Respuesta del servidor: "+ respuesta);
                    }

                    else if (cadena[1] == "Hello")
                    {
                        respuesta = "$Hello$Bienvenido" + cadena[2];
                        Console.WriteLine("Respuesta del servidor: " + respuesta);
                    }

                    else if (cadena[1] == "Echo")
                    {
                        respuesta = "$Echo$" + cadena[2];
                        Console.WriteLine("Respuesta del servidor: " + respuesta);
                    }

                    else if (cadena[1] == "Date")
                    {
                        string dia = Convert.ToString(System.DateTime.Now.Day);
                        string mes = Convert.ToString(System.DateTime.Now.Month);
                        string anio = Convert.ToString(System.DateTime.Now.Year);

                        respuesta = "$Date$"+dia+"/"+mes+"/"+anio;
                        Console.WriteLine("Respuesta del servidor: " + respuesta);
                    }

                    else if (cadena[1] == "Random")
                    {
                        Random a = new Random();
                        int numero = Convert.ToInt16(a.Next(0, 101));
                        respuesta = "$Random$" + numero;
                        Console.WriteLine("Respuesta del servidor: " + respuesta);
                    }

                    //Proceso de los mensajes

                    bytes = System.Text.Encoding.ASCII.GetBytes(respuesta);
                    manipuladorCliente.Send(bytes,
                        System.Text.Encoding.ASCII.GetByteCount(respuesta),
                        SocketFlags.None);

                } while (data != "$Exit");

                //Console.WriteLine("Conexion finalizada");
                //manipuladorCliente.Shutdown(SocketShutdown.Both);
                //manipuladorCliente.Close();
            }
            catch(Exception ex)
            {
                Console.WriteLine("Excepcion" + ex.Message);
            }
        }
    }
}
*/

UDPSocket

/*UDPSocket_Cliente
//Agregar
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ClienteUDP_Socket
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        byte[] bufferTx = new byte[1024];
        byte[] bufferRx = new byte[1024];
        string datosRx = "";
        string mensaje = "";

        Socket socketCliente = new Socket(AddressFamily.InterNetwork,
            SocketType.Dgram,
            ProtocolType.Udp);


        private void btnCOnectar_Click(object sender, EventArgs e)
        {
            if (txtDireccion.Text == "" || txtPuerto.Text == "")
            {
                MessageBox.Show("Ingrese los campos solicitados");
            }
            else
            {
                IPAddress direccionIp = IPAddress.Parse(txtDireccion.Text);
                int puertoRemoto = Convert.ToInt32(txtPuerto.Text);

                IPEndPoint puntoFinal = new IPEndPoint(direccionIp, puertoRemoto);

                //Envio de mensajes
                mensaje = "$Conectado";
                bufferTx = Encoding.ASCII.GetBytes(mensaje);

                socketCliente.SendTo(bufferTx, bufferTx.Length, SocketFlags.None, puntoFinal);

                //Recibir mensajes del servidor
                IPEndPoint recibe = new IPEndPoint(IPAddress.Any, 0);
                EndPoint puntoRemoto = (EndPoint)recibe;

                int cuenta = socketCliente.ReceiveFrom(bufferRx, ref  puntoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx, 0, cuenta);
                string[] cadena = datosRx.Split('$');

                if (cadena[1] == "Hola")
                {
                    lblRecibir.Text = "Cliente conectado.";
                }
            }

        }

        private void btnEnviar_Click(object sender, EventArgs e)
        {
            if( txtDireccion.Text=="" || txtPuerto.Text =="" || txtEnviar.Text=="")
            {
                MessageBox.Show("Ingrese los campos solicitados");
            }
            else
            {
                IPEndPoint puntoFinal = new IPEndPoint(IPAddress.Parse(txtDireccion.Text), Convert.ToInt32(txtPuerto.Text));

                //Envio de mensajes
                //mensaje = "$Random";
                mensaje = txtEnviar.Text;
                bufferTx = Encoding.ASCII.GetBytes(mensaje);

                socketCliente.SendTo(bufferTx, bufferTx.Length, SocketFlags.None, puntoFinal);

                //Recibir mensajes del servidor
                IPEndPoint recibe = new IPEndPoint(IPAddress.Any, 0);
                EndPoint puntoRemoto = (EndPoint)recibe;

                int cuenta = socketCliente.ReceiveFrom(bufferRx, ref  puntoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx, 0, cuenta);
                string[] cadena = datosRx.Split('$');

                lblMensajeRecibido.Text = "Mensaje Recibido: " + cadena[1];
            }
        }

    }
}

*/
======================================================================
/*UDPSocket_Servidor
//Agregar
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ServidorUDP_Socket
{
    class Program
    {
        static void Main(string[] args)
        {
            bool terminado = false;
            byte[] bufferRx = new byte[1024];
            byte[] bufferTx = new byte[1024];
            string datosRx = "";
            string datosTx = "";
            int puerto = 12345;
            int cuenta;

            IPAddress direccionIP = IPAddress.Parse("127.0.0.1");
            IPEndPoint puntoFinal = new IPEndPoint(direccionIP, puerto);
            Socket socketServidor = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram,
                ProtocolType.Udp);

            socketServidor.Bind(puntoFinal);

            //recibir mensaje del cliente
            IPEndPoint envio = new IPEndPoint(IPAddress.Any, 0);
            EndPoint puntoRemoto = (EndPoint)(envio);

            Console.WriteLine("Servidor iniciado....");

            while (!terminado)
            {
                cuenta = socketServidor.ReceiveFrom(bufferRx, ref puntoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx, 0, cuenta);
                string[] cadena = datosRx.Split('$');

                if(cadena[1] == "Conectado")
                {
                    Console.WriteLine("Estado: " + datosRx);
                    Console.WriteLine("Esperando por mensajes...");
                   
                    //mensaje de envio del servidor al cliente
                    datosTx = "$Hola";
                    bufferTx = Encoding.ASCII.GetBytes(datosTx);

                }

                else if (cadena[1] == "Random")
                {
                    Console.WriteLine("Mensaje recibido: " + cadena[1]);                  
                    Random random = new Random();

                    int numAleatorio = random.Next(0, 101);
                    Console.WriteLine("Mensaje enviado por el servidor: " + numAleatorio);
                    Console.WriteLine("Esperando por mensajes...");

                    //mensaje de envio del servidor al cliente
                    datosTx = "$"+Convert.ToString(numAleatorio);
                    bufferTx = Encoding.ASCII.GetBytes(datosTx);

                }

                //Envio de mensaje
                socketServidor.SendTo(bufferTx, bufferTx.Length, SocketFlags.None, puntoRemoto);
            }
        }
    }
}

*/

ServiceCedula

/*IService

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/validar/{ci}")]
    IngresarCedula Validar(string ci);

    [OperationContract]
    int[] ConvertirANumero(string ci);

    [OperationContract]
    int Procesar(int[] ci);

    [OperationContract]
    string TranformarDigitoATexto(int digito);
}

[DataContract]
public class IngresarCedula
{
    [DataMember]
    public string Cedula{get;set;}
}

*/
======================================================================
/*Service

//Agregar
using System.Text.RegularExpressions;//Para REGEX
using System.Windows.Input;

public class Service : IService
{
    public IngresarCedula Validar(string ci)
    {
        int ultimoDigito =Procesar(ConvertirANumero(ci));
        string numeroLetra = TranformarDigitoATexto(ultimoDigito);

        IngresarCedula mensaje = new IngresarCedula();
        mensaje.Cedula = String.Format("Su ultimo número es:  {0}", numeroLetra);
        return mensaje;
    }

    public int[] ConvertirANumero(string ci)
    {
        char[] cedulaDigitos = ci.ToCharArray();
        int i = 0;
        int[] cedulaFinal = new int[cedulaDigitos.Count()];//arreglo de 10 números

        foreach (char digito in cedulaDigitos)
        {
            cedulaFinal[i] = int.Parse(digito.ToString());
            i++;
        }
        return cedulaFinal;
    }

    public int Procesar(int[] ci)
    {
        int suma = 0;
        for (int i = 0; i < ci.Count(); i = i + 2)
        {
            ci[i] = ci[i] * 2;
            if (ci[i] > 9)
            {
                ci[i] = ci[i] - 9;
            }
        }
        foreach (int numero in ci)
        {
            suma = suma + numero;
        }
        int[] resultado = ConvertirANumero(suma.ToString());
        return 10 - resultado[1];
    }

    public string TranformarDigitoATexto(int digito)
    {
        string numero;

        switch (digito)
        {
            case 0:
                numero = "CERO";
                break;
            case 1:
                numero = "UNO";
                break;
            case 2:
                numero = "DOS";
                break;
            case 3:
                numero = "TRES";
                break;
            case 4:
                numero = "CUATRO";
                break;
            case 5:
                numero = "CINCO";
                break;
            case 6:
                numero = "SEIS";
                break;
            case 7:
                numero = "SIETE";
                break;
            case 8:
                numero = "OCHO";
                break;
            case 9:
                numero = "NUEVE";
                break;
            default:
                numero = "No existe";
                break;
        }
        return numero;
    }
}

*/

ValidarCI

/*
//Agregar
using System.Text.RegularExpressions;// Para usar REGEX


namespace ValidarCI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string cedula = textBox1.Text;
            Regex cadenaAcomparar = new Regex(@"\A[0-9]{9}\Z");//A-Z revisar cadena completa, Corchetes: caracteres a escoger. LLaves: número de caracteres
            if (cadenaAcomparar.IsMatch(cedula))
            {
                //MessageBox.Show(ConvertirANumero(cedula)[9].ToString());
 
                int ultimoDigito=Comprobar(ConvertirANumero(cedula));
                textBox2.Text = Convert.ToString(ultimoDigito);
                //MessageBox.Show(ultimoDigito.ToString());
            }
            else
            {
                MessageBox.Show("falló");
            }
        }

        public int[] ConvertirANumero (string cedula)
        {
            char[] cedulaDigitos = cedula.ToCharArray();
            int i =0;
            int[] cedulaFinal = new int[cedulaDigitos.Count()];//arreglo de 10 números

            foreach(char digito in cedulaDigitos)
            {  
                cedulaFinal [i]= int.Parse(digito.ToString());
                i++;
            }
            return cedulaFinal;
        }  

        public int Comprobar (int[] cedula)
        {          
            int suma=0;
            for (int i = 0; i < cedula.Count(); i = i + 2)
            {
                cedula [i]=cedula[i] * 2;
                if (cedula[i] > 9)
                {
                    cedula[i] = cedula[i] - 9;
                }
            }
            foreach (int numero in cedula)
            {
                suma = suma + numero;
            }
            int [] resultado =  ConvertirANumero(suma.ToString());
            return 10- resultado[1];
        }
    }
}

*/

TCP_Client

/*ClienteTCP
//Agregar
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ClienteTCP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        TcpClient cliente = new TcpClient();
        byte[] bufferTx;

        private void btnCOnectar_Click(object sender, EventArgs e)
        {
            int puerto = Convert.ToInt32(txtPuerto.Text);
            IPAddress direccionIp = IPAddress.Parse(txtDireccion.Text);

            IPEndPoint puntoRemoto = new IPEndPoint(direccionIp, puerto);

            cliente.Connect(puntoRemoto);

            NetworkStream mensaje = cliente.GetStream();

            bufferTx = Encoding.ASCII.GetBytes("$Conectar");

            if (mensaje != null)
            {
                mensaje.Write(bufferTx, 0, bufferTx.Length);
                btnCOnectar.Enabled = false;
            }
        }

        private void btnEnviar_Click(object sender, EventArgs e)
        {
            if (cliente.Connected)
            {
                NetworkStream mensaje = cliente.GetStream();
                bufferTx = Encoding.ASCII.GetBytes(txtEnviar.Text);

                mensaje.Write(bufferTx, 0, bufferTx.Length);

                //cliente.Close();
            }

        }
    }
}

*/
=======================================================================
/*ServidorTCP
//Agregar
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ServidorTCP
{
    class Program
    {
        private const int puertoEscucha = 12345;

        static void Main(string[] args)
        {
            bool terminado = false;
            int cuenta;
            byte[] bufferRx = new byte[1024];
            string datosRx = "";

            TcpClient manejoCliente;

            IPAddress direccionIp = IPAddress.Parse("127.0.0.1");
            IPEndPoint puntoLocal = new IPEndPoint(direccionIp,puertoEscucha);

            TcpListener servidor = new TcpListener(puntoLocal);
            Console.WriteLine("El servidor esta escuchando...");
            servidor.Start();

            while(!terminado)
            {
                manejoCliente = servidor.AcceptTcpClient();
                NetworkStream flujo = manejoCliente.GetStream();
                do
                {
                    bufferRx = new byte[1024];
                    cuenta = flujo.Read(bufferRx, 0, bufferRx.Length);

                    if (cuenta > 0)
                    {
                        datosRx = Encoding.ASCII.GetString(bufferRx);
                        Console.WriteLine("Mensaje recibido: "+datosRx);
                    }
                } while (cuenta > 0);
            }
        }
    }
}

*/

UDP_Client

/* CLiente_UDP
//Agregar
using System.IO;
using System.Net.Sockets;
using System.Net;

namespace ClienteUDP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        byte[] bufferRx;
        string datosRx = "";
        string mensaje = "";
        byte[] bufferTx;

        UdpClient cliente = new UdpClient();

        private void btnCOnectar_Click(object sender, EventArgs e)
        {
            IPAddress direccionIp = IPAddress.Parse(txtDireccion.Text);
            int puerto = Convert.ToInt32(txtPuerto.Text);

            //Envia el mensaje
            IPEndPoint puntoFinal = new IPEndPoint(direccionIp, puerto);

            mensaje = "$Conectado";

            if (mensaje.Length != 0)
            {
                bufferTx = Encoding.ASCII.GetBytes(mensaje);
                cliente.Send(bufferTx, bufferTx.Length, puntoFinal);
            }

            //Recibir los datos del servidor
            bufferRx = cliente.Receive(ref puntoFinal);
            datosRx = Encoding.ASCII.GetString(bufferRx, 0, bufferRx.Length);
            string[] cadena = datosRx.Split('$');

            lblMensaje.Text = cadena[1];
            txtRecibir.Text= cadena[2];
        }
    }
}
*/
==================================================================
/* ServidorUDP
//Agreagr
using System.IO;
using System.Net;
using System.Net.Sockets;


namespace ServidorUDP
{
    class Program
    {
        //private const int puertoEscucha = 12345;

        static void Main(string[] args)
        {
            bool terminado = false;
            int puertoEscucha = 12345;
            byte[] bufferRx;
            string datosRx = "";
            string datosTx = "";
            byte[] bufferTx;


            UdpClient servidor = new UdpClient(puertoEscucha);
            IPAddress direccionIp = IPAddress.Parse("127.0.0.1");
            IPEndPoint sitioRemoto = new IPEndPoint(direccionIp, puertoEscucha);

            Console.WriteLine("Empezando la comunicacion...");

            while (!terminado)
            {
                Console.WriteLine("Esperando por mensaje");
                //Recibe del cliente
                bufferRx = servidor.Receive(ref sitioRemoto);

                Console.WriteLine("Se recibio un mensaje de " + sitioRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx, 0, bufferRx.Length);

                string[] cadena = datosRx.Split('$');
                Console.WriteLine("Servidor recibio: " + cadena[1]);

                if (cadena[1] == "Conectado")
                {
                    Random random = new Random();
                    int numAleatorio = random.Next(0,101);

                    datosTx = "$Envie Datos$" + numAleatorio;
                    Console.WriteLine("El mensaje enviado es: " + datosTx);
                }

                bufferTx = Encoding.ASCII.GetBytes(datosTx);
                servidor.Send(bufferTx, bufferTx.Length, sitioRemoto);

            }
        }
    }
}

*/

jueves, 18 de febrero de 2016

Utilizacion de Servicios WCF

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/validar/{ci}")]
    IngresarCedula Validar(string ci);

    [OperationContract]
    int[] ConvertirANumero(string ci);

    [OperationContract]
    int Procesar(int[] ci);

    [OperationContract]
    string TranformarDigitoATexto(int digito);
}

[DataContract]
public class IngresarCedula
{
    [DataMember]
    public string Cedula{get;set;}
}

========================================================================

//Agregar
using System.Text.RegularExpressions;//Para REGEX
using System.Windows.Input;

public class Service : IService
{
    //public IngresarCedula Validar(string ci)
    //{
    //    IngresarCedula mensaje = new IngresarCedula();
    //    mensaje.Cedula = string.Format("Servicio WCF usando REST, Su numero de CI es: {0}", ci);
    //    return mensaje;
    //}

    public IngresarCedula Validar(string ci)
    {
        int ultimoDigito =Procesar(ConvertirANumero(ci));
        string numeroLetra = TranformarDigitoATexto(ultimoDigito);
        IngresarCedula mensaje = new IngresarCedula();

        mensaje.Cedula = String.Format("Su ultimo número es:  {0}", numeroLetra);
        return mensaje;
    }

    public int[] ConvertirANumero(string ci)
    {
        char[] cedulaDigitos = ci.ToCharArray();
        int i = 0;
        int[] cedulaFinal = new int[cedulaDigitos.Count()];//arreglo de 10 números

        foreach (char digito in cedulaDigitos)
        {
            cedulaFinal[i] = int.Parse(digito.ToString());
            i++;
        }
        return cedulaFinal;
    }

    public int Procesar(int[] ci)
    {
        int suma = 0;
        for (int i = 0; i < ci.Count(); i = i + 2)
        {
            ci[i] = ci[i] * 2;
            if (ci[i] > 9)
            {
                ci[i] = ci[i] - 9;
            }
        }
        foreach (int numero in ci)
        {
            suma = suma + numero;
        }
        int[] resultado = ConvertirANumero(suma.ToString());
        return 10 - resultado[1];
    }

    public string TranformarDigitoATexto(int digito)
    {
        string numero;

        switch (digito)
        {
            case 1:
                numero = "UNO";
                break;
            case 2:
                numero = "DOS";
                break;
            case 3:
                numero = "TRES";
                break;
            case 4:
                numero = "CUATRO";
                break;
            case 5:
                numero = "CINCO";
                break;
            case 6:
                numero = "SEIS";
                break;
            case 7:
                numero = "SIETE";
                break;
            case 8:
                numero = "OCHO";
                break;
            case 9:
                numero = "NUEVE";
                break;
            default:
                numero = "No existe";
                break;
        }
        return numero;
    }
}