Retos .Net

Iniciado por [D4N93R], 8 Septiembre 2010, 18:44 PM

0 Miembros y 1 Visitante están viendo este tema.

final_frontier

#20
@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 (sql) [Seleccionar]
CREATE TABLE contacto(

 nombre  VARCHAR(50) NOT NULL,
 sexo    CHAR(1),
 edad    INT,
 tlf     CHAR(9) NOT NULL,

 CONSTRAINT KeyAgenda PRIMARY KEY (nombre, tlf),
 CONSTRAINT CaracterSexo CHECK sexo IN ('H', 'M')
);


Y aquí el programa

Código (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Para conectar con base de datos
using MySql.Data.MySqlClient;


namespace Agenda
{
   class Program
   {
       private bool abierto = false;
       private MySqlDataReader Reader;
       private MySqlConnection connection;
       private MySqlCommand command;
       private int numContactos = 0;
       private string MyConString;
       private bool encontrar(string nom, string tel)
       {
           bool ret = false;

           if (numContactos != 0)
           {
               string comando = "SELECT * FROM contacto "
                                + "WHERE nombre = '" + nom + "' AND "
                                + "tlf = '" + tel + "';";
               //Comando de selección para la búsqueda
               command.CommandText = comando;
               Reader = command.ExecuteReader();

               while ((Reader.Read()) && (ret == false))
                   ret = true; //Si llega a entrar en el bucle es que por lo menos
               //ha encontrado un dato. Al estar buscando por la
               //clave primaria de la relación, sólo debería devolver
               //un único valor, el buscado.
               Reader.Dispose();
           }

           return ret;
       }

       public void agregarCon(string nom, char sex, int edad, string tlf)
       {
           if (!encontrar(nom, tlf))
           {
               string agrega = "INSERT INTO contacto VALUES('" + nom + "','" + sex + "','" + edad + "','" + tlf + "');";
               command.CommandText = agrega;
               command.ExecuteNonQuery();
               numContactos++;
           }
           else
           {
               System.Console.WriteLine("Contacto previamente accesible en la tabla");
           }
       }
       public void imprimeAgenda()
       {
           if (numContactos != 0)
           {
               command.CommandText = "SELECT * FROM contacto;";

               Reader = command.ExecuteReader();
               while (Reader.Read())
               {
                   for (int i = 0; i < Reader.FieldCount; i++)
                       System.Console.Write(Reader.GetValue(i).ToString() + " ");
                   System.Console.Write("\n");
               }

               Reader.Dispose();
           }
       }
       public void editarContacto(string nom, string tel)
       {
           if (numContactos != 0)
           {
               //Variables para la edición
               string nnom;
               char nsex;
               int nedad;
               string ntel;

               System.Console.WriteLine("Nuevo nombre: ");
               do
               {
                   nnom = System.Console.ReadLine();
                   System.Console.WriteLine();
               }while(nnom.Length>50);

               System.Console.WriteLine("Nuevo sexo: ");
               do
               {
                   string aux = System.Console.ReadLine();
                   nsex = aux[0];
                   System.Console.WriteLine();
               } while ((nsex != 'M') && (nsex != 'H'));

               System.Console.WriteLine("Nueva edad: ");
               do
               {
                   try
                   {
                       nedad = Convert.ToInt32(System.Console.ReadLine());
                   }
                   catch (InvalidCastException)
                   {
                       nedad = -1;
                   }
               } while (nedad == -1);

               System.Console.WriteLine("Nuevo teléfono: ");
               do
               {
                   ntel = System.Console.ReadLine();
                   System.Console.WriteLine();
               } while (ntel.Length > 9);

               eliminaContacto(nom, tel);
               agregarCon(nnom, nsex, nedad, ntel);
           }
       }
       public void eliminaContacto(string nom, string tel)
       {
           if (encontrar(nom, tel))
           {
               string comando = "DELETE FROM contacto "+
                                "WHERE nombre = '"+nom+"' AND tlf = '"+tel+"';";
               command.CommandText = comando;
               command.ExecuteNonQuery();
               System.Console.WriteLine("Contacto modificado satisfactoriamente");
           }
           else
           {
               System.Console.WriteLine("Contacto no encontrado...");
           }
       }
       public int getNumContactos()
       {
           return numContactos;
       }

       ~Program()
       {
           if (abierto)
           {
               Reader.Close();
               connection.Close();
           }
       }
       Program()
       {
           MyConString = "SERVER=localhost;" +
               "DATABASE=agenda;" +
               "UID=usuario;" +
               "PASSWORD=user;";
           connection = new MySqlConnection(MyConString);
           command = connection.CreateCommand();
           connection.Open();
           abierto = true;
           command.CommandText = "SELECT * FROM contacto;";
           Reader = command.ExecuteReader();
           while (Reader.Read())
               numContactos++;

           Reader.Dispose();
       }

       public static void menu()
       {
           System.Console.WriteLine("---------MENU---------");
           System.Console.WriteLine("1.- Agregar contacto");
           System.Console.WriteLine("2.- Modificar contacto");
           System.Console.WriteLine("3.- Eliminar contacto");
           System.Console.WriteLine("4.- Ver Base actual");
           System.Console.WriteLine("5.- Salir");
           System.Console.Write("Elija una opción: ");
       }

       static void Main(string[] args)
       {
           Program obj = new Program();
           int opcion;
           string nnom;
           char nsex;
           int nedad;
           string ntel;
           try
           {
               do
               {
                   Console.Clear();
                   Program.menu();
                   try
                   {
                       opcion = Convert.ToInt32(System.Console.ReadLine());
                   }
                   catch (InvalidCastException)
                   {
                       opcion = 0;
                   }

                   System.Console.WriteLine();
                   switch (opcion)
                   {
                       case 1:
                           System.Console.WriteLine("Nombre: ");
                           do
                           {
                               nnom = System.Console.ReadLine();
                               System.Console.WriteLine();
                           } while (nnom.Length > 50);

                           System.Console.WriteLine("Sexo: ");
                           do
                           {
                               string aux = System.Console.ReadLine();
                               nsex = aux[0];
                               System.Console.WriteLine();
                           } while ((nsex != 'M') && (nsex != 'H'));

                           System.Console.WriteLine("Edad: ");
                           do
                           {
                               try
                               {
                                   nedad = Convert.ToInt32(System.Console.ReadLine());
                               }
                               catch (InvalidCastException)
                               {
                                   nedad = -1;
                               }
                           } while (nedad == -1);

                           System.Console.WriteLine("Teléfono: ");
                           do
                           {
                               ntel = System.Console.ReadLine();
                               System.Console.WriteLine();
                           } while (ntel.Length > 50);

                           obj.agregarCon(nnom, nsex, nedad, ntel);
                           System.Console.ReadLine();
                           break;

                       case 2:
                           System.Console.WriteLine("Nombre: ");
                           do
                           {
                               nnom = System.Console.ReadLine();
                               System.Console.WriteLine();
                           } while (nnom.Length > 50);

                           System.Console.WriteLine("Teléfono: ");
                           do
                           {
                               ntel = System.Console.ReadLine();
                               System.Console.WriteLine();
                           } while (ntel.Length > 50);

                           obj.editarContacto(nnom, ntel);

                           System.Console.ReadLine();
                           break;
                       case 3:
                           System.Console.WriteLine("Nombre: ");
                           do
                           {
                               nnom = System.Console.ReadLine();
                               System.Console.WriteLine();
                           } while (nnom.Length > 50);

                           System.Console.WriteLine("Teléfono: ");
                           do
                           {
                               ntel = System.Console.ReadLine();
                               System.Console.WriteLine();
                           } while (ntel.Length > 50);

                           obj.eliminaContacto(nnom, ntel);
                           System.Console.ReadLine();
                           break;
                       case 4:
                           obj.imprimeAgenda();
                           System.Console.ReadLine();
                           break;
                       case 5:
                           break;

                       default:
                           System.Console.WriteLine("Opción incorrecta");
                           System.Console.ReadLine();
                           break;
                   }

               } while (opcion != 5);
           }
           catch (MySqlException e)
           {
               System.Console.WriteLine("Excepción: " + e.Message);
           }
           finally
           {
               System.Console.WriteLine("Presione una tecla para salir");
               System.Console.ReadLine();
           }
       }
   }
}


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
Sie ist der hellste Stern von allen und wird nie vom Himmel fallen...