Recoger parámetros de un programa por consola

Filed Under (.Net) by admin on 22-12-2011

Tagged Under : , ,


Para obtener los parámetros que se le pasan por consola a un programa se puede utilizar este código, por ejemplo en la consola pondríamos:

 

>Programa.exe argumento1

var x = Environment.GetCommandLineArgs();
if (x.Length > 0)
{
 // x[0] es el nombre del programa -> resultado : Programa.exe
 Console.WriteLine(x[1]); // -> resultado: argumento1
}

Curso Online (GRATIS) de Desarrollo de Aplicaciones en Silverlight para Windows Phone

Filed Under (.Net) by admin on 11-10-2011

Tagged Under : , , ,

Os dejo el enlace:

http://msdn.microsoft.com/es-es/windowsphone/hh307892

 

 

 

 

 

 

 

Linq to XML: carga de archivos XML enormes (más de 1Gb)

Filed Under (.Net, LINQ, SQLServer) by admin on 10-10-2011

Tagged Under : , , ,

Estos días he estado bastante liado ya que el proceso que teníamos de carga de XML realizaba una precarga en memoria del archivo (método Load()), la solución que hay es bastante sencilla con un XMLReader, os pongo un fragmento que seguro se entiende:

 

using (XmlReader reader = XmlReader.Create(directoryTemp + fichero))
{
 reader.MoveToContent();

 int count = 0; // una variable contador XElement nombretabla = null; // un XElement auxiliar

 while (!reader.EOF)
 {
 switch (reader.NodeType)
 {
 case XmlNodeType.Element: // se puede filtrar por tipo de XmlNodeType...
 if (count == 0)
 {
 // CUALQUIER CONDICION
 count++;
 reader.Read();

 } else if (count == 1)
 {
 nombretabla = new XElement((XName)reader.Name); // esto para crear un XELEMENT con el nombre del Reader actual
 count++;
 reader.Read();
 } else
 {
 if (string.IsNullOrEmpty(nodoReg)) nodoReg = reader.Name; // condicion para omitir anidados..

 if (nodoReg == reader.Name)
 {
 count++;
 nombretabla.Add(XElement.ReadFrom(reader) as XElement);

 // INSERCION .. cada X lanzo una inserción en BD
 if (count % numInserciones == 0)
 {
 nombrecondicionado.Add(nombretabla);
 docaux.Add(nombrecondicionado);

 // VALIDACION ...
 validado = ValidarEsquema(docaux, esquema);

 if (validado)
 {
 nreg += cond.Insertar(docaux, delete);
 delete = false;

 // vacio contenidos
 nombretabla.Elements().Remove();
 nombrecondicionado.Elements().Remove();
 docaux.Elements().Remove();
 }
 else
 {
 OnReportInformation(string.Format("ERROR fichero{0} no valido.", fichero), ReportLevel.Error);
 EstadoCarga = 2;
 }
 }

 }

 }
 break;

 default :
 reader.Read();
 break;

 }

 }
 // INSERCION DE LOS ULTIMOS QUE NO ENTRAN EN EL ÚLTIMO WHILE
 nombrecondicionado.Add(nombretabla);
 docaux.Add(nombrecondicionado);

 // VALIDACION
 validado = ValidarEsquema(docaux, esquema);

 if (validado)
 {
 nreg += cond.Insertar(docaux, delete);

 // vacio contenidos
 nombretabla.Elements().Remove();
 nombrecondicionado.Elements().Remove();
 docaux.Elements().Remove();
 }
 else
 {
 OnReportInformation(string.Format("ERROR fichero{0} no valido.", fichero), ReportLevel.Error);
 EstadoCarga = 2;
 }

}

Linq to XML: Diferencia entre Elements() y Descendants()

Filed Under (.Net, LINQ) by admin on 10-10-2011

Tagged Under : , , , , ,

La diferencia es sencilla, mientra Descendants() cuenta todos los nodos (anidados incluidos), Elements() solo cuenta los del mismo nivel.

 string xml = @"
                <Root>
                    <Item>
                        <id>1</id>
                    </Item>
                    <Item>
                        <id>2</id>
                    </Item>
                    <Item>
                        <id>3</id>
                        <Items>
                            <Item>
                                <id>5</id>
                            </Item>
                            <Item>
                                <id>6</id>
                            </Item>                            
                        </Items>
                    </Item>
                    <Item>
                        <id>4</id>
                    </Item>
                </Root>";

            XDocument doc1 = XDocument.Parse(xml);

            var q1 = from e in doc1.Root.Descendants("Item")
                     select e;

            var q2 = from e in doc1.Root.Elements("Item")
                     select e;

            int c1 = q1.Count(); //6
            int c2 = q2.Count(); //4

Tutorial sencillo de Servicio web ASP.NET

Filed Under (.Net, Videos YouTube) by admin on 29-07-2011

Tagged Under : , ,

Imagen de previsualización de YouTube

Problema mapeo LINQ to SQL de tipo nvarchar(1) de SQLSERVER

Filed Under (.Net, LINQ, SQLServer) by admin on 27-07-2011

Tagged Under : , , , ,

"La cadena debe contener exactamente un carácter"

Este es el mensaje que te aparece si has mapeado un nvarchar(1) y LINQ to SQL tiene que tratarlo cuando tiene el valor de string vacio es decir “”.

Si se hace sobre el DBML:

 

Botón derecho > Abrir Con > Editor XML

 

y se busca la tabla, nos damos cuenta que se esta mapeando de esta forma:

 

 

El problema reside en que al ser de 1 posición esta tratando el string de uno como si fuera tipo Char, la solución es editar a mano el DBML y ponerlo como tipo String:

 

Solución error método Load de XDocument: ‘.’, valor hexadecimal 0×00, es un carácter no válido.

Filed Under (.Net) by admin on 14-06-2011

Tagged Under : , , , , , ,

Siempre cargaba los documentos XML del streamReader de esta forma:

 

XDocument myXmlDocument = XDocument.Load(myReader, LoadOptions.None);

Hasta que hace unos días me salía un error con un documento que decía:

 

‘.’, valor hexadecimal 0×00, es un carácter no válido. Línea XXX, posición XX. (casualmente siempre me indicaba la última línea)

 

Bueno… y como podía ser esto posible… si yo veía el XML correcto, muy bien a ciencia cierta no lo se pero encontré una solución que al menos lo que hace es eliminar todos los caracteres hexadecimales de la cadena de carga de XML.

 

Utilizando esta función en mi caso:

public static string CleanInvalidXmlChars(string text)        {           
// From xml spec valid chars:             
// #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]                 
// any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.             
string re = @"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]";            
return Regex.Replace(text, re, "");        
}

Y cambiando el Load por el Parse:

XDocument myXmlDocument = XDocument.Parse( CleanInvalidXmlChars(myReader.ReadToEnd()), LoadOptions.None);

Utilizar Parallels Extensions de System.Threading en Framework .NET 3.5

Filed Under (.Net) by admin on 30-03-2011

Tagged Under : , , ,

1 -Descargar el Reactive Extensions de .NET (Rx) para 3.5:
http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx


2 – Instalar el paquete .msi

 

3 – Importar Referencia al proyecto que queramos utilizar, la ruta donde esta instalado es:
C:\Program Files (x86)\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2856.0\Net35\System.Threading.dll

 

4- Incluir los using:

using System.Threading;
using System.Threading.Tasks;
 

5- Documentación MSDN de Parallel:

http://msdn.microsoft.com/es-es/library/system.threading.tasks.parallel.aspx

WCF REST, un OperationContract con GET y otro con POST

Filed Under (.Net) by admin on 28-03-2011

Tagged Under : , , ,

A veces por motivos de seguridad o eficiencia hay que configurar las llamadas WCF REST por GET o por POST, es altamente recomendable que las peticiones GET al servidor se hagan por GET y las SET por POST, por motivos de seguridad sobretodo. Por eficiencia es siempre mejor el GET.

[ServiceContract]
public interface IGasPriceService
{
    [OperationContract]
    [WebGet // ESTO ES PARA UN GET
        (RequestFormat = WebMessageFormat.Xml,
        ResponseFormat = WebMessageFormat.Xml,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/GetGasPrice/For/City/{city}"
        )]
    GasPriceData GetPriceDataForCity(string city);

    [OperationContract]
    [WebInvoke // ESTO PARA UN POST
        (Method = "POST",
        RequestFormat = WebMessageFormat.Xml,
        UriTemplate = "/SetGasPrice/For/ZipCode/{zipCode}/Price/{price}"
        )]
    void SetPriceDataForZipCode(string zipCode, string price);
}

 

Configurar el tamaño de las peticiones WCF REST del servicio web

Filed Under (.Net) by admin on 28-03-2011

Tagged Under : , ,

Configurar el tamaño de las peticiones WCF REST, esto se realiza en el web.config

<bindings>
<basicHttpBinding>
 <binding name="LargeBuffer"
...
 <readerQuotas 
 maxDepth="2147483647" 
 maxStringContentLength="2147483647" 
 maxArrayLength="2147483647"
 maxBytesPerRead="2147483647" 
 maxNameTableCharCount="2147483647" />
....
 </binding>
 </basicHttpBinding>
 </bindings>
 <services>
 <service name="WcfService4.Service1" behaviorConfiguration="WcfService4.Service1Behavior">
 <endpoint
 bindingConfiguration="LargeBuffer" <!-- without this, the default quota of 8192 applies -->
 address=""
 binding="basicHttpBinding"
 contract="WcfService4.IService1">
....
 </endpoint>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
 </service>
 </services>