블로그 이미지
따시쿵

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Notice

2015. 6. 11. 16:15 C#

 

3. LINQ를 이용한 방법으로 표현하는 경우

using System;
using System.Collections.Generic;
using System.Linq;

namespace MylambdaExpression11
{
    class Program
    {
        static void Main(string[] args)
        {
            // 예제 - 1 
            // 다음 예제에서는 Func<T, TResult> 델리게이트를 선언하고 사용하는 방법을 보여 줍니다. 
            // 이 예제에서는 Func<T, TResult> 변수를 선언하고 문자열의 문자를 대문자로 변환하는 람다 식을 할당합니다. 
            // 이 메서드를 캡슐화하는 대리자는 이후에 문자열 배열의 문자열을 대문자로 변환하기 
            // 위해 Enumerable.Select 메서드에 전달됩니다. 

            Func<string, string> selector = (string s) => s.ToUpper();

            string[] words = {"orange", "apple", "Article", "elephant", "korea", "komani" };

            IEnumerable<string> aWords = words.Select(selector);

            foreach(string word in aWords)
                Console.WriteLine(word);

            Console.WriteLine();

            // 에제 - 2
            // words 배열에서 소문자 "k"로 시작하는 단어를 찾아서 알려줍니다.
            int count = words.Count(s => s.StartsWith("k"));
            Console.WriteLine("count = {0}", count);

            Console.ReadLine();
        }
    }
}

 

실행화면 입니다.

 

'C#' 카테고리의 다른 글

람다식(Lambda Expression) - 3  (0) 2015.06.09
람다식(Lambda Expression) - 2  (0) 2015.06.09
람다식(Lambda Expression) - 1  (0) 2015.06.08
EventHandler 와 EventHandler<TEventArgs> Delegate  (0) 2015.06.04
Event 와 Delegate  (0) 2015.06.01
posted by 따시쿵
2015. 6. 9. 16:35 C#

 

2. Func와 Action으로 더 간편하게 무명 함수 만드는 경우

 

익명 메서드와 무명 함수는 코드를 더 간결하게 만들어주는 요소들입니다. 하지만 이들을 선언하기 전에 해야 하는 일들을 생긱해 보면 익명 메소드를 만들기위해서 매번 델리게이트를 선언합니다. 이 문제를 해결하기 위해 마이크로소프트는 Func와 Action 델리게이트를 미리 선언해 두었습니다.Func 델리게이트는 결과를 반환하는 메소드를 참조하기 위해, Action 델리게이트는 결과를 반환하지 않는 메소드를 참조합니다.

 

 

2. Action 델리게이트

 

시스템이 입력 파라미터가 17개인 델리게이트를 미리 정의해 두었습니다. 

 

Action<T> 델리게이트

 

매개 변수가 하나이고 TResult 매개 변수에 지정된 형식의 값을 반환하는 메서드를 캡슐화 합니다.

 

 

구문

 

public delegate TResult Func<in T, out TResult>(
     T arg
)


형식 매개 변수

 

in T
      이 대리자로 캡슐화되는 메서드의 매개 변수 형식입니다.
      이 형식 매개 변수는 반공변입니다.

      즉, 지정한 형식이나 더 적게 파생되는 모든 형식을 사용할 수 있습니다.

 

설명

 

Action<T> 델리게이트를 사용하면 사용자 지정 대리자를 명시적으로 선언하지 않고도 메서드를 매개 변수로 전달할 수 있습니다.

 

캡슐화된 메서드는 이 대리자에 의해 정의되는 메서드 시그니처(파리미터 타입과 갯수)와 일치해야 합니다.

즉, 캡슐화된 메서드에는 값으로 전달되는 매개 변수 하나가 있어야 하고 값을 반환하지 않아야 합니다.

 

C#의 경우 이 메서드는 void를 반환해야 합니다. 무시되는 값을 반환하는 메서드일 수도 있습니다. 일반적으로 이러한 메서드는 작업을 수행하는 데 사용됩니다.

 

 

예제1

 

Action<T> 델리게이트를 사용하는 경우에는 매개 변수가 하나인 메서드를 캡슐화하는 대리자를 명시적으로 정의할 필요가 없습니다.

 

예를 들어, 다음 코드에서는 DisplayMessage라는 델리게이트를 명시적으로 선언하고 WriteLine 메서드 또는 ShowWindowsMessage 메서드에 대한 참조를 해당 델리게이트 인스턴스에 할당합니다.

    delegate void DisplayMessage(string message);
    class Program
    {
        static void Main(string[] args)
        {
            DisplayMessage messageTarget;

            if (Environment.GetCommandLineArgs().Length > 1)
                messageTarget = ShowWindowMessage;
            else
                messageTarget = Console.WriteLine;

            messageTarget("Hi, Korea world !!!");

            Console.ReadLine();
        }

        static void ShowWindowMessage(string message)
        {
            MessageBox.Show(message);
        }
    }

 

예제2

 

다음 예제에서는 새 델리게이트를 명시적으로 정의하고 명명된 메서드를 할당하는 대신 Action<T> 델리게이트를 인스턴스화하여 이 코드를 간소화합니다.

    class Program
    {
        static void Main(string[] args)
        {
            Action<string> messageTarget;

            if (Environment.GetCommandLineArgs().Length > 1)
                messageTarget = ShowWindowMessage;
            else
                messageTarget = Console.WriteLine;

            messageTarget("Hi, Korea world !!!");

            Console.ReadLine();
        }

        static void ShowWindowMessage(string message)
        {
            MessageBox.Show(message);
        }

예제3

 

Action<T> 델리게이트를 anonymous method와 함께 사용할 수도 있습니다.

    class Program
    {
        static void Main(string[] args)
        {
            Action<string> messageTarget;

            if (Environment.GetCommandLineArgs().Length > 1)
                messageTarget = delegate(string s) { ShowWindowMessage(s); };
            else
                messageTarget = delegate(string s) { Console.WriteLine(s); };

            messageTarget("Hi, Korea world !!!");

            Console.ReadLine();
        }

        static void ShowWindowMessage(string message)
        {
            MessageBox.Show(message);
        }

 

예제4

 

Action<T> 델리게이트 인스턴스에 람다 식을 할당할 수도 있습니다.

    class Program
    {
        static void Main(string[] args)
        {
            Action<string> messageTarget;

            if (Environment.GetCommandLineArgs().Length > 1)
                messageTarget = (string s) => { ShowWindowMessage(s); };
            else
                messageTarget = (string s) => { Console.WriteLine(s); };

            messageTarget("Hi, Korea world !!!");

            Console.ReadLine();
        }

        static void ShowWindowMessage(string message)
        {
            MessageBox.Show(message);
        }

 

 

실행화면은 아래와 같이 두 가지 화면이 동일하게 나옵니다. 

 

 

 

'C#' 카테고리의 다른 글

람다식(Lambda Expression) - 4  (0) 2015.06.11
람다식(Lambda Expression) - 2  (0) 2015.06.09
람다식(Lambda Expression) - 1  (0) 2015.06.08
EventHandler 와 EventHandler<TEventArgs> Delegate  (0) 2015.06.04
Event 와 Delegate  (0) 2015.06.01
posted by 따시쿵
2015. 6. 9. 11:04 C#

 

2. Func와 Action으로 더 간편하게 무명 함수 만드는 경우

 

익명 메서드와 무명 함수는 코드를 더 간결하게 만들어주는 요소들입니다. 하지만 이들을 선언하기 전에 해야 하는 일들을 생긱해 보면 익명 메소드를 만들기위해서 매번 델리게이트를 선언합니다. 이 문제를 해결하기 위해 마이크로소프트는 Func와 Action 델리게이트를 미리 선언해 두었습니다.Func 델리게이트는 결과를 반환하는 메소드를 참조하기 위해, Action 델리게이트는 결과를 반환하지 않는 메소드를 참조합니다.

 

 

1. Func 델리게이트

 

.Net 프레임워크에서는 모두 17가지의 Func 델리게이트가 미리 준비되어 있습니다.

입력 파라미터는 최대 16개까지 사용 가능합니다.

 

 

Func<T, TResult> 델리게이트

 

 

구문

 

public delegate TResult Func<in T, out TResult>(
 T arg
)

 

형식 매개 변수

 

in T

 

     이 대리자로 캡슐화되는 메서드의 매개 변수 형식입니다.

     이 형식 매개 변수는 반공변입니다.

     즉, 지정한 형식이나 더 적게 파생되는 모든 형식을 사용할 수 있습니다.

 

out TResult

 

     이 대리자로 캡슐화되는 메서드의 반환 값 형식입니다.

     이 형식 매개 변수는 공변입니다.

     즉, 지정한 형식이나 더 많이 파생되는 모든 형식을 사용할 수 있습니다.

 

 

매개 변수

 

arg
      형식: T
      이 대리자로 캡슐화되는 메서드의 매개 변수입니다.

 

반환 값
     형식: TResult
     이 대리자로 캡슐화되는 메서드의 반환 값입니다.

 


설명

 

1. 이 대리자를 사용하면 사용자 지정 대리자를 명시적으로 선언하지 않고 매개 변수로 전달할 수 있는 메서드를 나타낼 수 있습니다.

 

2. 캡슐화된 메서드는 이 델리게이트에 의해 정의되는 메서드 시그니처(파라미터 타입과 갯수)와 일치해야 합니다. 즉, 캡슐화된 메서드에는 값으로 전달되는 매개 변수 하나가 있어야 하고 값을 반환해야 합니다.

 

 

예제1

 

ConvertMethod라는 델리게이트를 명시적으로 선언하고 UppercaseString 메서드에 대한 참조를 해당 델리게이트 인스턴스에 할당합니다.

    delegate string ConvertMethod(string inString);
    class Program
    {
        static void Main(string[] args)
        {
            ConvertMethod convertMeth = UppercaseString;
            string name = "Korea Forever !!!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convertMeth(name));

            Console.ReadLine();
        }

        static string  UppercaseString(string inputString)
        {
            return inputString.ToUpper();
        }
    }

 

에제2

 

다음 예제에서는 새 델리게이트를 명시적으로 정의하고 명명된 메서드를 할당하는 대신 Func<T, TResult> 델리게이트를 인스턴스화하여 이 코드를 간소화합니다.

        static void Main(string[] args)
        {
            Func<string, string> convertMethod = UppercaseString;
            string name = "Korea Forever !!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convertMethod(name));

            Console.ReadLine();
        }

        static string UppercaseString(string inputString)
        {
            return inputString.ToUpper();
        }

 

예제3

 

C#에서는 다음 예제와 같이 Func<T, TResult> 델리게이트를 anonymous method와 함께 사용할 수도 있습니다.

        static void Main(string[] args)
        {
            Func<string, string> convert = delegate(string s)
            {
                return s.ToUpper();
            };

            string name = "Korea Forever !!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convert(name));

            Console.ReadLine();
        }

 

예제4

 

다음 예제와 같이 Func<T, TResult> 델리게이트에 람다식을 할당할 수도 있습니다.

            Func<string, string> convert = (string s) => s.ToUpper();

            string name = "Korea Forever !!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convert(name));

            Console.ReadLine();

 

4개 예제에 대한 동일한 결과화면 입니다.

 

 

 

'C#' 카테고리의 다른 글

람다식(Lambda Expression) - 4  (0) 2015.06.11
람다식(Lambda Expression) - 3  (0) 2015.06.09
람다식(Lambda Expression) - 1  (0) 2015.06.08
EventHandler 와 EventHandler<TEventArgs> Delegate  (0) 2015.06.04
Event 와 Delegate  (0) 2015.06.01
posted by 따시쿵
2015. 6. 8. 17:22 C#

람다식을 사용하는 이유와 목적을 먼저 살펴 보는게 순서일 듯 싶네요.

 

  • 익명 메소드를 만드는 경우
  • Func와 Action으로 더 간편하게 무명 함수 만드는 경우
  • LINQ를 이용한 방법으로 표현하는 경우
1. 익명 메소드(Anonymous method)를 만드는 경우

 

익명 메소드를 만드는 경우에는 delegate를 이용한 방법도 있습니다. 그런데 람다식을 이용한 방법도 제공하는 이유는 개발 히스토리에 해답이 있습니다.

 

마이크로소프트는 C# 2.0 에서 델리게이트를 이용한 익명 메소드를 만드는 방법을 제공했고, 람다식은 C# 3.0 에서 와서야 도입 되었습니다. 따라서 C# 2.0 에서 작성한 프로그램을 C# 3.0 에서 기능을 삭제할 수는 없는 일입니다.

 

식 형식

 

매개 변수 목록 => 식

 

문 형식

 

(매개 변수 목록) => {

                             ..........................

                             ..........................

                             ..........................

                           };

 

 

 

예제1 : 식 형식의 람다식 표현 

        delegate int Calculate(int a, int b);

        static void Main(string[] args)
        {
            // 1. 람다식을 이용한 표현(매개변수 타입 있는 경우)
            Calculate cal1 = (int a, int b) => a + b;
            Console.WriteLine("Lambda Expression : {0} + {1} = {2}", 4, 5, cal1(4, 5));

            // 2. 람다식을 이용한 표현(매개변수 타입 없는 경우)
            Calculate cal2 = (a, b) => a + b;
            Console.WriteLine("Lambda Expression : {0} + {1} = {2}", 4, 5, cal2(4, 5));

            // 3. 델리게이트를 이용한 표현
            Calculate cal3 = delegate(int a, int b) { return a + b; };
            Console.WriteLine("Delegate : {0} + {1} = {2}", 4, 5, cal3(4,5));

            Console.ReadLine();
        }

 

 

 

 

예제 2: 문 형식의 람다식

 

식 형식의 람다식에서는 반환 형식이 없는 무명 함수를 만들 수 없지만, 문 형식의 람다식을 이용하면 가능합니다.

        delegate void DoSomething();
        static void Main(string[] args)
        {
            DoSomething DoIt = () =>
            {
                Console.WriteLine("여기는 ");
                Console.WriteLine("대한민국 ");
                Console.WriteLine("입니다");
            };

            DoIt();

            Console.ReadLine();
        }

 

 

 

 

 

예제3 : 람다식이 익명 메소드를 대치하는 경우. 파라미터가 생략되는 경우가 있습니다.

 

 

button control 의 Click 이벤트는 EventHandler 델리게이트이며, 두 개의 파라미터를 가집니다. object sender, EventArgs e. 파라미터가 익명 메소드 안에서 사용하지 않는 경우에는 생략하는 경우도 있습니다.

        private void Form1_Load(object sender, EventArgs e)
        {
            Button button1 = new Button();
            button1.Text = "Click me !!!";

            // 1. 델리게이트 이용 & 파라미터를 생략한 경우
            button1.Click += delegate
            {
                MessageBox.Show("Button1 Clicked!");
            };

            // 2. 델리게이트 이용 & 파라미터가 있는 경우
            button1.Click += delegate(object eventSender, EventArgs eventArgs)
            {
                MessageBox.Show("Button1 Clicked!");
            };

            // 3. 람다식을 이용한 식으로 표현함
            button1.Click += (object eventSender, EventArgs eventArgs) => MessageBox.Show("Button1 Clicked!");

            // 4. 람다식을 이용한 문으로 표현함
            button1.Click += (object eventSender, EventArgs eventArgs) => { MessageBox.Show("Button1 Clicked!"); };

            // 5. 람다식 이용 & 파라미터 타입 생략하는 경우
            button1.Click += (eventSender, eventArgs) => { MessageBox.Show("Button1 Clicked!"); };

            this.Controls.Add(button1);
        }

 

 

 

 

 

'C#' 카테고리의 다른 글

람다식(Lambda Expression) - 3  (0) 2015.06.09
람다식(Lambda Expression) - 2  (0) 2015.06.09
EventHandler 와 EventHandler<TEventArgs> Delegate  (0) 2015.06.04
Event 와 Delegate  (0) 2015.06.01
초단위 시간 경과 보이기  (0) 2015.05.12
posted by 따시쿵
2015. 6. 4. 12:10 C#

프로그램 설명


EventHandler 와 EventHandler<TEventArgs> Delegate 를 비교하여 설명하는 예제입니다.

  • EventHandler Delegate  - 이벤트 데이터가 없는 이벤트를 처리할 메서드를 나타냅니다.
  • EventHandler<TEventArgs> Delegate - 이벤트가 데이터를 제공할 때 이벤트를 처리할 메서드를 나타냅니다.

1. EventHandler delegate


구문


[SerializableAttribute]

[ComVisibleAttribute(true)]

public delegate void EventHandler(

Object sender,

EventArgs e

)



매개 변수


sender

형식: System.Object

이벤트 소스입니다. 


e

형식: System.EventArgs

이벤트 데이터가 포함되지 않은 개체입니다. 


설명


.NET Framework의 이벤트 모델은 이벤트와 이벤트 처리기를 연결하는 이벤트 대리자가 있다는 사실을 기초로 만들어졌습니다. 이벤트를 발생시키려면 다음과 같은 두 가지 요소가 필요합니다.


  • 이벤트에 응답하는 메서드를 식별하는 대리자입니다.
  • 이벤트 데이터를 제공 하는 경우 이벤트 데이터를 보유하 고 필요한 경우는 클래스입니다.


대리자는 시그니처를 정의하는 형식, 즉 메서드에 대한 반환 값 형식과 매개 변수 목록 형식입니다. 대리자 형식을 사용하여 대리자와 같은 시그니처가 있는 모든 메서드를 참조하는 변수를 선언할 수 있습니다.


이벤트 처리기 대리자의 표준 시그니처에서 값을 반환 하지 않는 메서드를 정의 합니다. 


첫 번째 매개 변수 형식이 Object 이벤트를 발생 시키는 인스턴스를 참조 합니다. 

두 번째 매개 변수 형식에서 파생 된 EventArgs 및 이벤트 데이터를 보유 합니다. 이벤트에서 이벤트 데이터를 생성 하지 않습니다 두 번째 매개 변수는 단순히 값의 경우는 EventArgs.Empty 필드입니다. 그렇지 않으면 두 번째 매개 변수에서 파생 된 형식입니다 EventArgs 하 고 모든 필드 또는 속성은 이벤트 데이터를 보관 하는 데 필요한을 제공 합니다.


EventHandler 대리자는 특별히 데이터를 생성 하지 하는 이벤트에 대한 이벤트 처리기 메서드를 나타내는 미리 정의된 대리자입니다. 


이벤트를 처리할 메서드와 이벤트를 연결하려면 대리자의 인스턴스를 해당 이벤트에 추가합니다. 대리자를 제거하지 않는 경우, 이벤트가 발생할 때마다 이벤트 처리기가 호출됩니다.


예제

    class Program
    {
        #region Event Publisher
        class Publisher
        {
            public event EventHandler Somethinghappened;

            public void DoSometing()
            {
                EventHandler hanlder = Somethinghappened;
                if (hanlder != null)
                    hanlder(this, EventArgs.Empty);
            }
        }
        #endregion

        #region event Subscriber
        class Subscriber
        {
            public void HanldeEvent(object sender, EventArgs e)
            {
                Console.WriteLine("Something happened to " + sender.ToString());
                Console.ReadLine();
            }
        }
        #endregion

        static void Main(string[] args)
        {
            Publisher publisher = new Publisher();
            Subscriber subscriber = new Subscriber();
            publisher.Somethinghappened += subscriber.HanldeEvent;

            publisher.DoSometing();
        }
    }

소스 파일 : 

MyEventHandler2.zip



2. EventHandler<TEventArgs> delegate


구문


[SerializableAttribute]

public delegate void EventHandler<TEventArgs>(

Object sender,

TEventArgs e

)



형식 매개 변수

TEventArgs

이벤트에서 생성한 이벤트 데이터의 형식입니다.


매개 변수

sender

형식: System.Object

이벤트 소스입니다.

e

형식: TEventArgs

이벤트 데이터를 포함하는 개체입니다. 



설명


.NET Framework의 이벤트 모델은 이벤트와 이벤트 처리기를 연결하는 이벤트 대리자가 있다는 사실을 기초로 만들어졌습니다. 이벤트를 발생시키려면 다음과 같은 두 가지 요소가 필요합니다.


  • 이벤트에 응답하는 메서드를 참조하는 대리자입니다.
  • 이벤트 데이터를 제공 하는 경우 이벤트 데이터를 보유하고 필요한 경우는 클래스입니다.


대리자는 시그니처를 정의하는 형식, 즉 메서드에 대한 반환 값 형식과 매개 변수 목록 형식입니다. 대리자 형식을 사용하여 대리자와 같은 시그니처가 있는 모든 메서드를 참조하는 변수를 선언할 수 있습니다.


이벤트 처리기 대리자의 표준 시그니처에서 값을 반환 하지 않는 메서드를 정의 합니다. 


첫 번째 매개 변수 형식이 Object 이벤트를 발생 시키는 인스턴스를 참조 합니다. 

두 번째 매개 변수 형식에서 파생 된 EventArgs 및 이벤트 데이터를 보유 합니다. 

이벤트에서 이벤트 데이터를 생성 하지 않습니다 두 번째 매개 변수는 단순히 값의 경우는 EventArgs.Empty 필드입니다. 그렇지 않으면 두 번째 매개 변수에서 파생 된 형식입니다 EventArgs 하 고 모든 필드 또는 속성은 이벤트 데이터를 보관 하는 데 필요한을 제공 합니다.


EventHandler<TEventArgs> 대리자는 미리 정의 된 데이터를 생성 하는 이벤트에 대한 이벤트 처리기 메서드를 나타내는 대리자입니다. 


이벤트에서 이벤트 데이터를 생성할 때 EventHandler<TEventArgs>을 사용하면 사용자 지정 대리자를 직접 코딩할 필요가 없습니다. 단순히 이벤트 데이터 개체의 형식을 제네릭 매개 변수로 제공합니다.


이벤트를 처리할 메서드와 이벤트를 연결하려면 대리자의 인스턴스를 해당 이벤트에 추가합니다. 대리자를 제거하지 않는 경우, 이벤트가 발생할 때마다 이벤트 처리기가 호출됩니다.




예제

    class Program
    {
        static void Main(string[] args)
        {
            Counter c = new Counter(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");
                c.Add(1);
            }            
        }

        static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
        {
            Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
            Console.ReadLine();
        }
    }

    class Counter
    {
        private int threshold;
        private int total;

        public Counter(int passedThreshold)
        {
            threshold = passedThreshold;
        }

        public void Add(int x)
        {
            total += x;
            if (total >= threshold)
            {
                ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
                args.Threshold = threshold;
                args.TimeReached = DateTime.Now;
                OnThresholdReached(args);
            }
        }

        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
        {
            EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
    }

    public class ThresholdReachedEventArgs : EventArgs
    {
        public int Threshold { get; set; }
        public DateTime TimeReached { get; set; }
    }


소스 파일 :


MyEventHandler1.zip






'C#' 카테고리의 다른 글

람다식(Lambda Expression) - 2  (0) 2015.06.09
람다식(Lambda Expression) - 1  (0) 2015.06.08
Event 와 Delegate  (0) 2015.06.01
초단위 시간 경과 보이기  (0) 2015.05.12
로그인 창  (0) 2015.05.08
posted by 따시쿵
2015. 6. 1. 17:28 C#

프로그램 설명


이벤트와 델리게이트에 간단한 예제입니다.


1. 이벤트란?


1. A mechanism for communication between objects.

2. Used in building Loosely Coupled Applications.

   Encodo C# Handbook 7.30 – Loose vs. Tight Coupling

3. Helps Extending Applications.


오브젝트간에 통신(신호)을 담당하는 부분이며 Loosely Coupled 이 가장 큰 특징입니다.

 

 

델리게이트란?

 

1. Agreement / Contract between Publisher and Subscriber

2. Determines the signature of the event handler method in Subscriber

 

 

델리게이트와 이벤트를 만드는 순서


1. Define a delegate

2. Define an event based on that delegate 

3. Raise the event


2. 예제 시나리오를 위해서 3개의 클래스를 미리 만들어 두고, 여기에 델리게이트와 이벤트를 추가하는 것으로 하겠습니다.

 

전체적인 그림은 다음과 같으며, 기본 프로그램에 추가해 보도록 하겠습니다. 

 

기본 소스 파일 :

 

MainForm.cs MainForm.Designer.cs MainForm.resx Video.cs VideoEncoder.cs

 

mainform class

    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            Thread t_handler = new Thread(WorkingThread);
            t_handler.IsBackground = true;
            t_handler.Start();
        }

        private void WorkingThread()
        {
            var video = new Video() { Title = "video 1" };
            var videoEncoder = new VideoEncoder();

            videoEncoder.Encode(video, textBox1);
        }
    }

 

Video class

    public class Video
    {
        public string Title { get; set; }
    }

 

VideoEncoder class

    public class VideoEncoder
    {
        private delegate void SetDisplayText(string displayText, TextBox textbox1);
        public void Encode(Video video, TextBox textbox1)
        {
            TextDisplay("Encoding video...\n", textbox1);
            Thread.Sleep(3000);
            TextDisplay("End.", textbox1);
        }

        private void TextDisplay(string displayText, TextBox textbox1)
        {
            if(textbox1.InvokeRequired)
            {   
                textbox1.Invoke(new SetDisplayText(TextDisplay), displayText, textbox1);
                Application.DoEvents();
                return;
            }
            else
            {
                textbox1.AppendText(displayText + "\n");
            }
        }
    }

 

3. 델리게이트와 이벤트를 VideoEncoder class 에 정의합니다. (Publisher 정의)

    public class VideoEncoder
    {
        private delegate void SetDisplayText(string displayText, TextBox textbox1);

        // 1. Define a delegate
        // 2. Define an event based on that delegate
        // 3. Raise the event
        public delegate void VideoEncodedEventHandler(object sender, EventArgs args, TextBox textbpx1);
        public event VideoEncodedEventHandler VideoEncoded;

        public void Encode(Video video, TextBox textbox1)
        {
            TextDisplay("Encoding video...\n", textbox1);
            Thread.Sleep(3000);

            OnVideoEncoded(textbox1);

            TextDisplay("End.", textbox1);
        }

        private void TextDisplay(string displayText, TextBox textbox1)
        {
            if(textbox1.InvokeRequired)
            {   
                textbox1.Invoke(new SetDisplayText(TextDisplay), displayText, textbox1);
                Application.DoEvents();
                return;
            }
            else
            {
                textbox1.AppendText(displayText + "\n");
            }
        }
    }

 

이벤트를 호출합니다.

        protected virtual void OnVideoEncoded(TextBox textbox1)
        {
            if (VideoEncoded != null)
                VideoEncoded(this, EventArgs.Empty, textbox1);
        }

 

 

4. 이벤트 핸들러 구현합니다.(Subscriber 정의)

    public class MailService
    {
        public void OnVideoEncoded(object sender, EventArgs e, TextBox textbox1)
        {
            textbox1.Invoke((MethodInvoker)delegate
            {
                textbox1.AppendText("MailService: Sending an email....\n");
            });
        }
    }

    public class MessageService
    {
        public void OnVideoEncoded(object sender, EventArgs e, TextBox textbox1)
        {
            textbox1.Invoke((MethodInvoker)delegate
            {
                textbox1.AppendText("MessageService: Sending an message text....\n");
            });
        }
    }

 

5. 이벤트와 이벤트 핸들러를 추가합니다. (매개체 역할)  

            var video = new Video() { Title = "video 1" };
            var videoEncoder = new VideoEncoder();      // publisher
            var mailService = new MailService();        // subscriber
            var messageService = new MessageService();  // subscriber

            videoEncoder.VideoEncoded += mailService.OnVideoEncoded;
            videoEncoder.VideoEncoded += messageService.OnVideoEncoded;

            videoEncoder.Encode(video, textBox1);


현재까지 작업한 소스 파일 : MyEvnetnDelegate1.zip


6. 파라미터를 encapsulation 시켜서 구현하는 방법입니다.


파라미터를 숨길 VideoEventArgs class 를 추가 합니다.

    public class VideoEventArgs : EventArgs
    {
        public Video Video { get; set; }
    }

기존의 델리게이트 정의 부분의 두 번째 파라미터를 아래와 같이 VideoEventArgs class 로 변경합니다.


변경 전

public delegate void VideoEncodedEventHandler(object sender, EventArgs args, TextBox text1);

변경 후

public delegate void VideoEncodedEventHandler(object sender, VideoEventArgs args, TextBox text1);


이벤트를 호출하는 부분도 변경해 줍니다.


기존에 EventArgs 를 파라미터로 받는 부분을 VideoEventArgs 로 변경을 해 줍니다.


소스 파일 : 

MyEvnetnDelegate1(2).zip


7.EventHandler<TEventargs> 를 이용한 델리게이트


이벤트에서 이벤트 데이터를 생성할 때 EventHandler<TEventArgs>을 사용하면 사용자 지정 대리자를 직접 코딩할 필요가 없습니다. 단순히 이벤트 데이터 개체의 형식을 제네릭 매개 변수로 제공합니다.


VideoEventArgs class 를 다음과 같이 변경합니다.

    public class VideoEventArgs : EventArgs
    {
        public Video Video { get; set; }
        public TextBox Textbox1 { get; set; }
    }


다음 줄을 삭제합니다.

public delegate void VideoEncodedEventHandler(object sender, EventArgs args, TextBox text1);
public event VideoEncodedEventHandler VideoEncoded;


EventHanlder<TEventArgs> 델리게이트를 추가합니다.

public event EventHandler VideoEncoded;


소스 파일 : 

MyEvnetnDelegate1(3).zip



실행 화면





'C#' 카테고리의 다른 글

람다식(Lambda Expression) - 1  (0) 2015.06.08
EventHandler 와 EventHandler<TEventArgs> Delegate  (0) 2015.06.04
초단위 시간 경과 보이기  (0) 2015.05.12
로그인 창  (0) 2015.05.08
멀티플(multiple) 윈도우 - 2  (0) 2015.05.07
posted by 따시쿵
2015. 5. 12. 16:30 C#
프로그램 설명

타이머 클래스를 이용해서 초단위로 경과 시간을 보이는 예제입니다.



실행 후


폼 로드시에 현재 날자와 시간을 보여주고 1초 단위로 화면에 업데이트 합니다.

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            // Set up a timer to trigger every minute.
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 1000;                          // 1 seconds
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();
        }

        public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.
            Invoke((MethodInvoker)delegate
            {
                label1.Text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            });
        }


소스 파일 : 

MyTimer1.zip


'C#' 카테고리의 다른 글

EventHandler 와 EventHandler<TEventArgs> Delegate  (0) 2015.06.04
Event 와 Delegate  (0) 2015.06.01
로그인 창  (0) 2015.05.08
멀티플(multiple) 윈도우 - 2  (0) 2015.05.07
데이타베이스 라이브러리  (0) 2015.04.22
posted by 따시쿵
2015. 5. 8. 15:48 C#

프로그램 설명


로그인 창에서 메인창으로 이동하는 예제입니다.

이를 위해서 access db를 사용했으며 구조는 이메일, 비밀번호 필드와, idx 자동증가값 필드로 구성되어 있습니다.


테스트를 위해서 데이타는 아래와 같습니다.



실행 후



프로그램 작성


1. access db 에 접근하기 위해서 oledb 를 import 함.

using System.Data.OleDb;

2. [로그인] 버튼에 아래 프로그램을 작성함


        private void btnLogin_Click(object sender, EventArgs e)
        {
            OleDbConnection connect = null;
            OleDbCommand command = null;
            OleDbDataReader reader = null;

            try
            {
                connect = new OleDbConnection();
                connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=../../SampleDB.accdb;Persist Security Info=False";
                connect.Open();

                command = new OleDbCommand();
                command.Connection = connect;
                command.CommandText = "select user_email, user_password from tbl_member where user_email ='" + txtUser_email.Text.Trim()
                                     + "' and user_password = '" + txtUser_password.Text.Trim() + "'";

                reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Trace.WriteLine(string.Format("User email : {0}, password : {1}",
                            reader["user_email"].ToString(), reader["user_password"].ToString()));
                    }

                    // 로그인창을 숨기기
                    this.Hide();

                    // 메인폼으로 이동하는 스크립트
                    MainForm f = new MainForm();
                    f.Show();
                    f.WindowState = FormWindowState.Maximized;
                }
                else
                    MessageBox.Show("이메일과 비밀번호를 확인 하시기 바랍니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch { }
            finally
            {
                connect.Close();
            }
        }



소스 파일 : 

Login1.zip

'C#' 카테고리의 다른 글

Event 와 Delegate  (0) 2015.06.01
초단위 시간 경과 보이기  (0) 2015.05.12
멀티플(multiple) 윈도우 - 2  (0) 2015.05.07
데이타베이스 라이브러리  (0) 2015.04.22
BackgroundWorker class  (0) 2015.03.02
posted by 따시쿵
2015. 5. 7. 15:43 C#

MDI(Multiple Document Interface) 를 만드는 예제입니다.


MDI 만드는 방법


1. 일반 폼에 isMdiContainer 속성값을 true 로 설정함으로써 폼 컨테이너로 설정


실행화면


프로그램 작성

        #region Form2
        Form2 f2 = null;
        private void form2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (f2 == null)
            {
                f2 = new Form2();
                f2.MdiParent = this;
                f2.FormClosed += new FormClosedEventHandler(f2_FormClosed);
                f2.Show();
            }
            else
                f2.Activate();
        }

        void f2_FormClosed(object sender, FormClosedEventArgs e)
        {
            f2 = null;
        }
        #endregion

        #region Form3
        private void form3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            f3.MdiParent = this;
            f3.Show();
        }
        #endregion


2. 폼을 만드는 시점에 MDI 부모 폼 으로 폼 자체를 만듦


실행화면


프로그램 작성

        private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form1 f1 = new Form1();
            f1.MdiParent = this;
            f1.Show();
        }

        private void form2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.MdiParent = this;
            f2.Show();
            f2.WindowState = FormWindowState.Maximized;
        }


'C#' 카테고리의 다른 글

초단위 시간 경과 보이기  (0) 2015.05.12
로그인 창  (0) 2015.05.08
데이타베이스 라이브러리  (0) 2015.04.22
BackgroundWorker class  (0) 2015.03.02
텍스트 로그 파일 라이브러리 - 3  (0) 2015.02.21
posted by 따시쿵
2015. 4. 22. 15:50 C#

데이타베이스 작업을 할시에 필요한 라이브러리를 소개합니다.

select, update, delete, insert 모두에 사용되며, ad-hoc 쿼리나 스토어프로시저 모두에 사용 가능합니다.


사용하는 방법

아래 예제는 모두 Contacts class 가 있어서, UI 버튼 클릭시 Contacts 클래스의 property 에 개별적인 값을 대입한 후, 필요한 작업을 수행합니다.

Contacts.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using DataGridViewExample.lib;

namespace DataGridViewExample.data
{
    public class Contacts
    {
        #region Properties
        public int Idx { get; set; }
        public string Name { get; set; }
        public string BirthInfo { get; set; }
        public string ZipCode { get; set; }
        #endregion

        #region Functions
        /// 
        // Add the contacts info
        /// 
        /// 
        public bool AddContacts()
        {
            bool retval = false;
            try
            { 
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"insert into [dbo].[tbl_contacts](Name, BirthInfo, ZipCode)
                                    values(@Name, @BirthInfo, @ZipCode);";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Name", Name),
                                        new SqlParameter("@BirthInfo", BirthInfo),
                                        new SqlParameter("@ZipCode", ZipCode)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch(Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }

        /// 
        /// Modify the contacts info
        /// 
        /// 
        public bool ModifyContacts()
        {
            bool retval = false;
            try
            {
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"update [dbo].[tbl_contacts]
                                set  Name = @Name, BirthInfo = @BirthInfo, ZipCode = @ZipCode
                                where Id = @Idx;";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Name", Name),
                                        new SqlParameter("@BirthInfo", BirthInfo),
                                        new SqlParameter("@ZipCode", ZipCode),
                                        new SqlParameter("@Idx", Idx)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }

        public bool RemoveContacts()
        {
            bool retval = false;
            try
            {
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"delete from [dbo].[tbl_contacts]
                                where Id = @Idx;";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Idx", Idx)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }
        #endregion
    }
}


1. select 시


DataTable set 을 가져와서 DataGridView 의 DataSource 에 바인드 합니다.

            SQLOperator sdo = new SQLOperator("SampleDBConnectionString");
            DataTable dt = sdo.ExecuteQuery("select Id, Name, BirthInfo, ZipCode from [dbo].[tbl_contacts]");

            dataGridView1.DataSource = dt;

            dt.Dispose();
            sdo.Dispose();

DataTable set 을 가져와서 List에 넣는 후 DataGridView 의 DataSource 에 바인드 합니다.

            SQLOperator sdo = new SQLOperator("SampleDBConnectionString");
            DataTable dt = sdo.ExecuteQuery("select Id, Name, BirthInfo, ZipCode from [dbo].[tbl_contacts]");

            List<Contacts>  pContact = new List<Contacts>();
            if(dt.Rows.Count > 0)
            {
                foreach(DataRow row in dt.Rows)
                {
                    pContact.Add(new Contacts()
                        {
                            Idx = Convert.ToInt32(row["Id"]),
                            Name = row["Name"].ToString(),
                            BirthInfo = row["BirthInfo"].ToString(),
                            ZipCode = row["ZipCode"].ToString()
                        });
                }
            }

            dataGridView1.DataSource = pContact;

            dt.Dispose();
            sdo.Dispose();


2. update 시

            Contacts contact = new Contacts();

            contact.Idx = Convert.ToInt32(lblIdx.Text);
            contact.Name = txtName.Text.Trim();
            contact.BirthInfo = txtBirthInfo.Text.Trim();
            contact.ZipCode = txtZipCode.Text.Trim();

            if (contact.ModifyContacts())
            {
                toolStripStatusLabel1.Text = Properties.Resources.AddConfirmMsg;
            }
            else
            {
                toolStripStatusLabel1.Text = Properties.Resources.AddErrorMsg;
            }


3. delete 시

            Contacts contact = new Contacts();

            contact.Idx = Convert.ToInt32(lblIdx.Text);
            string message = string.Format("[{0}] 정보를 삭제하시겠습니까", txtName.Text.Trim());

            if (MessageBox.Show(message, "확인", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
            { 
                if (contact.RemoveContacts())
                {
                    toolStripStatusLabel1.Text = Properties.Resources.RemoveConfirmMsg;
                }
                else
                {
                    toolStripStatusLabel1.Text = Properties.Resources.RemoveErrorMsg;
                }
            }



4. insert 시

            Contacts contact = new Contacts();

            contact.Name = txtName.Text.Trim();
            contact.BirthInfo = txtBirthInfo.Text.Trim();
            contact.ZipCode = txtZipCode.Text.Trim();

            if (contact.AddContacts())
            {
                toolStripStatusLabel1.Text = Properties.Resources.AddConfirmMsg;
            }
            else 
            { 
                toolStripStatusLabel1.Text = Properties.Resources.AddErrorMsg;
            }




데이타베이스 라이브러리는 아래와 같습니다.

SQLOperator.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace DataGridViewExample.lib
{
    /// 


/// Summary description for SqlDataOperator /// public class SQLOperator : IDisposable { private SqlConnection conn; private SqlCommand comm; private SqlDataAdapter adap; private SqlTransaction tran; public SqlConnection Connection { get { return conn; } set { conn = value; } } public SqlCommand Command { get { return comm; } set { comm = value; } } public SqlTransaction Transaction { get { return tran; } } public SQLOperator() : this("default") { } public SQLOperator(string connectionStringName) { conn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString); //conn = new SqlConnection(Properties.Settings.Default.SampleDBConnectionString); comm = new SqlCommand(); comm.Connection = conn; adap = new SqlDataAdapter(); } public SqlTransaction BeginTransaction() { if (conn.State == ConnectionState.Closed) conn.Open(); tran = conn.BeginTransaction(); return tran; } public void RollBackTran() { if (tran != null) tran.Rollback(); } public void CommitTran() { if (tran != null) tran.Commit(); } public SqlDataReader ExecuteReader(string query, SqlParameter[] parameters, CommandType commType) { comm.CommandType = commType; comm.CommandText = query; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection); return dr; } public SqlDataReader ExecuteReader(string spName, SqlParameter[] parameters) { comm.CommandType = CommandType.StoredProcedure; comm.CommandText = spName; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection); return dr; } public SqlDataReader ExecuteReader(string query) { comm.CommandType = CommandType.Text; comm.CommandText = query; if (conn.State == ConnectionState.Closed) conn.Open(); SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection); return dr; } public object ExecuteScalar(string sql) { comm.CommandText = sql; comm.CommandType = CommandType.Text; if (conn.State == ConnectionState.Closed) conn.Open(); object result = comm.ExecuteScalar(); comm.Parameters.Clear(); return result; } public object ExecuteScalar(string spName, SqlParameter[] parameters) { comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); object result = comm.ExecuteScalar(); comm.Parameters.Clear(); return result; } public object ExecuteScalar(string spName, SqlParameter[] parameters, CommandType commType) { comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); object result = comm.ExecuteScalar(); comm.Parameters.Clear(); return result; } public object ExecuteScalar(string spName, SqlParameter[] parameters, CommandType commType, SqlTransaction tran) { comm.Transaction = tran; return ExecuteScalar(spName, parameters, commType); } public object ExecuteScalar(string spName, SqlParameter[] parameters, SqlTransaction tran) { comm.Transaction = tran; return ExecuteScalar(spName, parameters); } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters) { comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); SqlParameter para = new SqlParameter("@RETURN_VALUE", SqlDbType.Int); para.Direction = ParameterDirection.ReturnValue; comm.Parameters.Add(para); if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); comm.Parameters.Clear(); } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters, CommandType commType) { comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); SqlParameter para = new SqlParameter("@RETURN_VALUE", SqlDbType.Int); para.Direction = ParameterDirection.ReturnValue; comm.Parameters.Add(para); if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); comm.Parameters.Clear(); } public int ExecuteNoneQuery_Retrun_Param(string spName, SqlParameter[] parameters, CommandType commType) { comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); SqlParameter para = new SqlParameter("@RETURN_VALUE", SqlDbType.Int); para.Direction = ParameterDirection.ReturnValue; SqlParameter return_param = comm.Parameters.Add(para); if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); var return_param_1 = return_param.Value; comm.Parameters.Clear(); return (int)return_param_1; } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters, CommandType commType, SqlTransaction tran) { comm.Transaction = tran; ExecuteNoneQuery(spName, parameters, commType); } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters, SqlTransaction tran) { comm.Transaction = tran; ExecuteNoneQuery(spName, parameters); } public void ExecuteNoneQuery(string sql, SqlTransaction tran) { comm.Transaction = tran; ExecuteNoneQuery(sql); } public void ExecuteNoneQuery(string sql) { comm.CommandText = sql; comm.CommandType = CommandType.Text; if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); } public DataTable ExecuteQuery(string tableName, string spName, SqlParameter[] parameters) { DataTable dtResult = new DataTable(tableName); comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dtResult); comm.Parameters.Clear(); return dtResult; } public DataTable ExecuteQuery(string tableName, string spName, SqlParameter[] parameters, CommandType commType) { DataTable dtResult = new DataTable(tableName); comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dtResult); comm.Parameters.Clear(); return dtResult; } public DataSet ExecuteQueryToDS(string spName, SqlParameter[] parameters) { DataSet dsResult = new DataSet(); comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dsResult); comm.Parameters.Clear(); return dsResult; } public DataTable ExecuteQuery(string tableName, string sql) { DataTable dtResult = ExecuteQuery(sql); dtResult.TableName = tableName; return dtResult; } public DataTable ExecuteQuery(string sql) { DataTable dtResult = new DataTable(); comm.CommandText = sql; comm.CommandType = CommandType.Text; adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dtResult); return dtResult; } private void AddParameters(SqlParameter[] parameters) { comm.Parameters.Clear(); foreach (SqlParameter parameter in parameters) { comm.Parameters.Add(parameter); } } public string AntiInjection(string val) { val = RemoveScriptTag(val).Replace("'", "''"); return val; } public static string RemoveScriptTag(string s) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("(?<capture><[/]?script[a-zA-Z_0-9=\"\'\\s]*>)"); System.Text.RegularExpressions.MatchEvaluator evaluator = new System.Text.RegularExpressions.MatchEvaluator(MatchReplace); return reg.Replace(s, evaluator); } public static string MatchReplace(System.Text.RegularExpressions.Match m) { string s = m.Groups["capture"].Value; s = s.Replace("<", "<").Replace(">", ">"); return s; } #region IDisposable 멤버 public void Dispose() { comm.Parameters.Clear(); if (conn.State == ConnectionState.Open) conn.Close(); } #endregion } }

'C#' 카테고리의 다른 글

로그인 창  (0) 2015.05.08
멀티플(multiple) 윈도우 - 2  (0) 2015.05.07
BackgroundWorker class  (0) 2015.03.02
텍스트 로그 파일 라이브러리 - 3  (0) 2015.02.21
텍스트 로그 파일 라이브러리 - 2  (0) 2015.02.21
posted by 따시쿵
prev 1 2 next