LINQ(통합 언어 쿼리)
LINQ(통합 언어 쿼리)는 강력한 쿼리 기능을 C# 및 Visual Basic의 언어 구문으로 확장하는 Visual Studio 2008의 기능 집합입니다. LINQ에는 데이터 쿼리 및 업데이트에 사용할 수 있고 쉽게 배울 수 있는 표준적인 패턴이 도입되었으며 거의 모든 종류의 데이터 소스를 지원하도록 기술을 확장할 수 있습니다. Visual Studio 2008에는 LINQ 공급자 어셈블리가 포함되어 있으므로 LINQ를 .NET Framework 컬렉션, SQL Server 데이터베이스, ADO.NET 데이터 집합 및 XML 문서와 함께 사용할 수 있습니다.

Lina to Object (http://msdn.microsoft.com/ko-kr/library/bb397919.aspx)
기본적으로 LINQ to Objects는 컬렉션에 대한 새로운 방식을 나타냅니다. 이전 방식에서는 컬렉션에서 데이터를 검색하는 방법을 지정하는 복잡한 foreach 루프를 작성해야 했습니다. LINQ 방식에서는 검색할 내용을 설명하는 선언 코드를 작성합니다.또한 LINQ 쿼리는 일반적인 foreach 루프에 비해 세 가지 주요 장점을 제공합니다.이러한 쿼리는 특히 여러 조건을 필터링할 때 더욱 명료하며 읽기 쉽습니다.이러한 쿼리는 최소한의 응용 프로그램 코드를 사용하여 강력한 필터링, 정렬 및 그룹화 기능을 제공합니다.이러한 쿼리는 거의 수정하지 않거나 약간만 수정하여 다른 데이터 소스에 이식할 수 있습니다.

Lina to XML (http://msdn.microsoft.com/ko-kr/library/bb387098.aspx)
LINQ to XML은 .NET LINQ(통합 언어 쿼리) Framework를 활용하는 메모리 내 XML 프로그래밍 인터페이스를 제공합니다. LINQ to XML은 최신 .NET Framework 언어 기능을 사용하며 업데이트되고 다시 디자인된 DOM(문서 개체 모델) XML 프로그래밍 인터페이스와 유사합니다.

Lina to SQL (http://msdn.microsoft.com/ko-kr/library/bb386976.aspx)
LINQ to SQL은 관계형 데이터를 개체로 관리하는 데 필요한 런타임 인프라를 제공하는 .NET Framework 버전 3.5의 구성 요소입니다. LINQ to SQL에서 관계형 데이터베이스의 데이터 모델은 개발자의 프로그래밍 언어로 표현되는 개체 모델에 매핑됩니다. 응용 프로그램을 실행하면 LINQ to SQL에서는 개체 모델의 SQL 언어 통합 쿼리를 변환하여 실행을 위해 데이터베이스로 전송합니다. 데이터베이스에서 결과를 반환하면 LINQ to SQL에서는 해당 결과를 사용자의 프로그래밍 언어로 작업할 수 있는 개체로 다시 변환합니다.


LINQ 샘플

  • Visual Studio 2008 Samples

  • The Visual Basic Developer Center

  • The Visual C# Developer Center

  • Posted by 사나에

    System.Globalization 네임스페이스에는 KoreanCalendar 클래스를 제공해준다.

    윤년의 정의 : 4로 나누어 떨어지되~ 100의 배수인 연도는 윤년에서 제외한다. 단, 400의 배수인 연도는 무조건 윤년이다.
    평년의 날짜 수는 365일이고, 윤년의 날짜 수는 366일입니다.

    한국식 달력의 월 수는 12개월이며, 각 월의 날짜 수는 28일에서 31일 사이입니다.

    GetMonth 값 평년의 날짜 수 윤년의 날짜 수
    1 1월 (January) 31 31
    2 2월 (February) 28 29
    3 3월 (March) 31 31
    4 4월 (April) 30 30
    5 5월 (May) 31 31
    6 6월 (June) 30 30
    7 7월 (July) 31 31
    8 8월 (August) 31 31
    9 9월 (September) 30 30
    10 10월 (October) 31 31
    11 11월 (November) 30 30
    12 12월 (December) 31 31


    [C# Code]
    System.Globalization.KoreanLunisolarCalendar KoreanLunisolar = new System.Globalization.KoreanLunisolarCalendar();
    DateTime BirthLift = new DateTime(1983, 05, 03);
    DateTime BirthLunar = new DateTime(KoreanLunisolar.GetYear(BirthLift), KoreanLunisolar.GetMonth(BirthLift), KoreanLunisolar.GetDayOfMonth(BirthLift));


    Posted by 사나에
    개발 이야기/Visual C#2008. 6. 30. 15:26

    파일에서 텍스트 읽어올때 한글깨짐 현상 처리
    Encoding시 한글을 적용시켜준다.

    HttpWebRequest로 URL에 XML파싱의 경우 한글이 깨지는 현상도 Encoding을 통해 해결 할 수 있다.
    간단한 Tip정도..~

    Encoding.GetEncoding("euc-kr")

    사용자 삽입 이미지

    Posted by 사나에
    개발 이야기/Visual C#2008. 4. 13. 18:29
    문자열을 다루때 문자열 형식 지정 및 변환작업을 많이하게된다.
    string.Format 형식이 뭐가 있을까? 간단히 바꾸는 방법을 정리해보자.

    숫자를 문자열로~~
    형식
    지정자
    이름 설명
    0 0 자리 표시자 형식을 지정할 값이 형식 문자열의 '0'이 표시된 위치에 숫자를 가지고 있으면
    해당 숫자가 결과 문자열로 복사됩니다.
    소수점 앞 가장 왼쪽의 '0'과 소수점 뒤 가장 오른쪽 '0'의 위치는
    결과 문자열에 항상 표시될 자릿수의 범위를 결정합니다.
    "00" 지정자를 사용하면 해당 값이 소수점 뒤 첫째 자리에서 반올림되며
    항상 0 이상의 정수 값으로 표시됩니다. 예를 들어, 34.5의 형식을 "00"으로 지정하면 결과는 35가 됩니다.
    # 10진수 자리 표시자 형식을 지정할 값이 형식 문자열의 '#'이 표시된 위치에 숫자를 가지고 있으면
    해당 숫자가 결과 문자열로 복사되고, 그렇지 않으면 결과 문자열의 해당 위치에 아무 것도 저장되지 않습니다.
    0이 유효 자릿수가 아니면 이 지정자는 문자열에서 '0'이 유일한 숫자라 할지라도
    '0'을 표시하지 않습니다. 표시되는 숫자에서 0이 유효 자릿수이면 이 지정자는 '0'을 표시합니다.
    "##" 형식 문자열을 사용하면 해당 값이 소수점 뒤 첫째 자리에서 반올림되며
    항상 0 이상의 정수로 표시됩니다. 예를 들어, 34.5의 형식을 "##"으로 지정하면 결과는 35가 됩니다.
    . 소수점 형식 문자열의 첫 번째 '.' 문자는 형식이 지정될 값에서 소수 구분 기호의 위치를 결정하며, 다른 '.' 문자는 무시됩니다.
    소수 구분 기호로 사용되는 실제 문자는 형식 지정을 제어하는 NumberFormatInfo의 NumberDecimalSeparator 속성에 의해 결정됩니다.
    , 1000 단위 구분 기호 및 숫자 배율 ',' 문자는 1000 단위 구분 기호 지정자와 숫자 배율 지정자로 사용됩니다.
    1000 단위 구분 기호 지정자: 두 개의 10진수 자리 표시자(0 또는 #) 사이에
    정수 계열 자릿수의 형식을 지정하는 하나 이상의 ',' 문자가 지정된 경우,
    정수 계열 출력 부분의 각 숫자 그룹 사이에 그룹 구분 문자가 삽입됩니다.
    현재 NumberFormatInfo 개체의 NumberGroupSeparatorNumberGroupSizes
    속성은 숫자 그룹 구분 기호로 사용되는 문자와 각 숫자 그룹의 크기를 결정합니다.
    예를 들어, 문자열 "#,#"과 고정 culture를 사용하여 숫자 1000의 형식을 지정할 경우 "1,000"이 출력됩니다.
    숫자 배율 지정자: 명시적 또는 암시적 소수점의 바로 왼쪽에 하나 이상의 ',' 문자가 지정된 경우
    형식을 지정할 숫자는 숫자 배율 지정자가 나타날 때마다 1000으로 나뉩니다.
    예를 들어, 문자열 "0,,"을 사용하여 숫자 100000000의 형식을 지정할 경우 "100"이 출력됩니다.
    동일한 형식 문자열에 1000 단위 구분 기호와 숫자 배율 지정자를 함께 사용할 수 있습니다.
    예를 들어, 문자열 "#,0,,"과 고정 culture를 사용하여 숫자 1000000000의 형식을 지정할 경우 "1,000"이 출력됩니다.
    % 백분율 자리 표시자 형식 문자열에 '%' 문자가 있으면 형식이 지정되기 전에 해당 수에 100이 곱해집니다.
    형식 문자열에서 '%'가 표시된 위치에는 숫자 자체에서 적절한 기호가 삽입됩니다.
    사용되는 백분율 문자는 현재 NumberFormatInfo 클래스에 의해 결정됩니다.
    E0 과학적 표기법 형식 문자열에 "E", "E+", "E-", "e", "e+" 또는 "e-" 문자열이 표시되고 바로 뒤에
    적어도 하나의 '0' 문자가 오면, 해당 수와 지수 사이에 'E' 또는 'e'가 삽입되는 과학적 표기법으로 형식이 지정됩니다.
    과학적 표기법 표시기 뒤에 오는 '0' 문자의 개수는 이 숫자의 지수로 나타낼 최소 자릿수를 결정합니다.
    "E+" 및 "e+" 형식은 기호 문자(더하기나 빼기)가 지수보다 항상 앞에 와야한다는 것을 나타냅니다.
    "E", "E-", "e" 또는 "e-" 형식은 기호 문자가 음의 지수 앞에만 온다는 것을 나타냅니다.
    E+0
    E-0
    e0
    e+0
    e-0
    \ 이스케이프 문자 C# 및 C++에서 백슬래시 문자가 오면 형식 문자열의 다음 문자가 이스케이프 시퀀스로 해석됩니다.
    이것은 '\n'(새 줄)처럼 전통적인 형식 지정 시퀀스에서 사용합니다.
    일부 언어에서 이스케이프 문자를 리터럴로 사용할 때는, 이 이스케이프 문자 앞에 이스케이프 문자를 넣어야 합니다.
    그렇지 않으면 컴파일러에서 이 문자를 이스케이프 시퀀스로 해석합니다. '\'를 표시하려면 "\\" 문자열을 사용합니다.
    Visual Basic에서는 이 이스케이프 문자를 지원하지 않지만 ControlChars에서 같은 기능을 제공합니다.
    'ABC' 리터럴 문자열 작은따옴표나 큰따옴표로 묶은 문자는 결과 문자열에 복사되며 형식 지정에 영향을 주지 않습니다.
    "ABC"
    ; 섹션 구분 기호 ';' 문자는 형식 문자열에서 양수, 음수 및 0 섹션을 구분하는 데 사용됩니다.
    기타 다른 모든 문자 다른 모든 문자는 결과 문자열에 복사되며 형식 지정에는 영향을 주지 않습니다.


    DateTime 문자열 지정 형식~~

    형식
    지정자
    이름 설명
    d 간단한 날짜 패턴 현재 ShortDatePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    예를 들어, 고정 culture에 대한 사용자 지정 형식 문자열은 "MM/dd/yyyy"입니다.
    D 자세한 날짜 패턴 현재 LongDatePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    예를 들어, 고정 culture에 대한 사용자 지정 형식 문자열은 "dddd, dd MMMM yyyy"입니다.
    f 전체 날짜/시간 패턴(간단한 시간) 자세한 날짜(D) 패턴과 간단한 시간(t) 패턴을 공백으로 구분하여 조합한 형식을 나타냅니다.
    F 전체 날짜/시간 패턴(자세한 시간) 현재 FullDateTimePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    예를 들어, 고정 culture에 대한 사용자 지정 형식 문자열은 "dddd, dd MMMM yyyy HH:mm:ss"입니다.
    g 일반 날짜/시간 패턴(간단한 시간) 간단한 날짜(d) 패턴과 간단한 시간(t) 패턴을 공백으로 구분하여 조합한 형식을 나타냅니다.
    G 일반 날짜/시간 패턴(자세한 시간) 간단한 날짜(d) 패턴과 자세한 시간(t) 패턴을 공백으로 구분하여 조합한 형식을 나타냅니다.
    M 또는 m 월 일 패턴 현재 MonthDayPattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    예를 들어, 고정 culture에 대한 사용자 지정 형식 문자열은 "MMMM dd"입니다.
    o 라운드트립 날짜/시간 패턴 표준 시간대 정보를 유지하는 패턴을 사용하여 사용자 지정 DateTime 형식 문자열을 나타냅니다. 이 패턴은 Kind 속성을 포함하여 DateTime 형식을 텍스트로 라운드트립합니다. 그런 다음 형식이 지정된 문자열을 Parse 또는 ParseExact와 올바른 Kind 속성 값을 사용하여 다시 구문 분석할 수 있습니다.
    사용자 지정 형식 문자열은 "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"입니다.
    이 지정자의 패턴은 표준으로 정의되어 있습니다. 따라서 이 패턴은 사용된 culture나 제공된 형식 공급자에 관계없이 항상 같습니다.
    R 또는 r RFC1123 패턴 현재 RFC1123Pattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다. 이 패턴은 표준으로 정의되어 있으며 해당 속성은 읽기 전용입니다. 따라서 이 패턴은 사용된 culture나 제공된 형식 공급자에 관계없이 항상 같습니다.
    사용자 지정 형식 문자열은 "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"입니다.
    형식을 지정해도 해당 형식이 지정되는 DateTime 개체의 값은 수정되지 않습니다. 따라서 응용 프로그램에서는 이 형식 지정자를 사용하기 전에 값을 UTC(지역 표준시)로 변환해야 합니다.
    s 정렬 가능한 날짜/시간 패턴;
    ISO 8601에 부합
    현재 SortableDateTimePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다. 이 패턴은 표준으로 정의되어 있으며 해당 속성은 읽기 전용입니다. 따라서 이 패턴은 사용된 culture나 제공된 형식 공급자에 관계없이 항상 같습니다.
    사용자 지정 형식 문자열은 "yyyy'-'MM'-'dd'T'HH':'mm':'ss"입니다.
    t 간단한 시간 패턴 현재 ShortTimePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    예를 들어, 고정 culture에 대한 사용자 지정 형식 문자열은 "HH:mm"입니다.
    T 자세한 시간 패턴 현재 LongTimePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    예를 들어, 고정 culture에 대한 사용자 지정 형식 문자열은 "HH:mm:ss"입니다.
    u 정렬 가능한 유니버설 날짜/시간 패턴 현재 UniversalSortableDateTimePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다. 이 패턴은 표준으로 정의되어 있으며 해당 속성은 읽기 전용입니다. 따라서 이 패턴은 사용된 culture나 제공된 형식 공급자에 관계없이 항상 같습니다.
    사용자 지정 형식 문자열은 "yyyy'-'MM'-'dd HH':'mm':'ss'Z"입니다.
    날짜 및 시간의 형식이 지정될 때 표준 시간대는 변환되지 않습니다. 따라서 응용 프로그램에서는 이 형식 지정자를 사용하기 전에 현지 날짜 및 시간을 UTC(지역 표준시)로 변환해야 합니다.
    U 정렬 가능한 유니버설 날짜/시간 패턴 현재 FullDateTimePattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    이 패턴은 전체 날짜/자세한 시간(F) 패턴과 동일합니다. 그러나 형식 지정 작업이 형식을 지정할 DateTime 개체에 해당하는 UTC(지역 표준시)에 대해 수행된다는 점이 다릅니다.
    Y 또는 y 년 월 패턴 현재 YearMonthPattern 속성으로 정의된 사용자 지정 DateTime 형식 문자열을 나타냅니다.
    예를 들어, 고정 culture에 대한 사용자 지정 형식 문자열은 "yyyy MMMM"입니다.
    기타 모든 단일 문자 알 수 없는 지정자 알 수 없는 지정자는 런타임 형식 예외를 throw합니다.


    예제

     // This code example demonstrates the ToString(String) and
    // ToString(String, IFormatProvider) methods for integral and
    // floating-point numbers, in conjunction with the standard
    // numeric format specifiers.
    // This code example uses the System.Int32 integral type and
    // the System.Double floating-point type, but would yield
    // similar results for any of the numeric types. The integral
    // numeric types are System.Byte, SByte, Int16, Int32, Int64,
    // UInt16, UInt32, and UInt64. The floating-point numeric types
    // are Decimal, Single, and Double.

    using System;
    using System.Globalization;
    using System.Threading;

    class Sample
    {
        public static void Main()
        {
    // Format a negative integer or floating-point number in various ways.
        int    integralVal = -12345;
        double floatingVal = -1234.567d;

        string msgCurrency =    "(C) Currency: . . . . . . ";
        string msgDecimal  =    "(D) Decimal:. . . . . . . ";
        string msgScientific =  "(E) Scientific: . . . . . ";
        string msgFixedPoint =  "(F) Fixed point:. . . . . ";
        string msgGeneral =     "(G) General (default):. . ";
        string msgNumber =      "(N) Number: . . . . . . . ";
        string msgPercent =     "(P) Percent:. . . . . . . ";
        string msgRoundTrip =   "(R) Round-trip: . . . . . ";
        string msgHexadecimal = "(X) Hexadecimal:. . . . . ";

        string msg1 = "Use ToString(String) and the current thread culture.\n";
        string msg2 = "Use ToString(String, IFormatProvider) and a specified culture.\n";
        string msgCulture     = "Culture:";
        string msgIntegralVal = "Integral value:";
        string msgFloatingVal = "Floating-point value:";

        CultureInfo ci;
    //
        Console.Clear();
        Console.WriteLine("Standard Numeric Format Specifiers:\n");
    // Display the values.
        Console.WriteLine(msg1);

    // Display the thread current culture, which is used to format the values.
        ci = Thread.CurrentThread.CurrentCulture;
        Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName);

    // Display the integral and floating-point values.
        Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal);
        Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal);
        Console.WriteLine();

    // Use the format specifiers that are only for integral types.
        Console.WriteLine("Format specifiers only for integral types:");
        Console.WriteLine(msgDecimal     + integralVal.ToString("D"));
        Console.WriteLine(msgHexadecimal + integralVal.ToString("X"));
        Console.WriteLine();

    // Use the format specifier that is only for the Single and Double
    // floating-point types.
        Console.WriteLine("Format specifier only for the Single and Double types:");
        Console.WriteLine(msgRoundTrip   + floatingVal.ToString("R"));
        Console.WriteLine();

    // Use the format specifiers that are for integral or floating-point types.
        Console.WriteLine("Format specifiers for integral or floating-point types:");
        Console.WriteLine(msgCurrency    + floatingVal.ToString("C"));
        Console.WriteLine(msgScientific  + floatingVal.ToString("E"));
        Console.WriteLine(msgFixedPoint  + floatingVal.ToString("F"));
        Console.WriteLine(msgGeneral     + floatingVal.ToString("G"));
        Console.WriteLine(msgNumber      + floatingVal.ToString("N"));
        Console.WriteLine(msgPercent     + floatingVal.ToString("P"));
        Console.WriteLine();

    // Display the same values using a CultureInfo object. The CultureInfo class
    // implements IFormatProvider.
        Console.WriteLine(msg2);

    // Display the culture used to format the values.
    // Create a European culture and change its currency symbol to "euro" because
    // this particular code example uses a thread current UI culture that cannot
    // display the euro symbol (€).
        ci = new CultureInfo("de-DE");
        ci.NumberFormat.CurrencySymbol = "euro";
        Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName);

    // Display the integral and floating-point values.
        Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal);
        Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal);
        Console.WriteLine();

    // Use the format specifiers that are only for integral types.
        Console.WriteLine("Format specifiers only for integral types:");
        Console.WriteLine(msgDecimal     + integralVal.ToString("D", ci));
        Console.WriteLine(msgHexadecimal + integralVal.ToString("X", ci));
        Console.WriteLine();

    // Use the format specifier that is only for the Single and Double
    // floating-point types.
        Console.WriteLine("Format specifier only for the Single and Double types:");
        Console.WriteLine(msgRoundTrip   + floatingVal.ToString("R", ci));
        Console.WriteLine();

    // Use the format specifiers that are for integral or floating-point types.
        Console.WriteLine("Format specifiers for integral or floating-point types:");
        Console.WriteLine(msgCurrency    + floatingVal.ToString("C", ci));
        Console.WriteLine(msgScientific  + floatingVal.ToString("E", ci));
        Console.WriteLine(msgFixedPoint  + floatingVal.ToString("F", ci));
        Console.WriteLine(msgGeneral     + floatingVal.ToString("G", ci));
        Console.WriteLine(msgNumber      + floatingVal.ToString("N", ci));
        Console.WriteLine(msgPercent     + floatingVal.ToString("P", ci));
        Console.WriteLine();
        }
    }
    /*
    This code example produces the following results:

    Standard Numeric Format Specifiers:

    Use ToString(String) and the current thread culture.

    Culture:                  English (United States)
    Integral value:           -12345
    Floating-point value:     -1234.567

    Format specifiers only for integral types:
    (D) Decimal:. . . . . . . -12345
    (X) Hexadecimal:. . . . . FFFFCFC7

    Format specifier only for the Single and Double types:
    (R) Round-trip: . . . . . -1234.567

    Format specifiers for integral or floating-point types:
    (C) Currency: . . . . . . ($1,234.57)
    (E) Scientific: . . . . . -1.234567E+003
    (F) Fixed point:. . . . . -1234.57
    (G) General (default):. . -1234.567
    (N) Number: . . . . . . . -1,234.57
    (P) Percent:. . . . . . . -123,456.70 %

    Use ToString(String, IFormatProvider) and a specified culture.

    Culture:                  German (Germany)
    Integral value:           -12345
    Floating-point value:     -1234.567

    Format specifiers only for integral types:
    (D) Decimal:. . . . . . . -12345
    (X) Hexadecimal:. . . . . FFFFCFC7

    Format specifier only for the Single and Double types:
    (R) Round-trip: . . . . . -1234,567

    Format specifiers for integral or floating-point types:
    (C) Currency: . . . . . . -1.234,57 euro
    (E) Scientific: . . . . . -1,234567E+003
    (F) Fixed point:. . . . . -1234,57
    (G) General (default):. . -1234,567
    (N) Number: . . . . . . . -1.234,57
    (P) Percent:. . . . . . . -123.456,70%

    */


    출처 : http://msdn.microsoft.com/ko-kr/library/fht0f5be(VS.80).aspx
    Posted by 사나에
    개발 이야기/Visual C#2008. 4. 13. 18:29
    Hoons .NET 정기 모임 CodeDom 주제발표





    Posted by 사나에
    개발 이야기/Visual C#2008. 4. 13. 18:29

    System.CodeDom, System.CodeDom.Compiler 네임스페이스를 통해 코드컴파일러를 구성 할 수 있다.

    [클래스 생성 및 컴파일] ==> 클래스를 생성하고 컴파일까지 완료하여 파일을 생성한다.

               static string providerName = "cs";
            static string sourceFileName = "test.cs";

            /// <summary>
            /// 클래스 생성 및 컴파일
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button1_Click(object sender, EventArgs e)
            {
                CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName);
             
                CodeCompileUnit cu = new CodeCompileUnit();
                cu = BuildHelloWorldGraph();

                StreamWriter sourceFile = new StreamWriter(sourceFileName);
                provider.GenerateCodeFromCompileUnit(cu, sourceFile, null);
                sourceFile.Close();

                CompilerParameters opt = new CompilerParameters(new string[] { "System.dll" });
                opt.GenerateExecutable = true;
                opt.OutputAssembly = "HelloWorld.exe";
                opt.TreatWarningsAsErrors = true;
                opt.IncludeDebugInformation = true;
                opt.GenerateInMemory = true;
                opt.CompilerOptions = "/doc:HelloWorldDoc.xml";

                CompilerResults results;
                results = provider.CompileAssemblyFromFile(opt, sourceFileName);
            }

            /// <summary>
            /// 코드컴파일유닛 : 그래프를 생성하징
            /// </summary>
            /// <returns></returns>
            public static CodeCompileUnit BuildHelloWorldGraph()
            {
                // Create a new CodeCompileUnit to contain the program graph.
                CodeCompileUnit compileUnit = new CodeCompileUnit();

                // Declare a new namespace called Samples.
                CodeNamespace samples = new CodeNamespace("Samples");
                // Add the new namespace to the compile unit.
                compileUnit.Namespaces.Add(samples);
                // Add the new namespace import for the System namespace.
                samples.Imports.Add(new CodeNamespaceImport("System"));


                #region 클래스 주석부분 선언하기

                // Declare a new type called Class1.
                CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");
                class1.Comments.Add(new CodeCommentStatement("<summary>", true));
                class1.Comments.Add(new CodeCommentStatement("Create a Hello World application.", true));
                class1.Comments.Add(new CodeCommentStatement(@"<seealso cref=" + '"' + "Class1.Main" + '"' + "/>", true));
                class1.Comments.Add(new CodeCommentStatement("</summary>", true));
                // Add the new type to the namespace type collection.
                samples.Types.Add(class1);

                // Declare a new code entry point method.
                CodeEntryPointMethod start = new CodeEntryPointMethod();
                start.Comments.Add(new CodeCommentStatement("<summary>", true));
                start.Comments.Add(new CodeCommentStatement("Main method for HelloWorld application.", true));
                start.Comments.Add(new CodeCommentStatement(@"<para>Add a new paragraph to the description.</para>", true));
                start.Comments.Add(new CodeCommentStatement("</summary>", true));

                #endregion

                // Create a type reference for the System.Console class.
                CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console");

                // CodeMethodInvokeExpression.CodeMethodInvokeExpression(CodeExpression targetObject, string methodName, params CodeExpression[] parameters)
                // Build a Console.WriteLine statement.
                CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(csSystemConsoleType, "WriteLine",
                    new CodePrimitiveExpression("Hello World!"));

                // Add the WriteLine call to the statement collection.
                start.Statements.Add(cs1);

                // Build another Console.WriteLine statement.
                CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(csSystemConsoleType, "WriteLine",
                    new CodePrimitiveExpression("Press the ENTER key to continue."));

                // Add the WriteLine call to the statement collection.
                start.Statements.Add(cs2);

                // Build a call to System.Console.ReadLine.
                CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression(csSystemConsoleType, "ReadLine");

                // Add the ReadLine statement.
                start.Statements.Add(csReadLine);
                // Add the code entry point method to the Members collection of the type.
                class1.Members.Add(start);

                return compileUnit;
            }


    Posted by 사나에
    개발 이야기/Visual C#2008. 3. 31. 16:53
    .NetFramwork 2.0에서 추가 된 내용으로 기존의 WebMail방식이 바뀌었다.

    SmtpClient 클래스
    참고: 이 클래스는 .NET Framework 버전 2.0에서 새로 추가되었습니다.

    응용 프로그램에서 SMTP(Simple Mail Transfer Protocol)를 사용하여 전자 메일을 보낼 수 있도록 합니다.

    네임스페이스: System.Net.Mail
    어셈블리: System(system.dll)

     
    Posted by 사나에
    개발 이야기/Visual C#2008. 3. 25. 15:20
    * 구성 요소에서 요청한 자동 트랜잭션 형식을 지정합니다.
    .NET Framework 클래스 라이브러리
    TransactionOption 열거형

    System.EnterpriseServices의 TransactionOption을 통해 COM+에서 Transaction 설정을 간단히 할 수 있다.

    MSDN의 내용을 간단히 살펴보면 다음과 같다.
    구성 요소에서 요청한 자동 트랜잭션 형식을 지정합니다.

    네임스페이스: System.EnterpriseServices
    어셈블리: System.EnterpriseServices(system.enterpriseservices.dll)

    C#
    [SerializableAttribute]
    public enum TransactionOption

      멤버 이름 설명
    Disabled 현재 컨텍스트에서 모든 트랜잭션을 무시합니다.
    NotSupported 트랜잭션을 제어하지 않고 컨텍스트에서 구성 요소를 만듭니다.
    Required 트랜잭션이 있으면 트랜잭션을 공유하고 필요하면 새 트랜잭션을 만듭니다.
    RequiresNew 현재 컨텍스트의 상태에 관계 없이 새 트랜잭션으로 구성 요소를 만듭니다.
    Supported 트랜잭션이 있으면 트랜잭션을 공유합니다.

    .NET 설치 도구(Regsvcs.exe)를 사용하면 ServicedComponent [ http://msdn2.microsoft.com/ko-kr/library/3kk2dasz(VS.80,printer).aspx ] 트랜잭션 옵션의 기본값을 Disabled [ http://msdn2.microsoft.com/ko-kr/library/bb462165(VS.80,printer).aspx ] 로 설정합니다.

    다음 코드 예제에서는 TransactionOption 형식을 사용하는 방법을 보여 줍니다.

    C#
    using System;
    using System.EnterpriseServices;
    using System.Reflection;

    // References: System.EnterpriseServices
    // ServicedComponent  : COM+

    // TransactionOption값을 Disabled로 설정하였을 때는 현재의 모든 트랜잭션이 무시됩니다.
    // 현재 트랜잭션이 있다고하여도 트랜젹션을 처리하지않고 무시가됩니다.
    [Transaction(TransactionOption.Disabled)]
    public class TransactionAttribute_TransactionDisabled : ServicedComponent
    {
    }

    // TransactionOption값을 NotSupported로 설정하였을 때는 트랜잭션을 전혀 구성하지않는다고 생각하시면됩니다.
    // 즉, 트랜잭션 처리가 없는 Select 문경우 NotSupported를 사용하시면됩니다.
    [Transaction(TransactionOption.NotSupported)]
    public class TransactionAttribute_TransactionNotSupported : ServicedComponent
    {
    }

    // TransactionOption값을 Supported로 설정하였을 때는 트랜잭션을 사용하게 됩니다.
    // 이는 트랜잭션이 있으면 트랜잭션을 공유하게 됩니다.
    [Transaction(TransactionOption.Supported)]
    public class TransactionAttribute_TransactionSupported : ServicedComponent
    {
    }

    // TransactionOption값을 Required로 설정하였을 때는 트랜잭션을 지원하겠다는것입니다.
    // 이는 트랜잭션이 있으면 트랜잭션을 공유하고 없으면 새 트랜잭션을 만들게됩니다.
    // Insert, Delete, Update 경우 사용하면 되겠지요~
    [Transaction(TransactionOption.Required)]
    public class TransactionAttribute_TransactionRequired : ServicedComponent
    {
    }

    // TransactionOption값을 RequiresNew로 설정하였을 때는 무조건 트랜잭션을 지원하겠다는것입니다.
    // 이는 트랜잭션이 있든지없든지 상관없이  새 트랜잭션을 만들게됩니다.

    [Transaction(TransactionOption.RequiresNew)]
    public class TransactionAttribute_TransactionRequiresNew : ServicedComponent
    {
    }

    http://msdn2.microsoft.com/ko-kr/library/system.enterpriseservices.transactionoption(VS.80).aspx

    Posted by 사나에
    개발 이야기/Visual C#2008. 3. 17. 14:47

    public class SamplesDelegate
    {
        public delegate String myMethodDelegate(int myInt); // 클래스와 동급으로 정의

        public class mySampleClass
        {
            // 인스턴스 메서드 선언
            public String myStringMethod(int myInt)
            {
                if(myInt > 0)
                    return "positive";
                if (myInt < 0)
                    return "negative";

                return "zero";
            }

            // 정적 메서드 선언
            public static String mySignMethod(int myInt)
            {
                if (myInt > 0)
                    return ("+");

                if (myInt < 0)
                    return ("-");

                return ("");
            }
        }

        public static void Main()
        {
            // 클래스 선언
            mySampleClass mClass = new mySampleClass();

            // 각 델리케이트 선언
            myMethodDelegate mDele1 = new myMethodDelegate(mClass.myStringMethod);  // 인스턴스 메서드시
            myMethodDelegate mDele2 = new myMethodDelegate(mySampleClass.mySignMethod); // 정적 메서드시

            Console.WriteLine("{0} is {1}; use the sign \"{2}\".", 5, mDele1(5), mDele2(5));
            Console.WriteLine("{0} is {1}; use the sign \"{2}\".", -3, mDele1(-3), mDele2(-3));
            Console.WriteLine("{0} is {1}; use the sign \"{2}\".", 0, mDele1(0), mDele2(0));

            Console.ReadKey();
        }
    }

    Posted by 사나에
    개발 이야기/Visual C#2008. 3. 14. 17:46
    난이도 : ★★★☆☆

    프로그램을 제작하고 클래스, 메서드, 변수 등등 주석들의 도움말이나 chm파일의 설명서를 쉽게 만드는 방법이다. 그냥 쉽게 따라하면된다.

    1. Visual Studio 빌드 속성 변경하기.
    Visual Studio 2005나 Visual Studio 2008에서 프로젝트를 하나 생성한다. 프로젝트 생성후 클래스나 변수를 선언하고 주석(///)을 단다. 프로젝트 속성을 선택하고 빌드텝에서 XML 문서 파일을 체크해준다. 그러면 프로젝트 빌드시 XML파일이 하나 생성된다. 하지만 이것을 설정하면 빌드시 주석이 없으면 경고 메세지가 나온다. 필히 주석이 100% 달아주어야한다.


    2. sandcastle과 HTML Help Workshop을 설치하자.
    HTML Help Workshop은 sandcastle이 이 프로그램의 모듈을 이용하기때문에 로컬에 우선적으로 설치되어있어야한다. HTML Help Workshop은 프리웨어로 네이버자료실등등 어디서든 구할수있다. HTML Help Workshop 설치되었다면 sandcastle 을 다운받아 설치한다. 설치가 끝나면 바탕화면이나 시작메뉴에 아무것도 생성이 되지않는다. 잘못되어다고 생각 할 필요가없다. 원래그런다. OTL.. 단, C:\Program Files\Sandcastle 에 파일이 생성되었는지만 확인하면된다. 확인되었다면 다음으로 고고고~

    사용자 삽입 이미지

    무조건 긍정적으로 버튼을 클릭!!


    3. ChmBuilder.config 파일에 한글을 추가한다.
    우리는 주석에서 한글을 사용하기때문에 한글이 인식되도록 설정해줘야한다.
    C:\Program Files\Sandcastle\ProductionTools에 ChmBuilder.config파일이 있다.
    그 파일에서 언어 부분에 한국어를 추가해주면된다. 빨간색의 Language 선언부분을 복사해서 붙여넣는다.
    <languages>
        <language id="1033" codepage="65001" name="0x409 English (United States)" />
        <language id="2052" codepage="936" name="0x804 Chinese (PRC)" />
        <language id="1042" codepage="949" name="0x412 Korean (KOREA)" />
    </languages>

    4. 이제 만들어보자.
    설정이 다 끝났다면 아까 만든 프로젝트에 클래스나 변수등을 추가하고 빌드를 하면 \프로제트명\bin\Debug 폴더에 XML파일이 하나 생성된다. (당근 디버그모드에 따라 경로명은 다르다.) 
    C:\Program Files\Sandcastle\Examples\generic에 SandcastleGui가 있다. 이걸 실행하면 아래 그림과 같은 화면이 띈다.
    Assemblies에 프로젝트 빌드 후 생성된 exe나 dll 실행파일을 넣는다. Comments에는 아까 생성된 XML파일을 설정해준다. Dependent Assemblies에는 참조하는 dll이 있다면 추가해주면된다. 없다면 그냥 비워둔다.
    다음은 Options를 설정한다. Name에는 생성될 파일의 이름을 넣어준다. Presenation Style에 vs2005를 설정한다. vs2008도 그냥 vs2005로 설정해서 사용하면된다.  LanguageID에는 1042 로 바꿔야한다.
    DefaultTargets 에는 생성물을 선택하는것이다. Chm파일로 생성물을 출력하고자한다면 Chm을 선택하고 Hxs로 출력하고 싶다면 Hxs를 선택한다. 둘다 동시에 선택해도된다. 다만 시간이 많이 걸릴뿐.. ㅋ

    사용자 삽입 이미지
    마지막으로 빌드 버튼을 클릭한다. 그리고 끝났다는 메세지가 나올때까지 기다린다. 시간이 좀 걸린다. 그냥 다른 일을 하고있으면된다. 다 되었다면 C:\Program Files\Sandcastle\Examples을 확인하면 설정한 Name 이름의 폴더가 하나 생겼을것이다. 그 폴더 안에 결과물이 생성되어 있을것이다. 끝~~~
    사용자 삽입 이미지

    Chm 실행 후 캡처 화면


     PPT : SandCastle
     링크 : http://blogs.msdn.com/sandcastle

    Posted by 사나에