Archivo

Archivo para la Categoría "Generico"

C#: Bosquejo de un ActiveRecord con Insert y Select

Aburrido en una noche de primavera comence a escribir un pequeño programa que era el bosquejo básico pero bien básico un ActiveRecord llegando sólo a implementar las funciones Insert y Select, aun tengo pendiente las funciones Update y Delete.

Este código se conecta a un base de datos Postgres a la tabla test con los campos id, nombre, apellidos y edad, primero inserta y luego lista el dato ingresado.

Antes de probar el código, deben crear la tabla y las columnas en minuscula.

Program.cs

using System;
using System.Collections.Generic;

namespace MiActiveRecord
{
    public class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test() {Nombre="Alexis",
                                    Apellidos="Nuñez Riquelme"};
            test.Save();

            IList<Test> tests = Test.GetAll();

            foreach (Test item in tests)
            {
                Console.WriteLine("{0,2} - {1, 10} - {2, 15} - {3, 2}",
                item.Id, item.Nombre, item.Apellidos, item.Edad);
            }
        }

        public class Test : Base<Test>
        {
            public string Nombre { get ; set; }
            public string Apellidos { get; set; }
            public int? Edad { get; set; }
        }
    }
}

Base.cs


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
using System.Text;
using Npgsql;

namespace MiActiveRecord
{
 public class Base<T> : BaseSQL<T>
 {
 public long Id { get; set; }

 public static IList<T> GetAll()
 {
 IList<T> lst = new List<T>();

 using (NpgsqlConnection sqlCnn = new NpgsqlConnection("User ID=postgres; Password=postgres; Host=localhost; Port=5432; Database=MiActiveRecord"))
 {
 sqlCnn.Open();

 StringBuilder sql = GetSelect();

 NpgsqlDataReader reader = new NpgsqlCommand(sql.ToString(), sqlCnn).ExecuteReader();

 while (reader.Read())
 {
 T item = (T)typeof(T).Assembly.CreateInstance(typeof(T).FullName);

 (item as Base<T>).LoadValues(reader);

 lst.Add(item);
 }

 reader.Close();
 sqlCnn.Close();
 }

 return lst;
 }

 public void LoadValues(NpgsqlDataReader reader)
 {
 for (int i = 0; i < reader.FieldCount; i++)
 {
 foreach (PropertyInfo property in (this).GetType().GetProperties())
 {
 if (property.Name.ToUpper() == reader.GetName(i).ToUpper())
 {
 if (reader[reader.GetName(i).ToUpper()] is DBNull)
 property.SetValue(this, null, null);
 else
 property.SetValue(this, reader[reader.GetName(i).ToUpper()], null);

 break;
 }
 }
 }
 }

 public void Save()
 {
 using (NpgsqlConnection sqlCnn = new NpgsqlConnection("User ID=postgres; Password=postgres; Host=localhost; Port=5432; Database=MiActiveRecord"))
 {
 StringBuilder strSQL = GetInsert();

 sqlCnn.Open();

 NpgsqlCommand sqlcmd = new NpgsqlCommand(strSQL.ToString(), sqlCnn);

 sqlcmd.ExecuteNonQuery();

 sqlCnn.Close();
 }
 }
 }
}

BaseSQL.cs


using System.Text;
using System.Reflection;
using System.Collections.Generic;
using System;

namespace MiActiveRecord
{
 public class BaseSQL<T>
 {
 internal StringBuilder GetInsert()
 {
 StringBuilder sql = new StringBuilder("INSERT INTO ")
 .AppendFormat("{0} (", this.GetType().Name);

 foreach (PropertyInfo property in Base<T>.GetProperties(this.GetType(), true))
 {
 if (property.GetValue(this, null) != null)
 sql.AppendFormat("{0}, ", property.Name);
 }

 sql.Remove(sql.Length - 2, 2);

 sql.Append(") VALUES (");

 foreach (PropertyInfo property in Base<T>.GetProperties(this.GetType(), true))
 {
 if (property.GetValue(this, null) != null)
 {
 if (property.PropertyType == typeof(string) || property.PropertyType == typeof(char))
 sql.AppendFormat("'{0}', ", property.GetValue(this, null));
 else
 sql.AppendFormat("{0}, ", property.GetValue(this, null));
 }
 }

 sql.Remove(sql.Length - 2, 2);

 sql.Append(")");

 return sql;
 }

 internal static StringBuilder GetSelect()
 {
 StringBuilder sql = new StringBuilder("SELECT ");

 foreach (PropertyInfo property in Base<T>.GetProperties(typeof(T), false))
 {
 sql.AppendFormat("{0}, ", property.Name);
 }

 sql.Remove(sql.Length - 2, 2);

 sql.AppendFormat(" FROM {0}", typeof(T).Name);
 return sql;
 }

 private static IList<PropertyInfo> GetProperties(Type type, bool skipBase)
 {
 IList<PropertyInfo> properties = new List<PropertyInfo>();

 bool exist;

 foreach (PropertyInfo proItem in type.GetProperties())
 {
 exist = false;

 if (skipBase)
 {
 foreach (PropertyInfo proBase in typeof(Base<T>).GetProperties())
 {
 if (proBase.Name == proItem.Name)
 {
 exist = true;
 break;
 }
 }
 }

 if (!exist)
 properties.Add(proItem);
 }

 return properties;
 }
 }
}

C#: Ordenando una lista genérica

El siguiente código muestra el ordenamiento de una lista genérica, siendo necesario que los objetos implementen la interfaz Icomparable.

using System;
using System.Collections.Generic;

namespace nitrogeno
{
    class Program
    {
        static void Main(string[] args)
        {
            IList<string> list1 = new List<string>();

            list1.Add("Casa");  // 1
            list1.Add("Auto");  // 2
            list1.Add("Arbol"); // 3
            list1.Add("Sapo");  // 4
            list1.Add("Nuevo"); // 5

            SortList.Bubble<string>(list1);

            foreach (string item in list1)
                Console.WriteLine("{0}", item);

            Console.WriteLine();

            IList<int> list2 = new List<int>();

            list2.Add(5);  // 1
            list2.Add(2);  // 2
            list2.Add(3);  // 3
            list2.Add(1);  // 4
            list2.Add(4);  // 5

            SortList.Bubble<int>(list2);

            foreach (int item in list2)
                Console.WriteLine("{0}", item);
        }
    }

    public class SortList
    {
        public static IList<T> Bubble<T>(IList<T> list)
               where T : IComparable
        {
            T tmp;

            for (int i = 0; i < list.Count; i++)
            {
                for (int x = 0; x < list.Count - (i + 1); x++)
                {
                    if (list[x].CompareTo(list[x + 1]) > 0)
                    {
                        tmp = list[x + 1];
                        list[x + 1] = list[x];
                        list[x] = tmp;
                    }
                }
            }

            return list;
        }
    }
}

C#: Árbol Binario Genérico

19/01/2009 1 Comentario

Este árbol binario lo desarrolle en un momento de aburrimiento  en el trabajo y nunca lo temine, por eso me faltó implementar el método eliminar, asi que espero añadirlo en un futuro próximo.

Lo interesante de este código es que permite utilizar los tipos de datos char, string, datetime, int, decimal, o cual  otro objeto que tenga implementado la interfaz Icomparable. Porque el árbol binario hace uso del método CompareTo de la interfaz Icomparable, para ir comparando el nuevo nodo con los nodos existentes y asi saber que camino debe tomar.

using System.Collections.Generic;

namespace ArbolBinarioGenerico
{
    class Program
    {
        static void Main(string[] args)
        {
            ArbolBinario<int> arbol = new ArbolBinario<int>(8); //1

            arbol.Insertar(ref arbol, 7); //2
            arbol.Insertar(ref arbol, 5); //3
            arbol.Insertar(ref arbol, 3); //4
            arbol.Insertar(ref arbol, 4); //5
            arbol.Insertar(ref arbol, 0); //6
            arbol.Insertar(ref arbol, 2); //7
            arbol.Insertar(ref arbol, 6); //8
            arbol.Insertar(ref arbol, 9); //9
            arbol.Insertar(ref arbol, 1); //10

            foreach(int valor in arbol.Listar(arbol, new List&ltint&lt()))
                Console.WriteLine(valor);
        }
    }

    public class ArbolBinario<T> where T : IComparable
    {
        private T valor;
        private ArbolBinario<T> nodoIzq = null; // nodo derecho
        private ArbolBinario<T> nodoDer = null; // nodo izquierdo

        public ArbolBinario(T valor) // constructor
        {
            this.valor = valor;
        }

        public void Insertar(ref ArbolBinario<T> nodo, T valor)
        {
            if (nodo == null)
                nodo = new ArbolBinario<T>(valor);
            else
            {
                if (nodo.valor.CompareTo(valor) > 0)
                    Insertar(ref nodo.nodoIzq, valor);
                else
                    Insertar(ref nodo.nodoDer, valor);
            }
        }

        public List<T> Listar(ArbolBinario<T> nodo, List<T> arbol)
        {
            if (nodo.nodoIzq != null)
                Listar(nodo.nodoIzq, arbol);

            arbol.Add(nodo.valor);

            if (nodo.nodoDer != null)
                Listar(nodo.nodoDer, arbol);

            return arbol;
        }
    }
}

Seguir

Get every new post delivered to your Inbox.