<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>crunchlife: Tag CSharp</title>
    <link>http://crunchlife.com/articles/tag/csharp</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>And finally, kill Excel...</title>
      <description>&lt;p&gt;Everyone who&amp;#8217;s worked with Excel on the Microsoft .NET framework has dealt with the problem of hanging Excel processes. The C# solution below is not very elegant, but it stops those pesky Excel processes from hanging around.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;using System.Diagnostics;
using System.Runtime.InteropServices;

[DllImport(&amp;quot;user32.dll&amp;quot;)]
private static extern
    int GetWindowThreadProcessId(int hWnd, out int processId);

private static void CreateSpreadsheet()
{
    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

    try
    {
      // Create Excel spreadsheet.
    }
    catch (Exception ex)
    {
      // Do something with the exception.
    }
    finally
    {
      KillExcel(excel.hWnd);
    }
}

private static void KillExcel(int hWnd)
{
    int processId;
    int threadProcessId = GetWindowThreadProcessId(hWnd, out processId);

    Process.GetProcessById(processId).Kill();
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</description>
      <pubDate>Wed, 14 Jan 2009 20:07:00 -0800</pubDate>
      <guid isPermaLink="false">urn:uuid:48876e48-1801-44ba-a6d2-73902582a453</guid>
      <author>Ryan Baxter</author>
      <link>http://crunchlife.com/articles/2009/01/14/and-finally-kill-excel</link>
      <category>Code Snippets</category>
      <category>CSharp</category>
      <category>dotNET</category>
    </item>
    <item>
      <title>Yet Another Join Method</title>
      <description>&lt;p&gt;The .NET String type has a &lt;a href="http://msdn.microsoft.com/en-us/library/57a79xd0.aspx" target="_blank"&gt;Join method&lt;/a&gt;, but in my latest ASP.NET project I had the need for joining String array elements with additional prefix and suffix values. The method below delimits array elements with the provided separator and concatenates the elements with the prefix and suffix string parameters.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve found this particularly handy when creating SQL statements that require the IN keyword.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;string[] names = { &amp;quot;Bobby&amp;quot;, &amp;quot;Suzy&amp;quot; };

sql += &amp;quot;WHERE People.FirstName IN (&amp;quot; + Utility.Join(&amp;quot;,&amp;quot;, names, &amp;quot;'&amp;quot;, &amp;quot;'&amp;quot;) + &amp;quot;)&amp;quot;;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Add this method to your utility class or extended String type.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public static string Join(string separator, string[] value, string
prefix, string suffix)
{
    string toReturn = String.Empty;

    int i;
    for (i = 0; i &amp;lt; value.Length; i++)
    {
        if (i != value.Length - 1)
            toReturn += prefix + value[i] + suffix + separator;
        else
            toReturn += prefix + value[i] + suffix;
    }

    return toReturn;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</description>
      <pubDate>Fri, 12 Sep 2008 14:27:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:05392c66-db31-4f67-80a6-e73740c41523</guid>
      <author>Ryan Baxter</author>
      <link>http://crunchlife.com/articles/2008/09/12/yet-another-join-method</link>
      <category>Code Snippets</category>
      <category>CSharp</category>
      <category>dotNET</category>
    </item>
    <item>
      <title>Removing Duplicate Items from an Abstract Generic List</title>
      <description>&lt;p&gt;&lt;img src="/files/rocking_chair.jpg" class="right" /&gt;I&amp;#8217;ve got some explaining to do. I
was hesitant in posting this code for fear that it might be too niche
to benefit anyone. It may be, but the underlying problem affects many
programmers working in the IT industry. What do you do when the company
legacy system&amp;#8217;s data model doesn&amp;#8217;t work with your fancy &lt;a href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank"&gt;ORM (Object-relational mapping)&lt;/a&gt;?&lt;/p&gt;

&lt;blockquote&gt;
&amp;#8220;Any problem in computer science can be solved with another layer of indirection. But that usually will create another problem.&amp;#8221; - &lt;a href="http://en.wikipedia.org/wiki/David_Wheeler_(computer_scientist)" target="_blank"&gt;David Wheeler&lt;/a&gt;
&lt;/blockquote&gt;

&lt;p&gt;At my last job, the &lt;a href="http://en.wikipedia.org/wiki/Enterprise_resource_planning" target="_blank"&gt;ERP (Enterprise resource planning)&lt;/a&gt; system was something of mystery and voodoo. Only a few had sufficient knowledge to work with it and because of its arcane nature it was deemed untouchable. Within my first months as an employee I wrote a rudimentary ORM to serve as a layer between our client applications and the ERP system. Its performance was terrible. I wrote it off as &amp;#8220;experience&amp;#8221; and the department ultimately decided to ignore interfacing directly with the ERP system.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m using the &lt;a href="http://subsonicproject.com/" target="_blank"&gt;SubSonic&lt;/a&gt; ORM on a few ASP.NET projects with my current employer. SubSonic has worked great, but a
few of its database requirements have left me in the dust with yet another ERP system. The ERP&amp;#8217;s tables have no primary keys, constraints, or relationships, but rather than write a complete ORM I decided to roll my own data layer.&lt;/p&gt;

&lt;p&gt;All of the strongly-typed collections in the ERP&amp;#8217;s data layer implement the AbstractList type. AbstractList implements List&lt;ItemType&gt; where ItemType implements IUniqueIdentifier. That is a mouthful, but the key (pun intended) to removing duplicate items is to make sure they&amp;#8217;re unique.&lt;/p&gt;

&lt;p&gt;The IUniqueIdentifier interface contains only one property, UniqueIdentifier.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public interface IUniqueIdentifier
{
    string UniqueIdentifier
    {
        get;
        set;
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt; 

&lt;p&gt;If the ERP system contained a table called Customers a Customer type implementing IUniqueIdentifier would be created. &lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public class Customer : IUniqueIdentifier
{
    private string uniqueIdentifier;

    // etc...

    public UniqueIdentifier
    {
        get { return this.uniqueIdentifier; }
        set { this.uniqueIdentifier = value; }
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;I&amp;#8217;d also have a CustomerCollection class:&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public class CustomerCollection : AbstractList&amp;lt;Customer, CustomerCollection&amp;gt;
{
    // etc...
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;After such a long-winded introduction I can feel better about dumping the following code on anyone that has happened to read this far (kudos to you).&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public abstract class AbstractList&amp;lt;ItemType, ListType&amp;gt; :
List&amp;lt;ItemType&amp;gt; where ItemType:IUniqueIdentifier where
ListType:AbstractList&amp;lt;ItemType, ListType&amp;gt;, new()
{
    public ListType RemoveDuplicates()
    {
        Dictionary&amp;lt;string, int&amp;gt; uniqueStore = new Dictionary&amp;lt;string, int&amp;gt;();
        ListType list = new ListType();

        foreach (ItemType item in this)
        {
            if (!uniqueStore.ContainsKey(item.UniqueIdentifier))
            {
                uniqueStore.Add(item.UniqueIdentifier, 0);
                list.Add(item);
            }
        }

        return list;
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;I&amp;#8217;d love to hear how others have worked around legacy systems and still kept their code clean. &lt;/p&gt;</description>
      <pubDate>Thu, 31 Jul 2008 07:40:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:f418da7f-eb68-46f7-9192-6c8254e39b4f</guid>
      <author>Ryan Baxter</author>
      <link>http://crunchlife.com/articles/2008/07/31/removing-duplicate-items-from-an-abstract-generic-list</link>
      <category>Code Snippets</category>
      <category>Expect the Unexpected</category>
      <category>CSharp</category>
      <category>dotNET</category>
      <category>ORM</category>
      <enclosure type="image/jpeg" length="61497" url="http://crunchlife.com/files/rocking_chair.jpg"/>
      <trackback:ping>http://crunchlife.com/articles/trackback/75</trackback:ping>
    </item>
    <item>
      <title>A Few Date Methods</title>
      <description>&lt;p&gt;An ASP.NET project of mine recently required the calculation of the start and end date of the current date&amp;#8217;s previous month. This was more difficult putting into words than code.  It did, however, get me thinking about other common date routines.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public static DateTime FirstDayOfPreviousMonth
{
    get
    {
        return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
    }    
}

public static DateTime LastDayOfPreviousMonth
{
    get
    {
        return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Being preemptive, I decided to include a few methods for determining the start and end date of the current date&amp;#8217;s fiscal quarter. I started by calculating the current date&amp;#8217;s quarter. This was accomplished with just a little division.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public static int CurrentQuarter
{
    get
    {
        return (DateTime.Now.Month + 2) / 3;
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Finding the start and end dates of the current quarter was harder, but could still be expressed in a single line of code (or two).&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public static DateTime FirstDayOfCurrentQuarter
{
    get
    {
        return new DateTime(DateTime.Now.Year, 1 + ((CurrentQuarter - 1) * 3), 1);
    }
}

public static DateTime LastDayOfCurrentQuarter
{
    get
    {
        int lastMonthOfCurrentQuarter = 3 + ((CurrentQuarter - 1) * 3);

        return new DateTime(DateTime.Now.Year, lastMonthOfCurrentQuarter, DateTime.DaysInMonth(DateTime.Now.Year, lastMonthOfCurrentQuarter));
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;I&amp;#8217;d like to extend this collection to include other common date routines. Feel free to post your date methods as comments if you&amp;#8217;d like to share.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;*The methods I&amp;#8217;ve created for calculating the current quarter&amp;#8217;s start and end dates assume the fiscal year starts on January 1st. This may not be suitable for your needs.&lt;/strong&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 06 May 2008 11:45:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:0f4f646c-7a7d-42c8-b6b1-306d40200836</guid>
      <author>Ryan Baxter</author>
      <link>http://crunchlife.com/articles/2008/05/06/a-few-date-methods</link>
      <category>Code Snippets</category>
      <category>dotNET</category>
      <category>CSharp</category>
      <enclosure type="image/jpeg" length="22591" url="http://crunchlife.com/files/clock.jpg"/>
    </item>
  </channel>
</rss>

