<?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 :. &#187; c#</title>
	<atom:link href="http://www.microcode.es/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.microcode.es</link>
	<description>Un blog sobre programación en .NET y otras locuras más...</description>
	<lastBuildDate>Mon, 30 Aug 2010 21:29:38 +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>C# Como hacer una captura de pantalla</title>
		<link>http://www.microcode.es/2010/08/30/c-como-hacer-una-captura-de-pantalla/</link>
		<comments>http://www.microcode.es/2010/08/30/c-como-hacer-una-captura-de-pantalla/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 21:27:22 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/08/30/c-como-hacer-una-captura-de-pantalla/</guid>
		<description><![CDATA[En muchas aplicaciones de escritorio puede sernos útil recopilar información cuando se produzca una excepción no controlada. Podemos recopilar la información de la excepción analizando las propiedades Message o StackTrace. Otra información útil puede ser capturar la pantalla y ver que estaba haciendo el usuario en nuestra aplicación en el momento que falló.

Ojo, antes de [...]]]></description>
			<content:encoded><![CDATA[<p>En muchas aplicaciones de escritorio puede sernos útil recopilar información cuando se produzca una <a href="http://msdn.microsoft.com/es-es/library/c18k6c59.aspx" target="_blank">excepción</a> no controlada. Podemos recopilar la información de la <a href="http://msdn.microsoft.com/es-es/library/c18k6c59.aspx" target="_blank">excepción</a> analizando las propiedades <a href="http://msdn.microsoft.com/es-es/library/system.exception.message.aspx" target="_blank">Message</a> o <a href="http://msdn.microsoft.com/es-es/library/system.exception.stacktrace.aspx" target="_blank">StackTrace</a>. Otra información útil puede ser capturar la pantalla y ver que estaba haciendo el usuario en nuestra aplicación en el momento que falló.<br />
<span id="more-367"></span><br />
Ojo, antes de continuar me gustaría comentar que en todos los casos, la información que se envía deberá ser aprobada por el usuario, antes del envío, o través de las herramientas de configuración de la propia aplicación. No hagamos las cosas a escondidas ya que tarde o temprano estás cosas se terminan detectando y las consecuencias pueden ser desastrosas.</p>
<p>Bien para esto he creado una clase que he llamado <strong>ScreenHelper</strong> con un método estático <strong>Capture</strong>, que nos ayudará a conseguir dicha funcionalidad devolviéndonos un objeto <a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx" target="_blank">Image</a>.</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:8047e3f2-0356-486b-a52e-bfbe08c82ff7" 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; ">public class ScreenHelper
{
   public static Image Capture()
   {
       Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
       Graphics graphics = Graphics.FromImage(printscreen as Image);
       graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
       return (Image)printscreen;
   }
}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Este objeto <a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx" target="_blank">Image</a> lo podemos manipular, para por ejemplo redimensionarlo, o guardarlo en disco, para posteriormente enviarlo por correo electrónico. Para capturar y grabar la imagen usaremos otro método estático que llamaremos CaptureAndSave()</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:87ce1f73-5cb3-4cfb-ac77-205eb174ef6d" 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; ">private static void CaptureAndSave()
{
  Image image = Capture();
  if (!Directory.Exists("directorio"))
      Directory.CreateDirectory("directorio");

  string path = Path.Combine("directorio", "nombrefichero");
  image.Save(path, ImageFormat.Png);
}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Como nota final destacar que antes de grabar la imagen, comprobaremos que el directorio donde vamos a grabar existe. También sería “casi obligatorio” utilizar el bloque try…catch para capturar cualquier excepción que se produzca en el proceso.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/08/30/c-como-hacer-una-captura-de-pantalla/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WPF &#8211; Como asignar la propiedad ZIndex</title>
		<link>http://www.microcode.es/2010/08/03/wpf-como-asignar-la-propiedad-zindex/</link>
		<comments>http://www.microcode.es/2010/08/03/wpf-como-asignar-la-propiedad-zindex/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 16:35:02 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[wpf]]></category>
		<category><![CDATA[zindex]]></category>

		<guid isPermaLink="false">http://www.microcode.es/2010/08/03/wpf-como-asignar-la-propiedad-zindex/</guid>
		<description><![CDATA[Según la MSND la propiedad ZIndex del objeto Panel sirve para el establecer el orden en el que se muestran los elementos en el plano Z.

Una vez dicho esto es fácil ver para que nos puede servir esta propiedad. El problema surge cuando intentamos establecer este valor en tiempo de ejecución en el codebehind, ya [...]]]></description>
			<content:encoded><![CDATA[<p>Según la MSND la propiedad <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.panel.zindex.aspx" target="_blank">ZIndex</a> del objeto Panel sirve para el establecer el orden en el que se muestran los elementos en el plano Z.<br />
<span id="more-363"></span><br />
Una vez dicho esto es fácil ver para que nos puede servir esta propiedad. El problema surge cuando intentamos establecer este valor en tiempo de ejecución en el <strong>codebehind</strong>, ya que esta propiedad no sale en el <strong>Intellisense</strong>.</p>
<p><a href="http://www.microcode.es/wp-content/uploads/2010/08/zindex01.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="zindex01" src="http://www.microcode.es/wp-content/uploads/2010/08/zindex01_thumb.png" border="0" alt="zindex01" width="244" height="83" /></a></p>
<p>Mirando la MSDN podemos pensar que si hacemos un typecast de nuestro <strong>StackPanel</strong> a <strong>Panel</strong> esta propiedad nos aparecerá, pero tampoco es así.</p>
<p>La única forma que he encontrado de poder asignar el valor al <strong>ZIndex</strong> es mediante el método <strong>SetValue</strong> de la siguiente forma</p>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:f85fc5b3-ff69-473c-9137-83d6d8d232ee" 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; ">StackPanel stackPanel = new StackPanel();
stackPanel.SetValue(Panel.ZIndexProperty, 1);</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/08/03/wpf-como-asignar-la-propiedad-zindex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>¿Que es Windows Presentation Foundation (WPF)?</title>
		<link>http://www.microcode.es/2010/08/02/que-es-windows-presentation-foundation-wpf/</link>
		<comments>http://www.microcode.es/2010/08/02/que-es-windows-presentation-foundation-wpf/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 14:46:34 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.microcode.es/?p=352</guid>
		<description><![CDATA[¿Qué es WPF?
De una manera rápida, WPF (Windows Presentation Foundation) es una tecnología que nos permite aprovechar al máximo las características gráficas de nuestros equipos ofreciendo interfaces más ricas de las que estamos acostumbrados. El objetivo de WPF es proporcionar avances en el entorno de las aplicaciones de escritorio que permitan crear interfaces mucho más [...]]]></description>
			<content:encoded><![CDATA[<p><strong>¿Qué es WPF?</strong><br />
De una manera rápida, WPF (Windows Presentation Foundation) es una tecnología que nos permite aprovechar al máximo las características gráficas de nuestros equipos ofreciendo interfaces más ricas de las que estamos acostumbrados. El objetivo de WPF es proporcionar avances en el entorno de las aplicaciones de escritorio que permitan crear interfaces mucho más atractivas evitando una disminución del rendimiento de nuestras aplicaciones, como ocurre actualmente con Windows.Forms.<br />
<span id="more-352"></span><br />
<strong> Arquitectura de WPF</strong><br />
<strong><img class="alignleft size-full wp-image-353" style="margin-right:5px" title="arquitectura-wpf" src="http://www.microcode.es/wp-content/uploads/2010/08/arquitectura-wpf.png" alt="arquitectura-wpf" width="250" height="309" /> </strong> <em>- PresentationCore.dll</em>: Es donde encontramos el soporte para todos los tipos base como “UIElement” y “Visual”, y es de donde todas las formas (shapes) y controles (controls) derivan.<br />
<em>- WindowsBase.dll</em>: Es donde encontramos clases de apoyo que puede ser usadas fuera del ámbito de WPF, como por ejemplo el “DispatcherObject” o el “DependencyObject”.<br />
<em>- milcore.dll</em>: Es el núcleo del sistema de renderizado de WPF. Su misión es transformar los elementos visuales en los triángulos y texturas que Direct3D espera. Aunque sea considerado como parte de WPF esta dll forma parte de Windows Vista. De hecho, el Desktop Window Manager (DWM) en Windows Vista usa esta dll para renderizar el escritorio.<br />
<em>- WindowsCodecs.dll</em>: Es una API de bajo nivel que nos da soporte para el tratamiento de imágenes.<br />
<em>- Direct3D</em>: Es la API de bajo nivel que se encarga del renderizado de los gráficos generados mediante WPF.<br />
<em>- User32</em>: Pese a que forma parte de WPF no interviene en el renderizado de los controles.</p>
<p><strong>Ventajas</strong><br />
- Existe una separación clara entre nuestro código y la presentación (XAML).<br />
- Es bastante fácil crear estilos lo que nos permite hacer aplicaciones muchos más ricas de cara al usuario final.<br />
- Usa directamente la potencia de las tarjetas gráficas modernas para el renderizado de nuestras aplicaciones, liberando al procesador. Con esto evitamos que el dibujado interfaces complejas disminuya el rendimiento de nuestras aplicaciones.</p>
<p>Aquí termino esta pequeña introducción teórica de WPF. Próximamente explicaré algunas cosas como estilos, animaciones&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2010/08/02/que-es-windows-presentation-foundation-wpf/feed/</wfw:commentRss>
		<slash:comments>0</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><span id="more-315"></span><br />
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<br />
<span id="more-312"></span><br />
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>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 id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e501b3d1-80f4-4a8c-83d7-55fca2d40cf7" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<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><span id="more-310"></span><br />
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 id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:3de322ff-9a95-4bdc-9aa2-e1d92d04f311" 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; ">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>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>.<br />
<span id="more-297"></span><br />
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>
		<item>
		<title>C# Reproducir un fichero wav (SoundPlayer)</title>
		<link>http://www.microcode.es/2008/11/23/c-reproducir-un-fichero-wav-soundplayer/</link>
		<comments>http://www.microcode.es/2008/11/23/c-reproducir-un-fichero-wav-soundplayer/#comments</comments>
		<pubDate>Sun, 23 Nov 2008 14:54:58 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[soundplayer]]></category>

		<guid isPermaLink="false">http://www.microcode.es/?p=292</guid>
		<description><![CDATA[Uno de los motivos por lo que he estado tanto tiempo sin actualizar el blog es porque he estado metido en una puesta de producción dondo todo lo que ha podido ir mal, ha ido mal (siempre se cumplen la leyes de Murphy). Una de las cosas que se cambiaron a última hora, fueron unas [...]]]></description>
			<content:encoded><![CDATA[<p>Uno de los motivos por lo que he estado tanto tiempo sin actualizar el blog es porque he estado metido en una puesta de producción dondo todo lo que ha podido ir mal, ha ido mal (siempre se cumplen la leyes de Murphy). Una de las cosas que se cambiaron a última hora, fueron unas notificaciones sonoras en muchas partes del programa. Yo tenía un código relativamente antiguo para reproducir un sonido.</p>
<p>[sourcecode language="csharp"]public int SND_ASYNC = 0&#215;0001; // play asynchronously<br />
public int SND_FILENAME = 0&#215;00020000; // use file name<br />
public int SND_PURGE = 0&#215;0040; // purge non-static events</p>
<p>[System.Runtime.InteropServices.DllImport("WinMM.dll")]<br />
public static extern bool PlaySound(string fname, int Mod, int flag);</p>
<p>private void button1_Click(object sender, EventArgs e)<br />
{<br />
PlaySound(&#8221;tada.wav&#8221;, 0, SND_FILENAME | SND_ASYNC);<br />
}[/sourcecode]</p>
<p>Este código funciona perfectamente, pero nunca me ha gustado usar este tipo de codigo usando liberirías externas. Mirando en la MSDN encontré otra solución que me parece muchísimo mejor. Resulta que desde .NET 2.0 tenemos la clase <strong>SoundPlayer</strong> en el espacio de nombre <strong>System.Media</strong> que nos ayuda perfectamente a reproducir un sonido. El código para ésto es así de fácil</p>
<p>[sourcecode language="csharp"]private void button2_Click(object sender, EventArgs e)<br />
{<br />
System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer();<br />
soundPlayer.SoundLocation = &#8220;tada.wav&#8221;;<br />
soundPlayer.Play();<br />
}[/sourcecode]</p>
<p>Tenemos más información sobre esta clase en <a href="http://msdn.microsoft.com/en-us/library/system.media.soundplayer(VS.80).aspx" target="_blank">http://msdn.microsoft.com/en-us/library/system.media.soundplayer(VS.80).aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2008/11/23/c-reproducir-un-fichero-wav-soundplayer/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Presentadas las novedades de C# 4.0 en el PDC 2008</title>
		<link>http://www.microcode.es/2008/10/29/presentadas-las-novedades-de-c-40-en-el-pdc-2008/</link>
		<comments>http://www.microcode.es/2008/10/29/presentadas-las-novedades-de-c-40-en-el-pdc-2008/#comments</comments>
		<pubDate>Wed, 29 Oct 2008 10:24:58 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[novedades]]></category>
		<category><![CDATA[pdc]]></category>

		<guid isPermaLink="false">http://www.microcode.es/?p=282</guid>
		<description><![CDATA[En el PDC 2008 (Professional Developers Conference) de este año se están presenta muchísimas cosas. En este post hablaré de las novedades de C# 4.0.  En una presentación de Anders Hejlsberg (Technical fellow en Microsoft, uno de los padres de la criatura y arquitecto principal) y tras una pequeña introducción sobre la evolución de C [...]]]></description>
			<content:encoded><![CDATA[<p>En el <a href="http://www.microsoftpdc.com/" target="_blank">PDC 2008</a> (Professional Developers Conference) de este año se están presenta muchísimas cosas. En este post hablaré de las novedades de <strong>C# 4.0</strong>.  En una presentación de <strong>Anders Hejlsberg</strong> (Technical fellow en Microsoft, uno de los padres de la criatura y arquitecto principal) y tras una pequeña introducción sobre la evolución de C #, y antes de dejar encandilada a la audiencia, Anders ha realizado un pequeño repaso de las tendencias actuales en cuanto a lenguajes de programación:</p>
<ul>
<li>Programación más declarativa.</li>
<li>Programación dinámica.</li>
<li>Programación concurrente (multicore), ya que como todos sabéis, la tendencia actual (una vez que la ley de Moore podemos decir que se ha parado) es añadir más y más procesadores&#8230;¿Cómo construimos aplicaciones para este nuevo escenario en el que la concurrencia es necesaria? En plataforma .NET la respuesta la tenemos en las Parallel Extensions para .NET, que formarán parte de la nueva versión de Visual Studio (VS 2010) y de .NET Framework (4.0).</li>
</ul>
<p>Para la <strong>programación dinámica</strong> ello,  C# 4.0 tendrá una serie de características dinámicas que permitan:</p>
<ul>
<li> Objetos tipados de manera dinámica. La clave estará en una nueva palabra clave que aparece en escena: dynamic.</li>
<li>Mejorada la interoperabilidad COM.</li>
<li>Optinal and named parameters.</li>
<li>Co-and Contra-Variance.</li>
</ul>
<p>Tendremos un nuevo runtime para C# 4.0 que nos habilitará esta programación dinámica sobre la base de innovaciones ya existentes como los árboles de expresión y las expresiones lambda de C# 3.0, pero añadiendo nuevas innovaciones:</p>
<ul>
<li> Dynamic trees.</li>
<li>Dynamic Dispatch invocer.</li>
<li>Call Site Caching.</li>
</ul>
<p>Sobre este nuevo runtime, tendremos los lenguajes de programación tradicionales de .NET, C# y VB.NET, pero también lenguajes dinámicos como IronRuby y IronPhyton, y por supuesto cualquier otro lenguaje que cumpla la correspondiente CLS (Common Language Specification). Pero además, podremos hacer desde cualquier lenguaje comentado un binding con otro de los lenguajes, es decir, podremos llamar de manera sencilla código Phyton desde C# y utilizarlo. Tendremos bindings para .NET (Object), para JavaScript (Silverlight), para Phyton, Para Ruby y otros.</p>
<p>Dejaré para otros post otras novedades como <strong>Visual Studio 2010</strong>, el nuevo <strong>Windows Azure</strong> o la presentación del <strong>Windows 7</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2008/10/29/presentadas-las-novedades-de-c-40-en-el-pdc-2008/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C# Enviar correo electronico desde .NET</title>
		<link>http://www.microcode.es/2008/10/23/c-enviar-correo-electronico-desde-net/</link>
		<comments>http://www.microcode.es/2008/10/23/c-enviar-correo-electronico-desde-net/#comments</comments>
		<pubDate>Thu, 23 Oct 2008 08:05:11 +0000</pubDate>
		<dc:creator>Indigo</dc:creator>
				<category><![CDATA[Programacion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[email]]></category>

		<guid isPermaLink="false">http://www.microcode.es/?p=271</guid>
		<description><![CDATA[ara enviar un correo electrónico tenemos que usar los siguientes espacios de nombres
[sourcecode language='csharp']using System.Net;
using System.Net.Mail;[/sourcecode]
Con esto tendremos a nuestra disposición una serie de clases que nos harán la vida muy fácil para conseguir nuestro objetivo. Para enviar un correo electrónico necesitamos la siguiente información

Servidor smtp
Puerto (normalmente 25)
Nombre de usuario y contraseña en caso que [...]]]></description>
			<content:encoded><![CDATA[<p>ara enviar un correo electrónico tenemos que usar los siguientes espacios de nombres</p>
<p>[sourcecode language='csharp']using System.Net;<br />
using System.Net.Mail;[/sourcecode]</p>
<p>Con esto tendremos a nuestra disposición una serie de clases que nos harán la vida muy fácil para conseguir nuestro objetivo. Para enviar un correo electrónico necesitamos la siguiente información</p>
<ul>
<li>Servidor smtp</li>
<li>Puerto (normalmente 25)</li>
<li>Nombre de usuario y contraseña en caso que el servidor requiera autencación.</li>
</ul>
<p>El código es tan simple como este</p>
<p>[sourcecode language='csharp']try<br />
{<br />
SmtpClient smtpClient = new SmtpClient(&#8221;Servidor SMTP&#8221;, 25);</p>
<p>// Si tu servidor necesita autenticación<br />
if ((_userName != string.Empty) &amp;amp;amp;&amp;amp;amp; (_password != string.Empty))<br />
{<br />
NetworkCredential networkCredential = new NetworkCredential(&#8221;username&#8221;, &#8220;passwor&#8221;);<br />
smtpClient.UseDefaultCredentials = false;<br />
smtpClient.Credentials = networkCredential;<br />
}</p>
<p>string body = string.Empty;<br />
if (_isBodyHtml)<br />
body = &#8220;Tu mensaje en html.&#8221;;<br />
else<br />
body = &#8220;Tu mensaje en texto plano.&#8221;;</p>
<p>MailMessage mailMessage = new MailMessage(&#8221;from&#8221;, &#8220;to&#8221;, &#8220;subject&#8221;, body);<br />
mailMessage.IsBodyHtml = _isBodyHtml;</p>
<p>if (_sendAsync)<br />
smtpClient.SendAsync(mailMessage, null);<br />
else<br />
smtpClient.Send(mailMessage);<br />
}<br />
catch<br />
{<br />
throw;<br />
}</p>
<p>[/sourcecode]</p>
<ul>
<li>Al principio creamos una instancia del objeto SmtpClient para lo cual necesitamos una dirección del host y el puerto de conexión.</li>
<li>Despues, es caso de que nuestro servidor requiera autenticación, creamos la credenciales que se usar al conectar con nuestro servidor de correo.</li>
<li>Despues construimos el mensaje, en base a la variable _isBodyHtml que nos dirá si el mensaje irá en texto plano o en html.</li>
<li>Posteriormente creamos el mensaje de correo, con un from (de), to (para), subject(asunto) y el mensaje.</li>
<li>Y para finalizar se envia el correo de manera síncrona o asíncrona dependiendo de _sendAsync.</li>
</ul>
<p>Como vemos es realmente fácil. En caso que el envio te falle ten en cuenta</p>
<ol>
<li>Comprueba que los datos del host, nombre de usuario y contraseña sean correctos.</li>
<li>Tengas acceso a la red y no salgas a Internet a través de un proxy.</li>
<li>Comprobar si el antivirus te está bloqueando el envio del correo. A mi con el McAfee activado no puedo enviar correos.</li>
</ol>
<p>Saludos.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.microcode.es/2008/10/23/c-enviar-correo-electronico-desde-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
