elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía rápida para descarga de herramientas gratuitas de seguridad y desinfección


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Ejercicios
| | | |-+  Retos .Net
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 2 [3] Ir Abajo Respuesta Imprimir
Autor Tema: Retos .Net  (Leído 19,080 veces)
final_frontier
Wiki

Desconectado Desconectado

Mensajes: 583


WOLOLOOO! Deal with it x)


Ver Perfil
Re: Retos .Net
« Respuesta #20 en: 6 Diciembre 2010, 03:26 am »

@Lord R.N.A.

Cacho de ca**** yo no descansaba si no daba con la tecla :xD :xD :xD :xD

Mi solución propuesta

Antes que nada, la tabla que he utilizado

Código
  1. CREATE TABLE contacto(
  2.  
  3.  nombre  VARCHAR(50) NOT NULL,
  4.  sexo    CHAR(1),
  5.  edad    INT,
  6.  tlf     CHAR(9) NOT NULL,
  7.  
  8.  CONSTRAINT KeyAgenda PRIMARY KEY (nombre, tlf),
  9.  CONSTRAINT CaracterSexo CHECK sexo IN ('H', 'M')
  10. );

Y aquí el programa

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. //Para conectar con base de datos
  6. using MySql.Data.MySqlClient;
  7.  
  8.  
  9. namespace Agenda
  10. {
  11.    class Program
  12.    {
  13.        private bool abierto = false;
  14.        private MySqlDataReader Reader;
  15.        private MySqlConnection connection;
  16.        private MySqlCommand command;
  17.        private int numContactos = 0;
  18.        private string MyConString;
  19.        private bool encontrar(string nom, string tel)
  20.        {
  21.            bool ret = false;
  22.  
  23.            if (numContactos != 0)
  24.            {
  25.                string comando = "SELECT * FROM contacto "
  26.                                 + "WHERE nombre = '" + nom + "' AND "
  27.                                 + "tlf = '" + tel + "';";
  28.                //Comando de selección para la búsqueda
  29.                command.CommandText = comando;
  30.                Reader = command.ExecuteReader();
  31.  
  32.                while ((Reader.Read()) && (ret == false))
  33.                    ret = true; //Si llega a entrar en el bucle es que por lo menos
  34.                //ha encontrado un dato. Al estar buscando por la
  35.                //clave primaria de la relación, sólo debería devolver
  36.                //un único valor, el buscado.
  37.                Reader.Dispose();
  38.            }
  39.  
  40.            return ret;
  41.        }
  42.  
  43.        public void agregarCon(string nom, char sex, int edad, string tlf)
  44.        {
  45.            if (!encontrar(nom, tlf))
  46.            {
  47.                string agrega = "INSERT INTO contacto VALUES('" + nom + "','" + sex + "','" + edad + "','" + tlf + "');";
  48.                command.CommandText = agrega;
  49.                command.ExecuteNonQuery();
  50.                numContactos++;
  51.            }
  52.            else
  53.            {
  54.                System.Console.WriteLine("Contacto previamente accesible en la tabla");
  55.            }
  56.        }
  57.        public void imprimeAgenda()
  58.        {
  59.            if (numContactos != 0)
  60.            {
  61.                command.CommandText = "SELECT * FROM contacto;";
  62.  
  63.                Reader = command.ExecuteReader();
  64.                while (Reader.Read())
  65.                {
  66.                    for (int i = 0; i < Reader.FieldCount; i++)
  67.                        System.Console.Write(Reader.GetValue(i).ToString() + " ");
  68.                    System.Console.Write("\n");
  69.                }
  70.  
  71.                Reader.Dispose();
  72.            }
  73.        }
  74.        public void editarContacto(string nom, string tel)
  75.        {
  76.            if (numContactos != 0)
  77.            {
  78.                //Variables para la edición
  79.                string nnom;
  80.                char nsex;
  81.                int nedad;
  82.                string ntel;
  83.  
  84.                System.Console.WriteLine("Nuevo nombre: ");
  85.                do
  86.                {
  87.                    nnom = System.Console.ReadLine();
  88.                    System.Console.WriteLine();
  89.                }while(nnom.Length>50);
  90.  
  91.                System.Console.WriteLine("Nuevo sexo: ");
  92.                do
  93.                {
  94.                    string aux = System.Console.ReadLine();
  95.                    nsex = aux[0];
  96.                    System.Console.WriteLine();
  97.                } while ((nsex != 'M') && (nsex != 'H'));
  98.  
  99.                System.Console.WriteLine("Nueva edad: ");
  100.                do
  101.                {
  102.                    try
  103.                    {
  104.                        nedad = Convert.ToInt32(System.Console.ReadLine());
  105.                    }
  106.                    catch (InvalidCastException)
  107.                    {
  108.                        nedad = -1;
  109.                    }
  110.                } while (nedad == -1);
  111.  
  112.                System.Console.WriteLine("Nuevo teléfono: ");
  113.                do
  114.                {
  115.                    ntel = System.Console.ReadLine();
  116.                    System.Console.WriteLine();
  117.                } while (ntel.Length > 9);
  118.  
  119.                eliminaContacto(nom, tel);
  120.                agregarCon(nnom, nsex, nedad, ntel);
  121.            }
  122.        }
  123.        public void eliminaContacto(string nom, string tel)
  124.        {
  125.            if (encontrar(nom, tel))
  126.            {
  127.                string comando = "DELETE FROM contacto "+
  128.                                 "WHERE nombre = '"+nom+"' AND tlf = '"+tel+"';";
  129.                command.CommandText = comando;
  130.                command.ExecuteNonQuery();
  131.                System.Console.WriteLine("Contacto modificado satisfactoriamente");
  132.            }
  133.            else
  134.            {
  135.                System.Console.WriteLine("Contacto no encontrado...");
  136.            }
  137.        }
  138.        public int getNumContactos()
  139.        {
  140.            return numContactos;
  141.        }
  142.  
  143.        ~Program()
  144.        {
  145.            if (abierto)
  146.            {
  147.                Reader.Close();
  148.                connection.Close();
  149.            }
  150.        }
  151.        Program()
  152.        {
  153.            MyConString = "SERVER=localhost;" +
  154.                "DATABASE=agenda;" +
  155.                "UID=usuario;" +
  156.                "PASSWORD=user;";
  157.            connection = new MySqlConnection(MyConString);
  158.            command = connection.CreateCommand();
  159.            connection.Open();
  160.            abierto = true;
  161.            command.CommandText = "SELECT * FROM contacto;";
  162.            Reader = command.ExecuteReader();
  163.            while (Reader.Read())
  164.                numContactos++;
  165.  
  166.            Reader.Dispose();
  167.        }
  168.  
  169.        public static void menu()
  170.        {
  171.            System.Console.WriteLine("---------MENU---------");
  172.            System.Console.WriteLine("1.- Agregar contacto");
  173.            System.Console.WriteLine("2.- Modificar contacto");
  174.            System.Console.WriteLine("3.- Eliminar contacto");
  175.            System.Console.WriteLine("4.- Ver Base actual");
  176.            System.Console.WriteLine("5.- Salir");
  177.            System.Console.Write("Elija una opción: ");
  178.        }
  179.  
  180.        static void Main(string[] args)
  181.        {
  182.            Program obj = new Program();
  183.            int opcion;
  184.            string nnom;
  185.            char nsex;
  186.            int nedad;
  187.            string ntel;
  188.            try
  189.            {
  190.                do
  191.                {
  192.                    Console.Clear();
  193.                    Program.menu();
  194.                    try
  195.                    {
  196.                        opcion = Convert.ToInt32(System.Console.ReadLine());
  197.                    }
  198.                    catch (InvalidCastException)
  199.                    {
  200.                        opcion = 0;
  201.                    }
  202.  
  203.                    System.Console.WriteLine();
  204.                    switch (opcion)
  205.                    {
  206.                        case 1:
  207.                            System.Console.WriteLine("Nombre: ");
  208.                            do
  209.                            {
  210.                                nnom = System.Console.ReadLine();
  211.                                System.Console.WriteLine();
  212.                            } while (nnom.Length > 50);
  213.  
  214.                            System.Console.WriteLine("Sexo: ");
  215.                            do
  216.                            {
  217.                                string aux = System.Console.ReadLine();
  218.                                nsex = aux[0];
  219.                                System.Console.WriteLine();
  220.                            } while ((nsex != 'M') && (nsex != 'H'));
  221.  
  222.                            System.Console.WriteLine("Edad: ");
  223.                            do
  224.                            {
  225.                                try
  226.                                {
  227.                                    nedad = Convert.ToInt32(System.Console.ReadLine());
  228.                                }
  229.                                catch (InvalidCastException)
  230.                                {
  231.                                    nedad = -1;
  232.                                }
  233.                            } while (nedad == -1);
  234.  
  235.                            System.Console.WriteLine("Teléfono: ");
  236.                            do
  237.                            {
  238.                                ntel = System.Console.ReadLine();
  239.                                System.Console.WriteLine();
  240.                            } while (ntel.Length > 50);
  241.  
  242.                            obj.agregarCon(nnom, nsex, nedad, ntel);
  243.                            System.Console.ReadLine();
  244.                            break;
  245.  
  246.                        case 2:
  247.                            System.Console.WriteLine("Nombre: ");
  248.                            do
  249.                            {
  250.                                nnom = System.Console.ReadLine();
  251.                                System.Console.WriteLine();
  252.                            } while (nnom.Length > 50);
  253.  
  254.                            System.Console.WriteLine("Teléfono: ");
  255.                            do
  256.                            {
  257.                                ntel = System.Console.ReadLine();
  258.                                System.Console.WriteLine();
  259.                            } while (ntel.Length > 50);
  260.  
  261.                            obj.editarContacto(nnom, ntel);
  262.  
  263.                            System.Console.ReadLine();
  264.                            break;
  265.                        case 3:
  266.                            System.Console.WriteLine("Nombre: ");
  267.                            do
  268.                            {
  269.                                nnom = System.Console.ReadLine();
  270.                                System.Console.WriteLine();
  271.                            } while (nnom.Length > 50);
  272.  
  273.                            System.Console.WriteLine("Teléfono: ");
  274.                            do
  275.                            {
  276.                                ntel = System.Console.ReadLine();
  277.                                System.Console.WriteLine();
  278.                            } while (ntel.Length > 50);
  279.  
  280.                            obj.eliminaContacto(nnom, ntel);
  281.                            System.Console.ReadLine();
  282.                            break;
  283.                        case 4:
  284.                            obj.imprimeAgenda();
  285.                            System.Console.ReadLine();
  286.                            break;
  287.                        case 5:
  288.                            break;
  289.  
  290.                        default:
  291.                            System.Console.WriteLine("Opción incorrecta");
  292.                            System.Console.ReadLine();
  293.                            break;
  294.                    }
  295.  
  296.                } while (opcion != 5);
  297.            }
  298.            catch (MySqlException e)
  299.            {
  300.                System.Console.WriteLine("Excepción: " + e.Message);
  301.            }
  302.            finally
  303.            {
  304.                System.Console.WriteLine("Presione una tecla para salir");
  305.                System.Console.ReadLine();
  306.            }
  307.        }
  308.    }
  309. }

Reto 11: A partir de una clase base llamada Polígono, generar las clases Esfera, Círculo, Rectángulo y Triángulo que permita en todos los casos obtener el área y perímetro de las figuras que representa cada clase.

Feliz navidad :B


« Última modificación: 6 Diciembre 2010, 05:30 am por final_frontier » En línea

Sie ist der hellste Stern von allen und wird nie vom Himmel fallen...
Páginas: 1 2 [3] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Retos
Desafíos - Wargames
@synthesize 8 9,206 Último mensaje 13 Junio 2010, 04:24 am
por @synthesize
Retos C/C++ « 1 2 ... 8 9 »
Ejercicios
[L]ord [R]NA 85 52,495 Último mensaje 3 Octubre 2010, 16:57 pm
por Komodo
cuando consigo nuevos retos? « 1 2 »
WarZone
Tyrz 11 5,500 Último mensaje 15 Junio 2011, 23:11 pm
por [-Franko-]
Desarrollo de Retos Informaticos
Desarrollo Web
Sinedra 0 3,059 Último mensaje 23 Febrero 2011, 19:23 pm
por Sinedra
Retos C/C++
Programación C/C++
N0body 5 10,548 Último mensaje 9 Mayo 2011, 09:54 am
por ghastlyX
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines