Archivos para ‘C#’

13 enero 2012

C/C++ Punteros

por auraham

El siguiente programa muestra el valor de una variable entera y su dirección en memoria.

/*
| Programa 1 c
| Muestra el valor de la variable n
| y su direccion
|
| gcc ejemplo_1.cpp -o salida
|
| Salida:
| n = 75
| &n = 0xbfc4250c
|
| Notas:
| En la linea 
|	printf("&n= %p \n", &n);
| Se utiliza %p para imprimir la direccion del puntero, 
| en este caso, la direccion de n
*/

#include <stdio.h>

int main()
{
	int n = 75;
	printf("n = %d \n", n);
	printf("&n= %p \n", &n);

	return 0;
}

/*
| Programa 1 c++
| Muestra el valor de la variable n
| y su direccion
|
| g++ ejemplo_1.cpp -o salida
|
| Salida:
| n = 75
| &n = 0xbfd283fc
|
| Notas:
| La forma correcta de incluir la libreria es
| #include <iostream>
| no
| #include <iostream.h>
|
| Recuerda, cout solo se puede usar si incluyes iostream
*/

#include <iostream>

using namespace std;

int main()
{
	int n = 75;
	cout<<"n = "<<n<<endl;
	cout<<"&n = "<<&n<<endl;

	return 0;
}

10 noviembre 2011

C# y Excel: Cómo leer un rango de celdas

por auraham

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;

namespace my_excel
{
    class Program
    {
        static void Main(string[] args)
        {
            // archivo de entrada
            string file = "libro.xls";
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string xlsFilePath = Path.Combine(dir, file);

            read_file(xlsFilePath);

            Console.ReadKey();
            
            
        }

        public static void read_file(string xlsFilePath)
        {
            if (!File.Exists(xlsFilePath))
                return;

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;
            var misValue = Type.Missing;//System.Reflection.Missing.Value;

            // abrir el documento
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open(xlsFilePath, misValue, misValue,
                misValue, misValue, misValue, misValue, misValue, misValue,
                misValue, misValue, misValue, misValue, misValue, misValue);

            // seleccion de la hoja de calculo
            // get_item() devuelve object y numera las hojas a partir de 1
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            // seleccion rango activo
            range = xlWorkSheet.UsedRange;


            // leer las celdas
            int rows = range.Rows.Count;
            int cols = range.Columns.Count;


            for (int row = 1; row <= rows; row++)
            {
                for (int col = 1; col <= cols; col++)
                {

                    // lectura como cadena
                    string str_value = (range.Cells[row, col] as Excel.Range).Value2.ToString();

                    // conversion
                    int int_value = Convert.ToInt32(str_value, 10);

                    Console.WriteLine("string:{0}", str_value);
                    Console.WriteLine("int:{0}", int_value);
                }


            }


            // cerrar
            xlWorkBook.Close(false, misValue, misValue);
            xlApp.Quit();

            // liberar
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

        }


        public static void releaseObject(object obj) 
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to release the object(object:{0})", obj.ToString());
            }
            finally 
            {
                obj = null;
                GC.Collect();
            }
        }
    }
}

Fuente:
CSharp
DotNetPerls

6 junio 2011

Eliminación de nodos con HtmlAgilityPack

por auraham

HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table");

// Validacion de tabla nula
if (tables != null)
	doc.LoadHtml(tables[0].OuterHtml);

// Recorrido de la tabla
foreach (HtmlNode tr in doc.DocumentNode.SelectNodes("//tr"))
{
	// Coleccion de columnas
	HtmlNodeCollection cols = tr.SelectNodes("td");

	
	// Elimina la etiqueta bold y br
	cols[0].RemoveChild(cols[0].SelectNodes("b")[0]);
	cols[0].RemoveChild(cols[0].SelectNodes("br")[0]);

	string valor = cols[0].InnerHtml;
	
}

27 abril 2011

Validar un número con Regex en C#

por auraham

//Patron de busqueda
string pattern = "^\\d+$";
Regex regex = new Regex(pattern);

//Lista de posibles numeros
List<string> lista = new List<string>();

lista.Add("6.53569E+11");   //No valido
lista.Add("6.53569E11");    //No valido
lista.Add("653569E11");     //No valido
lista.Add("65356911");      //Valido

//Recorrido de la lista
foreach(string item in lista)
{
	if(regex.IsMatch(item))
		MessageBox.Show(item + " es valido");
	else
		MessageBox.Show(item + " no valido");
}

18 abril 2011

Herencia en C#

por auraham

using System;

public class Parent
{
    string parentString;

    public Parent()
    {
        Console.WriteLine("Parent Constructor");
    }

    public Parent(string msg)
    {
        parentString = msg;
        Console.WriteLine(parentString);
    }

    public void print()
    {
        Console.WriteLine("Im a parent class");
    }

}

public class Child : Parent
{

    ///
<summary> /// En este constructor se llama explicitamente al constructor que coincida con la
 /// lista de parametros del padre
 ///
 /// Si no se usara : base("From derived") se llamaria al constructor por defecto en la
 /// clase padre, Parent()
 /// </summary>
    public Child() : base("From derived")
    {
        Console.WriteLine("Child Constructor");
    }

    ///
<summary> /// new puede ser usado como modificador en la declaracion de una funcion
 /// en este caso padre e hijo tienen una misma funcion, print(), pero con new
 /// se usara solo la del hijo, ocultando la del padre
 ///
 /// esto es util especialmente cuando se quiere una implementacion distinta a
 /// una funcion existente en la clase padre
 ///
 /// se puede decir que es un override como en java
 /// </summary>
    public new void print()
    {
        //Llama explicitamente al metodo print() del padre
        base.print();

        Console.WriteLine("Im a child class");
    }

    public static void Main()
    {
        Child child = new Child();

        child.print();

        //Otra forma de llamar explicitamente a los miembros de la clase padre
        //es por medio de un cast
        ((Parent)child).print();
    }

}

Fuente:
C# Station

6 abril 2011

Extracción zip con DotNetZip

por auraham

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;
using System.IO;

namespace readMyZip
{
    class Program
    {
        static void Main(string[] args)
        {
            //Ruta del archivo zip
            string filename = "myzip.zip";
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string filepath = Path.Combine(path, filename);

            //Ruta de extraccion
            string target = Path.Combine(path, "extract");

            //Extraccion
            using (ZipFile zip = ZipFile.Read(filepath))
            {
                foreach(ZipEntry item in zip)
                {
                    item.Extract(target, ExtractExistingFileAction.OverwriteSilently);
                }
            }

        }
    }
}

Fuente:
DotNetZip
Ejemplos en Codeplex

1 marzo 2011

C# y Namespace

por auraham

using System;

namespace main_namespace
{
    namespace namespace_uno
    {
        class clase_uno
        {
            public static void print1()
            {
                Console.WriteLine("print 1");
            }
        }
    }

    namespace namespace_dos
    {
        class clase_dos
        {
            public static void print2 ()
            {
                Console.WriteLine("print 2");
            }
        }
    }

    class main_class
    {
        public static void Main()
        {
            namespace_uno.clase_uno.print1();
            namespace_dos.clase_dos.print2();

            Console.ReadKey();
        }
    }
}

Fuente:
C# Station

21 septiembre 2010

Copiar celdas de una hoja de excel a otra en C#

por auraham

using System;

using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
    public class excel_n
    {
        static void Main()
        {
            string source = "E:\\archivos\\source.xls";         //debe existir
            string destiny = "E:\\archivos\\destiny.xls";       //debe existir
            string temp = "E:\\archivos\\destiny_temp.xls";
            copy(source,destiny,temp);
            Console.ReadKey();

        }

        public static void copy(string source,string destiny,string temp)
        {
            //source
            Excel.Application xlAppSource;
            Excel.Workbook xlWorkBookSource;
            Excel.Worksheet xlWorkSheetSource;
            Excel.Range rangeSource;

            //destiny
            Excel.Application xlAppDestiny;
            Excel.Workbook xlWorkBookDestiny;
            Excel.Worksheet xlWorkSheetDestiny;
            Excel.Range rangeDestiny;

            string str;
            int rCnt = 0;
            int cCnt = 0;

            //Apps
            xlAppSource = new Excel.ApplicationClass();
            xlAppDestiny = new Excel.ApplicationClass();

            //Source
            xlWorkBookSource = xlAppSource.Workbooks.Open(source, 0, false, 5, null, null, false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, null, true, false, 0, true, false, false);
            xlWorkSheetSource = (Excel.Worksheet)xlWorkBookSource.Worksheets.get_Item(1);
            rangeSource = xlWorkSheetSource.UsedRange;

            //Destiny
            xlWorkBookDestiny = xlAppDestiny.Workbooks.Open(destiny, 0, false, 5, null, null, false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, null, true, false, 0, true, false, false);
            xlWorkSheetDestiny = (Excel.Worksheet)xlWorkBookDestiny.Worksheets.get_Item(1);//hoja BASE
            rangeDestiny = xlWorkSheetDestiny.UsedRange;

            for (rCnt = 1; rCnt <= rangeSource.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= rangeSource.Columns.Count; cCnt++)
                {
                    str = (string)(rangeSource.Cells[rCnt, cCnt] as Excel.Range).Text;
                    //xlWorkSheetDestiny.Cells[rCnt, cCnt] = 10;
                    xlWorkSheetDestiny.Cells[rCnt, cCnt] =  xlWorkSheetSource.Cells[rCnt, cCnt];
                    Console.WriteLine(str);
                }
            }

            //xlWorkBook.Save();
            //xlWorkBook.Close(true, source);

            //Source
            xlWorkBookSource.Close(false,null,null);
            xlAppSource.Quit();

            //Destiny
            xlWorkBookDestiny.Close(true, temp, null);  //guarda destiny con otro nombre
            xlAppDestiny.Quit();

            releaseObject(xlWorkSheetSource);
            releaseObject(xlWorkBookSource);
            releaseObject(xlAppSource);

            releaseObject(xlWorkSheetDestiny);
            releaseObject(xlWorkBookDestiny);
            releaseObject(xlAppDestiny);
        }

        public static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                Console.WriteLine("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

    }
}

Fuente
Csharp.net

11 septiembre 2010

Excel & C#

por auraham

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
//using Microsoft.Office;

namespace excel_test
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Prueba de excel");
            RegogerDatos("E:\\libro.xlsx");
            Console.ReadKey();

        }//Main

        //public static List<string> RegogerDatos(string filePath)
        public static void RegogerDatos(string filePath)
        {
            List<string> list = new List<string>();

            //Declaracion de variables
            Microsoft.Office.Interop.Excel._Application xlApp;
            Microsoft.Office.Interop.Excel._Workbook xlWorkBook;    //xlLibro
            Microsoft.Office.Interop.Excel._Worksheet xlWorkSheet;  //xlHoja1
            Microsoft.Office.Interop.Excel.Sheets xlSheets;         //xlHojas

            //File Path
            string path = filePath;

            //Inicializar la variable xlApp (referente a la aplicacion)
            xlApp = new Microsoft.Office.Interop.Excel.Application();

            //Muestra la aplicacion si esta en TRUE
            xlApp.Visible = false;

            //Abrimos el libro de excel
            xlWorkBook = xlApp.Workbooks.Open(path, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            try
            {
                //Asignamos las hojas
                xlSheets = xlWorkBook.Sheets;

                //Asignamos la hoja con la que se va a trabajar
                xlWorkSheet = (Microsoft.Office.Interop.Excel._Worksheet)xlSheets["Hoja1"];

                /////aqui iria el resto del codigo para copiar la macro/////
                //string value = (string)xlWorkSheet.get_Range(object cel1, object cell2);
                //string value = (string)xlWorkSheet.get_Range("B" + j, Missing.Value).Text;
                int i = 0;
                //string value = "";
                for (i =1 ; i <=4; i++)
                {
                    string value = (string)xlWorkSheet.get_Range("A" + i, Missing.Value).Text;
                    //value = (string)xlWorkSheet.get_Range("A" + i, Missing.Value).Text;
                    Console.WriteLine("A" + i + " = " + value);

                    string value2 = (string)xlWorkSheet.get_Range("B"+i, Missing.Value).Text;
                    Console.WriteLine("B" + i + " = " + value2);
                }
            }
            finally
            {
                //Cerrar el libro
                xlWorkBook.Close(false, Missing.Value, Missing.Value);

                //Cerrar la aplicacion
                xlApp.Quit();
            }

        }//RecogerDatos()
    }//public class Program
}//namespace excel_test

Fuente

Patopollo

11 septiembre 2010

Hola, C#

por auraham

<pre>
//Declaration de namespace
//Indica que se usara el namespace de System. Un namespace contiene conjuntos de codigo.
//Con esta declaracion se le indica al programa que haras una referencia al namespace System
//sin necesidad de usar "System" en cada uso.
using System;

//Declaracion de clase
//Contiene los datos y metodos de la clase. Una clase es uno de los diferentes tipos de elementos
//que se usan para describir objetos, como structs, interfaces, delegates y enums. Esta clase
//solo tiene un metodo, Main, el cual es el punto de partida para la clase al momento de ejecucion
class Welcome {

    //Metodo Main
    //Se usa el modificador static para especificar que este metodo trabaja solo para esta clase
    //en lugar de una instancia de clase. Esto es necesario porque cuando un programa inicia,
    //no existen instancias de clase
    static void Main() {

        //Console es una clase de namespace System
        //WriteLine() es un metodo de la clase Console
        //Opcionalmente se pudo haber escrito System.Console.WriteLine("Hola Mundo");
        //siguiendo el patron namespace.class.method como "fully qualified statement"
        //pero al usar using System, esto deja de ser necesario.
        Console.WriteLine("Hola Mundo");
        Console.ReadKey();
    }
}
</pre>

Fuente
C# Station

Seguir

Get every new post delivered to your Inbox.