<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog de Oxxigeno &#187; Tecnologías</title>
	<atom:link href="http://www.oxxigeno.com/blog/categoria/tecnologias/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.oxxigeno.com/blog</link>
	<description>Blog corporativo de Oxxigeno</description>
	<lastBuildDate>Tue, 23 Feb 2010 10:11:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Buenas Prácticas en .NET: Uso estructurado del fichero de configuración</title>
		<link>http://www.oxxigeno.com/blog/2009/06/buenas-practicas-en-net-uso-estructurado-del-fichero-de-configuracion/</link>
		<comments>http://www.oxxigeno.com/blog/2009/06/buenas-practicas-en-net-uso-estructurado-del-fichero-de-configuracion/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 17:08:02 +0000</pubDate>
		<dc:creator>ivinuales</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[app.config]]></category>
		<category><![CDATA[ascx]]></category>
		<category><![CDATA[aspx]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://www.oxxigeno.com/blog/?p=467</guid>
		<description><![CDATA[Una práctica habitual en desarrollos asp net es utilizar el fichero de configuración (o el app config en aplicativos de escritorio) como almacén de valores configurables que luego se utilizarán en el aplicativo para uno u otro propósito.
Lo que en principio se nos antoja como una buena práctica, en la mayoría de las ocasiones, debido [...]]]></description>
			<content:encoded><![CDATA[<p>Una práctica habitual en desarrollos asp net es utilizar el fichero de configuración (o el app config en aplicativos de escritorio) como almacén de valores configurables que luego se utilizarán en el aplicativo para uno u otro propósito.</p>
<p>Lo que en principio se nos antoja como una buena práctica, en la mayoría de las ocasiones, debido a una utilización mal estructurada del fichero de configuración, se convierte en una lista incontrolable y sin organización alguna de entradas en el nodo <em>appSettings</em>.</p>
<p>Para evitar esto existe una solución alternativa, más elegante, más clara y, más optima. Las clases <em>ConfigurationSection</em>, <em>ConfigurationElement </em>y <em>ConfigurationElementCollection </em>permiten <strong>definir secciones, elementos y colecciones de elementos en el fichero de configuración</strong> y utilizarlas como cualquier otro objeto en nuestro aplicativo.</p>
<p>Vamos a definir una pequeña sección en el fichero de configuración y comentamos un poquito cómo realizarla.</p>
<p><span id="more-467"></span><br />
La clase <em>EjemploData </em>heredará de <em>ConfigurationElement </em>y tendrá dos propiedades <em>Name </em>y <em>PropiedadBooleana</em>, de tipo string y bool respectivamente. Las propiedades de ambas deberán tener el atributo <em>ConfigurationProperty </em>con el nombre que tomará en el fichero de configuración, su valor por defecto (si queremos especificarlo) y si es obligatoria.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> EjemploData <span style="color: #008000;">:</span> ConfigurationElement
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080;">#region Public Properties</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> NamePropertyName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;name&quot;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>ConfigurationProperty<span style="color: #000000;">&#40;</span>NamePropertyName, IsRequired <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> <span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span>NamePropertyName<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span>NamePropertyName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> PropiedadBooleanaPropertyName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;propiedadBooleana&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#91;</span>ConfigurationProperty<span style="color: #000000;">&#40;</span>PropiedadBooleanaPropertyName, DefaultValue <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;true&quot;</span>, IsRequired <span style="color: #008000;">=</span> <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> PropiedadBooleana
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span><span style="color: #000000;">&#41;</span><span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span>PropiedadBooleanaPropertyName<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span>PropiedadBooleanaPropertyName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Crearemos una clase <em>EjemploDataCollection </em>que herede de <em>ConfigurationElementCollection</em>, tal y como se muestra, no requiere mucha explicación</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> EjemploDataCollection <span style="color: #008000;">:</span> ConfigurationElementCollection
<span style="color: #000000;">&#123;</span>
<span style="color: #008080;">#region ConfigurationElementCollection Members</span>
&nbsp;
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> ConfigurationElement CreateNewElement<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> EjemploData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">object</span> GetElementKey<span style="color: #000000;">&#40;</span>ConfigurationElement element<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>EjemploData<span style="color: #000000;">&#41;</span>element<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Name</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> EjemploData <span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">int</span> index<span style="color: #000000;">&#93;</span>
<span style="color: #000000;">&#123;</span>
get
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>EjemploData<span style="color: #000000;">&#41;</span>BaseGet<span style="color: #000000;">&#40;</span>index<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
set
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>BaseGet<span style="color: #000000;">&#40;</span>index<span style="color: #000000;">&#41;</span> <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
BaseRemoveAt<span style="color: #000000;">&#40;</span>index<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
BaseAdd<span style="color: #000000;">&#40;</span>index, value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080;">#endregion</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Finalmente, crearemos la clase que nos permita manejar este tipo de objetos. Esta clase debe heredar de <em>ConfigurationSection</em>, la cual nos servirá para marcar el ámbito en el cual obtendremos los valores dentro del fichero de configuración. Debe tener:</p>
<ul>
<li>Una constante pública que nos indique cómo llegar a la sección adecuada del fichero de configuración.</li>
<li>Constantes privadas que nos marquen cómo se llamarán los atributos.</li>
<li>Nodos hijos que podremos definir en el fichero de configuración</li>
<li>Sus respectivas propiedades públicas que nos permitirán utilizarlas en cualquier parte de nuestro aplicativo.</li>
</ul>
<p>En nuestro ejemplo definiremos la seccion como “<em>oxxigeno/ejemploSettings</em>”, lo que significa que en el fichero de configuración tendremos que definir un nodo <em>oxxigeno</em> y dentro uno <em>ejemploSettings</em>.</p>
<p>Queremos que exista una atributo en el nodo <em>ejemploSettings</em>, para lo cual crearemos una constante privada que nos diga como debe llamarse, “<em>nuevaPropiedad</em>”, y una propiedad pública que nos permita recuperarlo del fichero de configuración y utilizarlo en el aplicativo. Para ello crearemos una propiedad normal que nos devolverá un objeto de tipo string y le establecemos un atributo a la propiedad de tipo <em>ConfigurationProperty</em><strong>, </strong>que indique cómo se va a llamar ese atributo en el fichero de configuración y si es obligatorio o no que exista.</p>
<p>Además nos interesa que bajo el nodo <em>ejemploSettings </em>exista una colección de nodos del mismo tipo (en nuestro caso <em>EjemploData</em>). Para ello procederemos igual que para la propiedad actual, pero definiremos su salida como <em>EjemploDataCollection</em><strong>, </strong>y le agregaremos el atributo <em>ConfigurationCollection</em><strong> </strong>pasándole como parámetro el tipo de objetos que se coleccionarán.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">sealed</span> <span style="color: #FF0000;">class</span> EjemploSettings <span style="color: #008000;">:</span> ConfigurationSection
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> SectionName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;oxxigeno/ejemploSettings&quot;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080;">#region Public Properties</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> NuevaPropiedadPropertyName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;nuevaPropiedad&quot;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>ConfigurationProperty<span style="color: #000000;">&#40;</span>NuevaPropiedadPropertyName, IsRequired <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> NuevaPropiedad
<span style="color: #000000;">&#123;</span>
get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> <span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span>NuevaPropiedadPropertyName<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
set <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span>NuevaPropiedadPropertyName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> ColeccionDeEjemploPropertyName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;coleccionDeEjemplo&quot;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>ConfigurationProperty<span style="color: #000000;">&#40;</span>ColeccionDeEjemploPropertyName, IsRequired <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span>, IsDefaultCollection <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #000000;">&#91;</span>ConfigurationCollection<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>EjemploData<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> EjemploDataCollection ColeccionDeEjemplo
<span style="color: #000000;">&#123;</span>
get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>EjemploDataCollection<span style="color: #000000;">&#41;</span><span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span>ColeccionDeEjemploPropertyName<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080;">#endregion</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Así pues, para cargar datos en el fichero de configuración, debemos cargar la clase controladora (<em>EjemploSettings</em>) y montar el árbol de nodos que hemos definido en las clases.</p>
<p>Dentro del nodo <em>configurationSections </em>debemos crear un nodo <em>SectionGroup </em>como se muestra, y dentro un nodo <em>section</em>. Pueden existir múltiples nodos <em>sectionGroup </em>pero no con el mismo nombre. Cada nodo <em>sectionGroup </em>puede tener en su interior multiples nodos <em>section</em>.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sectionGroup</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;oxxigeno&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;section</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;ejemploSettings&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;Oxxigeno.Ejemplo.Configuration.EjemploSettings, Oxxigeno.Ejemplo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=96df930e30970c00&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sectionGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</blockquote>
<p>Y despues creamos el árbol de nodos tal como lo hemos definido, quedaría algo así:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;oxxigeno<span style="color: #000000; font-weight: bold;">&gt;</span></span></span> 
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ejemploSettings</span> <span style="color: #000066;">nuevaPropiedad</span>=<span style="color: #ff0000;">&quot;valorDeLaPropiedad&quot;</span>&amp;gt; </span>
<span style="color: #009900;">         <span style="color: #000000; font-weight: bold;">&lt;coleccionDeEjemplo</span>&amp;gt; <span style="color: #000000; font-weight: bold;">&lt;clear</span>/&amp;gt;</span>
<span style="color: #009900;">            <span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;nombreDeLaEntrada1&quot;</span> <span style="color: #000066;">propiedadBooleana</span>=<span style="color: #ff0000;">&quot;false&quot;</span> /&amp;gt; </span>
<span style="color: #009900;">            <span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;nombreDeLaEntrada2&quot;</span> <span style="color: #000066;">propiedadBooleana</span>=<span style="color: #ff0000;">&quot;true&quot;</span> /&amp;gt; </span>
<span style="color: #009900;">         <span style="color: #000000; font-weight: bold;">&lt;/coleccionDeEjemplo<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ejemploSettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/oxxigeno</span>&amp;gt;</span></pre></div></div>

</blockquote>
<p>La forma de recuperar estos valores sería la siguiente:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">EjemploSettings ejemploSettings <span style="color: #008000;">=</span> ConfigurationManager.<span style="color: #0000FF;">GetSection</span><span style="color: #000000;">&#40;</span>EjemploSettings.<span style="color: #0000FF;">SectionName</span><span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">as</span> EjemploSettings<span style="color: #008000;">;</span>
<span style="color: #FF0000;">string</span> nuevaPropiedad <span style="color: #008000;">=</span> ejemploSettings.<span style="color: #0000FF;">NuevaPropiedad</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>EjemploData obj <span style="color: #0600FF;">in</span> ejemploSettings.<span style="color: #0000FF;">ColeccionDeEjemplo</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #FF0000;">string</span> nombre <span style="color: #008000;">=</span> obj.<span style="color: #0000FF;">Name</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">bool</span> propiedadBooleana <span style="color: #008000;">=</span> obj.<span style="color: #0000FF;">PropiedadBooleana</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Considero que este método de utilización del fichero de configuración es:</p>
<ul>
<li><strong>Más útil</strong>: Los valores se encuentran parseados al tipo necesario, no se obtienen unicamente valores de tipo string como pasa si utilizamos AppSettings, lo cual facilita el trabajo del desarrollador.</li>
<li><strong>Más estructurado</strong>: Los valores dentro del fichero de configuración son facilmente localizables y, por lo tanto, modificables.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.oxxigeno.com/blog/2009/06/buenas-practicas-en-net-uso-estructurado-del-fichero-de-configuracion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nuevas Tecnologías &#8211; Windows Comunication Foundation</title>
		<link>http://www.oxxigeno.com/blog/2009/05/nuevas-tecnologias-windows-comunication-foundation/</link>
		<comments>http://www.oxxigeno.com/blog/2009/05/nuevas-tecnologias-windows-comunication-foundation/#comments</comments>
		<pubDate>Mon, 11 May 2009 13:55:17 +0000</pubDate>
		<dc:creator>ivinuales</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[.net 3.5]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[servicios]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.oxxigeno.com/blog/?p=500</guid>
		<description><![CDATA[Este nuevo modulo incluido en el .NET Framework 3.5 establece un modelo de programación unificado para la implementación de sistemas distribuidos, especialmente orientado a servicios.
 Esta tecnología integra en una única metodología de programación las hasta ahora incompatibles COM+ (Serviced Components), .NET Remoting y Servicios Web.  Para ello, un servicio WCF debe definir una [...]]]></description>
			<content:encoded><![CDATA[<p>Este nuevo modulo incluido en el .NET Framework 3.5 establece un modelo de programación unificado para la implementación de sistemas distribuidos, especialmente orientado a servicios.</p>
<p><span id="more-500"></span> Esta tecnología integra en una única metodología de programación las hasta ahora incompatibles COM+ (Serviced Components), .NET Remoting y Servicios Web.  Para ello, un servicio WCF debe definir una serie de puntos de acceso (denominados EndPoints) que representan una puerta de entrada al servicio publicado, permitiendo así que un mismo servicio sea consultado mediante distintos tipos de comunicación.<br />
Los EndPoints deben presentar:</p>
<ul>
<li><strong>Dirección</strong>: representada por la clase EndPointAddress, indica dónde está la aplicación</li>
<li><strong>Enlace</strong>: representada por la clase Binding, indica cómo se puede accesar esa aplicación: Protocolo del transporte, Codificación y Seguridad.</li>
<li><strong>Contrato</strong>: representada por una clase con atributos de tipo <strong>ServiceContractAttribute</strong>, se trata de una definición de los datos que van a ser comunicados por el aplicativo.</li>
</ul>
<p>WCF utiliza mensajes SOAP para la comunicación de estos datos, siguiendo así un estándar de comunicación. Sin embargo, cuando se realiza una comunicación entre dos procesos WCF se optimiza esta comunicación, aplicando una codificación en formato binario para los mensajes SOAP. De esto podemos olvidarnos totalmente, ya que al fin podemos crear un servicio sin preocuparnos de cómo ni quién va a acceder a él.</p>
<p>Vayamos con un ejemplo y veamos si es realmente lo que nos venden. Creamos una interfaz y una entidad que serán las que utilizaremos para dar vida al servicio.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ServiceContract<span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IExample
    <span style="color: #000000;">&#123;</span>
        <span style="color: #000000;">&#91;</span>OperationContract<span style="color: #000000;">&#93;</span>
        <span style="color: #FF0000;">string</span> GetData<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>OperationContract<span style="color: #000000;">&#93;</span>
        ExampleType GetDataUsingDataContract<span style="color: #000000;">&#40;</span>ExampleType composite<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>OperationContract<span style="color: #000000;">&#93;</span>
        <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> GetNames<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>DataContract<span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ExampleType
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">bool</span> _delete <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
        <span style="color: #FF0000;">string</span> _name <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Name&quot;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>DataMember<span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> Delete
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _delete<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> _delete <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>DataMember<span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _name<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> _name <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Los atributos DataContract y OperationContract son, para entendernos, los atributos que sustituyen a WebService y WebMethod. Mientras que los atributos DataContract y DataMember son los atributos que servirán para serializar las entidades que se publicarán a través del servicio.</p>
<p>Ahora, una vez creada la interfaz que publicará el servicio y la entidad, procedemos a implementar la funcionalidad del servicio.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ExampleService <span style="color: #008000;">:</span> IExample
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetData<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> value<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You entered: {0}&quot;</span>, value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> ExampleType GetDataUsingDataContract<span style="color: #000000;">&#40;</span>ExampleType composite<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>composite.<span style="color: #0000FF;">Delete</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                composite.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot; y Apellido&quot;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">return</span> composite<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> GetNames<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> lista <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                lista.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;nombre&quot;</span> <span style="color: #008000;">+</span> i.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">return</span> lista.<span style="color: #0000FF;">ToArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Con esto ya tenemos el código necesario para crear un servicio con WCF. Nos falta darle posibles puntos de entrada, para poder publicarlo. Lo hacemos a través del web.config del servicio.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system.serviceModel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;services<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;service</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Namespace.ExampleService&quot;</span> <span style="color: #000066;">behaviorConfiguration</span>=<span style="color: #ff0000;">&quot;Namespace.ExampleServiceBehavior&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #808080; font-style: italic;">&lt;!-- Service Endpoints --&gt;</span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">address</span>=<span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;wsHttpBinding&quot;</span> <span style="color: #000066;">contract</span>=<span style="color: #ff0000;">&quot;Namespace.IExample&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;identity<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dns</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;localhost&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/identity<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/endpoint<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">address</span>=<span style="color: #ff0000;">&quot;mex&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;mexHttpBinding&quot;</span> <span style="color: #000066;">contract</span>=<span style="color: #ff0000;">&quot;IMetadataExchange&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/service<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/services<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;behaviors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;serviceBehaviors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;behavior</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Namespace.ExampleServiceBehavior&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;serviceMetadata</span> <span style="color: #000066;">httpGetEnabled</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;serviceDebug</span> <span style="color: #000066;">includeExceptionDetailInFaults</span>=<span style="color: #ff0000;">&quot;false&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/behavior<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/serviceBehaviors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/behaviors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system.serviceModel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</blockquote>
<p>Voy a intentar explicarlo de forma esquemática. Dentro de la etiqueta “services” creamos cada uno de los servicios que queramos publicar, mientras que dentro de la etiqueta “behaviors” definiremos diferentes comportamientos que podrán utilizarse en los servicios publicados.</p>
<p>Pero volvamos a la etiqueta “services”. Dentro de ella crearemos tantas etiquetas “service” como servicios queramos publicar. Cada una se define mediante nombre y comportamiento (“name” y “behaviorConfiguration”). Además debemos definir una serie de puntos de entrada (“endpoint”) con las propiedades “address”, “binding” y “contract”, y un nodo interno de tipo “identity” (como se ve en el código). Vamos con ellos:</p>
<ul>
<li>Etiqueta Service:
<ul>
<li>Address: Especificamos la URI, que puede estar como cadena vacía.</li>
<li>Binding: Especificamos el binding a utilizar, lo cual define el tipo de transporte, la seguridad y el encoding utilizado. Podemos utilizar un binding definido por nosotros.</li>
<li>Contract: Especifica la interfaz que define se publicará con el servicio.</li>
</ul>
</li>
<li>Etiqueta Behavior:
<ul>
<li>Name: Nombre del behavior, único en el web.config</li>
<li>ServiceMetadata: Especifica la publicación de los metadatos del servicio y de la información asociada.</li>
<li>ServiceDebug: Especifica las características de la información de depuración y de la ayuda para un servicio de la WCF.</li>
</ul>
</li>
</ul>
<p>Para una descripción más detallada podemos recurrir a la siguiente url de Microsoft: <a href="http://msdn.microsoft.com/en-us/library/ms733932.aspx">http://msdn.microsoft.com/en-us/library/ms733932.aspx</a></p>
<p>Respecto al cliente, su uso es tan sencillo como agregar la referencia al servicio a la solucion e invocarlo desde el código.</p>
<p>Al agregar la referencia al servicio podemos ver que el web.config ha sido modificado, añadiendo la configuracion necesaria para accesar dicho servicio. Veamos qué ha añadido:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system.serviceModel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;wsHttpBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;binding</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;WSHttpBinding_IExample&quot;</span> <span style="color: #000066;">closeTimeout</span>=<span style="color: #ff0000;">&quot;00:01:00&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">openTimeout</span>=<span style="color: #ff0000;">&quot;00:01:00&quot;</span> <span style="color: #000066;">receiveTimeout</span>=<span style="color: #ff0000;">&quot;00:10:00&quot;</span> <span style="color: #000066;">sendTimeout</span>=<span style="color: #ff0000;">&quot;00:01:00&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">bypassProxyOnLocal</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">transactionFlow</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">hostNameComparisonMode</span>=<span style="color: #ff0000;">&quot;StrongWildcard&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">maxBufferPoolSize</span>=<span style="color: #ff0000;">&quot;524288&quot;</span> <span style="color: #000066;">maxReceivedMessageSize</span>=<span style="color: #ff0000;">&quot;65536&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">messageEncoding</span>=<span style="color: #ff0000;">&quot;Text&quot;</span> <span style="color: #000066;">textEncoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span> <span style="color: #000066;">useDefaultWebProxy</span>=<span style="color: #ff0000;">&quot;true&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">allowCookies</span>=<span style="color: #ff0000;">&quot;false&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;readerQuotas</span> <span style="color: #000066;">maxDepth</span>=<span style="color: #ff0000;">&quot;32&quot;</span> <span style="color: #000066;">maxStringContentLength</span>=<span style="color: #ff0000;">&quot;8192&quot;</span> <span style="color: #000066;">maxArrayLength</span>=<span style="color: #ff0000;">&quot;16384&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">maxBytesPerRead</span>=<span style="color: #ff0000;">&quot;4096&quot;</span> <span style="color: #000066;">maxNameTableCharCount</span>=<span style="color: #ff0000;">&quot;16384&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;reliableSession</span> <span style="color: #000066;">ordered</span>=<span style="color: #ff0000;">&quot;true&quot;</span> <span style="color: #000066;">inactivityTimeout</span>=<span style="color: #ff0000;">&quot;00:10:00&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">enabled</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;security</span> <span style="color: #000066;">mode</span>=<span style="color: #ff0000;">&quot;Message&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transport</span> <span style="color: #000066;">clientCredentialType</span>=<span style="color: #ff0000;">&quot;Windows&quot;</span> <span style="color: #000066;">proxyCredentialType</span>=<span style="color: #ff0000;">&quot;None&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">realm</span>=<span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;message</span> <span style="color: #000066;">clientCredentialType</span>=<span style="color: #ff0000;">&quot;Windows&quot;</span> <span style="color: #000066;">negotiateServiceCredential</span>=<span style="color: #ff0000;">&quot;true&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">algorithmSuite</span>=<span style="color: #ff0000;">&quot;Default&quot;</span> <span style="color: #000066;">establishSecurityContext</span>=<span style="color: #ff0000;">&quot;true&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/wsHttpBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bindings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;client<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">address</span>=<span style="color: #ff0000;">&quot;http://localhost:3153/ExampleService.svc&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;wsHttpBinding&quot;</span> <span style="color: #000066;">bindingConfiguration</span>=<span style="color: #ff0000;">&quot;WSHttpBinding_IExample&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">contract</span>=<span style="color: #ff0000;">&quot;ExampleServiceReference.IExample&quot;</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;WSHttpBinding_IExample&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;identity<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dns</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;localhost&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/identity<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/endpoint<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/client<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system.serviceModel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</blockquote>
<p>Él solo ha creado todo el arbol de etiquetas de configuracion necesario para acceder al servicio mediante el endpoint que deseemos. Si nos fijamos en la etiqueta “endpoint” dentro de “client” podemos ver cómo ha agregado la direccion del servicio, el tipo de binding, la configuracion del mismo, la interfaz que presenta y el nombre (que es lo que utilizaremos para crear el objeto client en código):</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ExampleClient clientDefault <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ExampleClient<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;WSHttpBinding_IExample&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> namesDefault <span style="color: #008000;">=</span> clientDefault.<span style="color: #0000FF;">GetNames</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

</blockquote>
<p>Vamos a crear otro endpoint en el web.config del servicio y vamos a refrescar la referencia en el cliente para ver cómo cambia el web.config, añadiendo el nuevo endpoint y veremos cómo referenciarlo.  Agregamos dos endpoints:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"> <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">address</span>=<span style="color: #ff0000;">&quot;Soap11&quot;</span> <span style="color: #000066;">contract</span>=<span style="color: #ff0000;">&quot;Namespace.IExample&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;basicHttpBinding&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">address</span>=<span style="color: #ff0000;">&quot;Soap12&quot;</span> <span style="color: #000066;">contract</span>=<span style="color: #ff0000;">&quot;Namespace.IExample&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;wsHttpBinding&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

</blockquote>
<p>Y refrescamos la referencia al servicio en el cliente. Miramos el web.config y descubrimos que tenemos nuevas formas de acceder al servicio:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"> <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">address</span>=<span style="color: #ff0000;">&quot;http://localhost:3153/ExampleService.svc/Soap11&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;basicHttpBinding&quot;</span> <span style="color: #000066;">bindingConfiguration</span>=<span style="color: #ff0000;">&quot;BasicHttpBinding_IExample&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">contract</span>=<span style="color: #ff0000;">&quot;ExampleServiceReference.IExample&quot;</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;BasicHttpBinding_IExample&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;endpoint</span> <span style="color: #000066;">address</span>=<span style="color: #ff0000;">&quot;http://localhost:3153/ExampleService.svc/Soap12&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;wsHttpBinding&quot;</span> <span style="color: #000066;">bindingConfiguration</span>=<span style="color: #ff0000;">&quot;WSHttpBinding_IExample&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">contract</span>=<span style="color: #ff0000;">&quot;ExampleServiceReference.IExample&quot;</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;WSHttpBinding_IExample1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;identity<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;userPrincipalName</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ivinuales@oxxigeno-networks.spain&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/identity<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/endpoint<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</blockquote>
<p>Además, nos ha creado una nueva entrada dentro de bindings:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;basicHttpBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;binding</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;BasicHttpBinding_IExample&quot;</span> <span style="color: #000066;">closeTimeout</span>=<span style="color: #ff0000;">&quot;00:01:00&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">openTimeout</span>=<span style="color: #ff0000;">&quot;00:01:00&quot;</span> <span style="color: #000066;">receiveTimeout</span>=<span style="color: #ff0000;">&quot;00:10:00&quot;</span> <span style="color: #000066;">sendTimeout</span>=<span style="color: #ff0000;">&quot;00:01:00&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">allowCookies</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">bypassProxyOnLocal</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">hostNameComparisonMode</span>=<span style="color: #ff0000;">&quot;StrongWildcard&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">maxBufferSize</span>=<span style="color: #ff0000;">&quot;65536&quot;</span> <span style="color: #000066;">maxBufferPoolSize</span>=<span style="color: #ff0000;">&quot;524288&quot;</span> <span style="color: #000066;">maxReceivedMessageSize</span>=<span style="color: #ff0000;">&quot;65536&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">messageEncoding</span>=<span style="color: #ff0000;">&quot;Text&quot;</span> <span style="color: #000066;">textEncoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span> <span style="color: #000066;">transferMode</span>=<span style="color: #ff0000;">&quot;Buffered&quot;</span></span>
<span style="color: #009900;">                    <span style="color: #000066;">useDefaultWebProxy</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;readerQuotas</span> <span style="color: #000066;">maxDepth</span>=<span style="color: #ff0000;">&quot;32&quot;</span> <span style="color: #000066;">maxStringContentLength</span>=<span style="color: #ff0000;">&quot;8192&quot;</span> <span style="color: #000066;">maxArrayLength</span>=<span style="color: #ff0000;">&quot;16384&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">maxBytesPerRead</span>=<span style="color: #ff0000;">&quot;4096&quot;</span> <span style="color: #000066;">maxNameTableCharCount</span>=<span style="color: #ff0000;">&quot;16384&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;security</span> <span style="color: #000066;">mode</span>=<span style="color: #ff0000;">&quot;None&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transport</span> <span style="color: #000066;">clientCredentialType</span>=<span style="color: #ff0000;">&quot;None&quot;</span> <span style="color: #000066;">proxyCredentialType</span>=<span style="color: #ff0000;">&quot;None&quot;</span></span>
<span style="color: #009900;">                            <span style="color: #000066;">realm</span>=<span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;message</span> <span style="color: #000066;">clientCredentialType</span>=<span style="color: #ff0000;">&quot;UserName&quot;</span> <span style="color: #000066;">algorithmSuite</span>=<span style="color: #ff0000;">&quot;Default&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/basicHttpBinding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</blockquote>
<p>De tal forma que ahora en el código fuente podemos instanciarlo de 3 formas distintas:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">            ExampleClient clientDefault <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ExampleClient<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;WSHttpBinding_IExample&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> namesDefault <span style="color: #008000;">=</span> clientDefault.<span style="color: #0000FF;">GetNames</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            ExampleClient clientSOAP11 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ExampleClient<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;BasicHttpBinding_IExample&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> namesSOAP11 <span style="color: #008000;">=</span> clientSOAP11.<span style="color: #0000FF;">GetNames</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            ExampleClient clientSOAP12 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ExampleClient<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;WSHttpBinding_IExample1&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> namesSOAP12 <span style="color: #008000;">=</span> clientSOAP12.<span style="color: #0000FF;">GetNames</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.oxxigeno.com/blog/2009/05/nuevas-tecnologias-windows-comunication-foundation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#, .NET 2.0 y procesamiento de CSV</title>
		<link>http://www.oxxigeno.com/blog/2009/04/generalizando-procesamiento-csv/</link>
		<comments>http://www.oxxigeno.com/blog/2009/04/generalizando-procesamiento-csv/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 14:06:41 +0000</pubDate>
		<dc:creator>ivinuales</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ascx]]></category>
		<category><![CDATA[aspx]]></category>
		<category><![CDATA[microsoft]]></category>

		<guid isPermaLink="false">http://www.oxxigeno.com/blog/?p=483</guid>
		<description><![CDATA[Los ficheros csv son ficheros de texto que contienen valores separados por alguna caracter (en nuestro caso punto y coma) y agrupados en líneas. Es decir, cada línea podemos considerarla un conjunto de valores completo y podemos identificar a este conjunto de valores como una entidad.

Lo primero que debemos hacer es identificar esa entidad y [...]]]></description>
			<content:encoded><![CDATA[<p>Los ficheros csv son ficheros de texto que contienen valores separados por alguna caracter (en nuestro caso punto y coma) y agrupados en líneas. Es decir, cada línea podemos considerarla un conjunto de valores completo y podemos identificar a este conjunto de valores como una entidad.</p>
<p><span id="more-483"></span><br />
Lo primero que debemos hacer es <strong>identificar esa entidad y crear una clase para guardar esos datos</strong>. Después debemos tener algun mecanismo para rellenar esta clase con los valores de cada una de las filas (cada fila del fichero supondrá un objeto de ésta clase).</p>
<p>Pongamos un ejemplo.  Supongamos un fichero csv como el siguiente:</p>
<blockquote>
<pre>Edad; Nombre; Apellido
15; Pepito; Perez
57; Ernesto; Román
RowCount = 2</pre>
</blockquote>
<p>En ocasiones los csv traen una cabecera y/o un pie de fichero y en otras no, por lo que no podemos tratar de procesarlas siempre.</p>
<p>Vamos a empezar creando una clase entidad como la siguiente:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Edades
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">int</span> _edad<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _nombre<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _apellido<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Edad
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _edad<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        set <span style="color: #000000;">&#123;</span> _edad <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Nombre
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _nombre<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        set <span style="color: #000000;">&#123;</span> _nombre <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Apellido
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _apellido<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        set <span style="color: #000000;">&#123;</span> _apellido <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Como vemos, se trata de una clase tonta con 3 atributos y sus 3 correspondientes propiedades publicas. En este ejemplo sería muy sencillo por cada fila crearnos un objeto y asignar a Edad el primer valor de la fila, a Nombre la segunda y a Apellido la tercera, serían 3 simples líneas. Sin embargo, a medida que el csv (y la clase) contengan más campos esto se haría más complejo, y sería muy complejo de modificar si algún día deciden introducir un campo nuevo en mitad del csv.</p>
<p>Claro este punto, debemos tener alguna forma de <strong>relacionar cada propiedad de la clase con la posicion que ocupa ese valor en el csv</strong>. Para esto tenemos dos opciones:</p>
<ul>
<li>Si la posición de cada campo es susceptible de ser modificada periódicamente deberíamos determinar esta relación en el web.config (si es una aplicación web) o en app.config (si es una aplicación de escritorio)</li>
<li>Si la posición de cada campo no es susceptible de ser modificada, es preferible agregar atributos a la clase que indique donde debemos buscar el valor de cada propiedad.</li>
</ul>
<p>Voy a centrarme en este segundo supuesto, el primero posiblemente lo trataremos en otro artículo.  Vamos a generar una clase que herede de Attribute para poder indicar en la clase que acabamos de crear donde buscaremos cada valor.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CSVFieldAttribute <span style="color: #008000;">:</span> Attribute
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">int</span> _order<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Order
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _order<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        set <span style="color: #000000;">&#123;</span> _order <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> CSVFieldAttribute<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> order<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _order <span style="color: #008000;">=</span> order<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Ahora modificamos la clase de la entidad, añadiéndole a cada propiedad un atributo indicando su posición en el csv. La clase quedaría como sigue:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Edades
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">int</span> _edad<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _nombre<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _apellido<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>CSVField<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Edad
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _edad<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        set <span style="color: #000000;">&#123;</span> _edad <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#91;</span>CSVField<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Nombre
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _nombre<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        set <span style="color: #000000;">&#123;</span> _nombre <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#91;</span>CSVField<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Apellido
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _apellido<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        set <span style="color: #000000;">&#123;</span> _apellido <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>En este punto podemos elegir partir de una base en 0 o una base en 1. Yo he preferido partir de base 0 porque es la utilizada en los arrays por C#.<br />
Ya tenemos relacionada la clase de entidad con los valores del csv, ahora falta buscarnos la vida para rellenar un objeto a partir de una fila del csv. Propongo utilizar Reflexion y las Templated classes para generalizar este proceso, creando una clase que trasforme un array de valores en un objeto del tipo que le indiquemos. A las propiedades de ese objeto les asignaremos el valor (mediante reflexion) que haya en el array de valores en la posición indicada. Vayamos al tema:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CSVConverter<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> T Convert<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> values<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Type type <span style="color: #008000;">=</span> <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>T<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        T obj <span style="color: #008000;">=</span> Activator.<span style="color: #0000FF;">CreateInstance</span><span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">try</span>
        <span style="color: #000000;">&#123;</span>
            CSVFieldAttribute att <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
            <span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> attributes <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PropertyInfo prop <span style="color: #0600FF;">in</span> type.<span style="color: #0000FF;">GetProperties</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                attributes <span style="color: #008000;">=</span> prop.<span style="color: #0000FF;">GetCustomAttributes</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>CSVFieldAttribute<span style="color: #000000;">&#41;</span>, <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>attributes.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">&amp;</span>gt<span style="color: #008000;">;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    att <span style="color: #008000;">=</span> attributes<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span> <span style="color: #0600FF;">as</span> CSVFieldAttribute<span style="color: #008000;">;</span>
                    <span style="color: #008080; font-style: italic;">/* Si hemos optado por usar base 1 debemos poner:
                        values[att.Order - 1]
                    */</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #000000;">&#40;</span>values<span style="color: #000000;">&#91;</span>att.<span style="color: #0000FF;">Order</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">Trim</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Equals</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Empty</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        prop.<span style="color: #0000FF;">SetValue</span><span style="color: #000000;">&#40;</span>obj,
                           Convert.<span style="color: #0000FF;">ChangeType</span><span style="color: #000000;">&#40;</span>values<span style="color: #000000;">&#91;</span>att.<span style="color: #0000FF;">Order</span><span style="color: #000000;">&#93;</span>, prop.<span style="color: #0000FF;">PropertyType</span><span style="color: #000000;">&#41;</span>,
                           <span style="color: #0600FF;">null</span>
                        <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Error al intentar hacer la conversión de tipos.<span style="color: #008080; font-weight: bold;">\r</span><span style="color: #008080; font-weight: bold;">\n</span>&quot;</span> <span style="color: #008000;">+</span> ex.<span style="color: #0000FF;">Message</span>, ex<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">return</span> obj<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Ya solo queda <strong>procesar el fichero para ir creando los objetos</strong> y hacer lo que tengamos que hacer con ellos. Para ello, nos crearemos una clase base a partir de la cual heredaremos las clases de negocio que creamos oportunas para procesar distintos modelos de csv.</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ProcessCSV<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">protected</span> StreamReader _streamReader<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #FF0000;">string</span> _line<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Process<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> filename<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">try</span>
        <span style="color: #000000;">&#123;</span>
            _streamReader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamReader<span style="color: #000000;">&#40;</span>filename<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">ProcessHeader</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">ProcessBody</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">ProcessFooter</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">throw</span> ex<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">finally</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_streamReader <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                _streamReader.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> ProcessHeader<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;No implementado&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> ProcessFooter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;No implementado&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> ProcessOneObject<span style="color: #000000;">&#40;</span>T obj<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;No implementado&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> ProcessBody<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        T obj <span style="color: #008000;">=</span> Activator.<span style="color: #0000FF;">CreateInstance</span><span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _line <span style="color: #008000;">=</span> _streamReader.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_streamReader.<span style="color: #0000FF;">EndOfStream</span> <span style="color: #008000;">&amp;&amp;</span> _line <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> _line.<span style="color: #0000FF;">Trim</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">!=</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Empty</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">try</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> values <span style="color: #008000;">=</span> _line.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">';'</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                CSVConverter<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> converter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CSVConverter<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                obj <span style="color: #008000;">=</span> converter.<span style="color: #0000FF;">Convert</span><span style="color: #000000;">&#40;</span>values<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">ProcessOneObject</span><span style="color: #000000;">&#40;</span>obj<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// Aquí escribiríamos algo en el log indicando qué fila ha fallado</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Ya tenemos nuestra clase genérica. Pero claro, con esto no hacemos nada, si intentas parsear algo llamando a esta clase te van a saltar excepciones porque no está implementados algunos métodos necesarios. Generemos la clase que realmente usaremos.</p>
<p>Partimos de varios supuestos: el csv es el que he puesto arriba (con cabecera y pie), no vamos a usar para nada ni la cabecera ni el pie y queremos agregar a una lista para luego procesarlos (esto no lo voy a contemplar en el articulo).<br />
Al tema:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> EdadesBL <span style="color: #008000;">:</span> ProcessCSV<span style="color: #008000;">&lt;</span>Edades<span style="color: #008000;">&gt;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> List<span style="color: #008000;">&lt;</span>Edades<span style="color: #008000;">&gt;</span> _list<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> EdadesBL<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _list <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>Edades<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> ProcessHeader<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Solo leemos porque no queremos conservar la cabecera</span>
        _streamReader.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> ProcessFooter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Solo leemos porque no queremos conservar la cabecera</span>
        _streamReader.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> ProcessOneObject<span style="color: #000000;">&#40;</span>Edades obj<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Solo queremos agregarlo a la lista.</span>
        _list.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>obj<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span>Edades<span style="color: #008000;">&gt;</span> Edades
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _list<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>Ahora solo tenemos que <strong>procesar el fichero con dos simples líneas</strong> (en nuestro pequeño ejemplo 3 para recoger tambien la lista de Edades):</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">EdadesBL business <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> EdadesBL<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
business.<span style="color: #0000FF;">Process</span><span style="color: #000000;">&#40;</span>filename<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
List todos <span style="color: #008000;">=</span> business.<span style="color: #0000FF;">Edades</span><span style="color: #008000;">;</span></pre></div></div>

</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.oxxigeno.com/blog/2009/04/generalizando-procesamiento-csv/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Instalación avanzada de Linux</title>
		<link>http://www.oxxigeno.com/blog/2009/03/instalacion-avanzada-de-linux/</link>
		<comments>http://www.oxxigeno.com/blog/2009/03/instalacion-avanzada-de-linux/#comments</comments>
		<pubDate>Thu, 26 Mar 2009 10:13:10 +0000</pubDate>
		<dc:creator>Ricardo Palacios</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Sistemas]]></category>

		<guid isPermaLink="false">http://www.oxxigeno.com/blog/?p=438</guid>
		<description><![CDATA[Con este post, el lector aprenderá a realizar instalaciones avanzadas (sin CD). Después de su estudio, deberá ser capaz de realizar una instalación de red, describir los servidores de instalación de red y describir las instalaciones de tipo kickstart de Red Hat y fedora.
Instalaciones en red
La mayoría de los sistemas Linux se instalan desde los [...]]]></description>
			<content:encoded><![CDATA[<p>Con este <em>post</em>, el lector aprenderá a realizar instalaciones avanzadas (sin CD). Después de su estudio, deberá ser capaz de realizar una instalación de red, describir los servidores de instalación de red y describir las instalaciones de tipo <em>kickstart</em> de Red Hat y fedora.</p>
<p><span id="more-438"></span><strong>Instalaciones en red</strong></p>
<p>La mayoría de los sistemas Linux se instalan desde los CD-ROM (o DVD) de distribución. Este método es cómodo si sólo necesita instalar uno o pocos sistemas, pero puede ser muy tedioso si necesita instalar 10 o más sistemas, especialmente si cada uno tiene que ser instalado con los mismos parámetros.</p>
<p>Existen métodos de instalación más avanzados que son adecuados para estas situaciones, y en la mayoría de los casos, involucran instalaciones de red, donde los RPMs a instalar son descargados de la red.</p>
<p>Existen varios protocolos de red para recuperar los RPMs de instalación, y los protocolos soportados dependen de la distribución. Puede que se incluya soporte para NFS, FTP, HTTP y SMB.</p>
<p>Un requisito obvio para una instalación basada en red es que necesitará configurar un servidor de instalación en red en algún lugar de ésta, el cual contendrá todos los RPMs de su distribución.</p>
<p>Otro requisito es que los sistemas que se van a instalar estén equipados con un adaptador de red, que esté soportado por el disquete de arranque de red. Si su adaptador de red no está soportado en el disquete de arranque, puede necesitar un disquete adicional que contenga el soporte de dispositivo en forma de módulos de kernel de Linux.</p>
<p><strong>Servidor de instalación de red</strong></p>
<p>Un servidor de instalación en red es normalmente un servidor Linux/UNIX, aunque a veces también se pueden utilizar servidores Windows. El contenido de todos los CDs importantes se copia en disco y se deja disponible. Es una buena idea usar un esquema de denominación que permita copiar en disco múltiples versiones de múltiples distribuciones.</p>
<p>Casi todos los servidores de instalación en red exportan los CDs a través de NFS, sin embargo, también puede utilizarse FTP (anónimo), HTTP y SMB.</p>
<p>Si decide usar NFS, tenga presente que las distribuciones más nuevas utilizan normalmente NFS versión 3, mientras que las más antiguas suelen utilizar NFS versión 2. Esto puede generar problemas de compatibilidad, que pueden ser fácilmente solucionados forzando al servidor NFS a utilizar siempre la versión 2.</p>
<p>Si decide ofrecer instalaciones de FTP anónimo, necesitará crear la estructura de directorios en algún lugar bajo el directorio <em>/var/ftp</em>, ya que el demonio ftp realizará el <strong><em>chroot </em></strong>en este directorio cuando se solicite FTP anónimo.</p>
<p>Si decide ofrecer instalaciones HTTP, simplemente puede crear un enlace simbólico desde el directorio <em>document_root</em> al directorio donde se copian los CDs, siempre que se establezca &#8220;FollowSymLinks&#8221; en la configuración del servidor web.</p>
<p>Después de crear el directorio de instalación, necesitará copiar el contenido de los CDs importantes en dicho directorio. Esta acción tiene que llevarse a cabo preservando intactos todos los permisos, los usuarios, etc. y la mejor forma de realizarlo puede ser mediante la utilización del parámetro <strong><em>cp -a </em></strong></p>
<p>Para una distribución Red Hat o fedora, asegúrese de copiar al menos el fichero .discinfo y los directorios RedHat/ e images/.</p>
<p><strong>Instalaciones &#8220;Kickstart&#8221; de Red Hat/Fedora</strong></p>
<p>&#8220;Kickstart&#8221; es el método de Red Hat y Fedora para la automatización de instalaciones. Implica la creación de un archivo ks.cfg, que contiene tres secciones:</p>
<ul>
<li>La primera sección, que empieza en la parte superior del archivo, contiene la respuestas a todas las preguntas del proceso de instalación. Por ejemplo, si existe la declaración <em>lang en_US </em>en el archivo de kickstart, la pregunta &#8220;¿Qué idioma desea utilizar durante el proceso de instalación? no será formulada, sino que se utilizará el inglés de EEUU.</li>
<li>La segunda sección empieza con el identificador %packages. Contiene una lista con todos los paquetes (RPMs) que se van a instalar. Al igual que en el propio proceso de instalación, también puede utilizar los grupos de paquetes que están definidos en el archivo [RedHat|Fedora]/base/comps.xml. Estos grupos de paquetes están identificados con un símbolo arroba, por ejemplo &#8220;@ Printing Support&#8221;.</li>
<li>La tercera sección empieza con el identificador %post. Contiene una serie de manadatos de shell que se ejecutan en el sistema recién instalado, con todas las rutas de acceso, redes, etc, intactas. Esto significa que es posible realizar prácticamente cualquier acción, incluido montar sistemas de archivos remotos, crear cuentas de usuario, etc.</li>
</ul>
<p>También es posible crear una sección %pre, que se ejecuta antes de que se inicie la instalación. Esto suele utilizarse para implementar esquemas de partición personalizados.</p>
<p>Los archivos kickstart pueden hacerse a mano (veáse anexo), pero Red Hat ha creado una herramienta que le ayudará a generar ficheros kickstart: <strong>redhat-config-kickstart </strong>(anteriormente conocida como <strong>ksconfig</strong>). Esta herramienta está disponible en los CDs de distribución en el paquete RPM ksconfig. Como un extra añadido, el instalador de Red Hat/Fedora, Anaconda, genera un fichero kickstart basado en las elecciones determinadas durante el propio proceso de instalación. Este fichero se llama <em>/root/anaconda-ks.cfg</em>.</p>
<p>Ejemplos son <em>ks=floppy</em> y <em>ks=http://192.168.0.1/kickstat/ks.cfg</em>, si no suministra una URL (&#8220;linux ks&#8221;), entonces la localización del fichero kickstat se tomará del siguiente servidor DHCP y las respuestas de las opciones &#8220;next server&#8221; y &#8220;filenam&#8221; desde el servidor DHCP.</p>
<p>El fichero de configuración kickstart puede guardarse en un disquete de arranque o en un servidor de la red. La instalación de Kickstart comienza entonces tecleando <strong>linux ks=&lt;URL&gt;,</strong> donde &lt;URL&gt; es la localización en donde se guarda el fichero ks.cfg.</p>
<p>Para instalaciones kickstart completamente automatizadas, modifique el fichero syslinux.cfg en su disco bootdisk.img, y defina kickstart por defecto. Debería desactivar la opción de delay. La cabecera del fichero se verá de la siguiente manera:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="apache" style="font-family:monospace;">default linux ks
prompt <span style="color: #ff0000;">0</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="apache" style="font-family:monospace;">&lt;!--more--&gt;</pre></div></div>

</blockquote>
<p><strong>Conclusiones</strong></p>
<p>Se ha visto como los servidores de instalación en red son mecanismos apropiados para la distribución de software, con objeto de actualizar e instalar. Así como un servidor de instalación en red, normalmente, exporta varias versiones de distintas distribuciones vía NFS, FTP o HTTP. Habitualmente para realizar una instalación en red, necesitará un disquete y, en ciertas ocasiones, discos de módulos adicionales.</p>
<p>Por último, se ha visto como &#8220;Kickstart&#8221; de Red Hat/Fedora es un método de instalación que le permite automatizar las instalaciones.</p>
<p> </p>
<p><strong>Anexo</strong></p>
<p>Un archivo de kickstart de ejemplo tendrá este aspecto:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="apache" style="font-family:monospace;">&lt;!--more--&gt;install
nfs --server 192.168.0.1 --dir /export/rh80
lang en_US
langsupport --default en_US.iso885915 en_US.iso885915
keyboard es
mouse generic3ps/<span style="color: #ff0000;">2</span> --device psaux
skipx
network --device eth0 --bootproto dhcp
rootpw oxxigeno
firewall --disabled
authconfig --enableshadow --wnablemd5
timezone Europe/Madrid
bootloader
clearpart --<span style="color: #00007f;">all</span>
part /boot --fstype ext3 --size=<span style="color: #ff0000;">100</span>
part / --fstype ext3 --size=<span style="color: #ff0000;">3000</span>
part swap --size=<span style="color: #ff0000;">1024</span>
&nbsp;
%packages
@ Printing Support
@ X Window System
@ GNOME Desktop Environment
@ KDE Desktop Environment
@ Development Tools
@ Kernel Development
@ Network Servers
&nbsp;
%post
adduser oxx1
echo oxx1 | passwd --stdin oxx1</pre></div></div>

</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.oxxigeno.com/blog/2009/03/instalacion-avanzada-de-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Planificación física y mantenimiento</title>
		<link>http://www.oxxigeno.com/blog/2009/03/linux-planificacion-fisica-y-mantenimiento/</link>
		<comments>http://www.oxxigeno.com/blog/2009/03/linux-planificacion-fisica-y-mantenimiento/#comments</comments>
		<pubDate>Fri, 13 Mar 2009 09:48:09 +0000</pubDate>
		<dc:creator>Ricardo Palacios</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Sistemas]]></category>

		<guid isPermaLink="false">http://www.oxxigeno.com/blog/?p=397</guid>
		<description><![CDATA[Este post describe los diversos aspectos que están relacionados con la planificación física y el mantenimiento de los sistemas Linux. Se pretende que, una vez estudiado, se pueda describir los elementos a considerar al planificar la instalación física del sistema y enumerar las prácticas más adecuadas para el mantenimiento físico.
Durante la planificación de la instalación física, deben ser consideradas [...]]]></description>
			<content:encoded><![CDATA[<p>Este <em>post </em>describe los diversos aspectos que están relacionados con la planificación física y el mantenimiento de los sistemas Linux. Se pretende que, una vez estudiado, se pueda describir los elementos a considerar al planificar la instalación física del sistema y enumerar las prácticas más adecuadas para el mantenimiento físico.</p>
<p><span id="more-397"></span>Durante la planificación de la instalación física, deben ser consideradas varias cuestiones y elementos:</p>
<ul>
<li> Peso</li>
<li>Superficie del suelo</li>
<li>Accesibilidad</li>
<li>Alimentación eléctrica</li>
<li>Temperatura</li>
<li>Humedad</li>
<li>Electricidad estática</li>
<li>Limpieza.</li>
</ul>
<p><strong>Alojamiento del sistema</strong></p>
<p>En la mayoría de los casos, los servidores se sitúan en salas de sistemas dedicadas.</p>
<p><img class="aligncenter size-full wp-image-415" title="cpd1" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/03/cpd1.png" alt="cpd1" width="432" height="484" /></p>
<p>Las ventajas son muchas. Los suelos técnicos facilitan mantener el orden y facilitan la regulación de aire acondicionado por separado, permitiendo conseguir un entorno ambiental óptimo. Además, los sistemas de control de acceso impiden el acceso no autorizado a la consola. La mayor desventaja es la dificultad de accesibilidad si se precisara acceder a la consola.</p>
<p><strong>Montaje en bastidor</strong></p>
<p>Los bastidores de fabricación estándar (19&#8221;) pueden almacenar una gran variedad de equipamiento informático, como servidores, bandejas de servidores blade, equipos de red, monitores, teclados, conmutadores KVM, UPS, etc.</p>
<p><img class="aligncenter size-medium wp-image-419" title="rv40862" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/03/rv40862-153x300.jpg" alt="rv40862" width="153" height="300" /></p>
<p>Las principales ventajas son la reducción significatica de la superficie necesaria, la facilidad para limitar el acceso físisco al sistema y la facilidad para mantener el orden, así como un mejor aspecto visual. Como desventajas tendríamos el precio, la mayor dificultad para el acceso físico y la posible necesidad de reforzar el suelo para un bastidor completo.</p>
<p><strong>Consideraciones sobre la alimentación eléctrica</strong></p>
<p>Se debe tener en cuenta el consumo eléctrico de los dispositivos. La cantidad total de vatios no deberá exceder el voltaje multiplicado por el número de amperios del circuito eléctrico. En Europa, habitualmente sería:</p>
<p>240V * 16A = 3840W</p>
<p>Puede considerarse la utilización de disipadores de sobrevoltaje para eliminar los picos producidos por rayos, etc, además de fuentes de alimentación continua (UPS) para los componentes críticos (servidores y segmentos centrales de la red). Estas UPS normalmente funcionan mediante baterías, manteniendo la alimentación entre 10 y 30 minutos.</p>
<p><strong>Aire Acondicionado</strong></p>
<p>Suele ser necesario disponer de aire acondicionado para el mantenimiento: temperatura estable y humedad constante.</p>
<p>La temperatura ideal es entre 17 y 20 ºC. Una temperatura inestable puede provocar daños físicos, como consecuencia de la expansión y contracción de los componentes internos. Y una temperatura alta puede producir un sobrecalentamiento de los componentes internos.</p>
<p>En cuanto a la humedad, la ideal sería entre un 40 y un 60%. Una baja humedad puede provocar un aumento de la electricidad estática. Y una alta humedad puede originar condensación.</p>
<p>Por último, debe tenerse en cuenta que el consumo de un vatio precisa de un enfriamiento de 3,1412 BTU/hr (la capacidad de A/C de una tonelada equivale a 12000 BTU/hr).</p>
<p><strong>Sistema de detección y supresión de incendios</strong></p>
<p>Debemos asegurarnos de detectar el fuego lo antes posible. Los detectores de humo detectan el monóxido de carbono, y deben ponerse bajo el suelo flotante y por encima de los falsos techos. Debemos considerar los métodos de extinción de incendios, ¿agua?, ¿CO2?, ¿gas inerte?.</p>
<p>Por último, podemos considerar la instalación de un conmutador maestro que corte toda la alimentación eléctrica de la sala de sistemas de manera inmediata.</p>
<p><strong>Procedimientos recomendados</strong></p>
<p>Se debe tener cuidado con la electricidad estática al reemplazar componentes:</p>
<ul>
<li>Conecte a tierra todos los componentes de manera adecuada.</li>
<li>Tocar la carcasa externa o un conector con conexión a tierra antes de manipular algún componente interno.</li>
<li>Guarde componentes no utilizados en bolsas de protección contra la electricidad estática.</li>
<li>No toque circuitos eléctricos si puede evitarlo.</li>
<li>Considere el uso de muñequeras y alfombras antiestáticas.</li>
</ul>
<p>Debemos utilizar únicamente materiales/herramientas/empresas especializadas en la limpieza de equipos informáticos,  comprobar regularmente el buen funcionamiento de los ventiladores y tener a mano una caja de herramientas completa.</p>
<p><strong>Conclusiones</strong></p>
<p>En las instalaciones grandes es beneficioso tener una sala de sistemas dedicada con suelos flotantes y equipos montados en  bastidor.</p>
<p>La cantidad máxima de potencia eléctrica consumida por todos los sistemas no deberá exceder los límites de los circuitos.</p>
<p>El aire acondicionado deberá ser suficientemente potente para enfriar todo el equipo cuando funcione al máximo, y además deberá ser capaz de conservar la humedad dentro de los límites aceptables.</p>
<p>Por último, también puede ser necesario un sistema de detección y extinción del fuego; solicite consejo a su departamento de bomberos local.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.oxxigeno.com/blog/2009/03/linux-planificacion-fisica-y-mantenimiento/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Animaciones en Flash sin actionscript</title>
		<link>http://www.oxxigeno.com/blog/2009/02/animaciones-en-flash-sin-actionscript/</link>
		<comments>http://www.oxxigeno.com/blog/2009/02/animaciones-en-flash-sin-actionscript/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 09:07:26 +0000</pubDate>
		<dc:creator>ecorrea</dc:creator>
				<category><![CDATA[Diseño]]></category>
		<category><![CDATA[Flash, Flex y ActionScript]]></category>

		<guid isPermaLink="false">http://www.oxxigeno.com/blog/?p=366</guid>
		<description><![CDATA[El reto diario al que se tiene que enfrentar un diseñador al usar Flash es compensar la utilización de animación tradicional y de programación actionscript según las necesidades del momento.
Muchas veces tendemos a buscar una solución programada a problemas que pueden ser resueltos fácil y rápidamente sin recurrir al actionscript. Preferimos buscar trozos de código [...]]]></description>
			<content:encoded><![CDATA[<p>El reto diario al que se tiene que enfrentar un diseñador al usar Flash es compensar la utilización de animación tradicional y de programación actionscript según las necesidades del momento.</p>
<p>Muchas veces tendemos a buscar una solución programada a <strong>problemas que pueden ser resueltos fácil y rápidamente sin recurrir al actionscript</strong>. Preferimos buscar trozos de código en la web que muchas veces solo entendemos por encima en lugar de desarrollar efectos hechos por animación desde cero. En definitiva nos volvemos un poco ciegos a la alternativa animada y preferimos el engorro del código.</p>
<p>Si bien actionscript te permite realizar efectos espectaculares en tiempo real, esto muchas veces no es necesario y la utilización de código no esta justificada. Ademas siempre es mas fácil que otra persona entienda una linea de tiempo animada que un montón de lineas de código, por lo tanto un proyecto puede ser retomado mas fácilmente por diferentes personas.</p>
<p>Vamos a ver como animar un objeto que desprende una estela, utilizando únicamente las interpolaciones de movimiento, clips de película anidados y algún filtro.</p>
<p><span id="more-366"></span>1º <strong>Dibujamos el objeto que queremos animar</strong>. En mi ejemplo una bolita que dibujare utilizando la herramienta <em>Óvalo</em>.</p>
<p>Seleccionando el objeto y pulsando F8 lo convertimos en un clip de película (no me preguntéis del porque no un gráfico ya que es simplemente una preferencia personal).</p>
<p><img class="alignnone size-full wp-image-368" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/imagen-1.png" alt="bolita" width="95" height="81" /></p>
<p>2º <strong>Seleccionamos el clip y nuevamente lo convertimos en otro clip</strong>. Por lo que tendremos un clip anidado en otro. Al que encierra la forma de la bolita lo he llamado <em>bola </em>y al segundo que lo contiene lo he llamado <em>anima bola</em>.</p>
<p><img class="alignnone size-full wp-image-369" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/imagen-2.png" alt="otro clip" width="233" height="26" /></p>
<p>3º Editamos <em>anima bola</em> y <strong>creamos la siguiente linea de tiempo</strong></p>
<p><strong><img class="alignnone size-full wp-image-370" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/imagen-3.png" alt="línea de tiempo" width="537" height="50" /><br />
</strong></p>
<p>El primer y el ultimo fotograma clave tiene <em>bola</em> en la misma posición inicial y en el del medio desplazo <em>bola</em>. Después interpolo y ya tengo una animación en la que <em>bola </em>se desplaza y vuelve a su posición una y otra vez.</p>
<p>Para adornar un poco le doy aceleración 100 al primer fotograma clave y -100 al segundo. Y una rotación CW x3 en el primer fotograma clave y de CCW x3 en el segundo.</p>
<p><img class="alignnone size-full wp-image-374" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/imagen-7.png" alt="aceleración" width="226" height="91" /></p>
<p>4º Volvemos a la escena, seleccionamos  &#8216;anima bola&#8217; y pulsamos F8 para <strong>volver a anidarlo</strong>. Yo he llamo a mi nuevo clip <em>estela bola</em>. Así que tenemos el siguiente esquema:</p>
<p><img class="alignnone size-full wp-image-371" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/imagen-4.png" alt="estela bola" width="314" height="31" /></p>
<p>5º Editamos <em>estela bola </em>y <strong>creamos la siguiente linea de tiempo</strong>:</p>
<p><img class="alignnone size-full wp-image-372" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/imagen-5.png" alt="línea de tiempo estela bola" width="213" height="122" /></p>
<p>Las capas llamadas <em>estela </em>son una copia del contenido de la capa llamada <em>bola</em>. Así tenemos el clip de película <em>anima bola</em> en 5 capas diferentes. En la última superior y el último fotograma he puesto un <em>stop()</em>. <strong>El único trozo de código de la animación</strong>.</p>
<p>En las capas llamadas <em>estela </em>selecciono el clip de película y le doy un Alfa del 30% y un filtro de desenfoque de 5px. en los ejes X e Y. Por lo que cada clip <em>anima bola</em> nos quedaría así:</p>
<p><img class="alignnone size-full wp-image-373" src="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/imagen-6.png" alt="anima bola" width="68" height="71" /></p>
<p>6º <strong>Publicamos </strong>y <a href="http://www.oxxigeno.com/blog/wp-content/uploads/2009/02/ejemplo2.swf" rel="shadowbox[post-366];width=640;height=385;">¡tachán!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.oxxigeno.com/blog/2009/02/animaciones-en-flash-sin-actionscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Buenas prácticas: aspx sin código de servidor</title>
		<link>http://www.oxxigeno.com/blog/2009/02/buenas-practicas-aspx-sin-codigo-de-servidor/</link>
		<comments>http://www.oxxigeno.com/blog/2009/02/buenas-practicas-aspx-sin-codigo-de-servidor/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 13:45:35 +0000</pubDate>
		<dc:creator>ivinuales</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ascx]]></category>
		<category><![CDATA[aspx]]></category>
		<category><![CDATA[microsoft]]></category>

		<guid isPermaLink="false">http://www.oxxigeno.com/blog/?p=293</guid>
		<description><![CDATA[La capa de presentación de un sitio web es una parte muy sensible del mismo, pues debe proporcionar al usuario toda la información que solicita, de forma que la carga de proceso en la misma sea mínima.
Los sitios web desarrollados bajo el .NET framework son publicados con una precompilación del código fuente, sin embargo, las [...]]]></description>
			<content:encoded><![CDATA[<p>La capa de presentación de un sitio web es una parte muy sensible del mismo, pues debe proporcionar al usuario toda la información que solicita, de forma que la carga de proceso en la misma sea mínima.</p>
<p>Los sitios web desarrollados bajo el .NET framework son publicados con una <strong>precompilación del código fuente</strong>, sin embargo, las páginas <strong>aspx</strong> y los controles <strong>ascx</strong> son interpretados en tiempo de ejecución. Es decir: cada vez que un usuario solicita una página aspx ésta es interpretada por el servidor de aplicaciones y presentada al cliente.</p>
<p>Como puede suponerse, el hecho de que la página aspx contenga código fuente que deba ser compilado ralentizará la carga de la misma, puesto que se pasa de interpretar html y devolverlo a compilar código de servidor con más o menos lógica.</p>
<p>En muchas ocasiones es posible pensar que no nos es posible <strong>crear la página aspx tal y como queremos sin incluir código de servidor</strong> en la misma, esto es un error muy común, pero facilmente subsanable, siguiendo las siguientes recomendaciones.</p>
<p><span id="more-293"></span></p>
<ul>
<li>Solo está permitido <strong>utilizar código de servidor para cargar elementos dentro de controles de tipo DataBound </strong>(GridView, FormView, etc.). Aun así es poco recomendable porque sigue requiriendo compilación. Se recomienda la utilización del <strong>control Repeater</strong>.</li>
</ul>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">&nbsp;
                <span style="color: #ddbb00;">&amp;lt;</span>%# Eval(&quot;TipoDePagina.Nombre&quot;) %<span style="color: #ddbb00;">&amp;gt;</span>
&nbsp;
                Editar Contenidos</pre></div></div>

</blockquote>
<ul>
<li>Si necesitamos que <strong>un elemento HTML obtenga propiedades</strong> (style, href, title, etc.) desde el lado del servidor, porque utilice alguna lógica de negocio debemos identificar a éste elemento con <strong>runat=server</strong> y asignar dichas propiedades desde el <strong>code-behind</strong>, que va precompilado cuando se publica.</li>
</ul>
<p>aspx no recomendado:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;global&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;fondo-menu-&amp;lt;%= ambitoCabecera %&amp;gt;&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;cabecera&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;cabecera-&amp;lt;%= ambitoCabecera%&amp;gt;&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;cabecera-logo&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">title</span>=<span style="color: #ff0000;">&quot;Alt&quot;</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;img</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;imgLogo&quot;</span> <span style="color: #000066;">src</span>=<span style="color: #ff0000;">&quot;../images/&amp;lt;%= image%&amp;gt;&quot;</span> <span style="color: #000066;">alt</span>=<span style="color: #ff0000;">&quot;Grupo Banco Popular&quot;</span> <span style="color: #000066;">width</span>=<span style="color: #ff0000;">&quot;148&quot;</span> <span style="color: #000066;">height</span>=<span style="color: #ff0000;">&quot;50&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;shortcuts&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ul</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Atención al cliente<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span> |<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Sucursales<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span> |<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Tarifas<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span> |<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Simuladores<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ul<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;buscador&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;fieldset<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/fieldset<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</blockquote>
<p>Código no recomendado:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Imagen por omision para el logo</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> _image <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;default.jpg&quot;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// Ambito por omision para la cabecera</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> _ambitoCabecera <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;normal&quot;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Page_Load<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #008080;">#region Dar valores a las variables</span>
    ...
    <span style="color: #008080;">#endregion</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<p>aspx recomendado:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;global&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;cabecera&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;cabecera-logo&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">title</span>=<span style="color: #ff0000;">&quot;Alt&quot;</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;img</span> <span style="color: #000066;">alt</span>=<span style="color: #ff0000;">&quot;Grupo Banco Popular&quot;</span> <span style="color: #000066;">width</span>=<span style="color: #ff0000;">&quot;148&quot;</span> <span style="color: #000066;">height</span>=<span style="color: #ff0000;">&quot;50&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;shortcuts&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ul</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;horizontal&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Atención al cliente<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span> |<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Sucursales<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span> |<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Tarifas<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span> |<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;li<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;#&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Simuladores<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/li<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ul<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;buscador&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;fieldset<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/fieldset<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</blockquote>
<p>Código recomendado:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Page_Load<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Imagen por omision para el logo</span>
    <span style="color: #FF0000;">string</span> image <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;default.jpg&quot;</span><span style="color: #008000;">;</span>
    <span style="color: #008080; font-style: italic;">// Ambito por omision para la cabecera</span>
    <span style="color: #FF0000;">string</span> ambitoCabecera <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;normal&quot;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080;">#region Dar valores a las variables</span>
    ...
    <span style="color: #008080;">#endregion</span>
&nbsp;
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">global</span>.<span style="color: #0000FF;">Attributes</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;class&quot;</span>, <span style="color: #666666;">&quot;fondo-menu-&quot;</span> <span style="color: #008000;">+</span> ambitoCabecera<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">cabecera</span>.<span style="color: #0000FF;">Attributes</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;class&quot;</span>, <span style="color: #666666;">&quot;cabecera-&quot;</span> <span style="color: #008000;">+</span> ambitoCabecera<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">imgLogo</span>.<span style="color: #0000FF;">Src</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;../images/&quot;</span> <span style="color: #008000;">+</span> image<span style="color: #008000;">;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
<ul>
<li>Si necesitamos que <strong>un elemento HTML reciba su identificador</strong>, propiedades sensibles o una maquetación compleja dependiente de una lógica de negocio, la solución optima es crear un <strong>custom web control</strong> para definirlo, éste tipo de controles heredan de la clase WebControl.</li>
</ul>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">namespace</span> Example.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">UI</span>.<span style="color: #0000FF;">Controls</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>DefaultProperty<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Text&quot;</span><span style="color: #000000;">&#41;</span>, ToolboxData<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;&amp;lt;{0}:OnlyText runat=server&amp;gt;&lt;!--{0}:OnlyText--&gt;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> OnlyText <span style="color: #008000;">:</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">UI</span>.<span style="color: #0000FF;">WebControls</span></span>.<span style="color: #0000FF;">WebControl</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080;">#region Attributes</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _text <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Properties</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>Bindable<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;true&quot;</span><span style="color: #000000;">&#41;</span>, Category<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Data&quot;</span><span style="color: #000000;">&#41;</span>, DefaultValue<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Text
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _text<span style="color: #008000;">;</span><span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> _text <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span><span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Overrides Methods</span>
&nbsp;
        <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span>  Render<span style="color: #000000;">&#40;</span>HtmlTextWriter writer<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
             writer.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>Text<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.oxxigeno.com/blog/2009/02/buenas-practicas-aspx-sin-codigo-de-servidor/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 1.502 seconds -->
