<?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; Tecnicas de Programação</title>
	<atom:link href="http://diariodecodigos.info/category/tecnicas-de-programacao/feed/" rel="self" type="application/rss+xml" />
	<link>http://diariodecodigos.info</link>
	<description>Codigos Fonte, Artigos e Dicas</description>
	<lastBuildDate>Wed, 11 Apr 2012 18:56:43 +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>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>1</slash:comments>
		</item>
		<item>
		<title>Try ,Catch e Finally</title>
		<link>http://diariodecodigos.info/2009/07/try-catch-e-finally/</link>
		<comments>http://diariodecodigos.info/2009/07/try-catch-e-finally/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 12:00:21 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[C# Linguagem]]></category>
		<category><![CDATA[Tecnicas de Programação]]></category>
		<category><![CDATA[Catch e Finally]]></category>
		<category><![CDATA[Tecnicas]]></category>
		<category><![CDATA[Try]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=262</guid>
		<description><![CDATA[Try ,Catch e Finally são nossos amigos&#8230; de todos os dias, dias de luta contra os catastróficos erro de RunTime e outros&#8230; eu os odeio&#8230; não por serem inúteis mas sim por parecer que nossas aplicações estão um tanto quanto mal feitas, por isso usa-las. try { return new SubSonic.Select(&#34;nome&#34;).From(&#34;clientes&#34;) .WhereExpression(&#34;nome&#34;).Like(&#34;%&#34;+nm+&#34;%&#34;) .ExecuteAsCollection&#60;ClienteCollection&#62;(); }catch(SubSonic.SqlQueryException ex) {]]></description>
			<content:encoded><![CDATA[<p>Try ,Catch e Finally são nossos amigos&#8230; de todos os dias, dias de luta contra os catastróficos erro de RunTime e outros&#8230; eu os odeio&#8230; não por serem inúteis mas sim por parecer que nossas aplicações estão um tanto quanto mal feitas, por isso usa-las.</p>
<p><span id="more-262"></span></p>
<pre class="brush: csharp;">
try
            {
            return new SubSonic.Select(&quot;nome&quot;).From(&quot;clientes&quot;)
                .WhereExpression(&quot;nome&quot;).Like(&quot;%&quot;+nm+&quot;%&quot;)
                .ExecuteAsCollection&lt;ClienteCollection&gt;();
             }catch(SubSonic.SqlQueryException ex)
            {
                throw new SubSonic.SqlQueryException(ex.ToString());
            }finally{
 Connection().Close();
}
</pre>
<p>1º o try ele vai fazer o que está la dentro<br />
2º se houver algum erro ele captura com o catch<br />
3º independente se houver erro ou não ele executa o que esta no finally</p>
<p>Lógico que podemos colocar algo mais gostoso e complexo ai, mas não é o que estamos tentando abordar neste post&#8230; =P</p>
<p>Simples Assim&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/07/try-catch-e-finally/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Patterns: Flyweight</title>
		<link>http://diariodecodigos.info/2009/07/patterns-flyweight/</link>
		<comments>http://diariodecodigos.info/2009/07/patterns-flyweight/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 19:08:42 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[flyweight]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://diariodecodigos.info/?p=208</guid>
		<description><![CDATA[Em foco hoje o padrão Flyweight: Classificação segundo GoF: Estrutural de Objeto Propósito: Usa compartilhamento para dar suporte a grandes quantidades de objetos, de granularidade fina, eficientemente. Para evitar o overhead associado com o uso de milhares de instâncias, queremos criar um pool de instâncias reutilizávuma nova instância tivesse sido criada para cada uso. Sabe]]></description>
			<content:encoded><![CDATA[<p>Em foco hoje o padrão Flyweight:</p>
<p>Classificação segundo GoF:<br />
Estrutural de Objeto</p>
<p>Propósito:<br />
Usa compartilhamento para dar suporte a grandes quantidades de objetos, de granularidade fina, eficientemente.</p>
<p><span id="more-208"></span></p>
<p>Para evitar o overhead associado com o uso de milhares de instâncias, queremos criar um pool de instâncias reutilizávuma nova instância tivesse sido criada para cada uso.<br />
<img src="http://www.dofactory.com/Patterns/Diagrams/flyweight.gif" alt="Flyweight" /></p>
<p>Sabe quando vc tem akele monte de objetos iguais, que vc usa e precisa toda hora instanciar, ou tem um monte de objetos iguais. ex.: um editor de textos. EX.:</p>
<p><img src="http://shopcart.site50.net/fly_varias_inst.JPG" alt="Flyweight" /></p>
<p>com esse padrão vc faz um pool que guarda as instancias e retorna a referencia do mesmo para ser usado, no caso da casa só é preciso de um triangulo um quadrado e um losango&#8230; que são reusados&#8230;</p>
<p><img src="http://shopcart.site50.net/fly_fly.JPG" alt="Flyweight" /></p>
<p>Facil assim&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/07/patterns-flyweight/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Template Method e Factoy Method</title>
		<link>http://diariodecodigos.info/2009/07/template-method-e-factoy-method/</link>
		<comments>http://diariodecodigos.info/2009/07/template-method-e-factoy-method/#comments</comments>
		<pubDate>Fri, 10 Jul 2009 14:11:00 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[Design Pattern]]></category>

		<guid isPermaLink="false">http://diariodecodigos.wordpress.com/2009/07/10/template-method-e-factoy-method/</guid>
		<description><![CDATA[Bom estava eu na aula de PDS ano passado e vi um padrao que sabia q ia usar logo de cara, porque? ele reduz codigo! e deixa o codigo bonito e OO. ehhehe o Design Pattern Template Method e Factoy Method são muito uteis pois tiram codigos inuteis da sua classe concreta e centraliza tudo]]></description>
			<content:encoded><![CDATA[<p>Bom estava eu na aula de PDS ano passado e vi um padrao que sabia q ia usar logo de cara, porque? ele reduz codigo! e deixa o codigo bonito e OO. ehhehe</p>
<p><span id="more-24"></span></p>
<p>o Design Pattern Template Method e Factoy Method são muito uteis pois tiram codigos inuteis da sua classe concreta e centraliza tudo em uma classe abstrata&#8230; ou seja seu codigo vai ficar limpo e lindo&#8230; OO =D SRP</p>
<p>Pra que serve?</p>
<p>O themplete method como o nome diz é um methodo que vc ia ter q fazer nas sub classes e teria que reescrevelo em todas as subclasses, igual em todas elas, mudando apenas uma regiao&#8230; o template method ajuda nesse ponto, pois se vc escrever o methodo na classe abstrata ele vai ser herdado pelas subclasses logo vc vai ter q modificar apenas akele pequeno fragmento de codigo que cada classe faz diferente&#8230;</p>
<p>1º Faça o seu templete method&#8230;</p>
<pre class="brush: java;">public Algarism getAlgarism(int code){
  if(code9){
   throw new IllegalArgumentException(&quot;Só pode estar entre 0 e 9 tolinho...&quot;);
  }else{
   if (this.algarismos[code]!=null){
    return this.algarismos[code];
   }else{
    Algarism alg = this.create(code);

    if (alg == null)
     throw new NullPointerException(&quot;Algarismo esta nulo...&quot;);

    this.algarismos[code]=alg;
    return this.algarismos[code];
   }
  }
 }</pre>
<p>veja q temos uma abstração Algarism que recebe um this.crate(code&gt;); esse vai ser o nosso metodo que muda nas subclasses, logo teremos que crialo como abstrato, para que seja forçada a criação dele nas subclasses...</p>
<pre class="brush: java;">protected abstract Algarism create(int code);</pre>
<p>2º pronto agora vamos nas subclasses e apenas criamos o metodo create... que é o nosso Factoy Method:</p>
<pre class="brush: java;">protected Algarism create(int code){
  return new SymbolAlgarism(code);
 }</pre>
<pre class="brush: java;"> protected Algarism create(int code){
  return new TextAlgarism(code);
 }</pre>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/07/template-method-e-factoy-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singleton em C#</title>
		<link>http://diariodecodigos.info/2009/06/singleton-em-c/</link>
		<comments>http://diariodecodigos.info/2009/06/singleton-em-c/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 11:43:00 +0000</pubDate>
		<dc:creator>paulodiogo</dc:creator>
				<category><![CDATA[Design Pattern]]></category>

		<guid isPermaLink="false">http://diariodecodigos.wordpress.com/2009/06/22/singleton-em-c/</guid>
		<description><![CDATA[Se vc quer fazer que sua aplicação rode apenas uma vez, ou seja, se o (burro) usuario clicar mais de uma vez no icone, só vai abrir uma aplicação, e nao 2 ou 3. public static Process RunningInstance() { Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName (current.ProcessName); //Loop through the running processes in with]]></description>
			<content:encoded><![CDATA[<p>Se vc quer fazer que sua aplicação rode apenas uma vez, ou seja, se o<span style="color:#cccccc;"> (</span><span style="font-style:italic;color:#cccccc;">burro)</span> usuario clicar mais de uma vez no icone, só vai abrir uma aplicação, e nao 2 ou 3.<span id="more-6"></span></p>
<pre class="brush: csharp;">public static Process RunningInstance()
            {
                Process current = Process.GetCurrentProcess();
                Process[] processes = Process.GetProcessesByName (current.ProcessName);

                //Loop through the running processes in with the same name
                foreach (Process process in processes)
                {
                    //Ignore the current process
                    if (process.Id != current.Id)
                    {
                        //Make sure that the process is running from the exe file.
                        if (Assembly.GetExecutingAssembly().Location.Replace(&quot;/&quot;, &quot;\\&quot;) ==
                        current.MainModule.FileName)
                        {
                            //Return the other process instance.
                            return process;
                        }
                    }
                }

            //No other instance was found, return null.
            return null;
            }

  public static void HandleRunningInstance(Process instance)
            {
                //Make sure the window is not minimized or maximized
                ShowWindowAsync (instance.MainWindowHandle , WS_SHOWNORMAL);

                //Set the real intance to foreground window
                SetForegroundWindow (instance.MainWindowHandle);
            }

            [DllImport(&quot;User32.dll&quot;)]

            private static extern bool ShowWindowAsync(
            IntPtr hWnd, int cmdShow);
            [DllImport(&quot;User32.dll&quot;)] private static extern bool
            SetForegroundWindow(IntPtr hWnd);
            private const int WS_SHOWNORMAL = 1;

       [STAThread]
        static void Main()
        {

            //Get the running instance.
            Process instance = RunningInstance();

            if (instance == null)
            {
                //There isn't another instance, show our form.
                Application.Run (new frmLogin());
            }
            else
            {
                //There is another instance of this process.
                HandleRunningInstance(instance);
            }

        }</pre>
<p>aplique isso a sua aplicação e terá sucesso&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://diariodecodigos.info/2009/06/singleton-em-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

