<?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>Sylverio &#187; C#</title>
	<atom:link href="http://sylverio.com.br/blog/tag/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://sylverio.com.br/blog</link>
	<description>Análise, Arquitetura, Orientação a Objetos, UML, Tecnologias e Programação</description>
	<lastBuildDate>Fri, 11 May 2012 02:35:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Manipulando Application Configuration em C#</title>
		<link>http://sylverio.com.br/blog/2012/05/manipulando-application-configuration-em-c/</link>
		<comments>http://sylverio.com.br/blog/2012/05/manipulando-application-configuration-em-c/#comments</comments>
		<pubDate>Fri, 11 May 2012 02:35:58 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=1115</guid>
		<description><![CDATA[O framework .NET permite o suporte de múltiplos arquivos de configuração XML, este formato permite que editar as configurações por meio programático. As aplicações podem obter essas configurações de duas formas: Machine.config &#8211; que pode ser acessado por todos as &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2012/05/manipulando-application-configuration-em-c/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>O framework .NET permite o suporte de múltiplos arquivos de configuração XML, este formato permite que editar as configurações por meio programático.</p>
<p>As aplicações podem obter essas configurações de duas formas:</p>
<ol>
<li> <strong>Machine.config</strong> &#8211; que pode ser acessado por todos as aplicações .NET. <br /><em>Caminho do arquivo</em>: %Windir%\Microsoft.NET\Framework\v2.0.50727\Config\Machine.config</li>
<li> <strong>application-specific.config</strong> &#8211; pode ser um app.config para desktop application ou web.config para web application.</li>
</ol>
<p>Pelo fato de impactar em todas as aplicação .NET da máquina, o arquivo Machine.config é dificilmente modificado. A melhor solução é a utilização do application-specific.config, com essa alternativa definimos configurações específicas e unicamente para a aplicação que estamos trabalhando.<br />
A seguir apresentarei as principais funcionalidades do pacote <a href="http://msdn.microsoft.com/en-us/library/system.configuration.aspx" target="_blank">System.Configuration</a>.</p>
<p>Uma das utilizações mais simples do arquivo de configuração é o <strong>AppSettings</strong>, nela os dados são gravados na estrutura de chave-valor.</p>
<p><strong>AppSettings</strong> permite gerenciar uma coleção do tipo <em>NameValueCollection</em>.</p>
<h3>Escrevendo Configurações no Application Configuration</h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Configuration config <span style="color: #008000;">=</span> ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">OpenExeConfiguration</span><span style="color: #008000;">&#40;</span>ConfigurationUserLevel<span style="color: #008000;">.</span><span style="color: #0000FF;">None</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
config<span style="color: #008000;">.</span><span style="color: #0000FF;">AppSettings</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Settings</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;MyKey&quot;</span>, <span style="color: #666666;">&quot;MyValue&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
config<span style="color: #008000;">.</span><span style="color: #0000FF;">Save</span><span style="color: #008000;">&#40;</span>ConfigurationSaveMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Modified</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Após a execução do código o arquivo de configuração será modificado da seguinte forma para conter a chave-valor conforme abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;">&lt; ?xml <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;appsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;MyKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;MyValue&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/appsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><strong>Dica</strong>: Sempre verifique o arquivo de configuração do executável da aplicação. As alterações não são refletidas no arquivo de configuração do código fonte.</p>
<h3>Lendo configurações do Application Configuration</h3>
<p>Abaixo o arquivo de configuração contem duas chaves (<em>MyKey</em> e <em>Greeting</em>).</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;">&lt; ?xml <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;appsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;MyKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;MyValue&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;Greeting&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Hello, world!&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/appsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>O código a seguir mostra todas as configurações de chave-valor contido no arquivo de configuração.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">AppSettings</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{0}: {1}&quot;</span>,
   ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">AppSettings</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AllKeys</span><span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span>,
   ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">AppSettings</span><span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Para acessar uma informação, campo <em>value </em>de uma determinada chave (<em>key</em>), podemos proceder da seguinte forma:</p>
</pre>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">AppSettings</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Greeting&quot;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3>Utilizando Connection Strings</h3>
<p>Para acessar strings de conexão, use a coleção estática <strong>ConfigurationManager.ConnectionStrings</strong>, o retorno dessa propriedade é um <em>ConnectionStringSettingsCollection</em>.<br />
As três propriedades mais utilizadas da classe Connection-StringSettings são:</p>
<ul>
<li><strong>Name</strong> - que define o nome da conexão.</li>
<li><strong>Provider-Name</strong> - que define de tipo da conexão com a base de dados.</li>
<li><strong>ConnectionString</strong> - que define como o cliente se conecta com o servidor.</li>
</ul>
<p>O elemento <em>connectionStrings</em> agrupa as informações de conexão do sistema. Um arquivo de configuração pode contar diversos definições de conexão.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;connectionstrings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;LocalSqlServer&quot;</span> <span style="color: #000066;">connectionString</span>=<span style="color: #ff0000;">&quot;data source=.\SQLEXPRESS; Integrated Security=SSPI; AttachDBFilename=|DataDirectory|aspnetdb.mdf; User Instance=true&quot;</span> <span style="color: #000066;">providerName</span>=<span style="color: #ff0000;">&quot;System.Data.SqlClient&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/connectionstrings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>O código a seguir mostra todas as strings de conexão contido no arquivo de configuração.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ConnectionStringSettingsCollection connections <span style="color: #008000;">=</span> ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">ConnectionStrings</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>ConnectionStringSettings connection <span style="color: #0600FF; font-weight: bold;">in</span> connections<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Name: {0}&quot;</span>, connection<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Connection string: {0}&quot;</span>, connection<span style="color: #008000;">.</span><span style="color: #0000FF;">ConnectionString</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Provider: {0}&quot;</span>, connection<span style="color: #008000;">.</span><span style="color: #0000FF;">ProviderName</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Source: {0}&quot;</span>, connection<span style="color: #008000;">.</span><span style="color: #0000FF;">ElementInformation</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Source</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Para acessar informações de uma conexão especifica, podemos proceder da seguinte forma:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">ConnectionStrings</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;LocalSqlServer&quot;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ConnectionString</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3>Lendo configurações do Machine Configuration</h3>
<p>Como mencionsado, dificilmente iremos manipular um Machine.config. Porem caso se faça necessário, o código a seguir cria o objeto Configuration que representa o arquivo Machine.config.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">   Configuration machineSettings <span style="color: #008000;">=</span> ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">OpenMachineConfiguration</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   ProtectedConfigurationSection pcs <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>ProtectedConfigurationSection<span style="color: #008000;">&#41;</span>machineSettings<span style="color: #008000;">.</span><span style="color: #0000FF;">GetSection</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;configProtectedData&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>pcs<span style="color: #008000;">.</span><span style="color: #0000FF;">DefaultProvider</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>pcs<span style="color: #008000;">.</span><span style="color: #0000FF;">Providers</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;DataProtectionConfigurationProvider&quot;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;description&quot;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3>Seção customizada - Custom Sections</h3>
<p>Definições de configurações de aplicação customizados, podem ser criadas de 2 formas. Implementando inteface <strong>IConfigurationSectionHandler </strong>ou derivando uma classe de <strong>ConfigurationSection</strong>.<br />
A segunda opção é recomentada para versões 2.0 ou anteriores, pore esse motivo vou apresentar somente como realizar a primeira implementação pois se aplica a versões mais recentes do Framework.NET.</p>
<h4>Criando uma seção Customizado utilizando IConfigurationSectionHandler</h4>
<p>Devemos criar uma única classe para a seção customizada na aplicação, essa classe deve implementar a interface <strong>IConfigurationSectionHandler</strong>.<br />
Implementando a interface, devemos criar um construtor vazio e implementar o método Create. Dos três parâmetros requiridos pelo método, normalmente utilizaremos omente o terceiro, um objeto do tipo System.Xml.XmlNode que contem os dados armazenados no arquivo xml contendo os dados da seção customizada.</p>
<p>Demonstração de como estruturar a seção de configuração customizada no arquivo .config.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configsections<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;section</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;customSettings&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;ConfigApp.CustomConfigHandler, ConfigApp&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configsections<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;appsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;Greeting&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Hello, world!&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;Another Key&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Another value&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/appsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;customsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;lastuser<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Tony<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/lastuser<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;lastnumber<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>32<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/lastnumber<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/customsettings<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
Abaixo o código que permite acessar a seção customizada.</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MySettings
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> lastUser<span style="color: #008000;">;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> lastNumber<span style="color: #008000;">;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> MySettings<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> CustomConfigHandler <span style="color: #008000;">:</span> IConfigurationSectionHandler
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> CustomConfigHandler<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> Create<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> parent, <span style="color: #6666cc; font-weight: bold;">object</span> configContext, <span style="color: #000000;">System.<span style="color: #0000FF;">Xml</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">XmlNode</span> section<span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      MySettings settings <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MySettings<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>				
      settings<span style="color: #008000;">.</span><span style="color: #0000FF;">lastUser</span> <span style="color: #008000;">=</span> section<span style="color: #008000;">.</span><span style="color: #0000FF;">SelectSingleNode</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;lastUser&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">InnerText</span><span style="color: #008000;">;</span>
      settings<span style="color: #008000;">.</span><span style="color: #0000FF;">lastNumber</span> <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Parse</span><span style="color: #008000;">&#40;</span>section<span style="color: #008000;">.</span><span style="color: #0000FF;">SelectSingleNode</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;lastNumber&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">InnerText</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #0600FF; font-weight: bold;">return</span> settings<span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      MySettings settings <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>MySettings<span style="color: #008000;">&#41;</span>ConfigurationManager<span style="color: #008000;">.</span><span style="color: #0000FF;">GetSection</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;customSettings&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>settings<span style="color: #008000;">.</span><span style="color: #0000FF;">lastUser</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>settings<span style="color: #008000;">.</span><span style="color: #0000FF;">lastNumber</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Observe no arquivo de configuração a seção <strong>&lt;configsections&gt;</strong>, que declara uma seção customizada e informa se noma na propriedade de <strong>name</strong> e do método que implementa IConfigurationSectionHandler e o nome do assembly na propriedade <strong>type</strong>.<br />
Então, podemos criar uma seção de configuração customizada, com elementos para cada valor personalizado.</p>
<p>O método CustomConfigHandler.<strong>Create</strong> irá ler os valores da sessão customizada e atribuir a uma classe de dados que irá retornar os dados de forma tipada. </p>
<p>A seção <em>&lt;appsettings&gt;</em> está incluído apenas para demonstrar que um arquivo. Config pode conter configurações personalizadas e configurações de aplicativos padrão.</p>
<p>Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2012/05/manipulando-application-configuration-em-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Encode XML com C#</title>
		<link>http://sylverio.com.br/blog/2012/02/encode-xml-com-c/</link>
		<comments>http://sylverio.com.br/blog/2012/02/encode-xml-com-c/#comments</comments>
		<pubDate>Wed, 22 Feb 2012 11:58:15 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Framework.NET]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=1032</guid>
		<description><![CDATA[Em um documento XML, existe alguns caracteres especiais que delimitam os elementos, atributos e valores. Quando a informação contida neles se utiliza desses caracteres especiais, o documento XML é corrompido, pois não consegue mais identificar onde é o começo ou &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2012/02/encode-xml-com-c/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>Em um documento XML, existe alguns caracteres especiais que delimitam os elementos, atributos e valores. Quando a informação contida neles se utiliza desses caracteres especiais, o documento XML é corrompido, pois não consegue mais identificar onde é o começo ou fim da informação.</p>
<p><strong>XML Correto</strong></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;elemento</span> <span style="color: #000066;">atributo</span>=<span style="color: #ff0000;">'Stacem'</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Formula matemática do item<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/elemento<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><strong>XML corrompido</strong></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;elemento</span> <span style="color: #000066;">atributo</span>=<span style="color: #ff0000;">'St'</span>acem<span style="color: #ff0000;">'&gt;</span></span>Valor de X &gt; que valor de Y.<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/elemento<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Para resolver esse problema, devesse utilizar em campos de informações (valores dos elementos ou atributos) um <em>&#8220;encode&#8221;</em> para esses caracteres.</p>
<h3>Encode XML</h3>
<p>Basicamente são 5 valores:</p>
<table>
<tr>
<td><strong>&lt;</strong></td>
<td>&amp;lt;</td>
</tr>
<tr>
<td><strong>&gt;</strong></td>
<td>&amp;gt;</td>
</tr>
<tr>
<td><strong>&quot;</strong></td>
<td>&amp;quot;</td>
</tr>
<tr>
<td><strong>&apos;</strong></td>
<td>&amp;apos;</td>
</tr>
<tr>
<td><strong>&amp;</strong></td>
<td>&amp;amp;</td>
</tr>
</table>
<p>No Framework.NET existem alguns caminhos de aplicar o encode XML:</p>
<p><strong>1. string.Replace()</strong><br />
A maneira mais feia, mas que funciona, seria utilizar o famoso string.Replace().<br />
Repetindo a rotina 5 vezes, uma para cada caracter especial.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> text <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Este é um <span style="color: #008080; font-weight: bold;">\&quot;</span>nó<span style="color: #008080; font-weight: bold;">\&quot;</span> XML com caracteres 'especiais' &amp; &lt;&gt; diferente de tudo!!&quot;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> encodedXml <span style="color: #008000;">=</span> text<span style="color: #008000;">.</span><span style="color: #0000FF;">Replace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&amp;&quot;</span>, <span style="color: #666666;">&quot;&amp;amp;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Replace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&lt; &quot;</span>, <span style="color: #666666;">&quot;&amp;lt;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Replace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&gt;&quot;</span>, <span style="color: #666666;">&quot;&amp;gt;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Replace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\&quot;</span>&quot;</span>, <span style="color: #666666;">&quot;&amp;quot;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Replace</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;'&quot;</span>, <span style="color: #666666;">&quot;&amp;apos;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// RESULT: Este é um &amp;quot;nó&amp;quot; XML com caracteres &amp;apos;especiais&amp;apos; &amp;amp; &amp;lt;&amp;gt; diferente de tudo!!</span></pre></div></div>

<p><strong>2. System.Web.HttpUtility.HtmlEncode()</strong><br />
É utilizado para codificar textos em HTML, muito utilizado em ASP.NET, porem ele não codifica o apóstrofo e força você utilizar uma referência de pacote Web. Se for uma aplicação desktop, não recomendo sua utilização.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> text <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Este é um <span style="color: #008080; font-weight: bold;">\&quot;</span>nó<span style="color: #008080; font-weight: bold;">\&quot;</span> XML com caracteres 'especiais' &amp; &lt;&gt; diferente de tudo!!&quot;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> encodedXml <span style="color: #008000;">=</span> HttpUtility<span style="color: #008000;">.</span><span style="color: #0000FF;">HtmlEncode</span><span style="color: #008000;">&#40;</span>text<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// RESULT: Este é um &amp;quot;nó&amp;quot; XML com caracteres 'especiais' &amp;amp; &amp;lt;&amp;gt; diferente de tudo!!</span></pre></div></div>

<p><strong>3. System.Security.SecurityElement.Escape()</strong><br />
Outra maneiroa é utilizar o comando Escape() que trata os 5 caracteres especiais.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> text <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Este é um <span style="color: #008080; font-weight: bold;">\&quot;</span>nó<span style="color: #008080; font-weight: bold;">\&quot;</span> XML com caracteres 'especiais' &amp; &lt;&gt; diferente de tudo!!&quot;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> encodedXml <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Security</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">SecurityElement</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Escape</span><span style="color: #008000;">&#40;</span>text<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// RESULT: Este é um &amp;quot;nó&amp;quot; XML com caracteres &amp;apos;especiais&amp;apos; &amp;amp; &amp;lt;&amp;gt; diferente de tudo!!</span></pre></div></div>

<p>Gosto muito da opção de codificar com System.Security.SecurityElement.Escape(), acredito que seja a forma mais estética com relação ao código.<br />
Não sei quanto a desempenho das formas, mas manipulação de string não é a melhor das escolhas.<br />
E a segunda alem de não abranger todos os caracteres especiais, ainda fica limitada a aplicações web.</p>
<p>Espero ter ajudado <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2012/02/encode-xml-com-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gerenciando Threads</title>
		<link>http://sylverio.com.br/blog/2012/02/gerenciando-threads/</link>
		<comments>http://sylverio.com.br/blog/2012/02/gerenciando-threads/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 01:29:04 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Framework.NET]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=952</guid>
		<description><![CDATA[Talvez o mais difícil de se trabalhar com múltiplas thread seja a o bloqueio de recursos, onde um recurso não pode ser manipulado por diversas threads simultaneamente ou em determinadas situações que se torna necessário inciar, pausar, retornar e abandonar &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2012/02/gerenciando-threads/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>Talvez o mais difícil de se trabalhar com múltiplas thread seja a o bloqueio de recursos, onde um recurso não pode ser manipulado por diversas threads simultaneamente ou em determinadas situações que se torna necessário inciar, pausar, retornar e abandonar uma thread manualmente. </p>
<p>O Framework .NET possui o objeto <em>Thread</em> que permite mais flexibilidade e gerenciamento sobre as thread executadas em background do que o objeto <em>ThreadPool</em>.</p>
<p><strong>Thread Priority</strong><br />
Uma das propriedades do objeto Thread á sua prioridade. Após a thread criada, mas antes de iniciar a thread, podemos definir a prioridade da thread com  propriedade <em>Thread.Priority</em> usando o enumerador <em>ThreadPriority</em>.<br />
A Thread priority controla como o sistema operacional irá agendar o tempo para a execução da Thread. Geralmente threads com maior prioridade rodam antes das threads com baixo prioridades, por padrão as threads tem o valor de prioridade definida como Normal.</p>
<p><strong>Thread State</strong><br />
Outra propriedade do objeto é <em>Thread.ThreadState</em> pode ser utilizada para verificar o estado das threads em background.<br />
Os estados possíveis são:</p>
<ul>
<li><strong>Unstarted</strong>: estado inicial da thread (antes de executar o método Thread.Start).</li>
<li><strong>Running</strong>: estado ativo ou executando (após de executar o método Thread.Start).</li>
<li><strong>Stopped</strong>: estado parada.</li>
<li><strong>WaitSleepJoin</strong>: estado esperando outra thread completar.</li>
<li><strong>SuspendRequested</strong>: estado repondendo solicitanção de pausa.</li>
<li><strong>Suspended</strong>: estado suspensa.</li>
<li><strong>AbortRequested</strong>: estado respondendo a solicitanção de abandono.</li>
<li><strong>Aborted</strong>: estado abortado.</li>
</ul>
<h3>Thread com parâmetros e retorno em C#</h3>
<p>Para fornecer parâmetros para uma thread, criamos uma classe com um construtor que recebe um ou mais parâmetros e armazena o dado e a usa para criar o objeto ThreadStart.<br />
Para obter o retorno da Thread, criamos um método que recebe o resultado de retorno como uma parâmetro. Depois criamos um delegate para o método e passamos o delegado e próprio método como parâmetro para a classe.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Threading</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ManagerThread
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Program
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Calculator calculator <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Calculator<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Multiplicador&quot;</span>, <span style="color: #FF0000;">15</span>, ResultCallback<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            Thread thread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span>calculator<span style="color: #008000;">.</span><span style="color: #0000FF;">Execute</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            thread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Main Thread aguarda finalização das threads em background.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            thread<span style="color: #008000;">.</span><span style="color: #0000FF;">Join</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Thread completada.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadKey</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> ResultCallback<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> value<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Resultado: {0}&quot;</span>, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Calculator
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Delegate que define a assinatura do método de callback (retorno).</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">delegate</span> <span style="color: #6666cc; font-weight: bold;">void</span> ResultDelegate<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> ResultDelegate callback<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">string</span> message<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">int</span> value<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> Calculator<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> message, <span style="color: #6666cc; font-weight: bold;">int</span> value, ResultDelegate callback<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">message</span> <span style="color: #008000;">=</span> message<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">value</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">callback</span> <span style="color: #008000;">=</span> callback<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Execute<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>message<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>callback <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                callback<span style="color: #008000;">&#40;</span>value<span style="color: #008000;">*</span><span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>A thread é executada somente após o comando <em>thread.Start()</em>. O comando <em>thread.Join()</em> força a thread principal a ficar aguardando a finalização da thread em background para seguir o processo. </p>
<p><strong>Observações</strong>:<br />
Threads podem estar em mais de 1 estado ao mesmo tempo.<br />
Os métodos Thread.Suspend e Thread.Resume são utilizados para pausar e retornar a thread principal. Porem estes métos esta depreciados, e podem causar problemas de execuação, utilize o método Thread.Abort().</p>
<p>Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2012/02/gerenciando-threads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entendendo o Model do ASP.Net MVC</title>
		<link>http://sylverio.com.br/blog/2010/09/entendendo-o-model-do-asp-net-mvc/</link>
		<comments>http://sylverio.com.br/blog/2010/09/entendendo-o-model-do-asp-net-mvc/#comments</comments>
		<pubDate>Wed, 29 Sep 2010 02:18:11 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Arquitetura]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=576</guid>
		<description><![CDATA[Como prometi no último post Introdução ao ASP.Net MVC, que por sinal faz tempo que escrevi, pretendo dar continuidade ao assunto ASP.NET MVC e dessa vez falar um pouco do M de Model. O que é o M de Model &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2010/09/entendendo-o-model-do-asp-net-mvc/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>Como prometi no último post <a href="http://sylverio.com.br/blog/2010/04/criando-uma-asp-net-mvc-web-application/">Introdução ao ASP.Net MVC</a>, que por sinal faz tempo que escrevi, pretendo dar continuidade ao assunto ASP.NET MVC e dessa vez falar um pouco do M de Model.</p>
<h2>O que é o M de Model</h2>
<p>O <strong>Model representa os dados da aplicação</strong>, ou seja, são objetos que armazenam as informações a serem transportados da camada inferior para e pela interface, dessa forma a camada de interface é desacoplada das demais camadas. É muito comum iniciantes confundirem model com objetos de domínio, inclusive já li esse erro em diversas literaturas, o que ajuda a tornar as coisas mais confusas.<br />
Também não confunda arquitetura em camadas com MVC, pois a estruturação do MVC encontra-se somente na primeira camada.</p>
<h3>Exemplificando</h3>
<p>Criei um ASP.NET MVC Application chamado <em>NewsletterApp</em>. A idéia é criar nessa aplicação um cadastro de cliente, e exemplificar o conceito de Model.<br />
<img alt="Solution Explorer" src="http://sylverio.com.br/blog/image/solution_explorer_newsletter.png"  width="204" height="350" /></p>
<p>Nessa estrutura criei uma classe Model chamada Customer.cs</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Customer
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Name <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Email <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Phone <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> IsActive <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Um controller chamado HomeController que possui três Action Methods, um <em>Index()</em> que irá renderizar a View Index.aspx, os outros dois CustomerRegistration, repare nos atributos <em>AcceptVerbs</em> isso irá permitir que as requisições do tipo Get sejam atribuídas ao primeiro Action Method CustomerRegistration e os submits do formulário (requisições do tipo Post) sejam atribuídas ao segundo.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> HomeController <span style="color: #008000;">:</span> Controller
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> ViewResult Index<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> View<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008000;">&#91;</span>AcceptVerbs<span style="color: #008000;">&#40;</span>HttpVerbs<span style="color: #008000;">.</span><span style="color: #0000FF;">Get</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> ViewResult CustomerRegistration<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> View<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008000;">&#91;</span>AcceptVerbs<span style="color: #008000;">&#40;</span>HttpVerbs<span style="color: #008000;">.</span><span style="color: #0000FF;">Post</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> ViewResult CustomerRegistration<span style="color: #008000;">&#40;</span>Customer customer<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// TODO: executar o processo de cadastro do cliente </span>
        <span style="color: #008080; font-style: italic;">// Neste ponto, é chamada para camada de negócio ou banco de dados</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">return</span> View<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;CustomerResponse&quot;</span>, customer<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p><strong>Observação:</strong> No último Action Method coloquei um comentário. Ele se refere ao local onde o poderia ser realizada a chamada para camada de negócio ou banco de dados, para o cadastramento dos dados do cliente. Como o foco desse post não é o desenvolvimento desse processo. Optei em utilizar um comentário para exemplificar.</p>
<p>E duas páginas Index.aspx que é a nossa <em>Startup Page</em>. nela constem somente uma ancora (tag a) para a página CustomerRegistration.aspx que executa o processo de cadastro.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span>&lt; %= Html.ActionLink<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Cadastro Cliente&quot;</span>, <span style="color: #ff0000;">&quot;CustomerRegistration&quot;</span><span style="color: #66cc66;">&#41;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>E CustomerRegistration.aspx que possui um formulário com um input type=&#8221;submit&#8221;, para enviar os dados do cliente para a Action de destino do Form.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h1<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Cliente<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h1<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;fieldset<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;">&lt; % using<span style="color: #66cc66;">&#40;</span>Html.BeginForm<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Nome:<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span>&lt; %= Html.TextBox<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Name&quot;</span><span style="color: #66cc66;">&#41;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Email:<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span>&lt; %= Html.TextBox<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Email&quot;</span><span style="color: #66cc66;">&#41;</span>%<span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Telefone:<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span>&lt; %= Html.TextBox<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Phone&quot;</span><span style="color: #66cc66;">&#41;</span>%<span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Ativo: <span style="color: #009900;">&lt; %= Html.DropDownList<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;IsActive&quot;</span>, new<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#123;</span></span>
<span style="color: #009900;">                    new SelectListItem <span style="color: #66cc66;">&#123;</span> Text = <span style="color: #ff0000;">&quot;Sim&quot;</span>,Value = bool.TrueString <span style="color: #66cc66;">&#125;</span>,</span>
<span style="color: #009900;">                    new SelectListItem <span style="color: #66cc66;">&#123;</span> Text = <span style="color: #ff0000;">&quot;Não&quot;</span>,Value = bool.FalseString <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;input</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;submit&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Salvar&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;">&lt; % <span style="color: #66cc66;">&#125;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/fieldset<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Agora vamos criar mais uma página para a resposta do cadastramento.<br />
Para isso basta clicar com o botão direito sobre o diretório <em>Home > Add > View</em>. Informamos o nome da página, no exemplo utilizei CustomerResponse.<br />
E selecionamos a opção <strong>Create a strongly-typed view</strong>.<br />
<img alt="Strongly-Typed View" src="http://sylverio.com.br/blog/image/view_strongly_typed.png"  width="277" height="300" /></p>
<p>E inclui o seguinte código na página.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&lt;</span>h1<span style="color: #008000;">&gt;</span>Obrigado<span style="color: #008000;">!&lt;/</span>h1<span style="color: #008000;">&gt;</span>
<span style="color: #008000;">&lt;</span>p<span style="color: #008000;">&gt;&lt;</span> <span style="color: #008000;">%=</span> Html<span style="color: #008000;">.</span><span style="color: #0000FF;">Encode</span><span style="color: #008000;">&#40;</span>Model<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">%&gt;</span> foi cadastrado com sucesso<span style="color: #008000;">.&lt;/</span>p<span style="color: #008000;">&gt;</span>
<span style="color: #008000;">&lt;</span>p<span style="color: #008000;">&gt;</span>Seu status é 
<span style="color: #008000;">&lt;</span> <span style="color: #008000;">%</span> <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>Model<span style="color: #008000;">.</span><span style="color: #0000FF;">IsActive</span> <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span> <span style="color: #008000;">%&gt;</span>
        ativo<span style="color: #008000;">.</span>
<span style="color: #008000;">&lt;</span> <span style="color: #008000;">%</span> <span style="color: #008000;">&#125;</span><span style="color: #0600FF; font-weight: bold;">else</span><span style="color: #008000;">&#123;</span> <span style="color: #008000;">%&gt;</span>
        inativo<span style="color: #008000;">.</span>
<span style="color: #008000;">&lt;</span> <span style="color: #008000;">%</span> <span style="color: #008000;">&#125;</span> <span style="color: #008000;">%&gt;</span>
<span style="color: #008000;">&lt;/</span>p<span style="color: #008000;">&gt;</span></pre></td></tr></table></div>

<p>Neste momento você deve estar se perguntando como algumas algumas coisas acontecem?<br />
É agora que entra a mágica do MVC.</p>
<h2>Model Binding</h2>
<p>Na HomeController a primeira Action Method de CustomerRegistration simplismente renderiza a View, porém a segunda recebe uma instância de Customer como um parâmetro.<br />
A pergunta aqui é <em>como um método é invoca via HTTP request passando um tipo .NET como parâmetro se ele é totalmente desconhecido do HTTP</em>?<br />
Simples&#8230; Chama-se <strong>Model Binding</strong>. O ASP.NET MVC automaticamente instância e converte os parâmetros por meio de chave/valor que tenham os mesmos nomes das propriedades do tipo .NET utilizado como parâmetro no Action Method.<br />
Repare que os nomes dos elementos text do formulário possuem o mesmo nome dos atributos da classe Customer.</p>
<p>Outra característica apresentada pela segunda Action é a especificação da View que irá ser renderizada,  e definição do objeto Model que será passado para View, esse View é chamado de  <strong>strongly typed view</strong>, pois está fortemente tipada com um objeto da aplicação.<br />
Esta view permite que seja acessada a variável chamada Model que esta relacionada ao tipo da criação da página no caso do exemplo o objeto Customer.</p>
<h3>Conclusão</h3>
<p>Gostei muito da arquitetura MVC por permite uma melhor separação de responsabilidade dos componentes de interface. Como por exemplo a separação de Actions para Get E Post. O encapsulamento de parâmetro em instância de objetos reduz a escrita de código.<br />
A utilização de objetos Model na aplicação ficou mais presente, e sua interação com outros instâncias passa a ser mais requerida.</p>
<p>Até mais<br />
Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2010/09/entendendo-o-model-do-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Criando um ASP.NET MVC Web Application</title>
		<link>http://sylverio.com.br/blog/2010/04/criando-uma-asp-net-mvc-web-application/</link>
		<comments>http://sylverio.com.br/blog/2010/04/criando-uma-asp-net-mvc-web-application/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 01:49:27 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Arquitetura]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=421</guid>
		<description><![CDATA[No post ASP.Net MVC fiz uma introdução as caracteristicas desse novo tipo de projeto web. Neste post vou apresentar um pouco mais sobre esse projeto, sua estrutura, comportamento. Para isso é necessário instalar o ASP.NET MVC. Após a instalação o &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2010/04/criando-uma-asp-net-mvc-web-application/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>No post <a href="http://sylverio.com.br/blog/2010/02/asp-net-mvc/">ASP.Net MVC</a> fiz uma introdução as caracteristicas desse novo tipo de projeto web. Neste post vou apresentar um pouco mais sobre esse projeto, sua estrutura, comportamento.<br />
Para isso é necessário instalar o <a href="http://www.microsoft.com/web/gallery/install.aspx?appsxml=http://www.microsoft.com/web/webpi/2.0/WebProductList.xml&#038;appid=MVC2" target="_blanck">ASP.NET MVC</a>. Após a instalação o Visual Studio 2008  apresentará um novo tipo de projeto Web, chamado ASP.NET MVC Web Application.</p>
<p><img src="http://sylverio.com.br/blog/image/new_project_mvc.png" alt="New Project ASP.NET MVC Web Application" /></p>
<p>Ao criar um projeto do tipo ASP.NET MVC Web Application uma aplicação de demonstração (padrão) é apresentada na Solution Explorer.</p>
<p>O ASP.NET MVC a primeira vista parece ser bem complicado, mas apartir do momento que se conhece melhor a sua estrutura e seu funcionamento, ele passa a ser bem simples.</p>
<h2>Estrutura do ASP.NET MVC Web Application</h2>
<p>Primeiramente vamos nos atentarmos a estrutura, pois ela contem diversas convensões que devem ser utilizadas pelo ASP.NET MVC.<br />
<img style="float:right;width:280px;margin:5px 0 5px 15px;" src="http://sylverio.com.br/blog/image/solution_mvc.png" alt="Solution Explorer MVC Web Application" /><br />
Repare nos diretórios, obrigatóriamente teremos o Controller, Model e View.<br />
Outra convensão é para as classes controladoras (contidas no diretório <strong>Controller</strong>), devem possuir o sufixo Controller em seus nomes e um sub-diretório no diretorio View. Confuso? Repare na Solution o diretorio Controller, note que possui duas classes controladoras Account e Home ambas com o sufixo Controller. Agora veja o diretório View, ele possui dois sub-diretórios com o mesmo nome da controladora (Account e Home).<br />
No diretório <strong>View</strong> ficam os templates que correspondem a ações dos controllers  e seram renderizados.<br />
O sub-diretório <strong>View/Shared</strong> contém recorsos compartilhados com a aplicação, como página de erro genérica, master page, entre outros.<br />
O diretório <strong>Script</strong> é destinado a armazenar biblioteca JavaScript e scripts (.js)<br />
O diretório <strong>Content</strong> é destinado a armazenar arquivos de estilo (CSS), arquivos de imagens e outros não dinâmicos.<br />
Na raiz do ASP.NET MVC Web Application temos os arquivos Global.asax, default.aspx e web.config estes arquivos são utilizados em conjunto para realizarem a sobreescrita (rewrite) de URL, mas esse assunto ficará para um próximo post.</p>
<h2>Como ASP.NET MVC trabalha</h2>
<p>Para compreender melhor o funcionamento do ASP.NET MVC, vamos remover alguns arquivos e diretórios da aplicação padrão. </p>
<ul>
<li>App_Data <em>(diretório)</em></li>
<li>AccountController.cs <em>(arquivo)</em></li>
<li>Account <em>(diretório)</em></li>
<li>About.aspx <em>(arquivo)</em></li>
<li>Index.aspx <em>(arquivo)</em></li>
<li>Error.aspx <em>(arquivo)</em></li>
<li>LogOnUserControl.ascx <em>(arquivo)</em></li>
<li>Site.Master <em>(arquivo)</em></li>
</ul>
<h3>Hello Word</h3>
<p>Como é padrão e não pode faltar em qualquer tutorial de introdução, vamos criar a famosa aplicação Hello Word!. Para isso no arquivo HomeController reescreva o código para que fique da seguinte forma:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> HomeController <span style="color: #008000;">:</span> Controller
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Index<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #666666;">&quot;Hello, word!&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Pronto, ao executar (<em>F5</em>) criamos nosso primeiro ASP.NET MVC Application.</p>
<p>Na arquitetura MVC, os controllers são reponsáveis por manipular as requisições. No .NET, controller são classes derivadas de <em>System.Web.Mvc.Controller</em>. E cada <em>método público</em> no <strong>Controller</strong> é conhecido como <strong>Action Method</strong> (método de ação), que são chamados da web por meio de alguma URL. Em nossa aplicação acima temos nosso controller chamado <em>HomeController</em> com seu action method chamado <em>Index</em>.<br />
Quando executamos a aplicação o <strong>Routing System</strong> (sistema de rotas) do ASP.NET MVC decidiu qual controller e action method executar. Não por acaso utilizei este controller e action method, esta é a configuração padrão de nosso aplicação, que está configurada no arquivo <em>Global.asax.cs</em>, como pode ser visto:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> RegisterRoutes<span style="color: #008000;">&#40;</span>RouteCollection routes<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    routes<span style="color: #008000;">.</span><span style="color: #0000FF;">IgnoreRoute</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{resource}.axd/{*pathInfo}&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    routes<span style="color: #008000;">.</span><span style="color: #0000FF;">MapRoute</span><span style="color: #008000;">&#40;</span>
        <span style="color: #666666;">&quot;Default&quot;</span>,                                            <span style="color: #008080; font-style: italic;">// Route name</span>
        <span style="color: #666666;">&quot;{controller}/{action}/{id}&quot;</span>,                         <span style="color: #008080; font-style: italic;">// URL with parameters</span>
        <span style="color: #008000;">new</span> <span style="color: #008000;">&#123;</span> controller <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Home&quot;</span>, action <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Index&quot;</span>, id <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span> <span style="color: #008000;">&#125;</span><span style="color: #008080; font-style: italic;">// Parameter defaults</span>
    <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Em nosso Routing System, é definido a rota default com o controller Home e o action method Index sem passagem de parâmetro. Dessa forma as seguintes requisição serão manipuladas pela action Index no HomeController:</p>
<ul>
<li>/</li>
<li>/Home</li>
<li>/Home/Index</li>
</ul>
<h2>Renderizando Web Pages</h2>
<p>Como já mensionado, na arquitetura MVC o <strong>Controller</strong> é responsável por manipular as requisições e as <strong>Views</strong> são componentes de interface do usuário. Assim não está correto em nossa aplicação o controller enviar a resposta (no nosso caso texto) para o browser. Em uma aplicação real o controller deve passar essa tarefa para uma View. Para isso vamos reescrever o método Index da seguinte forma:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> HomeController <span style="color: #008000;">:</span> Controller
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> ViewResult Index<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> View<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Dessa forma a action retorna um objeto do tipo <strong>ViewResult</strong>, passando para o Framework a instrução de renderizar uma View. O próximo passo é criar a View, para isso podemos clicar com o botão direito no action method Index e selecione Add View, isto irá criar um novo template para o action method em <em>&#8220;~/Views/Home/Index.aspx&#8221;</em>.<br />
Altere o código HTML na tag body da seguinte forma:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">body</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">h1</span>&gt;</span>Hello, Word!<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">h1</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">p</span>&gt;</span>(renderizada apartir da View)<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">p</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">body</span>&gt;</span></pre></td></tr></table></div>

<p>Nossa aplicação está finalizada, execute para visualizar a página rendenrizada pela View.</p>
<p><img src="http://sylverio.com.br/blog/image/hello_word_aspnet_mvc.png" alt="Hello Word ASP.NET MVC Web Application" /></p>
<p>Repare que não é necessário informar o nome da View que será chamada. O Framework renderiza a View que contém o mesmo nome do action method.</p>
<p>Há outros objetos de retorno que um Action Method pode retornar que instrui o framework diferentes fins. Esses tipos de retorno são chamados <strong>Action Results</strong>, mas isso será assunto para um próximo post, assim como a compreensão do <strong>M</strong> de <strong>Model</strong> de nossa arquitetura MVC.</p>
<p>Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2010/04/criando-uma-asp-net-mvc-web-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cifrando e Decifrando dados com o Enterprise Library</title>
		<link>http://sylverio.com.br/blog/2010/03/cifrando-e-decifrando-dados-com-o-enterprise-library/</link>
		<comments>http://sylverio.com.br/blog/2010/03/cifrando-e-decifrando-dados-com-o-enterprise-library/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 18:18:59 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Enterprise Library]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=432</guid>
		<description><![CDATA[No post anterior apresentei O que é Enterprise Library. Neste post irei mostrar como é facil criptografar e descriptografar dados utilizando o Enterprise Library. Para o exemplo utilizei o Enterprise Library 4.1-October 2008. Que tem como pré requisitos, Framework.NET 3.5 &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2010/03/cifrando-e-decifrando-dados-com-o-enterprise-library/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>No post anterior apresentei <a href="http://sylverio.com.br/blog/2010/03/o-que-e-enterprise-library/" alt="O que é Enterprise Library">O que é Enterprise Library</a>.</p>
<p>Neste post irei mostrar como é facil <strong>criptografar e descriptografar dados</strong> utilizando o Enterprise Library.</p>
<p>Para o exemplo utilizei o  <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&#038;displaylang=en">Enterprise Library 4.1-October 2008</a>. Que tem como pré requisitos, Framework.NET 3.5 e Visual Studio 2008. <i>Para uma configuração inferior, utilize <a href="http://msdn.microsoft.com/en-us/library/cc467894.aspx">outras versões</a> do Enterprise Library.</i></p>
<p>Devido a flexibilidade do Enterprise Library, as configurações são mantidas em uma arquivo XML (app.config, web.config ou um arquivo .xml a parte) na aplicação.<br />
Ao instalar o Enterprise Library duas ferramentas de configuração são instaladas: uma embutida no Visual Studio (<i>Configuration Editor</i>), e uma  aplicação externa (<i>Enterprise Library Configuration Console</i>). As alterações feitas no arquivo de configuração não obrigam a recompilação da aplicação, tornando assim fácil a reconfiguração da aplicação. </p>
<h3>Configurando uma aplicação com Criptography Application Block</h3>
<p>Para o exemplo, crie um projeto do tipo Console Application, de nome EntLibCriptography (pode ser qualquer nome).<br />
Adicione as  refenrencias para os assembly do bloco de aplicação <i>Cryptography Application Block</i>. Para isso, no Visual Studio clique com o botão direito sobre o no de projeto da Solution Explorer, e clique em Add References.<br />
Clique em Browser e localize as dlls:</p>
<ul>
<li>Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll</li>
<li>Microsoft.Practices.EnterpriseLibrary.Common.dll</li>
<li>Microsoft.Practices.ObjectBuilder2.dll</li>
</ul>
<p>Agora adicione ao projeto um arquivo Application Configuration File (App.config).<br />
Clique com o botão direito sobre o arquivo App.config, e clique em Edit Enterprise Library Configuration.</p>
<p>O próximo passo é configurar o Cryptography Application Block no arquivo de configuração.<br />
Para isso, clique com o botão direito sobre o App.config (no Enterprise Library Configuration e não no Solution Explorer), selecione New e clique em Cryptography Application Block.</p>
<div class="observacao">
<strong>Observação</strong>: A ferramenta de configuração  adiciona o nó Cryptography Application Block e os sub-nó Hash Providers e Symmetric Providers, com uma configuração padrão.
</div>
<h3>Configurando Symmetric Algorithm Provider</h3>
<p>Clique em Symmetric Providers, selecione New, e clique em Symmetric Algorithm Provider. </p>
<p><img src="http://sylverio.com.br/blog/image/criptography_simmetric_provider.png" alt="Configuração do Symmetric Algorithm Provider"/></p>
<p>No Type Selector, selecione o tipo de symmetric algorithm provider, neste exemplo utilizaremos o RijndaelMananged, que é o tipo padrão.</p>
<p>Agora vamos gerar a chave de criptografia (o Cryptographic Key Wizard permite gerar ou importar uma chave existente).<br />
O Cryptographic Key Wizard,  apresentará as seguintes opções:</p>
<ul>
<li>Create a new key</li>
<li>Use an existing DPAPI-protected key file</li>
<li>Import a password-protected key file</li>
</ul>
<p>Escolha &#8220;create a new key&#8221; e clique em Next.<br />
No próximo passo, informamos nossa chave <i>CHAVETESTE</i> e clicamos em Generate para converter o texto em uma chave hexadecimal (pode ser informado uma chave hexadecimal diretamente).<br />
Depois clique em Next.<br />
Escolha um local para salvar o arquivo de chave, e clique em Next.<br />
O próximo passo será configura o modo de acesso a chave, escolha Machine mode e clique em Finish.</p>
<h3>Código de criptografia e decriptografia</h3>
<p>Abaixo o código de ciframento e deciframento utilizando utilizando o tipo de criptografia <strong>Rijndael</strong>.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">Microsoft.Practices.EnterpriseLibrary.Security.Cryptography</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> EntLibCriptography
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Program
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// Cifra mensagem</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> mensageEncrypted <span style="color: #008000;">=</span> Cryptographer<span style="color: #008000;">.</span><span style="color: #0000FF;">EncryptSymmetric</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;RijndaelManaged&quot;</span>, <span style="color: #666666;">&quot;senha&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;mensagem cifrada: {0}&quot;</span>, mensageEncrypted<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// Decifra mensagem</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> mensageDecrypted <span style="color: #008000;">=</span> Cryptographer<span style="color: #008000;">.</span><span style="color: #0000FF;">DecryptSymmetric</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;RijndaelManaged&quot;</span>, mensageEncrypted<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;mensagen decifrada: {0}&quot;</span>, mensageDecrypted<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Resultado:</p>
<p><img src="http://sylverio.com.br/blog/image/criptography_simmetric_result.png" alt="Resultado da criptografia e decriptografia" /></p>
<p>Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2010/03/cifrando-e-decifrando-dados-com-o-enterprise-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>O que é Enterprise Library</title>
		<link>http://sylverio.com.br/blog/2010/03/o-que-e-enterprise-library/</link>
		<comments>http://sylverio.com.br/blog/2010/03/o-que-e-enterprise-library/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 01:49:53 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Enterprise Library]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=423</guid>
		<description><![CDATA[Enterprise Library é uma biblioteca de aplicação que soluciona necessidades comuns. A Enterprise Library possui uma coleção de blocos de aplicação (Application Blocks) que são reutilizáveis, extensíveis e permitem a customização do código-fonte. A Enterprise Library faz parte de um &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2010/03/o-que-e-enterprise-library/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><strong>Enterprise Library</strong> é uma biblioteca de aplicação que soluciona necessidades comuns.<br />
A Enterprise Library possui uma coleção de blocos de aplicação (Application Blocks) que são reutilizáveis, extensíveis e permitem a customização do código-fonte. </p>
<p>A Enterprise Library faz parte de um grupo da Microsoft <img style="float:right;margin:15px 0 0 15px;" src="http://sylverio.com.br/blog/image/patterns_practices.png" alt="Patterns &#038; Practices" /> conhecido como <a href="http://msdn.microsoft.com/pt-br/practices/default.aspx">Patterns &#038; Practices</a>, e não é nativo do Framework.NET, não possui suporte, localização ou garantias de compatibilidade, porem pode ser <a href="http://msdn.microsoft.com/en-us/library/cc467894.aspx">baixado gratuitamente</a>. </p>
<p>O Enterprise Library prove blocos de código com funcionalidades que seria necessário desenvolver em uma aplicação caso já não estivesse pronto. Com a vantagem de já terem sidas testadas pela Microsoft e outras empresas de diversos tipos de aplicação. Estes blocos de aplicação tem a função de auxiliar equipes de desenvolvimento, permitindo que se concentre nas regras de negócio do cliente evitando que percam tempo criando tarefas comuns a uma aplicações como registro de log, autorização de usuários, acesso a dados, criptografia e outros.</p>
<p>Os blocos de aplicação fornecidos pelo Enterprise Library são:</p>
<ul>
<li><strong>Caching Application Block</strong>: possibilita a incorporação de cache local na aplicação.</li>
<li><strong>Cryptography Application Block</strong>: possilita a fácil implementação de criptografia simétrica ou de hash.</li>
<li><strong>Data Access Application Block</strong>: possibilita a implementação a funcionalidade de acesso ao banco de dados de forma padronizada e simplificada.</li>
<li><strong>Exception Handling Application Block</strong>: possilita criar uma estratégia consistente de tratamente de exceções entre as camadas de uma aplicação.</li>
<li><strong>Logging Application Block</strong>: possilita a criação de um procedimento padrão de registro de log na aplicação.</li>
<li><strong>Policy Injection Application Block</strong>: possibilita implementar politicas de interceptação de operações para implementar funcionalidades comuns como registro de log, uso de cache, tratamento de exceção, entre outros.</li>
<li><strong>Security Application Block</strong>: possibilita a incorporação de autenticação e cache de dados relacionados a segurança da aplicação.</li>
<li><strong>Validation Application Block</strong>: utilizado para criar regras de validação para objetos de negócio, podendo ser reutilizado em diversas camadas da aplicação.</li>
</ul>
<p>A instalação do Enterprise Library fornece os seguintes itens:</p>
<ul>
<li><strong>Arquivos Binários</strong>: inclui pre-compilado, strong-named assemblies para todos os códigos fontes.</li>
<li><strong>Código Fonte</strong>: inclui o código fonte para todos os blocos de aplicação, ferramenta de configuração, teste unitário, e o QuickStarts.</li>
<li><strong>Teste Unitário</strong>: inclui os teste unitários que foram criados enquanto os blocos de aplicação eram desenvolvidos.</li>
<li><strong>QuickStarts</strong>: aplicações de exemplo para o fácil entendimento das caracteristicas dos blocos de aplicação.</li>
<li><strong>Documentação</strong>: que pode ser visualizada como Visual Studio Help. A documentação inclui um guia sobre com utilizar o Enterprise Library e referência a biblioteca.</li>
</ul>
<p>Abaixo um mapa de dependência entre os blocos de aplicação:</p>
<p><img src="http://sylverio.com.br/blog/image/dependencia_entlib_appblock.png" alt="depêndencia entre os blocos de aplicação do Enterprise Library" /></p>
<p>Até mais <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2010/03/o-que-e-enterprise-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Garbage Collector (GC) &#8211; Gerenciamento de memória</title>
		<link>http://sylverio.com.br/blog/2010/01/garbage-collector-gc-gerenciamento-de-memoria/</link>
		<comments>http://sylverio.com.br/blog/2010/01/garbage-collector-gc-gerenciamento-de-memoria/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 13:25:37 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Framework.NET]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=331</guid>
		<description><![CDATA[O Framework.NET trouxe alguns benefícios referentes a utilização e gerenciamento de memória, permitindo mais liberdade de alocação e remoção de variáveis na memória em ordem aleatória, executado por meio de uma gerência complexa do espaço ocupado e identificação dos espaços &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2010/01/garbage-collector-gc-gerenciamento-de-memoria/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>O Framework.NET trouxe alguns benefícios referentes a utilização e gerenciamento de memória, permitindo mais liberdade de alocação e remoção de variáveis na memória em ordem aleatória,  executado por meio de uma gerência complexa do espaço ocupado e identificação dos espaços livres.<br />
Dessa forma vida de nós programadores se tornou muito mais fácil, pois não precisamos nos preocupar com o gerenciamento de memória (nada de malloc e free utilzados em C/C++), com isso temos menos erros relacionados ao vazamento de memória, bugs de ponteiros, entre outros.<br />
O principal componente que realiza esse gerenciamento e liberação de memória é o <strong>Garbage Collector</strong> (Coletor de Lixo ou GC) existente na arquitetura do <strong>Common Language Runtime</strong> (CLR) e tem como princípio atividade de funcionamento:</p>
<ol>
<li>Determinar quais objetos não mais será utilizado, ou seja, não estão mais acessíveis na aplicação;</li>
<li>Liberar os recursos (memória) utilizados por esses objetos</li>
</ol>
<h2>Entendendo o funcionamento do Garbage Collector</h2>
<p>Basicamente o GC divide a memória disponível em 3 áreas distintas:</p>
<ol>
<li>Maneged Heap</li>
<li>Pilha</li>
<li>Unmanaged Heap</li>
</ol>
<p>O GC em conjunto com a CLR por meio de diversos algoritmos executa o gerenciamento da área de memória managed heap, que aloca reference types.  Enquanto a pilha é utilizada para alocar value types. A unmanaged heap é utilizada para armazenar recursos não gerenciados de forma automática ou recursos nativos.<br />
Mais detalhe da arquitetura do GC ficará para um próximo post, pois irá envolver alguns temas ainda não tratados. </p>
<h2>Recursos Não Gerenciados</h2>
<p>Um ponto importante é controle de recursos não gerenciados (recursos nativos, que pode ser um arquivo, janela, conexões de banco de dados, sockets, Win32, entre outros).<br />
Implicitamente o Framework.NET mantém um controle das instâncias utilizadas pela aplicação, porem o mesmo não se repete para recursos não gerenciados. Para recursos não gerenciados deve-se fornecer uma maneira de liberar os recursos da memória depois que o aplicativo tiver terminado de usá-los, ou seja, deve ser um <em>processo manual (codificado) executado pelo programador</em>.<br />
Há duas maneiras de se finalizar um recurso não gerenciado:</p>
<ul>
<li>Implicitamente utilizando o método Finalize();</li>
<li>Explicitamente utilizando o método Dispose() do IDisposable;</li>
</ul>
<p><strong><em>Observação</em></strong>: Por padrão a Microsoft recomenda a implementar as duas formas de finalizar o objeto. Sendo que o método Finalize() serve de garantia de execução de liberação de memória impedindo que o recurso fique permanentemente vazando caso algum programador esqueça de chamar o método Dispose().<br />
<br />
A primeira impressão que temos ao ver o finalizador (redefinindo ao método Finalize de System.Object) existente no .NET é que este atua como um destruidor  (destructor)  presente em linguagens com C/C++  é que são similares. Porem não se iluda pela aparência, pois são bem diferentes em suas características.<br />
<br />
<strong><em>Caracteristicas do Finalizador:</em></strong><br />
</p>
<ul>
<li>Execução nem sempre é não garantida;</li>
<li>Execução não determinística (instante em que o método é executado não é conhecido);</li>
<li>Chamada ao método ocorre desde que não existam ciclos infinitos;</li>
<li>Quando chamado shutdown, sua execução só ocorre caso seu tempo de execução não seja superior a 2 segundos e o somatório não exceda 40 segundos (tempos aproximados);</li>
</ul>
<p>Em resumo <strong>o CLR não garante a ordem de chamada dos métodos Finalize()</strong>.</p>
<p><strong><em>Exemplo de implementação do finalize:</em></strong></p>
<p>Código C#.NET:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> AlgumaClasse
<span style="color: #008000;">&#123;</span>
   …
   ~AlgumaClasse<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008080; font-style: italic;">// finalizador</span>
   <span style="color: #008000;">&#123;</span>
      <span style="color: #008080; font-style: italic;">// código de limpeza</span>
   <span style="color: #008000;">&#125;</span>
   …
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Codigo gerado pelo compilador:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> AlgumaClasse
<span style="color: #008000;">&#123;</span>
   …
   <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">void</span> Finalize<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">try</span> <span style="color: #008000;">&#123;</span> <span style="color: #008080; font-style: italic;">/* código de limpeza */</span> <span style="color: #008000;">&#125;</span>
      <span style="color: #0600FF; font-weight: bold;">finally</span> <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Finalize</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
   <span style="color: #008000;">&#125;</span>
   …
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>O método Dispose é uma implementação de um padrão conhecido como <strong><em>“padrão de descarte”</em></strong> e impõe uma ordem na vida de um objeto.<br />
O método Dispose() deve liberar os recursos que ele possui assim como os recursos de propriedade de seus tipos base. Esse processo é executado através de uma hierarquia de tipos de base, ou seja, cada objeto irá chamar o método Dispose() da classe estendida ou implementada. Garantindo assim que os recursos são sempre limpos adequadamente.<br />
Um característica particular do método Dispose() é que este pode ser chamado várias vezes sem lançar exceção.<br />
É importante salientar que não há benefícios de desempenho na utilização do método Dispose() a objetos gerenciados pela CLR (tais como Arrays). Este método deve ser utilizado em objetos que utilizam recursos nativos e objetos COM que são expostas ao Framework.NET, como exemplo podemos citar a classe FileStream que implementa a interface IDisposable.</p>
<p><strong><em>Exemplo de implementação do métiodo Dispose():</em></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Design pattern para uma classe base.</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> <span style="color: #0600FF; font-weight: bold;">Base</span><span style="color: #008000;">:</span> IDisposable
<span style="color: #008000;">&#123;</span>
   <span style="color: #008080; font-style: italic;">//Implementação da interface IDisposable.</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Dispose<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> 
   <span style="color: #008000;">&#123;</span>
     Dispose<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      GC<span style="color: #008000;">.</span><span style="color: #0000FF;">SuppressFinalize</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> 
   <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">void</span> Dispose<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">bool</span> disposing<span style="color: #008000;">&#41;</span> 
   <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>disposing<span style="color: #008000;">&#41;</span> 
      <span style="color: #008000;">&#123;</span>
         <span style="color: #008080; font-style: italic;">// libera outros estados (managed objects).</span>
      <span style="color: #008000;">&#125;</span>
      <span style="color: #008080; font-style: italic;">// Libera sus próprios estados(unmanaged objects).</span>
      <span style="color: #008080; font-style: italic;">// Define campos grandes como null.</span>
   <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #008080; font-style: italic;">// Sintaxe para finalização do código.</span>
   ~<span style="color: #0600FF; font-weight: bold;">Base</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      <span style="color: #008080; font-style: italic;">//Chamada simples Dispose(false).</span>
      Dispose <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
<span style="color: #008080; font-style: italic;">// Design pattern para a classe derived.</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Derived<span style="color: #008000;">:</span> <span style="color: #0600FF; font-weight: bold;">Base</span>
<span style="color: #008000;">&#123;</span>   
   <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">void</span> Dispose<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">bool</span> disposing<span style="color: #008000;">&#41;</span> 
   <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>disposing<span style="color: #008000;">&#41;</span> 
      <span style="color: #008000;">&#123;</span>
         <span style="color: #008080; font-style: italic;">// Liberação de recursos gerenciados</span>
      <span style="color: #008000;">&#125;</span>
      <span style="color: #008080; font-style: italic;">// Liberação de recusos não gerenciados.</span>
      <span style="color: #008080; font-style: italic;">// Define campos grandes como null.</span>
      <span style="color: #008080; font-style: italic;">// Chama Dispose da classe base.</span>
      <span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Dispose</span><span style="color: #008000;">&#40;</span>disposing<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
   <span style="color: #008080; font-style: italic;">// A classe derived não tem o método Finalize</span>
   <span style="color: #008080; font-style: italic;">// ou um método Dispose com parametro pois herda da classe base.</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2010/01/garbage-collector-gc-gerenciamento-de-memoria/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comunicação via socket com C#</title>
		<link>http://sylverio.com.br/blog/2009/12/comunicacao-via-socket-com-c/</link>
		<comments>http://sylverio.com.br/blog/2009/12/comunicacao-via-socket-com-c/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 01:34:55 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Framework.NET]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=271</guid>
		<description><![CDATA[Introdução Primeiramente vamos conceiturar o que é socket, ou soquete em portugues. De uma visão geral um soquete pode ser definido como uma tomada que designa uma cavidade ou região usada para ligar algum artifício específico. No mundo da computação, &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2009/12/comunicacao-via-socket-com-c/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><strong>Introdução</strong></p>
<p>Primeiramente vamos conceiturar o que é socket, ou soquete em portugues. De uma visão geral um soquete pode ser definido como uma tomada que designa uma cavidade ou região usada para ligar algum artifício específico.</p>
<p>No mundo da computação, um socket é o elo de ligação entre os processos do servidor e do cliente. Ele é a “porta” na qual os processos enviam e recebem mensagens. De acordo com JAMES F KUROSE: <em>“socket é a interface entre a camada de aplicação e a de transporte dentro de uma máquina”</em>. Para quem não lembra, ou não sabe, camada de aplicação e transporte fazem parte do <a href="http://pt.wikipedia.org/wiki/Modelo_OSI" target="_blanck">modelo OSI</a>.<br />
Através de um socket podemos estabelecer a comunicação entre máquinas possibilitando o envio e recebimento de dados.</p>
<p>A interface padronizada de sockets surgiu originalmente no sistema operacional Unix BSD (Berkeley Software Distribution). Tinha a função de suporte a comunicação em rede. Esta interface é a base para a maioria das interfaces entre protocolos de internet TCP/IP existente. </p>
<p>A identificação de um socket na rede é realizada por um IP e um porta. Comumente utiliza-se portas acima de 1000 pois as inferiores são utilizadas pelo sistema operacional. Sua comunicação é realizada pelos protocolos UDP ou TCP. Assim, é possível termos tanto comunicação orientada a conexão (via TCP), quanta não orientada a conexão (via UDP). O socket abstrai esse conceito, permitindo assim a utilização de qualquer um dos meios.</p>
<p>No C# para se trabalhar com sockets os recursos enconstram-se no namespace System.Net.Sockets. </p>
<p><strong>Implementando uma aplicação com socket</strong></p>
<p>Este é um simples código de uma aplicação Client/Server utilizando socket.<br />
Abaixo o passo a passo de criação da aplicação:</p>
<p><strong>Server App</strong></p>
<ol>
<li>Criar um projeto do tipo WindowsForm com o nome CommunicationSocket.</li>
<li>Incluir um botão que será utilizado para enviar mensagem do servidor para o cliente.</li>
</ol>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Net</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Net.Sockets</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Threading</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Windows.Forms</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> CommunicationSocket
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> ServerApp <span style="color: #008000;">:</span> Form
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> Socket socket<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> Thread thread<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> NetworkStream networkStream<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> BinaryWriter binaryWriter<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> BinaryReader binaryReader<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> ServerApp<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            thread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #008000;">&#40;</span>RunServer<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            thread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> RunServer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            TcpListener tcpListener<span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">try</span>
            <span style="color: #008000;">&#123;</span>
                IPEndPoint ipEndPoint <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> IPEndPoint<span style="color: #008000;">&#40;</span>IPAddress<span style="color: #008000;">.</span><span style="color: #0000FF;">Parse</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;127.0.0.1&quot;</span><span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">2001</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                tcpListener <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TcpListener<span style="color: #008000;">&#40;</span>ipEndPoint<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                tcpListener<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Servidor habilitado e escutando porta...&quot;</span>, <span style="color: #666666;">&quot;Server App&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                socket <span style="color: #008000;">=</span> tcpListener<span style="color: #008000;">.</span><span style="color: #0000FF;">AcceptSocket</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                networkStream <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> NetworkStream<span style="color: #008000;">&#40;</span>socket<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                binaryWriter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BinaryWriter<span style="color: #008000;">&#40;</span>networkStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                binaryReader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BinaryReader<span style="color: #008000;">&#40;</span>networkStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;conexão recebida!&quot;</span>, <span style="color: #666666;">&quot;Server App&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                binaryWriter<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\n</span>conexão efetuada!&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #6666cc; font-weight: bold;">string</span> messageReceived <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF; font-weight: bold;">do</span> 
                <span style="color: #008000;">&#123;</span>
                    messageReceived <span style="color: #008000;">=</span> binaryReader<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                    MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Mensagem: &quot;</span> <span style="color: #008000;">+</span> messageReceived, <span style="color: #666666;">&quot;Server App&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #008000;">&#125;</span> <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span>socket<span style="color: #008000;">.</span><span style="color: #0000FF;">Connected</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span> 
            <span style="color: #0600FF; font-weight: bold;">catch</span> <span style="color: #008000;">&#40;</span>Exception ex<span style="color: #008000;">&#41;</span> 
            <span style="color: #008000;">&#123;</span>
                MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>ex<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span> 
            <span style="color: #0600FF; font-weight: bold;">finally</span> 
            <span style="color: #008000;">&#123;</span>
                binaryReader<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                binaryWriter<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                networkStream<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                socket<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;conexão finalizada&quot;</span>, <span style="color: #666666;">&quot;Server App&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> btnSendMsg_Click<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, EventArgs e<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">try</span>
            <span style="color: #008000;">&#123;</span>
                binaryWriter<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Server respondendo: Houston, we have a problem!!!&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0600FF; font-weight: bold;">catch</span> <span style="color: #008000;">&#40;</span>SocketException socketEx<span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>socketEx<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span>, <span style="color: #666666;">&quot;Erro&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><strong>Client App</strong></p>
<ol>
<li>Criar um projeto do tipo WindowsForm com o nome ClientApp.</li>
<li>Incluir botão que será utilizado para enviar mensagem do cliente para o servidor.</li>
</ol>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Net.Sockets</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Threading</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Windows.Forms</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ClientApplication 
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> ClientAppForm <span style="color: #008000;">:</span> Form 
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> NetworkStream networkStream<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> BinaryWriter binaryWriter<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> BinaryReader binaryReader<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> TcpClient tcpClient<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> Thread thread<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> ClientAppForm<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> 
        <span style="color: #008000;">&#123;</span>
            InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            thread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #008000;">&#40;</span>RunClient<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            thread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> RunClient<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> 
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">try</span> 
            <span style="color: #008000;">&#123;</span>
                tcpClient <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TcpClient<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                tcpClient<span style="color: #008000;">.</span><span style="color: #0000FF;">Connect</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;127.0.0.1&quot;</span>, <span style="color: #FF0000;">2001</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                networkStream <span style="color: #008000;">=</span> tcpClient<span style="color: #008000;">.</span><span style="color: #0000FF;">GetStream</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                binaryWriter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BinaryWriter<span style="color: #008000;">&#40;</span>networkStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                binaryReader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BinaryReader<span style="color: #008000;">&#40;</span>networkStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #6666cc; font-weight: bold;">String</span> message <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF; font-weight: bold;">do</span> 
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #0600FF; font-weight: bold;">try</span> 
                    <span style="color: #008000;">&#123;</span>
                        message <span style="color: #008000;">=</span> binaryReader<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                        MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>message, <span style="color: #666666;">&quot;Mensagem Recebida&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #008000;">&#125;</span> 
                    <span style="color: #0600FF; font-weight: bold;">catch</span> <span style="color: #008000;">&#40;</span>Exception ex<span style="color: #008000;">&#41;</span> 
                    <span style="color: #008000;">&#123;</span>
                        MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>ex<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span>, <span style="color: #666666;">&quot;Erro&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                        message <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;FIM&quot;</span><span style="color: #008000;">;</span>
                    <span style="color: #008000;">&#125;</span>
                <span style="color: #008000;">&#125;</span> <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span>message <span style="color: #008000;">!=</span> <span style="color: #666666;">&quot;FIM&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                binaryWriter<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                binaryReader<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                networkStream<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                tcpClient<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span> 
            <span style="color: #0600FF; font-weight: bold;">catch</span> <span style="color: #008000;">&#40;</span>Exception ex<span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>ex<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span>, <span style="color: #666666;">&quot;Erro&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> btnSendMsg_Click<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, EventArgs e<span style="color: #008000;">&#41;</span> 
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">try</span> 
            <span style="color: #008000;">&#123;</span>
                binaryWriter<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Mensagem do cliente&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span> 
            <span style="color: #0600FF; font-weight: bold;">catch</span> <span style="color: #008000;">&#40;</span>SocketException socketEx<span style="color: #008000;">&#41;</span> 
            <span style="color: #008000;">&#123;</span>
                MessageBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Show</span><span style="color: #008000;">&#40;</span>socketEx<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span>, <span style="color: #666666;">&quot;Erro&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Para realizar a comunicação o Servidor utiliza o objeto TcpListener que fica escutando toda requisição no IP &#8220;127.0.0.1&#8243; porta 2001.<br />
Na aplicação Cliente o objeto TcpClient é informado sobre o IP (ou DNS) e porta do servidor que irá se conectar. Após esse a realização toda a comunicação é feita por meio de stream através do objeto NetworkStream.</p>
<p>Repare que tanto Servidor quanto o Cliente trabalha com processamento em paralelo (Thread) para evitar que a aplicação fique travada até o término do processamento, ou para manter um processamento dedicado e contínuo que é o caso do servidor.</p>
<p>Nesse exemplo utilizei MessageBox para apresentar as mensagens, pois para inseri-las em um TextBox no Form é necessário utilizar delegates e reflections, senão teremos um erro de cruzamento de Threads (<em>Cross-thread operation not valid</em>).<br />
Mas isso acho que é assunto para o nosso próximo post.</p>
<p>Até mais <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2009/12/comunicacao-via-socket-com-c/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Extension Methods no C# 3.0</title>
		<link>http://sylverio.com.br/blog/2009/12/extension-methods-no-c-3-0/</link>
		<comments>http://sylverio.com.br/blog/2009/12/extension-methods-no-c-3-0/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 00:36:44 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Framework.NET]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=328</guid>
		<description><![CDATA[Extension Methods é uma das muitas características que torna o LINQ possível . Em resumo podemos dizer que Extension Methods é a possibilidade de inserir métodos em objetos já compilados. O método criado tem a característica de um método estático, &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2009/12/extension-methods-no-c-3-0/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><strong>Extension Methods</strong> é uma das muitas características que torna o <em>LINQ</em> possível .<br />
Em resumo podemos dizer que <em>Extension Methods</em> é a possibilidade de inserir métodos em objetos já compilados. O método criado tem a característica de um método estático, porem só está acessível ao objeto associado.<br />
Com esse recurso podemos adicionar aos .NET types novos métodos. Assim classes como  StringHelpers, Util, entre outras, com uma variedade de métodos de auxílio, podem ser inseridos diretamente no fonte.<br />
Exemplo de uma classe com validação:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text.RegularExpressions</span><span style="color: #008000;">;</span> 
<span style="color: #0600FF; font-weight: bold;">namespace</span> ExtensionMethodsExample
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Util
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;Verifica se o argumento do tipo string é um numérico&lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;arg&quot;&gt;argumento a ser validado&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;True - se for numérico&lt;/returns&gt;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> IsNumeric<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> arg<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> Regex<span style="color: #008000;">.</span><span style="color: #0000FF;">IsMatch</span><span style="color: #008000;">&#40;</span>arg, <span style="color: #666666;">@&quot;^\d+$&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Com o uso do <em>Extension Methods</em> podemos inserir o método que verifica se a variável é numérica no próprio tipo string.<br />
Abaixo um exemplo de seu uso, e depois vou explicar como o <em>extension methods</em> é declarado.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text.RegularExpressions</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ExtensionMethodsExample
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">class</span> Extensions
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">bool</span> IsNumeric<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #6666cc; font-weight: bold;">string</span> arg<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
             <span style="color: #0600FF; font-weight: bold;">return</span> Regex<span style="color: #008000;">.</span><span style="color: #0000FF;">IsMatch</span><span style="color: #008000;">&#40;</span>arg, <span style="color: #666666;">@&quot;^\d+$&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span> 
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">string</span> codigo1 <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;1234&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #6666cc; font-weight: bold;">string</span> codigo2 <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;ABCD&quot;</span><span style="color: #008000;">;</span>
&nbsp;
        Imprime<span style="color: #008000;">&#40;</span>codigo1<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        Imprime<span style="color: #008000;">&#40;</span>codigo2<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Imprime<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> codigo<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>codigo<span style="color: #008000;">.</span><span style="color: #0000FF;">IsNumeric</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Codigo numerico: {0}&quot;</span>, codigo<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">else</span>
        <span style="color: #008000;">&#123;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Codigo alphanumerico: {0}&quot;</span>, codigo<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Para criarmos um <em>extension methods</em> precisamos de uma classe e método estático. Todo método extension sempre terá seu primeiro parâmetro a palavra reservada this, seguido do tipo ao qual o método será inserido, no exemplo o tipo string. Esse parâmetro representa a própria instância do objeto. Para os parâmetros subseqüentes serão utilizados na chamada do método. O nome da classe é de livre escolha, ela não interfere na implementação do extension methods, a única ressalva é que seja uma classe estática.</p>
<p>Compare a diferença da verificação de condição utilizando a classe Util e o extension methods</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">Util util <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Util<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>util<span style="color: #008000;">.</span><span style="color: #0000FF;">IsNumeric</span><span style="color: #008000;">&#40;</span>codigo<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// faz algo</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>e</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>codigo<span style="color: #008000;">.</span><span style="color: #0000FF;">IsNumeric</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// faz algo</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>O código torna-se mais legível e mais implícito seus métodos, tornando a linguagem muito mais dinâmica.<br />
Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2009/12/extension-methods-no-c-3-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

