Mostrando entradas con la etiqueta c#. Mostrar todas las entradas
Mostrando entradas con la etiqueta c#. Mostrar todas las entradas

martes, 6 de octubre de 2015

Llenar atributos de una clase de forma dinámica. [Borrador]

private object ExcelRowToObject(DataColumnCollection pColumns, DataRow pRow, object pObjecto)
        {
            object wRt = pObjecto;
            foreach (DataColumn dc in pColumns)
            {
                //http://stackoverflow.com/questions/12970353/c-sharp-dynamically-set-property
                //-->objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)
                // Llamamos a las columnas en el excel como en las propiedades para hacer más fácil la automatización
                if (dc.ColumnName != null)
                {
                    if (dc.ColumnName != string.Empty && dc.ColumnName != c_ID)
                    {
                        try
                        {
                            System.Reflection.PropertyInfo wPI = pObjecto.GetType().GetProperty(dc.ColumnName.Trim());
                            if (wPI.PropertyType == Type.GetType("System.Decimal"))//si evoluciona a más, mejor hacer un swicht
                            {
                                if (pRow[dc.ColumnName.Trim()].ToString() != string.Empty)
                                {
                                    wPI.SetValue(wRt, decimal.Parse(pRow[dc.ColumnName.Trim()].ToString()), null);
                                }
                            }
                            else
                            {
                                wPI.SetValue(wRt, pRow[dc.ColumnName.Trim()].ToString(), null);
                            }
                        }
                        catch (Exception wExc)
                        {
                            //GestionError(wExc);
                            //throw wExc;
                            throw new Exception(dc.ColumnName.Trim() + ": " + wExc.Message);
                        }
                    }
                }
            }
            return wRt;
        }

        private bool ExcelValidarColumnas(Type pTypeToTest, string pTableName, DataColumnCollection pColumns)
        {
            //https://msdn.microsoft.com/en-us/library/system.type(v=vs.110).aspx
            //http://stackoverflow.com/questions/12970353/c-sharp-dynamically-set-property
            //-->objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)  

            string wMsgAux = string.Empty;
            foreach (DataColumn dc in pColumns)
            {
                try
                {
                    if (dc.ColumnName != null)
                    {
                        if (dc.ColumnName != string.Empty && dc.ColumnName != "_ID")
                        {
                            //System.Reflection.PropertyInfo wPI = wpinTest.GetType().GetProperty(dc.ColumnName.Trim());
                            System.Reflection.PropertyInfo wPI = pTypeToTest.GetProperty(dc.ColumnName.Trim());

                            if (wPI == null)
                            {
                                wMsgAux += dc.ColumnName + "; ";
                            }
                        }
                    }
                }
                catch
                {
                    wMsgAux += dc.ColumnName;
                }
            }
            if (wMsgAux != string.Empty)
            {
                wMsgAux = "Columnas en el Excel (" + pTableName + ") con nombre incorrecto: " + wMsgAux;
                GestionError(wMsgAux);
                return false;
            }
            else
            {
                return true;
            }

        }


Y las uso así
 foreach (DataRow row in P_IN.Rows)
                {
Miclase wpin = Miclase();

 wpin = (Miclase)ExcelRowToObject(P_IN.Columns, row, wpin);
}
Donde P_IN es una DataTable con los mismos nombres de columna que los atributos. De hecho el DataTable lo he creado cargando un Excel.

viernes, 1 de agosto de 2014

Quitar los espacios HTML ( ) y similares en C#.

Podemos limpiar el texto de código html que nos viene de la página para tratarlo con HttpUtility.HtmlDecode.

string wHoraIni1 = HttpUtility.HtmlDecode(gvr.Cells[3].Text);

viernes, 23 de noviembre de 2012

Evaluar celda vacía en un GridView.

Problema: Al recorrer los filas (GridViewRow) de un GridView y evalúa una celda que quiero comparar con  string.Empty recibo    y la comparación no funciona.

Solución: Usar HttpUtility.HtmlDecode.
...
string wValor = HttpUtility.HtmlDecode(e.Row.Cells[2].Text).Trim();
       
 if (wFechaXmlFin == string.Empty)
{
                CheckBox cb = new CheckBox();
                cb = (CheckBox)e.Row.FindControl("cbSeleccion");
                cb.Enabled = false;
}
...

jueves, 14 de abril de 2011

Truncar decimales en C#

No deja de ser sorprendente que no hay un método de decimal en C# para truncar decimales. He visto por ahí formas de hacerlo con formatos y al final he optado por multiplicar por 10^decimales, truncar quitando los decimales y volver a dividir entre 10^decimales. Lo necesitaba para poder truncar a 2 decimales, pero me he hecho un método genérico.


private static decimal Truncate(decimal pImporte, int pNumDecimales)
{
    decimal wRt = 0;
    decimal wPot10 = 1;

    //for (int i = 1; i <= pNumDecimales; i++)
    //{
    //    wPot10 = wPot10 * 10;
    //}
  
    wRt = pImporte * wPot10;
    wRt = decimal.Truncate(wRt);
    wRt = wRt / wPot10;
    //wRt = decimal.Round(wRt, 2);

    return wRt;
}

miércoles, 14 de abril de 2010

Desde el XML a nuestra clase con C#

El otro día me anoté en este blog para acordarme como generar la definición de clase (en C#) desde un esquema xsd con xsd.exe y poder generar luego el XML. ¿Pero qué hacer si nos dan el XML? La respuesta aquí. Así cerramos el círculo.

jueves, 1 de abril de 2010

Como crear una clase a partir de un fichero XML o XSD y luego el XML con C#.

Aquí está muy bien explicado como conseguir pasar desde un esquema (xsd) a tener la clase que corresponde al esquema. Una vez llenemos nuestra clase pondremos pasar a tener el xml serializando con un método como este:

private
static
void Serializar(object pObjeto, string pPathXml)

{
try
{


// Generamos el xml.

FileStream fs = null;

try

{

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(pObjeto.GetType());

fs = new
FileStream(pPathXml, FileMode.Create, FileAccess.Write);

serializer.Serialize(fs, pObjeto);

} catch

{
throw;

}
finally

{
if (fs != null)

{

fs.Close();

}

}

}


catch (Exception wExc) { throw wExc; }

}

Donde pObjeto es del tipo de Clase generada previamente, y pPathXml la ruta completa donde guardaremos el XML.

miércoles, 10 de febrero de 2010

Gestión y serialización de errores

En nuestras páginas necesitamos gestionar los errores no contralados. Una buena práctica es guardar un log de errores en XML. Si intentamos serializar la excepción (Exception) nos dar un error. Hay varias alternativas en internet pero yo estoy probando con algo sencillo y entendible.

Me he creado una clase Errores y dentro de ella un método que tendremos que poner en cada try catch.

El método:

public
class
Errores

{


const string cSaltoASP = "\r\n";

public Errores()

{

//


// TODO: Agregar aquí la lógica del constructor


//

}

public
static
void Gestionar(Exception pErr)

{

string wCarpetaLog = ConfigurationManager.AppSettings["CarpetaLog"].ToString() + @"\Excepciones\";

string wDocPath = wCarpetaLog + "fileErrores.xml";

string PathXml = wDocPath;


DataTable dt = new
DataTable("Excepcion");

dt.Columns.Add("NowTime");

dt.Columns.Add("Data");

dt.Columns.Add("HelpLink");

dt.Columns.Add("InnerException");

dt.Columns.Add("Message");

dt.Columns.Add("Source");

dt.Columns.Add("StackTrace");

dt.Columns.Add("TargetSite");



DataRow dr = dt.NewRow();

dr["NowTime"] = Excelium.Generales.AAAAMMDD(DateTime.Today) + " " + DateTime.Now.ToShortTimeString();



if (pErr.Data != null)

{

dr["Data"] = pErr.Data.ToString();

}


if (pErr.HelpLink != null)

{

dr["HelpLink"] = pErr.HelpLink.ToString();

}


if (pErr.InnerException != null)

{

dr["InnerException"] = pErr.InnerException.ToString();

}


if (pErr.Message != null)

{

dr["Message"] = pErr.Message.ToString();

}


if (pErr.Source != null)

{

dr["Source"] = pErr.Source.ToString();

}


if (pErr.StackTrace != null)

{

dr["StackTrace"] = pErr.StackTrace.ToString();

}


if (pErr.TargetSite != null)

{

dr["TargetSite"] = pErr.TargetSite.ToString();

}


dt.Rows.Add(dr);



DataSet ds = new
DataSet("Excepciones");

ds.Tables.Add(dt);



FileStream fs = null;

fs = new
FileStream(PathXml, FileMode.Append, FileAccess.Write);

ds.WriteXml(fs);

fs.Close();



string sAll = string.Empty;



using (System.IO.StreamReader sr = new System.IO.StreamReader(PathXml, System.Text.Encoding.Default))

{

sAll = sr.ReadToEnd();

}


//



sAll = sAll.Replace(cSaltoASP,"");

sAll = sAll.Replace("</Excepciones><Excepciones>", "");


//


using (System.IO.StreamWriter sw = new System.IO.StreamWriter(PathXml, false, System.Text.Encoding.Default))

{

sw.WriteLine(sAll);

sw.Flush();

}

}

}

Su Uso.


try

{


//Nuestro código;

catch (Exception e)

{


Errores.Gestionar(e);

}

Aviso.

Estoy probando todavía y queda mejorarlo.

martes, 12 de mayo de 2009

Nombre de los meses en castellano o cualquier otro idioma en asp.net.

¿Quién no ha necesitado poner los nombres de los meses en español? Es sencillo con DateTimeFormatInfo del namespace (System.Globalization).
La instrucción seria:

DateTimeFormatInfo myDTFI = new CultureInfo("es-ES", false).DateTimeFormat;
string wLiteralMesActual = myDTFI.MonthNames[DateTime.Today.Month - 1];

Cambiando el CultureInfo, podemos hacerlo en otros idiomas.

viernes, 17 de abril de 2009

Como unir 2 documentos RTF (ASP.NET C#).

Por necesidades del proyecto actual hemos tenido que trabajar con RFT, ya que no podíamos usar las dll de Word. En algunos foros recomiendan no utilizarlas y además en el servidor donde colocaremos la aplicación no podíamos instalar el office.

Generábamos varios documentos, que queríamos unir en uno sólo según la plantilla que usábamos. No hemos acabábamos de encontrar una satisfactoria a la complejidad de nuestros RTF’s.

Por ejemplo, usar el RichTextBox de (de Windows.Forms) como sugerían en algunos foros
, funciona bastante bien, incluso si trabajas con Web, aunque necesitas añadir la referencia. Pero en nuestro caso los ficheros son demasiado complejos y me imagino que si trabajamos con muchos documentos debe dar problemas de memoria.

Finalmente mirando una solución de codeproject
y con alguna sútil y leve pista hemos llegado a una conclusión que nos funciona. En el primer link hay toda una solución para tratar RTF’s, a mí no me ha acabado de funcionar porque la solución no es reconocida por mi versión de Visual Studio, y además me daba algunos errores de código. De todas formas me ha ayudado echarle un ojo, aunque me temo que sobretodo debe funcionar uniendo los RTF's generados por el mismo programa.

Finalmente aquí el código:


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;




public class RTFUtiles
{
const string cFuentes = "{\\fonttbl";
const string cColores = "{\\colortbl";
const string cHojaEstilos = "{\\stylesheet";
const string cAlmacen = @"{\*\datastore";
const string cEstilosLatentes = @"{\*\latentstyles";
public RTFUtiles()
{
//
//
}
///


/// Une dos documentos RTF.
///

/// Ruta del fichero al que vamos a a¤adir.
/// Ruta del fichero que queremos a¤adir.
public static void Merge(string pRtfPrincipalPath, string pRtfAnyadirPath)
{
if (System.IO.File.Exists(pRtfPrincipalPath))
{
string pPathProvisional = pRtfPrincipalPath.Replace(".rtf", "PROV.rtf");
System.IO.StreamWriter sw = new System.IO.StreamWriter(pPathProvisional, true, System.Text.Encoding.Default);
using (System.IO.StreamReader sr = new System.IO.StreamReader(pRtfPrincipalPath, System.Text.Encoding.Default))
{
// Escribimos el mensaje principal. Sin el final "}}".
string line;
while ((line = sr.ReadLine()) != null)
{
string miLinea = line;
if (sr.EndOfStream)
{
// Quitamos el final "}}".
miLinea = miLinea.TrimEnd().Substring(0, (miLinea.Length - 1));
}
sw.WriteLine(miLinea);
sw.Flush();
}
}
// Nueva p gina
sw.WriteLine("\\page");
sw.Flush();
// A¤adimos el contenido del segundo sin incio, definici¢n de colores y fuentes.
System.IO.StreamReader sr2 = new System.IO.StreamReader(pRtfAnyadirPath, System.Text.Encoding.Default);
string texto2 = sr2.ReadToEnd();
sr2.Close();
sw.WriteLine(Contenido(texto2.Trim()));
sw.Flush();
// A¤adimos el final de documento que hemos quitado al primero.
sw.WriteLine("}");
sw.Flush();
sw.Close();
// Reemplazamos el fichero para que sea el mismo que el original.
System.IO.File.Copy(pPathProvisional, pRtfPrincipalPath, true);
System.IO.File.Delete(pPathProvisional);
}
else
{
System.IO.File.Copy(pRtfAnyadirPath, pRtfPrincipalPath);
}
}
private static string Contenido(string pRtf)
{
string wRt = pRtf;
wRt = wRt.Replace(Inicio(wRt), "");
wRt = wRt.Replace(Colores(wRt), "");
wRt = wRt.Replace(Fuentes(wRt), "");
wRt = wRt.Replace(HojaEstilos(wRt), "");
wRt = wRt.Replace(Almacen(wRt), "");
wRt = wRt.Replace(EstilosLatentes(wRt), "");
wRt = wRt.Substring(0, (wRt.Length - 1));
return wRt;
}
private static string Fuentes(string pRtf)
{
return BuscarTag(pRtf, cFuentes);
}

private static string Colores(string pRtf)
{
return BuscarTag(pRtf, cColores);
}
private static string HojaEstilos(string pRtf)
{
return BuscarTag(pRtf, cHojaEstilos);
}
private static string Almacen(string pRtf)
{
return BuscarTag(pRtf, cAlmacen);
}
private static string EstilosLatentes(string pRtf)
{
return BuscarTag(pRtf, cEstilosLatentes);
}


private static string Inicio(string pRtf)
{
string wRt = string.Empty;
int intFuente = 0;
char[] rtfCh = pRtf.ToCharArray();
int pos = 0;
for (int i = intFuente; i < pRtf.Length; i++)
{
if (rtfCh[i] == char.Parse("{"))
{
pos++;
}
if (rtfCh[i] == char.Parse("}"))
{
pos--;
}
if (pos == 2)
{
return wRt;
}
wRt += rtfCh[i].ToString();
}
return wRt;
}
private static string BuscarTag(string pRtf, string pTag)
{
string wRt = string.Empty;
int intFuente = pRtf.IndexOf(pTag);
char[] rtfCh = pRtf.ToCharArray();
try
{
if (intFuente < 0) { intFuente = 0; }
int pos = 0;
for (int i = intFuente; i < rtfCh.Length; i++)
{
wRt += rtfCh[i].ToString();
if (rtfCh[i] == char.Parse("{"))
{
pos++;
}
if (rtfCh[i] == char.Parse("}"))
{
pos--;
}
if (pos == 0)
{
return wRt;
}
}
}
catch (Exception pErr)
{
throw pErr;
}
return wRt;
}
}