개발 이야기/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 사나에
IT/IT용어2008. 3. 16. 22:51
난이도 : ★★☆☆☆

자동 코드 생성기에 대해 자료를 찾다가 '실용주의 프로그래머'책에 나온 내용을 일부 정리해본다.

코드 생성기 : 우리가 판화를 이용해서 여러장의 동일한 문서를 뽑듯이 동일한 코드를 생성하는 코드를 만드는 것이다. 즉, 코드를 작성하는 코드를 작성하라!

종류
1. 수동적 코드 생성기
1) 결과를 내기 위해 한번만 실행된다.
2) 코드가 생성된 그 시점에서 코드 생성기와는 별개가된다.
3) 타이핑을 줄여준다. 즉, 기본적으로 몇 개의 입력에서 주어진 출력을 생성하는 매개 변수화된 템플릿이다.
4) 사용되는 예
- 새 소스파일 생성.
- 프로그래밍 언어간 일회용 변환을 수행하기
- 런타임에 계산하기엔 비용이 많이 드는 참조 테이블과 여타 자원을 생성하기

2. 능동적 코드 생성기
1) 코드 생성이 필요할때마다 작동한다.
2) 어떤 형태의 스크립트나 컨트롤 파일을 읽어서 결과물을 만들어 낸다.
3) DRY원칙을 따른다.
4) 필요할때 능동적으로 만들어진다.
5) 사용되는 예
- 데이터베이스의 테이블 스키마가 수정되었을 경우 코드에서 사용하는 구조체가 자동으로 수정된다.


Posted by 사나에