<?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>:. microcode.es :.</title>
	<atom:link href="http://www.microcode.es/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.microcode.es</link>
	<description>Un blog sobre programación en .NET y otras fumadas más...</description>
	<lastBuildDate>Tue, 02 Feb 2010 14:05:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Escribir un plugin para jQuery (3 parte)</title>
		<link>http://www.microcode.es/2010/02/02/escribir-un-plugin-para-jquery-3-parte/</link>
		<comments>http://www.microcode.es/2010/02/02/escribir-un-plugin-para-jquery-3-parte/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 13:56:34 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/02/02/escribir-un-plugin-para-jquery-3-parte/</guid>
		<description><![CDATA[En mis anteriores artículos (Escribir un plugin para jQuery parte 1 y parte 2) sobre desarrollar un plugin para jQuery hemos visto como crear un plugin básico y como configurarlo dinámicamente. En esta ocasión vamos a ver como podemos disparar nuestros propios eventos y por ejemplo, que otro plugin actue en consecuencia.
Para esto vamos a [...]]]></description>
			<content:encoded><![CDATA[<p>En mis anteriores artículos (Escribir un plugin para jQuery <a href="http://www.microcode.es/2010/01/27/escribir-un-plugin-para-jquery-1-parte/" target="_blank">parte 1</a> y <a href="http://www.microcode.es/2010/01/29/escribir-un-plugin-para-jquery-2-parte/" target="_blank">parte 2</a>) sobre desarrollar un <strong>plugin</strong> para <strong>jQuery</strong> hemos visto como crear un <strong>plugin</strong> básico y como configurarlo dinámicamente. En esta ocasión vamos a ver como podemos disparar nuestros propios eventos y por ejemplo, que otro <strong>plugin</strong> actue en consecuencia.</p>
<p>Para esto vamos a seguir con el <strong>plugin</strong> que hemos desarrollado y que sirve para cambiar el estilo de nuestras cajas de texto cuando ésta tiene el foco y lo pierde.</p>
<p>Para usar eventos necesitamos tres cosas, el evento en si mismo (click, blur, focus), algo que lo lance y alguien que lo maneje (delegado). En <strong>jQuery</strong> el encargado de lanzar un evento es el método <a href="http://api.jquery.com/trigger/" target="_blank"><strong>trigger</strong></a> y se hace de la siguiente manera</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:5f8d5435-be47-4f42-8e77-ae79cc8cccad" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">$(this).trigger('nombre_de_mi_evento', parametros_de_mi_evento);</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Para manejar un evento se usa el método <a href="http://api.jquery.com/bind/" target="_blank"><strong>bind</strong></a> de la siguiente manera</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e1f1b172-be39-4a3c-b117-a2dcd0a6eb0d" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">$(this).bind(nombre_de_mi_eveto, function(e, data) {
// Código de la función que manejera mi evento. En la variable data tenemos los parameotros que hemos enviado en el trigger.
});</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Aplicado esto a nuestro <strong>plugin</strong>, lo primero que haremos será crear un div donde iremos escribiendo todos lo eventos que vayamos manejando</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:15bdd968-f627-4266-8155-16e8709b5492" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">&lt;div id="status"&gt;&lt;/div&gt;</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>y en nuestro fichero common.js pondremos los delegados</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:7f6bfd7d-2ff8-4625-8dee-32b15918a029" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">$('input').bind('myfocus', function(e, data) {
   var html = $('#status').html();
   html += 'onfocus&lt;br /&gt;';
   $('#status').html(html);
});

$('input').bind('myblur', function(e, data) {
   var html = $('#status').html();
   html += 'onblur&lt;br /&gt;';
   $('#status').html(html);
});</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Luego sólo tendremos que modificar nuestro plugin para que lance los eventos</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:bf2df96a-4667-41f9-91c2-c5977db831f8" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "> $(this).focus(function() {
 	//...
    $(this).trigger('myfocus', "on focus");
	//...
 });
 $(this).blur(function() {
	//...
	$(this).trigger('myblur', "on blur");
	//...
 });</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Con esto ya tendríamos nuestros propios eventos <strong>myfocus</strong> y <strong>myblur</strong> gestionados.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/02/02/escribir-un-plugin-para-jquery-3-parte/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Escribir un plugin para jQuery (2 parte)</title>
		<link>http://www.microcode.es/2010/01/29/escribir-un-plugin-para-jquery-2-parte/</link>
		<comments>http://www.microcode.es/2010/01/29/escribir-un-plugin-para-jquery-2-parte/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 22:37:16 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/01/29/escribir-un-plugin-para-jquery-2-parte/</guid>
		<description><![CDATA[Lo más normal es que cuando escribamos un plugin para jQuery (o cualquier otro trozo de código reutilizable) lo dotemos de alguna forma para poder configurarlo dependiendo de las necesidades de cada momento.&#160; Siguiente con el ejemplo de mi artículo anterior “Escribir un plugin para jQuery (1 parte)” veremos como dotar al plugin de esta [...]]]></description>
			<content:encoded><![CDATA[<p>Lo más normal es que cuando escribamos un <strong>plugin</strong> para <strong>jQuery</strong> (o cualquier otro trozo de código reutilizable) lo dotemos de alguna forma para poder configurarlo dependiendo de las necesidades de cada momento.&#160; Siguiente con el ejemplo de mi artículo anterior “<a href="http://www.microcode.es/2010/01/27/escribir-un-plugin-para-jquery-1-parte/" target="_blank">Escribir un plugin para jQuery (1 parte)</a>” veremos como dotar al <strong>plugin</strong> de esta capacidad de configuración. En este caso configuraremos el color del fondo, asi como el borde de nuestros <strong>textbox</strong>, tanto cuando tiene foco (<strong>focus</strong>) como cuando no lo tiene (<strong>blur</strong>). El código para guardar estos valores es así</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:73f6d451-aa05-4b24-a826-2fab715b700a" class="wlWriterEditableSmartContent">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">$.fn.highlight.defaults = {
   focusbackground: '#EFF5FF',
   focusborder: 'solid 1px #73A6FF',
   blurbackground: '#EEEEEE',
   blurborder: 'solid 1px #DFDFDF'
};</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Para permitir que nuestro plugin admita parametros de configuración usaremos un parametros en la llamada del plugin donde pasaremos los valores que queramos</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:2cf0b8d8-ea2e-440c-966a-08e901e5e4ef" class="wlWriterEditableSmartContent">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">$.fn.highlight = function(options) {
   var opts = $.extend({}, $.fn.highlight.defaults, options);
   // Resto del c&#243;digo
}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Juntándolo todo tendríamos lo siguiente</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:f73463b4-f592-4f97-b579-b997aac7a053" class="wlWriterEditableSmartContent">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">(function($) {
    $.fn.highlight = function(options) {
        var opts = $.extend({}, $.fn.highlight.defaults, options);
        this.each(function() {
            var obj = $(this);
            // Valores por defecto
            obj.css('background', opts.blurbackground);
            obj.css('border', opts.blurborder);

            obj.focus(function() {
                obj.css('background', opts.focusbackground);
                obj.css('border', opts.focusborder);
            });

            obj.blur(function() {
                obj.css('background', opts.blurbackground);
                obj.css('border', opts.blurborder);
            });
        });
    };

    $.fn.highlight.defaults = {
        focusbackground: '#EFF5FF',
        focusborder: 'solid 1px #73A6FF',
        blurbackground: '#EEEEEE',
        blurborder: 'solid 1px #DFDFDF'
    };
})(jQuery); </pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Para hacer la llamada a nuestro plugin tan sólo hay que hacer lo siguiente</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:4082a165-a1d3-4159-a438-d1ac713c5acd" class="wlWriterEditableSmartContent">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">$().ready(function() {
    $('input').highlight({
        blurborder: 'red'
    });
});</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>Para la próxima entrega dejaremos otros detalles que podemos hacer para mejor el plugin y así aprender un poco mas de <strong>jQuery</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/01/29/escribir-un-plugin-para-jquery-2-parte/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Escribir un plugin para jQuery (1 parte)</title>
		<link>http://www.microcode.es/2010/01/27/escribir-un-plugin-para-jquery-1-parte/</link>
		<comments>http://www.microcode.es/2010/01/27/escribir-un-plugin-para-jquery-1-parte/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 20:25:09 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/01/27/escribir-un-plugin-para-jquery/</guid>
		<description><![CDATA[Durante el último año una de las cosas que más gratamente me ha sorprendido es jQuery y jQuery UI. Con muy poco código tenemos toda la potencia de javascript para poder hacer autenticas maravillas en cliente. Toda esta funcionalidad puede ser extendida mediante plugins. En la página de jQuery tener un gran cantidad de plugins [...]]]></description>
			<content:encoded><![CDATA[<p>Durante el último año una de las cosas que más gratamente me ha sorprendido es <a href="http://jquery.com" target="_blank">jQuery</a> y <a href="http://jqueryui.com/" target="_blank">jQuery UI</a>. Con muy poco código tenemos toda la potencia de javascript para poder hacer autenticas maravillas en cliente. Toda esta funcionalidad puede ser extendida mediante plugins. En la página de <strong>jQuery </strong>tener un gran cantidad de <a href="http://plugins.jquery.com/" target="_blank">plugins</a> preparados para ser usados en nuestra página con muy poco esfuerzo. Pero, ¿y si queremos hacernos un plugin personalizado? Pensé que hacer un plugin sería algo costoso y que requeriría de tener muchos conocimientos de <strong>javascript </strong>y <strong>jQuery</strong>, pero nada más lejos de la realidad. Para demostrarlo he hecho un pequeño <strong>plugin </strong>que cambia el estilo de todos las cajas de texto (inputs) cada vez que capture el foco y lo deje en un valor inicial cuando lo pierda. Para comenzar el plugin lo primero que tenemos que hacer es extender el propio objeto jquery para añadir nuestra funcionalidad (método). La forma de hacer esto es la siguiente</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:dd0af967-01a4-4805-9218-41c77ff8fce8" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">(function($) {
    $.fn.highlight = function(options) {
		// Nuestro método es 'highlight' y el código va a partir aquí.
    };
})(jQuery);</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Bien, con esto ya podríamos llamar a nuestro código de la siguiente manera</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:86f5718f-b30f-4e6d-9f2b-8c7096dcc65e" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">$().ready(function() {
    $('input').highlight();
});</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Este código llama a nuestro método para todos los ‘inputs’ (la potencia de jQuery es casi infinita) de nuestra página una vez que ésta esté disponible.</p>
<p>Volviendo a nuestro método, el código para cambiar los estilos de las cajas de texto quedaría de la siguiente manera</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:1433c485-28a5-413f-904a-29f014f18dd9" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">obj.focus(function() {
	obj.css('background', '#EFF5FF');
	obj.css('border', 'solid 1px #73A6FF');
});

obj.blur(function() {
	obj.css('background', '#EEE');
	obj.css('border', 'solid 1px #DFDFDF');
});</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Juntándolo todo tenemos</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:4706bde7-1bf1-4e17-b38c-c5ab9569254a" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">(function($) {
    $.fn.highlight = function(options) {
        this.each(function() {
            var obj = $(this);
            // Valores por defecto
            obj.css('background', '#EEE');
            obj.css('border', 'solid 1px #DFDFDF');

            obj.focus(function() {
                obj.css('background', '#EFF5FF');
                obj.css('border', 'solid 1px #73A6FF');
            });

            obj.blur(function() {
                obj.css('background', '#EEE');
                obj.css('border', 'solid 1px #DFDFDF');
            });
        });
    };
})(jQuery);</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Todo esto lo guardamos en un fichero con la extensión .js. Segun las buenas practicas nuestro plugin debería estar en un fichero con el nombre jquery.highlight.js.</p>
<p>El código que llama a nuestro plugin lo he puesto en un archivo llamado common.js, por lo que juntándolo todo en nuestra página aspx (o html) quedaría</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:d01cfbab-9deb-4b2f-a6b5-6274c2b28760" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">&lt;head runat="server"&gt;
    &lt;title&gt;&lt;/title&gt;
    &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script src="jquery.highlight.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script src="common.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div&gt;
        &lt;input id="text1" type="text" /&gt;
        &lt;input id="text2" type="text" /&gt;
    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Como vemos, crear nuestro primer plugin en jQuery ha sido muy sencillo. Próximamente veremos como podemos personalizar aun más nuestro script para que admita parámetros.</p>
<p><img id="myFxSearchImg" style="border: medium none; position: absolute; z-index: 2147483647; opacity: 0.6; display: none;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAADsElEQVR4nK2VTW9VVRSGn33OPgWpYLARbKWhQlCHTogoSkjEkQwclEQcNJEwlfgD/AM6NBo1xjhx5LyJ0cYEDHGkJqhtBGKUpm3SFii3vb2956wPB/t+9raEgSs52fuus89613rftdcNH8/c9q9++oe/Vzb5P+3McyNcfm2CcPj9af9w6gwjTwzvethx3Bx3x8xwd1wNM8dMcTNUHTfFLPnX6nVmZpeIYwf3cWD/PhbrvlPkblAzVFurKS6GmmGqqComaS+qmBoTI0Ncu3mXuGvWnrJ+ZSxweDgnkHf8ndVTdbiT3M7cQp2Z31dRTecHAfqydp4ejhwazh6Zezfnu98E1WIQwB3crEuJ2Y45PBTAQUVR9X4At66AppoEVO1Q8sgAOKJJjw6Am6OquDmvHskZ3R87gW+vlHz98zpmiqphkkRVbQtsfPTOC30lJKFbFTgp83bWh7Zx/uX1B6w3hI3NkkZTqEpBRDBRzG2AQHcwcYwEkOGkTERREbLQ/8HxJwuW7zdYrzfZ2iopy4qqEspKaDYravVm33k1R91Q69FA1VBRzFIVvXbx5AgXT44A8MWP81yfu0utIR2aVK3vfCnGrcUNxp8a7gKYKiLCvY2SUvo/aNtnM3e49ucK9S3p0aDdaT0UAVsKi2tVi6IWwNL9JvdqTdihaz79/l+u/rHMxmaJVMLkS2OoKKLWacdeE3IsSxctc2D5Qcl6vUlVVgNt+fkPPcFFmTw1xruvT7SCd7nuVhDQvECzJH90h0azRKoKFRkAmP5lKTWAGRdefoZL554FQNUxB92WvYeA5UN4PtSqwB2phKqsqMpBgAunRhFR3j49zuU3jnX8k6fHEQKXzh1jbmGDuYU6s4t1rt6socUeLLZHhYO2AHSHmzt19ihTZ48O8Hzl/AmunD/BjTvrvPfNX3hWsNpwJCvwYm+ngug4UilSCSq6k8YPtxDwfA+WRawIWFbgscDiULcCEaWqBFOlrLazurupOSHLqGnEKJAY8TwBEHumqUirAjNm52vEPPRV4p01XXMPAQhUBjcWm9QZwijwokgAeYHlHYA06KR1cT6ZvoV56pDUJQEjw0KeaMgj1hPEY4vz2A4eW0/e1qA7KtQdsxTYAG0H3iG4xyK1Y+xm7XmEPOJZDiENzLi2WZHngeOjj2Pe+sMg4GRYyLAsx7ME4FnsyTD9pr0PEc8zPGRAwKXBkYOPEd96cZRvf11g9MDe7e3R4Z4Q+vyEnn3P4t0XzK/W+ODN5/kPfRLewAJVEQ0AAAAASUVORK5CYII%3D" alt="" width="24" height="24" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/01/27/escribir-un-plugin-para-jquery-1-parte/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C# El m&#233;todo MapPath</title>
		<link>http://www.microcode.es/2010/01/23/c-el-mtodo-mappath/</link>
		<comments>http://www.microcode.es/2010/01/23/c-el-mtodo-mappath/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 16:58:37 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mappath]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/01/23/c-el-mtodo-mappath/</guid>
		<description><![CDATA[Un método bastante utilizado cuando desarrollamos aplicaciones web en ASP.NET es el método MapPath. Este método puede ser llamado de la siguiente manera

string path = HttpContext.Current.Server.MapPath("~");

La clase HostingEnvironment la tenemos en el espacio de nombre System.Web.Hosting, en el ensamblado System.Web.dll. Tenemos mas información de está clase en la MSDN al igual que del método MapPath.
]]></description>
			<content:encoded><![CDATA[<p>Un método bastante utilizado cuando desarrollamos aplicaciones web en ASP.NET es el <strong>método MapPath</strong>. Este método puede ser llamado de la siguiente manera</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:42803260-9cd0-48d7-bb4a-77cfbc2fef57" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">string path = HttpContext.Current.Server.MapPath("~");</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Llamado así este método nos devuelve la ruta física de la raiz de la aplicación web. Es útil para localizar directorios y así, por ejemplo, poder abrir ficheros de configuración propia. Pero ¿qué ocurre si llamamos a este método en un delegado?. La llamada fallará porque el object HttpContext no está creado. La solución es llamar al método de la siguiente forma</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:83d07d70-7a98-42f6-876b-60537278efd3" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">string path = HostingEnvironment.MapPath()</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>La clase <strong>HostingEnvironment</strong> la tenemos en el espacio de nombre <strong>System.Web.Hosting</strong>, en el ensamblado <strong>System.Web.dll</strong>. Tenemos mas información de está clase en la <a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.aspx" target="_blank">MSDN</a> al igual que del método <strong><a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx" target="_blank">MapPath</a>.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/01/23/c-el-mtodo-mappath/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Como obtener la fecha de compilaci&#243;n de un ensamblado</title>
		<link>http://www.microcode.es/2010/01/11/c-como-obtener-la-fecha-de-compilacin-de-un-ensamblado/</link>
		<comments>http://www.microcode.es/2010/01/11/c-como-obtener-la-fecha-de-compilacin-de-un-ensamblado/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 21:47:08 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[assembly]]></category>
		<category><![CDATA[assemblyfileversion]]></category>
		<category><![CDATA[assemblyversion]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/01/11/c-como-obtener-la-fecha-de-compilacin-de-un-ensamblado/</guid>
		<description><![CDATA[Para poder obtener la fecha de compilacion de un ensamblado, tendremos que hacer dos cosas
1.- Modificar las líneas AssemblyVersion y AssemblyFileVersion del fichero AssemblyInfo.cs

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build [...]]]></description>
			<content:encoded><![CDATA[<p>Para poder obtener la fecha de compilacion de un ensamblado, tendremos que hacer dos cosas</p>
<p>1.- Modificar las líneas <strong>AssemblyVersion</strong> y <strong>AssemblyFileVersion</strong> del fichero <strong>AssemblyInfo.cs</strong></p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e0b71070-949e-46a4-9808-18388f87fd46" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyFileVersion("0.1.1.0")]</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Del <strong>AssemblyVersion</strong> obtendremos la fecha de compilación mientras que la línea <strong>AssemblyFileVersion</strong> es de donde sacamos la versión del programa (aquí se puede usar cualquier numeración). Para esto usamos el siguiente código</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:92d96afa-4850-490b-9713-d656caa359f3" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">Assembly assembly = Assembly.GetExecutingAssembly();

FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);

DateTime assemblyDate = new DateTime(2000, 1, 1)
        .AddDays(assembly.GetName().Version.Build)
        .AddSeconds(assembly.GetName().Version.Revision * 2);

version = string.Format("{0}.{1}.{2} del {3}",
    versionInfo.ProductMajorPart,
    versionInfo.ProductMinorPart,
    versionInfo.ProductBuildPart,
    assemblyDate.ToString("dd/MM/yyyy"));</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/01/11/c-como-obtener-la-fecha-de-compilacin-de-un-ensamblado/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>c# Encriptar un string con MD5</title>
		<link>http://www.microcode.es/2010/01/07/c-encriptar-un-string-con-md5/</link>
		<comments>http://www.microcode.es/2010/01/07/c-encriptar-un-string-con-md5/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 14:05:14 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#;md5]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/01/07/c-encriptar-un-string-con-md5/</guid>
		<description><![CDATA[Tras la resaca navideña, volvemos al trabajo. En esta ocasión voy a escribir el código de método estático que nos permitiría codificar un string en MD5.&#160; Para saber que es MD5 te recomiendo este enlace.
El código es tan simple como

public static string MD5Encrypt(string value)
{
  MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();

  byte[] data = System.Text.Encoding.ASCII.GetBytes(value);
 [...]]]></description>
			<content:encoded><![CDATA[<p>Tras la resaca navideña, volvemos al trabajo. En esta ocasión voy a escribir el código de método estático que nos permitiría codificar un string en <strong>MD5</strong>.&#160; Para saber que es <strong>MD5</strong> te recomiendo este <a href="http://es.wikipedia.org/wiki/MD5" target="_blank">enlace</a>.</p>
<p>El código es tan simple como</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:abb93418-14ff-4fdf-bd26-e6318e72268b" class="wlWriterEditableSmartContent">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">public static string MD5Encrypt(string value)
{
  MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();

  byte[] data = System.Text.Encoding.ASCII.GetBytes(value);
  data = provider.ComputeHash(data);

  string md5 = string.Empty;

  for (int i = 0; i &lt; data.Length; i++)
      md5 += data[i].ToString(&quot;x2&quot;).ToLower();

  return md5;
}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p></p>
<p>También debemos añadir esto en los using de nuestra clase</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:4056170d-6743-46ee-a616-aea98c3829d4" class="wlWriterEditableSmartContent">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">using System.Security.Cryptography;</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/01/07/c-encriptar-un-string-con-md5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Error usando System.Linq</title>
		<link>http://www.microcode.es/2010/01/05/error-usando-system-linq/</link>
		<comments>http://www.microcode.es/2010/01/05/error-usando-system-linq/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 17:28:56 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/01/05/error-usando-system-linq/</guid>
		<description><![CDATA[El otro día el Visual Studio me dio el siguiente error de compilación

Error 8 Could not find an implementation of the query pattern for source type
'System.Data.Linq.Table&#60;Model.Provincia&#62;'. 'Select' not found.
Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?


]]></description>
			<content:encoded><![CDATA[<p>El otro día el Visual Studio me dio el siguiente error de compilación</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e501b3d1-80f4-4a8c-83d7-55fca2d40cf7" class="wlWriterEditableSmartContent">
<pre class="brush: plain; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">Error 8 Could not find an implementation of the query pattern for source type
'System.Data.Linq.Table&lt;Model.Provincia&gt;'. 'Select' not found.
Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p></p>
<p>La verdad es que el error es bastante raro y no deja muy claro a que se refiere. Una búsqueda por google y tras un ratillo leyendo respuestas encontré la solución. Tan sólo hay que añadir la referencia a System.Linq.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:3de322ff-9a95-4bdc-9aa2-e1d92d04f311" class="wlWriterEditableSmartContent">
<pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; ">using System.Linq;</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/01/05/error-usando-system-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A&#241;o nuevo&#8230;</title>
		<link>http://www.microcode.es/2010/01/04/ano-nuevo/</link>
		<comments>http://www.microcode.es/2010/01/04/ano-nuevo/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 21:41:42 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/01/04/ao-nuevo/</guid>
		<description><![CDATA[La verdad es que el blog lleva muchísimo tiempo sin actualizarse. Como propósito para este nuevo año está el escribir más a menudo en el blog (como inicialmente era la idea). Para conseguir esto el primer paso era mudar el blog a un nuevo hosting, actualizar el motor del blog (wordpress), recuperar toda la información [...]]]></description>
			<content:encoded><![CDATA[<p>La verdad es que el blog lleva muchísimo tiempo sin actualizarse. Como propósito para este nuevo año está el escribir más a menudo en el blog (como inicialmente era la idea). Para conseguir esto el primer paso era mudar el blog a un nuevo hosting, actualizar el motor del blog (<a href="http://www.wordpress.org">wordpress</a>), recuperar toda la información del blog anterior y dejarlo todo como estaba. Bien, todo este proceso ha acabado satisfactoriamente hoy, así que a partir de mañana espero poder escribir algún artículo que tengo en mente desde hace algunas semanas. En esta nueva época intentaré centrarme más en el código fuente que en hacer publicaciones del tipo “hoy se presenta tal producto, con tales novedades”. Otro objetivo es “reescribir” los artículos anteriores para dejar el blog con un aspecto más uniforme.</p>
<p>Esperemos que todo se cumpla, así que, feliz 2010 a todos. Nos vemos en los próximos posts.</p>
<p><img id="myFxSearchImg" style="border: medium none; position: absolute; z-index: 2147483647; opacity: 0.6; display: none;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAADsElEQVR4nK2VTW9VVRSGn33OPgWpYLARbKWhQlCHTogoSkjEkQwclEQcNJEwlfgD/AM6NBo1xjhx5LyJ0cYEDHGkJqhtBGKUpm3SFii3vb2956wPB/t+9raEgSs52fuus89613rftdcNH8/c9q9++oe/Vzb5P+3McyNcfm2CcPj9af9w6gwjTwzvethx3Bx3x8xwd1wNM8dMcTNUHTfFLPnX6nVmZpeIYwf3cWD/PhbrvlPkblAzVFurKS6GmmGqqComaS+qmBoTI0Ncu3mXuGvWnrJ+ZSxweDgnkHf8ndVTdbiT3M7cQp2Z31dRTecHAfqydp4ejhwazh6Zezfnu98E1WIQwB3crEuJ2Y45PBTAQUVR9X4At66AppoEVO1Q8sgAOKJJjw6Am6OquDmvHskZ3R87gW+vlHz98zpmiqphkkRVbQtsfPTOC30lJKFbFTgp83bWh7Zx/uX1B6w3hI3NkkZTqEpBRDBRzG2AQHcwcYwEkOGkTERREbLQ/8HxJwuW7zdYrzfZ2iopy4qqEspKaDYravVm33k1R91Q69FA1VBRzFIVvXbx5AgXT44A8MWP81yfu0utIR2aVK3vfCnGrcUNxp8a7gKYKiLCvY2SUvo/aNtnM3e49ucK9S3p0aDdaT0UAVsKi2tVi6IWwNL9JvdqTdihaz79/l+u/rHMxmaJVMLkS2OoKKLWacdeE3IsSxctc2D5Qcl6vUlVVgNt+fkPPcFFmTw1xruvT7SCd7nuVhDQvECzJH90h0azRKoKFRkAmP5lKTWAGRdefoZL554FQNUxB92WvYeA5UN4PtSqwB2phKqsqMpBgAunRhFR3j49zuU3jnX8k6fHEQKXzh1jbmGDuYU6s4t1rt6socUeLLZHhYO2AHSHmzt19ihTZ48O8Hzl/AmunD/BjTvrvPfNX3hWsNpwJCvwYm+ngug4UilSCSq6k8YPtxDwfA+WRawIWFbgscDiULcCEaWqBFOlrLazurupOSHLqGnEKJAY8TwBEHumqUirAjNm52vEPPRV4p01XXMPAQhUBjcWm9QZwijwokgAeYHlHYA06KR1cT6ZvoV56pDUJQEjw0KeaMgj1hPEY4vz2A4eW0/e1qA7KtQdsxTYAG0H3iG4xyK1Y+xm7XmEPOJZDiENzLi2WZHngeOjj2Pe+sMg4GRYyLAsx7ME4FnsyTD9pr0PEc8zPGRAwKXBkYOPEd96cZRvf11g9MDe7e3R4Z4Q+vyEnn3P4t0XzK/W+ODN5/kPfRLewAJVEQ0AAAAASUVORK5CYII%3D" alt="" width="24" height="24" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/01/04/ano-nuevo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Virtualizando un poco</title>
		<link>http://www.microcode.es/2009/02/28/virtualizando-un-poco/</link>
		<comments>http://www.microcode.es/2009/02/28/virtualizando-un-poco/#comments</comments>
		<pubDate>Sat, 28 Feb 2009 18:44:40 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[virtual pc]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2009/02/28/virtualizando-un-poco/</guid>
		<description><![CDATA[En en esta semana he mejorado un poco mi equipo. Debido al precio al que está la memoria RAM he decido comprar 8GB para mi equipo y de paso actualizar mi Windows Vista de la versión 32 a la 64 bits. De paso he cambiado también la tarjeta gráfica. Con esto mi Windows Vista ha [...]]]></description>
			<content:encoded><![CDATA[<p>En en esta semana he mejorado un poco mi equipo. Debido al precio al que está la memoria RAM he decido comprar 8GB para mi equipo y de paso actualizar mi Windows Vista de la versión 32 a la 64 bits. De paso he cambiado también la tarjeta gráfica. Con esto mi Windows Vista ha quedado en perfectas condiciones para poder trabajar.</p>
<p><a href="http://www.microcode.es/wp-content/uploads/2009/02/virtualizando01.png"><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="virtualizando01" src="http://www.microcode.es/wp-content/uploads/2009/02/virtualizando01-thumb.png" border="0" alt="virtualizando01" width="598" height="160" /></a></p>
<p>Para aprovechar un poco tanta RAM he decido probar el Virtual PC 2007 de Microsoft. Así podría montarme un entorno de desarrollo en Windows XP o Vista y tenerlo siempre listo independientemente del equipo “huésped”, o incluso llevármelo de viaje. Para bajarte el Virtual PC sólo hay que ir a la pagina de Microsoft y bajarnos la versión que queramos (32 o 64 bits). De paso, también nos bajaremos el SP1 que amplia en número de sistemas operativos soportados.</p>
<ul>
<li><a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;FamilyID=04d26402-3199-48a3-afa2-2dc0b40a73b6" target="_blank">Virtual PC 2007</a></li>
<li><a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;FamilyID=28c97d22-6eb8-4a09-a7f7-f6c7a1f000b5" target="_blank">Virtual PC 2007 SP1</a></li>
</ul>
<p>Una vez instalado, tan sólo tenemos que crearnos una máquina con las características que queramos e instalar nuestro sistema operativo. Analizado el Virtual PC esta son las conclusiones que he sacado</p>
<p><strong>Ventajas</strong></p>
<ul>
<li>Es gratuito.</li>
<li>Al ser un producto de Microsoft no debería plantear demasiados problemas con sus propios sistemas operativos.</li>
<li>Podemos ampliar la memoria y añadir hasta tres discos duros (que podemos compartir con otra máquinas virtuales.</li>
</ul>
<p><strong>Desventajas</strong></p>
<ul>
<li>Una vez creado el directorio virtual no se puede ampliar su tamaño.</li>
<li>No soporta máquinas de 64 bits.</li>
</ul>
<p><strong>Dudas</strong></p>
<ul>
<li>Estoy investigando si se puede tomar una “fotografía” (snapshot) del sistema, y revertirlo posteriormente a ese punto. Esto es ideal, en entornos donde se prueban instalables.</li>
</ul>
<p>Y para muestra mi máquina virtual de desarrollo sobre mi Windows Vista.</p>
<p><a href="http://www.microcode.es/wp-content/uploads/2009/02/virtualizando02.png"><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="virtualizando02" src="http://www.microcode.es/wp-content/uploads/2009/02/virtualizando02-thumb.png" border="0" alt="virtualizando02" width="644" height="320" /></a></p>
<p>Y como punto final dos consejos</p>
<ul>
<li>Para sacar el puntero del ratón de nuestra máquina virtual hay que usar la tecla “ALT GR”</li>
<li>Para maximizar nuestra máquina virtual hay que usar ALT GR + ENTER (con esto no nos daremos ni cuenta de que estamos en una máquina virtual).</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2009/02/28/virtualizando-un-poco/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C# Comprimir y descomprimir un String (GZipStream)</title>
		<link>http://www.microcode.es/2009/01/29/c-comprimir-y-descomprimir-un-string-gzipstream/</link>
		<comments>http://www.microcode.es/2009/01/29/c-comprimir-y-descomprimir-un-string-gzipstream/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 21:05:50 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[comprimir]]></category>
		<category><![CDATA[descomprimir]]></category>
		<category><![CDATA[gzipstream]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2009/01/29/c-comprimir-y-descomprimir-un-string-gzipstream/</guid>
		<description><![CDATA[La verdad es que hace tiempo que no escribo nada en el blog, pero es que he estado bastante liado. Una de las últimas cosas que he tenido que hacer es comprimir un xml antes de guardarlo a disco ya que este ocupaba más de 5 megas y no era cuestión de tener ese espacio [...]]]></description>
			<content:encoded><![CDATA[<p>La verdad es que hace tiempo que no escribo nada en el blog, pero es que he estado bastante liado. Una de las últimas cosas que he tenido que hacer es comprimir un xml antes de guardarlo a disco ya que este ocupaba más de 5 megas y no era cuestión de tener ese espacio ocupado “inútilmente”. Aunque visto al precio que esta el MB o el GB podría evitarme estas molestias. La primera idea sería usar un compresor externo vía línea de comandos para comprimir esa cadena de texto. Como es lógico esta opción es muy poco viable. Otra solución sería implementar nosotros mismos un algoritmo de compresión y descompresión. Esta opción sería bastante interesante si quisiéramos pasar algo de tiempo aprendiendo sobre algoritmos de compresión, pero como no es el caso, también queda descartada. Ya sólo nos queda la opción de buscar algo dentro del framework de .NET y como suele ocurrir casi siempre, el framework nos trae una clase para esta tarea. En concreto es la clase <strong>GZipStream</strong> de la cual podemos leer mas información <a href="http://msdn.microsoft.com/es-es/library/system.io.compression.gzipstream.gzipstream(VS.80).aspx" target="_blank">aquí</a>.</p>
<p>El código para comprimir es el siguiente</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   1:</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">string</span> Zip(<span style="color: #0000ff;">string</span> text)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   2:</span> {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   3:</span>     <span style="color: #0000ff;">byte</span>[] buffer = Encoding.UTF8.GetBytes(text);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   4:</span>     MemoryStream ms = <span style="color: #0000ff;">new</span> MemoryStream();</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   5:</span>     <span style="color: #0000ff;">using</span> (GZipStream zip = <span style="color: #0000ff;">new</span> GZipStream(ms, CompressionMode.Compress, <span style="color: #0000ff;">true</span>))</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   6:</span>     {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   7:</span>         zip.Write(buffer, 0, buffer.Length);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   8:</span>     }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   9:</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  10:</span>     ms.Position = 0;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  11:</span>     MemoryStream outStream = <span style="color: #0000ff;">new</span> MemoryStream();</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  12:</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  13:</span>     <span style="color: #0000ff;">byte</span>[] compressed = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[ms.Length];</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  14:</span>     ms.Read(compressed, 0, compressed.Length);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  15:</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  16:</span>     <span style="color: #0000ff;">byte</span>[] gzBuffer = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[compressed.Length + 4];</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  17:</span>     System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  18:</span>     System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  19:</span>     <span style="color: #0000ff;">return</span> Convert.ToBase64String(gzBuffer);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  20:</span> }</pre>
</div>
</div>
<p>y el código para descomprimir es muy parecido</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   1:</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">string</span> UnZip(<span style="color: #0000ff;">string</span> compressedText)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   2:</span> {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   3:</span>     <span style="color: #0000ff;">byte</span>[] gzBuffer = Convert.FromBase64String(compressedText);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   4:</span>     <span style="color: #0000ff;">using</span> (MemoryStream ms = <span style="color: #0000ff;">new</span> MemoryStream())</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   5:</span>     {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   6:</span>         <span style="color: #0000ff;">int</span> msgLength = BitConverter.ToInt32(gzBuffer, 0);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   7:</span>         ms.Write(gzBuffer, 4, gzBuffer.Length - 4);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">   8:</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">   9:</span>         <span style="color: #0000ff;">byte</span>[] buffer = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[msgLength];</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  10:</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  11:</span>         ms.Position = 0;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  12:</span>         <span style="color: #0000ff;">using</span> (GZipStream zip = <span style="color: #0000ff;">new</span> GZipStream(ms, CompressionMode.Decompress))</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  13:</span>         {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  14:</span>             zip.Read(buffer, 0, buffer.Length);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  15:</span>         }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  16:</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  17:</span>         <span style="color: #0000ff;">return</span> Encoding.UTF8.GetString(buffer);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"><span style="color: #606060;">  18:</span>     }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #606060;">  19:</span> }</pre>
</div>
</div>
<p>Como vemos el código es bastante simple y nos sirve para evitar que nuestros ficheros auxiliares crezcan de manera incontrolada.</p>
<p>Saludos y nos vemos en la próxima entrega.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2009/01/29/c-comprimir-y-descomprimir-un-string-gzipstream/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
