<?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>Diário de Códigos &#187; C# Dicas</title>
	<atom:link href="http://diariodecodigos.info/category/net/c-dicas/feed/" rel="self" type="application/rss+xml" />
	<link>http://diariodecodigos.info</link>
	<description>Codigos Fonte, Artigos e Dicas</description>
	<lastBuildDate>Tue, 03 May 2011 17:42:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Restaurar banco do MySQL em C# (2/2)</title>
		<link>http://diariodecodigos.info/2009/10/restaurar-banco-do-mysql-em-c/</link>
		<comments>http://diariodecodigos.info/2009/10/restaurar-banco-do-mysql-em-c/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 10:59:10 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=640</guid>
		<description><![CDATA[Process.Start(&#34;cmd.exe&#34;, &#34;/c /*CAMINHO DO MYSQL.EXE*/ + &#34; -u/*usuario*/ -p/*senha*/ /*banco*/ &#60; &#34;+/*CAMINHO DO ARQUIVO .SQL*/); Para fazer backup já fiz aqui. Simples assim.]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.4linux.com.br/files/imagecache/pic-02/cursos/images/imagem-412.jpg" alt="MySql" /></p>
<pre class="brush: csharp;">
Process.Start(&quot;cmd.exe&quot;, &quot;/c /*CAMINHO DO MYSQL.EXE*/ +
                          &quot; -u/*usuario*/ -p/*senha*/ /*banco*/ &lt; &quot;+/*CAMINHO DO ARQUIVO .SQL*/);</pre>
<p><span id="more-640"></span></p>
<p>Para fazer backup já fiz <a href="http://diariodecodigos.info/2009/09/fazendo-backup-do-mysql-com-c/">aqui</a>.</p>
<p>Simples assim.</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/10/restaurar-banco-do-mysql-em-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converter List para DataSet</title>
		<link>http://diariodecodigos.info/2009/09/converter-list-para-dataset/</link>
		<comments>http://diariodecodigos.info/2009/09/converter-list-para-dataset/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 14:23:47 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[Tecnicas de Programação]]></category>
		<category><![CDATA[Converter]]></category>
		<category><![CDATA[DataSet]]></category>
		<category><![CDATA[IList]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=457</guid>
		<description><![CDATA[Opa! olha eu ai novamente =D, tentando passar algo de (INUTIL) UTIL pra vocês. Hoje vou mostrar como converter uma List para DataSet, é Super Simples, vamos lá: public static class ListConvertor { public static DataSet ConvertToDataSet&#60;T&#62;(IList list) { DataSet dataSet = new DataSet(); CreateDataSet(dataSet, typeof(T), false); FillDataSet(typeof(T), list, dataSet, -1); CreateRelations(dataSet, typeof(T), null); return]]></description>
			<content:encoded><![CDATA[<p><img src="http://diariodecodigos.info/wp-content/uploads/2009/08/C.gif" alt="" /></p>
<p>Opa! olha eu ai novamente =D, tentando passar algo de <span style="text-decoration: line-through;">(INUTIL</span>) UTIL pra vocês.</p>
<p><span id="more-457"></span></p>
<p>Hoje vou mostrar como converter uma List para DataSet, é Super Simples, vamos lá:</p>
<pre class="brush: csharp;">

public static class ListConvertor
 {
 public static DataSet ConvertToDataSet&lt;T&gt;(IList list)
 {
 DataSet dataSet = new DataSet();

 CreateDataSet(dataSet, typeof(T), false);
 FillDataSet(typeof(T), list, dataSet, -1);
 CreateRelations(dataSet, typeof(T), null);

 return dataSet;
 }

 ///
 /// Create the structure for all the tables in the data set
 ///
 /// Data set in which tables will be created
 /// Type of which dataset has to be created
 /// Whether current type is a child table
 private static void CreateDataSet(DataSet dataSet, Type type, bool isChildTable)
 {
 DataTable dataTable = new DataTable(type.Name);

 //Create the ID columns for having relation in the tables
 dataTable.Columns.Add(new DataColumn(&quot;ID2&quot;, typeof(int)));
 if (isChildTable)
 {
 dataTable.Columns.Add(new DataColumn(&quot;ParentID2&quot;, typeof(int)));
 }

 // Create the structure for the data tables to be
 // added in the the data set
 foreach (PropertyInfo pInfo in type.GetProperties())
 {
 if (pInfo.PropertyType.IsGenericType &amp;&amp;
 (pInfo.PropertyType.GetGenericTypeDefinition() == typeof(List&lt;&gt;)
 || pInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList&lt;&gt;)))
 {
 // If associate lists are there make then another table
 CreateDataSet(dataSet,pInfo.PropertyType.GetGenericArguments()[0],true);
 }
 else
 {
 dataTable.Columns.Add(new DataColumn(pInfo.Name, pInfo.PropertyType));
 }
 }

 //Add the table to the dataset
 dataSet.Tables.Add(dataTable);
 }

 ///
 /// Fill all the tables of data set with data in the respective list
 ///
 /// Type of which datatable is to be filled
 /// List of data
 /// Data Set in which data tables will be filled with data
 /// ID of parent record. If -1 one then no parent
 private static void FillDataSet(Type type, IList list, DataSet dataSet, int parentID)
 {
 PropertyInfo[] propertyInfos = type.GetProperties();
 DataTable dataTable = dataSet.Tables[type.Name];
 int id = dataTable.Rows.Count + 1;

 foreach (object item in list)
 {
 DataRow row = dataTable.NewRow();

 // Set new id and related parent id
 row[&quot;ID&quot;] = id;
 if (parentID != -1)
 row[&quot;ParentID&quot;] = parentID;

 // Load all the data from the properties of the type
 // and save them into the datatable
 foreach (PropertyInfo info in propertyInfos)
 {
 if (info.PropertyType.IsGenericType &amp;&amp;
 (info.PropertyType.GetGenericTypeDefinition() == typeof(List&lt;&gt;)
 || info.PropertyType.GetGenericTypeDefinition() == typeof(IList&lt;&gt;)))
 {
 IList subList = (IList)info.GetValue(item, null);
 if (subList != null &amp;&amp; subList.Count &gt; 0)
 {
 FillDataSet(subList[0].GetType(),
 subList,
 dataSet, id);
 }
 }
 else
 {
 row[info.Name] = info.GetValue(item, null);
 }
 }

 dataTable.Rows.Add(row);
 id++;
 }
 }

 ///
 /// Creates the relation between the tables according to the
 /// type and parent table on field ID and ParentID
 ///
 /// Data set containing parent and child table
 /// Type of the list
 /// Parent table to which relations has to be done
 private static void CreateRelations(DataSet dataSet, Type type, DataTable parentTable)
 {
 DataTable dataTable = dataSet.Tables[type.Name];

 // If parent table exsits then create relation
 // with child table on field Parent ID
 if (parentTable != null)
 {
 dataSet.Relations.Add(
 new DataRelation(parentTable.TableName + &quot;_ID_&quot;
 + &quot;PARENTID_&quot; + dataTable.TableName,
 parentTable.Columns[&quot;ID&quot;],
 dataTable.Columns[&quot;ParentID&quot;]));
 }

 // Check for other lists under current object
 // go for another relation if exists
 foreach (PropertyInfo pInfo in type.GetProperties())
 {
 if (pInfo.PropertyType.IsGenericType &amp;&amp;
 (pInfo.PropertyType.GetGenericTypeDefinition() == typeof(List&lt;&gt;)
 || pInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList&lt;&gt;)))
 {
 // If associate lists are there make then another table
 CreateRelations(dataSet,pInfo.PropertyType.GetGenericArguments()[0],dataTable);
 }
 }
 }
 }
</pre>
<p>Vamos para as explicações:</p>
<pre class="brush: csharp;">

ArrayList sequence = new ArrayList();
 IList list = (IList)sequence;
 DataSet ds = ListConvertor.ConvertToDataSet&lt;LancamentosDetalhado&gt;(list);
</pre>
<p>Como nos queremos passar uma List para DataSet, vamos forçar um ArrayList ser uma lista, já que ele extend de IList, estamos fazendo isso com o cast (IList), logo após aplicamos o metodo STATIC, <strong>ListConvertor.ConvertToDataSet&lt;LancamentosDetalhado&gt;(list);,</strong></p>
<p>pois a assinatura do metodo esta como static, logo só pode ser chamado a partir da classe.</p>
<p>Simples assim.</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/09/converter-list-para-dataset/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fazendo backup do MySql com C# (1/2)</title>
		<link>http://diariodecodigos.info/2009/09/fazendo-backup-do-mysql-com-c/</link>
		<comments>http://diariodecodigos.info/2009/09/fazendo-backup-do-mysql-com-c/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 14:23:18 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=441</guid>
		<description><![CDATA[Agora vamos ver um método prático e sagaz de se fazer um backup em código do banco de dados. try { Process.Start(&#34;CAMINHO DO MYSQL NA SUA MAQUINA/bin/mysqldump.exe&#34;, &#34;-u USER --password=SENHA -B BANCO &#62; -r &#34; + arq).WaitForExit(5000); if (File.Exists(arq)) return true; else return false; } catch { throw new Exception(&#34;Backup não pode ser realizado nessa]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone" src="../wp-content/uploads/2009/08/C.gif" alt="" /></p>
<p>Agora vamos ver um método prático e sagaz de se fazer um backup em código do banco de dados.</p>
<p><span id="more-441"></span></p>
<pre class="brush: csharp;">
try
 {
 Process.Start(&quot;CAMINHO DO MYSQL NA SUA MAQUINA/bin/mysqldump.exe&quot;,
 &quot;-u USER --password=SENHA -B BANCO  &gt; -r &quot; + arq).WaitForExit(5000);
 if (File.Exists(arq))
 return true;
 else
 return false;
 }
 catch
 {
 throw new Exception(&quot;Backup não pode ser realizado nessa maquina.&quot;);
 }
</pre>
<p>Util pra mim&#8230; não sei pra vocês&#8230;</p>
<p>Simples Assim.</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/09/fazendo-backup-do-mysql-com-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Pegar endereço a partir de CEP</title>
		<link>http://diariodecodigos.info/2009/09/pegar-endereco-a-partir-de-cep/</link>
		<comments>http://diariodecodigos.info/2009/09/pegar-endereco-a-partir-de-cep/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 14:18:43 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=439</guid>
		<description><![CDATA[Depois de 2 semanas sem postar nada voltei =D Hoje vamos ver como pegar um endereço a partir de um cep&#8230; e ajudar os usuários. public String[] pegaEnderecoPeloCEP(String cep) { String[] aux = { &#34;&#34;, &#34;&#34;, &#34;&#34;, &#34;&#34;, &#34;&#34; }; aux[4] = &#34;Não foi encontrado um resultado&#34;; if (cepExiste(cep)) { string urlSite = string.Format( @&#34;http://www.buscarcep.com.br/?cep={0}&#38;amp;formato=xml&#34;]]></description>
			<content:encoded><![CDATA[<p><img src="http://diariodecodigos.info/wp-content/uploads/2009/08/C.gif" alt="C#" /></p>
<p>Depois de 2 semanas sem postar nada voltei =D</p>
<p><span id="more-439"></span></p>
<p>Hoje vamos ver como pegar um endereço a partir de um cep&#8230; e ajudar os usuários.</p>
<pre class="brush: csharp;">

public String[] pegaEnderecoPeloCEP(String cep)
 {
 String[] aux = { &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot; };
 aux[4] = &quot;Não foi encontrado um resultado&quot;;
 if (cepExiste(cep))
 {
 string urlSite = string.Format(
 @&quot;http://www.buscarcep.com.br/?cep={0}&amp;amp;formato=xml&quot;
 , cep);

 // Variavel para ler o XML.
 XmlTextReader lerXML = new XmlTextReader(urlSite);

 // Strins que vão receber o nó e o valor do XML
 string sNode;
 string sValue;
 // Retorno da ação da busca
 string sResultado = &quot;&quot;;

 // Verifica se o nó atual é um conteúdo de nó.
 lerXML.MoveToContent();

 do
 {
 sNode = lerXML.Name;
 if (lerXML.NodeType == XmlNodeType.Element)
 {
 lerXML.Read();
 sValue = lerXML.Value;
 // Recebe o nome do campo strTempName
 switch (sNode)
 {
 case &quot;tipo_logradouro&quot;:
 aux[0] = sValue + &quot; &quot;;
 break;
 // pega o logradouro
 case &quot;logradouro&quot;:
 //atribui valor ao componente
 aux[0] += sValue;
 break;
 // pega o bairro
 case &quot;bairro&quot;:
 //atribui valor ao componente
 aux[1] = sValue;
 break;
 // pega a cidade
 case &quot;cidade&quot;:
 //atribui valor ao componente
 aux[2] = sValue;
 break;
 // pega o uf
 case &quot;uf&quot;:
 //atribui valor ao componente
 aux[3] = sValue;
 break;
 // pega o resultado
 case &quot;resultado&quot;:
 //atribui valor a string que será tratada
 sResultado = sValue;
 break;
 }

 // Aqui damos um tratamento no resultado
 switch (sResultado)
 {
 // esses valores são retornos possiveis do site BuscaCEP
 case &quot;1&quot;:
 aux[4] = &quot;Cep encontrado!&quot;;
 break;
 case &quot;-1&quot;:
 aux[4] = &quot;Cep não encontrado!&quot;;
 break;
 case &quot;-2&quot;:
 aux[4] = &quot;Formato de CEP inválido&quot;;
 break;
 case &quot;-3&quot;:
 aux[4] = @&quot;Busca de CEP congestionada.
 Aguarde alguns segundos e tente novamente.&quot;;
 break;
 case &quot;&quot;:
 aux[4] = &quot;Não foi encontrado um resultado&quot;;
 break;
 }
 }
 } while (lerXML.Read()); // ate chegar no final do XML faça!
 return aux;
 }

 return aux;
 }
</pre>
<p>qualquer duvida me pergunte =D muito facil usar isso ai&#8230;</p>
<p>Simples assim.</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/09/pegar-endereco-a-partir-de-cep/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Colocar preço em formato Moeda</title>
		<link>http://diariodecodigos.info/2009/08/colocar-preco-em-formato-moeda/</link>
		<comments>http://diariodecodigos.info/2009/08/colocar-preco-em-formato-moeda/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 11:07:11 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[preco]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=346</guid>
		<description><![CDATA[Bom as vezes me deparo com a seguinte situação&#8230; Tenho um valor em Decimal só que na hora de formata-lo pra ele ficar bonitinho no text box eu faço um monte de coisa, descobri uma coisa muito util: Eu tenho uma variável Decimal aux = 1.9; Console.WriteLine(aux); Console.WriteLine(String.Format(&#34;{0:C}&#34;, v_uni)); A saida vai ser: 1.9 R$]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img src="http://www.shopcart.site50.net/post_122_.png" alt="Imagem" /></p>
<p><span id="more-346"></span></p>
<p>Bom as vezes me deparo com a seguinte situação&#8230;</p>
<p>Tenho um valor em Decimal só que na hora de formata-lo pra ele ficar bonitinho no text box eu faço um monte de coisa, descobri uma coisa muito util:<br />
Eu tenho uma variável</p>
<pre class="brush: csharp;">
    Decimal aux = 1.9;
   Console.WriteLine(aux);
   Console.WriteLine(String.Format(&quot;{0:C}&quot;, v_uni));
</pre>
<p>A saida vai ser:</p>
<p>1.9<br />
R$ 1,90</p>
<p>Simples assim =D</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/08/colocar-preco-em-formato-moeda/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Passando Form por Parâmetro</title>
		<link>http://diariodecodigos.info/2009/07/passando-form-por-parametro/</link>
		<comments>http://diariodecodigos.info/2009/07/passando-form-por-parametro/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 12:01:29 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[parametro]]></category>
		<category><![CDATA[referencia]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=264</guid>
		<description><![CDATA[Bem rápido esse Post&#8230; passando um form por parâmetros para, com o propósito de mudar algum valor por meio de outro form&#8230; no meu exemplo eu estava fazendo um form para travar maquinas no Laboratório que administro aqui no trabalho&#8230; Vamos para os códigos: 1º vamos declarar uma variável privada do mesmo tipo do form]]></description>
			<content:encoded><![CDATA[<p>Bem rápido esse Post&#8230; passando um form por parâmetros para, com o propósito de mudar algum valor por meio de outro form&#8230; no meu exemplo eu estava fazendo um form para travar maquinas no Laboratório que administro aqui no trabalho&#8230; Vamos para os <em><strong>códigos</strong></em>:</p>
<p><span id="more-264"></span></p>
<p>1º vamos declarar uma variável privada do mesmo tipo do form que queremos modificar&#8230;</p>
<pre class="brush: csharp;">
private frmMaquinas form;
</pre>
<p>2º Declaramos um Construtor com um parâmetro do tipo do nosso form<br />
vejam que é o 1º parâmetro do nosso construtor</p>
<pre class="brush: csharp;">
public frmFaixa(frmMaquinas fm, String etd, Color cr)
        {
            InitializeComponent();
            this.form = fm;
            this.estado = etd;
            this.cor = cr;
        }
</pre>
<p>3ºUsamos um método se tiver no nosso form para modifica-lo</p>
<pre class="brush: csharp;">
this.form.liberarPorIntervalo(this.estado,this.cor,
                Convert.ToInt32(this.numericUpDown1.Value),
                Convert.ToInt32(this.numericUpDown2.Value));
</pre>
<p>Se não tiver um método o que podemos fazer&#8230; podemos modificar as variáveis que o nosso form tem, Propriedades etc..</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/07/passando-form-por-parametro/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Preço com tamanho certo</title>
		<link>http://diariodecodigos.info/2009/07/preco-com-tamanho-certo/</link>
		<comments>http://diariodecodigos.info/2009/07/preco-com-tamanho-certo/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 11:27:00 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[preco]]></category>

		<guid isPermaLink="false">http://diariodecodigos.wordpress.com/2009/07/13/preco-com-tamanho-certo/</guid>
		<description><![CDATA[As vezes você tem em alguma parte do seu codigo um preço, mas ele teima em aparecer, 1,9&#8230; 12 sem o zero no final&#8230; este metodo vai ta ajudar =D private String concatenarPreco(String preco) { String pr = preco; if (!pr.Contains(',')) { pr += &#34;,00&#34;; } else { String[] prc = pr.Split(','); if (prc[1].Length &#60;]]></description>
			<content:encoded><![CDATA[<p>As vezes você tem em alguma parte do seu codigo um preço, mas ele teima em aparecer, 1,9&#8230; 12 sem o zero no final&#8230; este metodo vai ta ajudar =D</p>
<p><span id="more-27"></span></p>
<pre class="brush: csharp;">
private String concatenarPreco(String preco)
{
String pr = preco;
if (!pr.Contains(','))
{
pr += &quot;,00&quot;;
}
else
{
String[] prc = pr.Split(',');
if (prc[1].Length &lt; 2)
{
pr += &quot;0&quot;;
}
}

return pr;
}
</pre>
<p>PS: NÃO Existe só essa forma de se fazer isso, eu faço assim&#8230; existem 1 bilhão de formas de fazer esse mesmo caso&#8230; menores, maiores, mais bonitas, mais feias, mais inteligentes, menos inteligentes&#8230;<br />
<span><br />
=D<br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/07/preco-com-tamanho-certo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gerar comprovante em Impressora Matricial</title>
		<link>http://diariodecodigos.info/2009/07/gerar-comprovante-em-impressora-matricial/</link>
		<comments>http://diariodecodigos.info/2009/07/gerar-comprovante-em-impressora-matricial/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 14:35:00 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Impressão]]></category>
		<category><![CDATA[matricial]]></category>

		<guid isPermaLink="false">http://diariodecodigos.wordpress.com/2009/07/02/gerar-comprovante-em-impressora-matricial/</guid>
		<description><![CDATA[Levei um tempao resolvendo um problema idiota bem pequeno, consegui fazer&#8230; muito util&#8230; Baixe a DLL 1º eu criei uma classe pra fazer o serviço de impressão, hehehe SRP a seguir o codigo do metodo: public String gerarComprovante() { try { //quem vai imprimir MatrixReporter.Reporter mr = new MatrixReporter.Reporter(); //quem vai colocar em italico e]]></description>
			<content:encoded><![CDATA[<p>Levei um tempao resolvendo um problema <span style="text-decoration: line-through;">idiota</span> bem pequeno, consegui fazer&#8230; muito util&#8230;</p>
<p><span id="more-19"></span></p>
<p><a href="http://www.codigofonte.net/scripts-1384/matrixreporter-for-net" target="_blank">Baixe a DLL 1º</a></p>
<p>eu criei uma classe pra fazer o serviço de impressão, hehehe <span style="text-decoration: line-through;">SRP</span></p>
<p>a seguir o codigo do metodo:</p>
<pre class="brush: csharp;">public String gerarComprovante()
        {
            try
            {
                //quem vai imprimir
                MatrixReporter.Reporter mr = new MatrixReporter.Reporter();
                //quem vai colocar em italico e talz
                MatrixReporter.EpsonCodes me = new MatrixReporter.EpsonCodes();

                if (File.Exists(local))
                {
                    File.Delete(local);
                }

                mr.Output = local;

                mr.StartJob();
                mr.PrintText(01, 01, &quot;========================================&quot;);
                //o \n serve como paper feed na impressora...
                mr.PrintText(02, 01, &quot;========================================\n&quot;);

                mr.EndJob();
                //numero de copias
                mr.Copies = 2;

                mr.PrintJob();

                return &quot;OK&quot;;

            }
            catch (Exception ex)
            {
               return &quot;Erro no banco: &quot; + ex.Message;
            }

        }</pre>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/07/gerar-comprovante-em-impressora-matricial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reescrever App.config em tempo de execução!</title>
		<link>http://diariodecodigos.info/2009/06/reescrever-app-config-em-tempo-de-execucao/</link>
		<comments>http://diariodecodigos.info/2009/06/reescrever-app-config-em-tempo-de-execucao/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 18:50:00 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[App.config]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://diariodecodigos.wordpress.com/2009/06/25/reescrever-app-config-em-tempo-de-execucao/</guid>
		<description><![CDATA[1º fazer a classe AppConfig.cs public enum ConfigFileType { WebConfig , AppConfig } &#60;span id=&#34;more-17&#34;&#62;&#60;/span&#62; public class AppConfig : System.Configuration.AppSettingsReader { public string docName = String.Empty; private XmlNode node=null; private int _configType; public int ConfigType { get { return _configType; } set { _configType=value; } } public bool SetValue(string key, string value) { XmlDocument cfgDoc]]></description>
			<content:encoded><![CDATA[<p>1º fazer a classe AppConfig.cs</p>
<pre class="brush: csharp;">public enum   ConfigFileType
{
 WebConfig ,
 AppConfig
}

&lt;span id=&quot;more-17&quot;&gt;&lt;/span&gt;

public class AppConfig : System.Configuration.AppSettingsReader
{
 public string  docName = String.Empty;
 private  XmlNode node=null;
    private int _configType;

 public   int ConfigType
 {
  get
  {
   return _configType;
  }
  set
  {
   _configType=value;
  }
 }

 public bool SetValue(string key, string value)
 {
  XmlDocument cfgDoc = new XmlDocument();
  loadConfigDoc(cfgDoc);
   // retrieve the appSettings node
        node = cfgDoc.SelectSingleNode(&amp;quot;//connectionStrings&amp;quot;);

   if( node == null )
   {
                throw new System.InvalidOperationException(&amp;quot;connectionStrings section not found&amp;quot;);
   }

  try
  {
   // XPath select setting &amp;quot;add&amp;quot; element that contains this key
   XmlElement addElem= (XmlElement)node.SelectSingleNode(&amp;quot;//add[@name='&amp;quot; +key +&amp;quot;']&amp;quot;) ;
   if (addElem!=null)
   {
    addElem.SetAttribute(&amp;quot;value&amp;quot;,value);
   }
    // not found, so we need to add the element, key and value
   else
   {
    XmlElement entry = cfgDoc.CreateElement(&amp;quot;add&amp;quot;);
    entry.SetAttribute(&amp;quot;name&amp;quot;,key);
                entry.SetAttribute(&amp;quot;connectionString&amp;quot;, value);
    node.AppendChild(entry);
   }
   //save it
   saveConfigDoc(cfgDoc,docName);
   return true;
  }
  catch
  {
   return false;
  }
 }

 private void saveConfigDoc(XmlDocument cfgDoc,string cfgDocPath)
 {
  try
  {
   XmlTextWriter writer = new XmlTextWriter( cfgDocPath , null );
   writer.Formatting = Formatting.Indented;
   cfgDoc.WriteTo( writer );
   writer.Flush();
   writer.Close();
   return;
  }
  catch
  {
   throw;
  }
 }

 public bool removeElement ( string elementKey)
 {
  try
  {
   XmlDocument cfgDoc = new XmlDocument();
   loadConfigDoc(cfgDoc);
   // retrieve the appSettings node
            node = cfgDoc.SelectSingleNode(&amp;quot;//connectionStrings&amp;quot;);
   if( node == null )
   {
                throw new System.InvalidOperationException(&amp;quot;connectionStrings section not found&amp;quot;);
   }
   // XPath select setting &amp;quot;add&amp;quot; element that contains this key to remove
   node.RemoveChild( node.SelectSingleNode(&amp;quot;//add[@name='&amp;quot; +elementKey +&amp;quot;']&amp;quot;) );

   saveConfigDoc(cfgDoc,docName);
   return true;
  }
  catch
  {
   return false;
  }
 }

 private XmlDocument loadConfigDoc( XmlDocument cfgDoc )
 {
  // load the config file
        Console.WriteLine(Convert.ToInt32(ConfigFileType.AppConfig)+&amp;quot;___&amp;quot;+Convert.ToInt32(ConfigType));

  if(  Convert.ToInt32(ConfigType)==0)
  {

   docName= ((Assembly.GetEntryAssembly()).GetName()).Name;
   docName +=   &amp;quot;.exe.config&amp;quot;;
  }
  else
  {
   docName=System.Web.HttpContext.Current.Server.MapPath(&amp;quot;web.config&amp;quot;);
  }
  cfgDoc.Load( docName );
  return cfgDoc;
 }

}</pre>
<p>2º Na hora de usar</p>
<pre class="brush: csharp;">
AppConfig config = new AppConfig();
            config.removeElement(&quot;localhostcs&quot;);
            config.SetValue(&quot;QUAL KEY QUER MUDAR?&quot;, &quot;O QUE QUER ADD?&quot;);</pre>
<p>ps. o codigo da classe Appconfig.cs esta pronto para mudar a connectio string<br />
portanto prestar atenção na hora de mudar&#8230; mude para aquilo que vc quer mudar no seu app.config =D</p>
<p>flw</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/06/reescrever-app-config-em-tempo-de-execucao/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Concatenar String de preço (simples)</title>
		<link>http://diariodecodigos.info/2009/06/concatenar-string-de-preco-simples/</link>
		<comments>http://diariodecodigos.info/2009/06/concatenar-string-de-preco-simples/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 18:55:00 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Dicas]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[preco]]></category>

		<guid isPermaLink="false">http://diariodecodigos.wordpress.com/2009/06/24/concatenar-string-de-preco-simples/</guid>
		<description><![CDATA[private String concatenarPreco(String preco) { String pr = preco; if (pr.Length == 1 &#124;&#124; pr.Length == 2) { pr += &#38;quot;,00&#38;quot;; } else if (pr.Length == 3) { pr += &#38;quot;0&#38;quot;; } &#60;span id=&#34;more-14&#34;&#62;&#60;/span&#62; return pr; }]]></description>
			<content:encoded><![CDATA[<pre class="brush: csharp;">private String concatenarPreco(String preco)
        {
            String pr = preco;
            if (pr.Length == 1 || pr.Length == 2)
            {
                pr += &amp;quot;,00&amp;quot;;
            }
            else
                if (pr.Length == 3)
                {
                    pr += &amp;quot;0&amp;quot;;
                }

&lt;span id=&quot;more-14&quot;&gt;&lt;/span&gt;

            return pr;
        }</pre>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/06/concatenar-string-de-preco-simples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

