<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1025</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1025" rel="self"/>
  <title>Moonshield</title>
  <updated>Thu Mar 04 01:11:36 -0800 2010</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor468064</id>
    <published>2010-03-04T01:11:36-08:00</published>
    <title>[C#] On Properties surrounding arrays of bytes</title>
    <content type="html">&lt;p&gt;I used static property so you dont have to create an instance everytime. I moved the array creation in a static constructor so we don't have to recreate the same array everytime someone access the property. Also, the property use a private set so the collection can be changed from outside but its values could be changed though. If you dont want the values to be changed, just moved your array initialization inside your property, so you will end up with only 2 properties instead of 2 properties and 2 methods. Hope it helps.&lt;/p&gt;

&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] rich = Attivazioni.CodiceRichiesta;
            byte[] gest = Attivazioni.CodiceModuloGestionale;
        }
    }

    public partial class Attivazioni
    {
        public static byte[] CodiceRichiesta { get; private set; }
        public static byte[] CodiceModuloGestionale { get; private set; }

        static Attivazioni()
        {
            // CodiceRichiesta
            byte[] aRich = new byte[16];
            aRich[0] = 99;
            aRich[1] = 101;
            aRich[2] = 115;
            aRich[3] = 96;
            aRich[4] = 105;
            aRich[5] = 111;
            aRich[6] = 110;
            aRich[7] = 97;
            aRich[8] = 108;
            aRich[9] = 101;
            aRich[10] = 99;
            aRich[11] = 112;
            aRich[12] = 113;
            aRich[13] = 100;
            aRich[14] = 100;
            aRich[15] = 100;
            CodiceRichiesta = aRich;

            // CodiceModuloGestionale
            byte[] aGest = new byte[16];
            aGest[0] = 103;
            aGest[1] = 101;
            aGest[2] = 115;
            aGest[3] = 116;
            aGest[4] = 105;
            aGest[5] = 111;
            aGest[6] = 110;
            aGest[7] = 97;
            aGest[8] = 108;
            aGest[9] = 101;
            aGest[10] = 111;
            aGest[11] = 112;
            aGest[12] = 113;
            aGest[13] = 114;
            aGest[14] = 115;
            aGest[15] = 116;
            CodiceModuloGestionale = aGest;
        }      
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1198-properties-surrounding-arrays-of-bytes/refactors/468064" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor155516</id>
    <published>2009-04-22T04:47:57-07:00</published>
    <title>[C#] On Find the list's last satisfying element and skip the rest</title>
    <content type="html">&lt;p&gt;I haven't fully tested yet but you could do something similar to this. I changed the IEnumerator for IEnumerable as your comment was already suggesting it..&lt;/p&gt;

&lt;pre&gt;// this should be IEnumerable.
private IEnumerable&amp;lt;DevicePosition&amp;gt; ValidPositions()
{
    // stub
    return null;
}

public bool FindRecentRepresentatives(int milliseconds, out DevicePosition current, out DevicePosition previous)
{
    if (milliseconds &amp;lt;= 0)
        throw new ArgumentOutOfRangeException(&amp;quot;milliseconds&amp;quot;);

    var aValidPositions = ValidPositions();
    current = aValidPositions.First();
    previous = aValidPositions.Last(x =&amp;gt; x.Time.Ticks &amp;gt; (x.Time.Ticks - TimeSpan.FromMilliseconds(milliseconds).Ticks));

    return (current != null) &amp;amp;&amp;amp; (previous != null);
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/830-find-the-list-s-last-satisfying-element-and-skip-the-rest/refactors/155516" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor153212</id>
    <published>2009-03-27T01:39:34-07:00</published>
    <title>[C#] On Looking for a pattern to handle this situation</title>
    <content type="html">&lt;p&gt;I've already posted something similar, you can take a look at &lt;a href="http://refactormycode.com/codes/493-twitter-esque-relative-dates" target="_blank"&gt;http://refactormycode.com/codes/493-twitter-esque-relative-dates&lt;/a&gt;
&lt;br /&gt;The code below is probably what I would do, it is very similar to the code above but without the overhead&lt;/p&gt;

&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication4
{
    class Program
    {
        private static Dictionary&amp;lt;string, Action&amp;lt;string&amp;gt;&amp;gt; _QueryPriority;

        static void Main(string[] args)
        {
            if (_QueryPriority == null)
            {
                _QueryPriority = new Dictionary&amp;lt;string, Action&amp;lt;string&amp;gt;&amp;gt;();
                _QueryPriority.Add(&amp;quot;Foo&amp;quot;, DoFooWork);
                _QueryPriority.Add(&amp;quot;Bar&amp;quot;, DoBarWork);
                _QueryPriority.Add(&amp;quot;Beer&amp;quot;, DoBeerWork);
                _QueryPriority.Add(&amp;quot;Coffee&amp;quot;, DoCoffeeWork);
            }

            var action = Program._QueryPriority.FirstOrDefault(x =&amp;gt; !string.IsNullOrEmpty(Request.QueryString[x]));         
            if (action.Key != null)
                action.Value.Invoke(action.Key);
        }

        private static void DoFooWork(string pParam) { Console.WriteLine(pParam); }
        private static void DoBarWork(string pParam) { Console.WriteLine(pParam); }
        private static void DoBeerWork(string pParam) { Console.WriteLine(pParam); }
        private static void DoCoffeeWork(string pParam) { Console.WriteLine(pParam); }
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/800-looking-for-a-pattern-to-handle-this-situation/refactors/153212" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor153210</id>
    <published>2009-03-27T01:00:07-07:00</published>
    <title>[C#] On Showing several datetimes (event/concert style)</title>
    <content type="html">&lt;p&gt;Probably not perfect but you have the main idea and you can modify it to your needs.
&lt;br /&gt;I suggest to use the StringBuilder.AppendFormat method instead StringBuilder.Append(string.format(&amp;quot;&amp;quot;,something)), it's too much overhead :)
&lt;/p&gt;

&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime oDate = DateTime.Now;
            List&amp;lt;DateTime&amp;gt; aDate = new List&amp;lt;DateTime&amp;gt;()
            {
                oDate.AddHours(1),
                oDate,
                oDate.AddDays(10),
                oDate.AddYears(-1),
                oDate.AddDays(-10),
                oDate.AddYears(2)
            };

            string Result = Program.GetDateString(aDate);
            foreach (string Date in Result.Split(','))
                Console.WriteLine(Date.Trim());

            Console.ReadLine();
        }

        private static string GetDateString(List&amp;lt;DateTime&amp;gt; paDate)
        {
            StringBuilder oSb = new StringBuilder();

            if (paDate != null &amp;amp;&amp;amp; paDate.Count &amp;gt; 0)
            {
                int CurrentYear = int.MinValue;

                paDate.Sort();
                paDate.ForEach(oDate =&amp;gt;
                {
                    if (oDate.Year != CurrentYear)
                    {
                        CurrentYear = oDate.Year;
                        oSb.AppendFormat(CultureInfo.InvariantCulture, &amp;quot;{0:MMM dd yyyy HH:mm}, &amp;quot;, oDate);
                    }
                    else
                        oSb.AppendFormat(CultureInfo.InvariantCulture, &amp;quot;{0:MMM dd HH:mm}, &amp;quot;, oDate);
                });

                if (oSb.Length &amp;gt; 2)
                    oSb.Remove(oSb.Length - 2, 2);
            }

            return oSb.ToString();
        }
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/803-showing-several-datetimes-event-concert-style/refactors/153210" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor150002</id>
    <published>2009-03-08T20:36:57-07:00</published>
    <title>[C#] On C# HTML Encoding</title>
    <content type="html">&lt;p&gt;I know what it means and should be used for. For exemple : I think it should not be used to get the length of a string like in posted code var l = b.Length;, use and simple int. And for long type name, using keyword should be the right solution IMHO&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/777-c-html-encoding/refactors/150002" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor149719</id>
    <published>2009-03-06T00:13:18-08:00</published>
    <title>[C#] On C# HTML Encoding</title>
    <content type="html">&lt;p&gt;Use 'else if', so it doesn't need to evaluate other conditions when it succeeds to the first one. As Rikkus said, you better use the method provided in the framework. Still don't know why people use the var keyword when type is known, I'm curious. It is very usefull with Linq queries.. aside that&lt;/p&gt;

&lt;pre&gt;public static string CleanHtml(string pHtml)
{
    StringBuilder oSb = new StringBuilder();

    if (!string.IsNullOrEmpty(pHtml))
    {
        foreach (char c in pHtml)
        {
            // Known Replacements
            if (c == '&amp;amp;')
                oSb.Append(&amp;quot;&amp;amp;amp;&amp;quot;);
            else if (c == '&amp;lt;')
                oSb.Append(&amp;quot;&amp;amp;lt;&amp;quot;);
            else if (c == '&amp;gt;')
                oSb.Append(&amp;quot;&amp;amp;gt;&amp;quot;);
            else if (c == '`')
                oSb.Append(&amp;quot;'&amp;quot;);
            else if ((int)(c) &amp;gt; 127)
            {
                // Always Encode Extended Ascii Codes
                oSb.AppendFormat(&amp;quot;&amp;amp;#{0};&amp;quot;, (int)c);
            }
            else
            {
                // If nothing was added, add the original char
                oSb.Append(c);
            }
        }
    }

    return oSb.ToString();
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/777-c-html-encoding/refactors/149719" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor145850</id>
    <published>2009-02-06T01:36:35-08:00</published>
    <title>[C#] On Help me with ineritance or the best way to do this</title>
    <content type="html">&lt;p&gt;I would probably do something similar to this&lt;/p&gt;

&lt;pre&gt;public class MvNetDB
{
    protected mvAccount _account = null;
    private static Logger logger = LogManager.GetCurrentClassLogger();

    protected void Login()
    {
        _account = new mvAccount(ConfigHelper.ServerLogin, ConfigHelper.ServerAddress);
    }

    protected void Logout()
    {
        if (_account != null)
        {
            _account.Logout();
            _account.Dispose();
        }
    }

    protected mvItem ReadRecord(string filename, string recordID)
    {
        mvItem item = null;

        try
        {
            this.LoginToDB();
            item = _account.FileOpen(filename).Read(recordID);
        }
        catch { }
        finally
        {
            this.LogoutFromDB();
        }

        return item;
    }
}

public class MvNetServiceCallRepository : MvNetDB, IServiceCallRepository
{
    private Customer GetCustomerByID(string custID)
    {
        Customer oCustomer = null;

        mvItem oItem = ReadRecord(&amp;quot;CUSTOMER&amp;quot;, custID);
        if (oItem != null)
        {
            oCustomer = new Customer()
            {
                ID = custID,
                Name = oItem[&amp;quot;1&amp;quot;].ToString(),
                Address = oItem[&amp;quot;2&amp;quot;].ToString(),
                City = oItem[&amp;quot;3&amp;quot;].ToString(),
                State = oItem[&amp;quot;4&amp;quot;].ToString(),
                Zip = oItem[&amp;quot;5&amp;quot;].ToString(),
                CustCode = GetCustCodeByID(oItem[&amp;quot;42&amp;quot;].ToString())
            };
        }

        return oCustomer;
    }

    private CustCode GetCustCodeByID(string custCodeID)
    {
        CustCode oCustCode = null;

        mvItem oItem = ReadRecord(&amp;quot;CUST.CODE&amp;quot;, custCodeID);
        if (oItem != null)
        {
            oCustCode = new CustCode()
            {
                ID = custCodeID,
                Name = oItem[&amp;quot;1&amp;quot;].ToString()
            };
        }

        return oCustCode;
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/737-help-me-with-ineritance-or-the-best-way-to-do-this/refactors/145850" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor144121</id>
    <published>2009-01-22T03:45:27-08:00</published>
    <title>[C#] On Polymorphic XML serializer</title>
    <content type="html">&lt;p&gt;Unfortunately, your code wasn't working for me. I think that my default xml encoding differs from yours so that your hard-coded string manipulation isn&#226;&#8364;&#8482;t working properly. On the other side, I worked on a cleaner way to achieve what you want. It can serializes an object of type A, then deserializes it back to the same type or to an object of type B : A like you mentioned. The key of the implementation is to use a general root name (see XmlRoot in my code) for both objects. Enough talking, see the code below :)&lt;/p&gt;

&lt;pre&gt;using System;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            // Serialize a Person object and deserialize it back to a Person or an Employee
            string SerializedObject = SerializedObject = CustomSerializer.Serialize(new Person() { Id = 1, FirstName = &amp;quot;Peter&amp;quot;, LastName = &amp;quot;Pan&amp;quot; });
            Person oPerson = CustomSerializer.DeSerialize&amp;lt;Person&amp;gt;(SerializedObject);
            Employee oEmployee = CustomSerializer.DeSerialize&amp;lt;Employee&amp;gt;(SerializedObject);
            
            // At this point the Employee.Title is empty, everything's normal. Then we will
            // serialize the same Employee object and deserialize it back to a Person object
            oEmployee.Title = &amp;quot;Hero&amp;quot;;            
            SerializedObject = CustomSerializer.Serialize(oEmployee);
            oPerson = CustomSerializer.DeSerialize&amp;lt;Person&amp;gt;(SerializedObject);

            Console.ReadLine();
        }
    }

    /// &amp;lt;summary&amp;gt;
    /// Contains information about a person.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;remarks&amp;gt;
    /// The XmlRoot attribute allow to serialize a Person object 
    /// and to deserialize it back to a Person or an Employee 
    /// object without &amp;quot;manipulating&amp;quot; the xml string.
    /// &amp;lt;/remarks&amp;gt;
    [Serializable, XmlRoot(&amp;quot;Base&amp;quot;)]
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    /// &amp;lt;summary&amp;gt;
    /// Contains information about an employee.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;remarks&amp;gt;
    /// The XmlRoot attribute allow to serialize a Person object 
    /// and to deserialize it back to a Person or an Employee 
    /// object without &amp;quot;manipulating&amp;quot; the xml string.
    /// &amp;lt;/remarks&amp;gt;
    [Serializable, XmlRoot(&amp;quot;Base&amp;quot;)]
    public class Employee : Person
    {
        public string Title { get; set; }
    }

    /// &amp;lt;summary&amp;gt;
    /// 
    /// &amp;lt;/summary&amp;gt;
    public class CustomSerializer
    {
        /// &amp;lt;summary&amp;gt;
        /// Serialize an object to xml
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;pSource&amp;quot;&amp;gt;Object Type&amp;lt;/param&amp;gt;
        /// &amp;lt;returns&amp;gt;String&amp;lt;/returns&amp;gt;
        public static string Serialize(object pSource)
        {
            // Normally I'd use this 4 lines but since you need cleaner xml see below
            //StringWriter oWriter = new StringWriter();
            //XmlSerializer oSerializer = new XmlSerializer(pSource.GetType());
            //oSerializer.Serialize(oWriter, pSource);
            //return oWriter.ToString();

            XmlSerializerNamespaces oNamespaces = new XmlSerializerNamespaces();
            oNamespaces.Add(&amp;quot;&amp;quot;, &amp;quot;&amp;quot;);

            StringWriter oWriter = new StringWriter();
            XmlSerializer oSerializer = new XmlSerializer(pSource.GetType());
            oSerializer.Serialize(oWriter, pSource, oNamespaces);

            string Serialized = oWriter.ToString();
            return Serialized.Remove(0, Serialized.IndexOf('&amp;lt;', 1));
        }

        /// &amp;lt;summary&amp;gt;
        /// Deserialize an xml string to an object
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;pXmlSource&amp;quot;&amp;gt;Xml Source&amp;lt;/param&amp;gt;
        /// &amp;lt;returns&amp;gt;Deserialized object&amp;lt;/returns&amp;gt;
        public static T DeSerialize&amp;lt;T&amp;gt;(string pXmlSource)
        {
            return (T)(new XmlSerializer(typeof(T)).Deserialize(new StringReader(pXmlSource)));
        }
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/710-polymorphic-xml-serializer/refactors/144121" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor88165</id>
    <published>2008-11-27T02:15:57-08:00</published>
    <title>[C#] On Filterting a List&lt;&gt; with a Regular Expression</title>
    <content type="html">&lt;p&gt;Some advices : The way you are using the regular expression is equivalent to using the regular way to do a string comparaison. Also, I would suggest also to filter documents in your document layer by adding the name and author to your GetDocuments(username) method, I would be more efficient as your method can retrieve 500 documents from the database to finally display one or two results for exemple.&lt;/p&gt;

&lt;pre&gt;List&amp;lt;Document&amp;gt; aDocuments = documentLayer.GetDocuments(username);

string docName = (string)Session[&amp;quot;DocumentName&amp;quot;];
string docAuthor = (string)Session[&amp;quot;DocumentAuthor&amp;quot;];
bool docNameEmpty = string.IsNullOrEmpty(docName);
bool docAuthorEmpty = string.IsNullOrEmpty(docAuthor);

if (docNameEmpty &amp;amp;&amp;amp; docAuthorEmpty)
    gridDocuments.DataSource = aDocuments;
else
{
    List&amp;lt;Document&amp;gt; aDocumentsFilter = new List&amp;lt;Document&amp;gt;();
    aDocuments.ForEach(oDoc =&amp;gt;
        {
            if ((!docNameEmpty &amp;amp;&amp;amp; !docAuthorEmpty &amp;amp;&amp;amp; docName == oDoc.Name &amp;amp;&amp;amp; docAuthor == oDoc.Author)
             || (docNameEmpty &amp;amp;&amp;amp; docAuthor == oDoc.Author)
             || (docAuthorEmpty &amp;amp;&amp;amp; docName == oDoc.Name))
                aDocumentsFilter.Add(oDoc);
        });
    gridDocuments.DataSource = aDocumentsFilter;
}

gridDocuments.DataBind();&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/622-filterting-a-list-with-a-regular-expression/refactors/88165" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor68115</id>
    <published>2008-11-11T23:42:53-08:00</published>
    <title>[C#] On Drop all Indexes in SQL Server</title>
    <content type="html">&lt;p&gt;You can also reuse the example I gave you days ago
&lt;br /&gt;&lt;a href="http://refactormycode.com/codes/497-backup-all-ms-sql-server-databases" target="_blank"&gt;http://refactormycode.com/codes/497-backup-all-ms-sql-server-databases&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/522-drop-all-indexes-in-sql-server/refactors/68115" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor68113</id>
    <published>2008-11-11T23:34:34-08:00</published>
    <title>[C#] On DirectoryInfo.CopyTo</title>
    <content type="html">&lt;p&gt;Just add the parameters validations you need and you'll be good I think&lt;/p&gt;

&lt;pre&gt;namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileUtils.CopyDirectory(@&amp;quot;C:\MyFiles\Test&amp;quot;, @&amp;quot;C:\MyFiles\Test2&amp;quot;, true);
            Console.WriteLine(&amp;quot;Already done...&amp;quot;);
            Console.ReadLine();
        }

        public static class FileUtils
        {
            public static void CopyDirectory(string pSource, string pDestination, bool pOverrideExistingFile)
            {
                (from p in Directory.GetFiles(pSource, &amp;quot;*.*&amp;quot;, SearchOption.AllDirectories)
                 group p by Path.GetDirectoryName(p) into GroupByDirectory
                 select new
                 {
                     Directory = GroupByDirectory.Key.Replace(pSource, pDestination),
                     Files = (from p in GroupByDirectory
                              select new
                              {
                                  SourceFile = p,
                                  Destination = p.Replace(pSource, pDestination)
                              }).ToList()
                 })
                 .ToList()
                 .ForEach(item =&amp;gt;
                 {
                     if (!Directory.Exists(item.Directory)) 
                         Directory.CreateDirectory(item.Directory);
                     item.Files.ForEach(fileInfo =&amp;gt; File.Copy(fileInfo.SourceFile, fileInfo.Destination, pOverrideExistingFile));
                 });
            }
        }
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/600-directoryinfo-copyto/refactors/68113" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor67296</id>
    <published>2008-11-11T05:14:22-08:00</published>
    <title>[C#] On Strip Html Comments</title>
    <content type="html">&lt;p&gt;I ran the test unit on the regex : 7/15 passed. If you still want to do it with a loop I've cleaned your code a little. I can take a look tomorrow too. I'm too tired to think tonight :)&lt;/p&gt;

&lt;pre&gt;public static class HtmlHelper
{
    public static string StripHtmlComments(string pHtml)
    {
        if (pHtml == null)
            throw new ArgumentNullException(&amp;quot;pHtml&amp;quot;);

        // Contains cleaned content
        StringBuilder oSb = new StringBuilder();

        // Not comment --&amp;gt; skip
        if (pHtml.IndexOf(&amp;quot;&amp;lt;!&amp;quot;, StringComparison.Ordinal) &amp;lt; 0)
            oSb.Append(pHtml);

        // Not comment --&amp;gt; skip
        if (oSb.Length == 0)
        {
            bool InHtmlComment = false;
            bool InHtmlTag = false;
            char CurrentChar;
            char NextChar;

            for (int CharIndex = 0; CharIndex &amp;lt; pHtml.Length; CharIndex++)
            {
                CurrentChar = pHtml[CharIndex];

                if (!InHtmlComment &amp;amp;&amp;amp; !InHtmlTag)
                {
                    if (CurrentChar == '&amp;lt;' &amp;amp;&amp;amp; (CharIndex + 1 &amp;lt; pHtml.Length))
                    {
                        NextChar = pHtml[CharIndex + 1];
                        if (NextChar == '!')
                        {
                            InHtmlComment = true;
                            continue;
                        }
                        else if (NextChar.IsEnglishLetter())
                            InHtmlTag = true;
                    }
                }
                else if (InHtmlComment)
                {
                    if (CurrentChar == '&amp;gt;')
                    {
                        if (InHtmlComment)
                        {
                            InHtmlComment = false;
                            continue;
                        }
                    }
                    continue;
                }
                else if (InHtmlTag &amp;amp;&amp;amp; CurrentChar == '&amp;gt;')
                    InHtmlTag = false;

                oSb.Append(CurrentChar);
            }

        }

        // One entry point, one return point
        return oSb.ToString();
    }

    private static bool IsEnglishLetter(this char nextChar)
    {
        return ('a' &amp;lt;= nextChar &amp;amp;&amp;amp; nextChar &amp;lt;= 'z') || ('A' &amp;lt;= nextChar &amp;amp;&amp;amp; nextChar &amp;lt;= 'Z');
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/597-strip-html-comments/refactors/67296" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor61165</id>
    <published>2008-11-05T23:18:39-08:00</published>
    <title>[C#] On Sorting by dependencies</title>
    <content type="html">&lt;p&gt;I'd like to help but I'm not sure to understand what you try to achieve. Can you provide more details or provide a new Dictionnary to test with that produce something else then 1,2,3,4,5 when you execute it, it would help me to understand.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/579-sorting-by-dependencies/refactors/61165" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor55993</id>
    <published>2008-10-23T02:35:29-07:00</published>
    <title>[C#] On Generating a list of time values</title>
    <content type="html">&lt;p&gt;I have the same console result as your code with this. 
&lt;br /&gt;Not sure about the appended 'd', it is never displayed in my test. I'd like more explanations to know when to display it or not&lt;/p&gt;

&lt;pre&gt;int interval = 60; //in minutes
DateTime start = DateTime.Today;

for (int IntervalIndex = 0; IntervalIndex &amp;lt; (1440 / interval); IntervalIndex++)
    Console.WriteLine(&amp;quot;local time: {0:HHmm}, GMT value: {1}&amp;quot;, (start = start.AddMinutes(IntervalIndex == 0 ? 0 : interval)), start.ToUniversalTime());
Console.WriteLine(&amp;quot;local time: 2400, GMT value: {0}&amp;quot;, start.AddMinutes(interval).ToUniversalTime());&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/536-generating-a-list-of-time-values/refactors/55993" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code516</id>
    <published>2008-10-02T01:31:54-07:00</published>
    <updated>2008-10-02T01:31:54-07:00</updated>
    <title>[C#] Capitalize directory name with LINQ</title>
    <content type="html">&lt;p&gt;I wrote a method to capitalize the first letter of each directories for a given path. I used it at the same time to work on my LINQ skills so don't remove it when refactoring please, improve it if necessary. I need to perform two different sub query to know if the word to capitalize is the first one or not, but I'm not sure if all this is really necessary. Also, I had to add a \ or a blank space before to word because I don't want to replace all 'a' because there is the word a in the folder name. See third directory name.&lt;/p&gt;

&lt;p&gt;C:\MyFiles\Music\candlemass- ancient Dreams
&lt;br /&gt;C:\MyFiles\test\die apokalyptischen reiter - licht
&lt;br /&gt;C:\MyFiles\Music\a Dozen Furies - a Concept From Fire&lt;/p&gt;

&lt;p&gt;I commented the two lines that rename the directory because I don't want to be responsable for renaming all your folders :)&lt;/p&gt;

&lt;pre&gt;public static void Capitalize()
{
    TextInfo oTextInfo = CultureInfo.CurrentCulture.TextInfo;
    StringBuilder oSb = new StringBuilder();
    string Folder;

    var DirectoryToCapitalize =
       (from p in Directory.GetDirectories(@&amp;quot;C:\MyFiles&amp;quot;, &amp;quot;*.*&amp;quot;, SearchOption.AllDirectories)
        let directories = p.Substring(p.LastIndexOf(&amp;quot;\\&amp;quot;) + 1)
        let words = directories.Split(' ')                    
        from word in words                   
        where word.Length &amp;gt; 0 &amp;amp;&amp;amp; char.IsLower(word[0])
        group word by p into groupedChanges                
        select new
        {
            Folder = groupedChanges.Key,
            Words = (   from p in groupedChanges
                        where groupedChanges.Key.IndexOf(&amp;quot;\\&amp;quot; + p) &amp;gt; 0
                        select &amp;quot;\\&amp;quot; + p)
                        .Union( from p in groupedChanges
                                where groupedChanges.Key.IndexOf(&amp;quot; &amp;quot; + p) &amp;gt; 0
                                select &amp;quot; &amp;quot; + p)            
        });
    
    foreach (var GroupItem in DirectoryToCapitalize)
    {
        Folder = GroupItem.Folder;

        foreach (var Word in GroupItem.Words)
            Folder = Folder.Replace(Word, oTextInfo.ToTitleCase(Word));

        oSb.AppendLine(GroupItem.Folder); // Original path
        oSb.AppendLine(Folder); // New path

        // Can't rename C:\MyFiles\test to C:\MyFiles\Test
        // We need to rename the folder with a temp name and rename it back with capitalized words
        //Directory.Move(Folder, Folder + &amp;quot;1&amp;quot;);
        //Directory.Move(Folder + &amp;quot;1&amp;quot;, Folder);
    }

    Console.WriteLine(oSb.ToString());
}&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/516-capitalize-directory-name-with-linq" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor24687</id>
    <published>2008-09-19T23:55:56-07:00</published>
    <title>[C#] On Backup All MS SQL Server Databases</title>
    <content type="html">&lt;p&gt;Hi GateKiller&lt;/p&gt;

&lt;p&gt;If you don't have many databases, lets say less than 75, the code below would do the job without cursor. (In general, cursor are not a good way to do thing). If you have too many databases, your script is good, I'll just move the condition in your if statement to the query that the cursor is made of as in the exemple below.&lt;/p&gt;

&lt;p&gt;Hope you'll like it !&lt;/p&gt;

&lt;pre&gt;Use Master

Declare @ToExecute VarChar(8000)

Select @ToExecute = Coalesce (@ToExecute + 'Backup Database ' + [Name] + ' To Disk = ''D:\Backups\Databases\' + [Name] 	+ '.bak'' With Format;' + char(13),'')
From Master..Sysdatabases
Where [Name] Not In ('tempdb') And databasepropertyex ([Name],'Status') = 'online'

--Print @ToExecute
Exec (@ToExecute)&lt;/pre&gt;</content>
    <author>
      <name>Moonshield</name>
      <email>monsterinthepit@hotmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/497-backup-all-ms-sql-server-databases/refactors/24687" rel="alternate"/>
  </entry>
</feed>

