"콘솔 응용 프로그램"으로 프로젝트 하나 만듦.



==> Program.cs




// 프로세스(Process) : 하나의 프로그램 단위(프로젝트)
// 스레드(Thread) : 프로세스안에서 실행하는 단위 프로그램(메서드)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace 스레드
{
    class Program
    {
        static void Main(string[] args)
        {
            //Win();
            //Sql();
            //Ide();
            ThreadStart ts1 = new ThreadStart(Win);
            ThreadStart ts2 = new ThreadStart(Sql);
           

            Thread t1 = new Thread(ts1);
            Thread t2 = new Thread(ts2);
            Thread t3 = new Thread(new ThreadStart(Ide));

            t3.Priority = ThreadPriority.Highest; // 우선순위 높게

            t1.Start();
            t2.Start();
            t3.Start();

            // 프로세스
            Process.Start("IExplore.exe"); // 익스플로어 실행
            Process.Start("Notepad.exe"); // 메모장 실행

        }

        private static void Ide()
        {
            DelayTime();
            Console.WriteLine("[3] IDE : Visual Studio");
        }

        private static void Sql()
        {
            Thread.Sleep(3000); // 3초 딜레이
            Console.WriteLine("[2] DBMS : SQL Server");
        }

        private static void Win()
        {
            DelayTime();
            Console.WriteLine("[1] OS : Windows Server");
        }

        private static void DelayTime()
        {
            for (int i = 0; i < 1000000000; i++) { } // 시간지연 메서드           
        }
    }
}



/*
스레드 영역에 메서드 올려놓고 운영체제에서 실행함
- 프로세스는 코드에서 작성(호출)한대로 절차지향식으로 실행됨.
*/




< 실행결과 >

--> 콘솔창에서는 스레드를 실행한 결과가 나왔으며("Program.cs"의 분홍색 형광펜 부분), "프로세스"를 실행한 결과 "웹브라우저 창"과 "메모장"이 순서대로 실행되고 열렸다("Program.cs"의 하늘색 형광펜 부분).




Posted by holland14
:


* MainForm.cs [디자인]에서 '속성' 중 "이벤트" 속성에서 "FormClosing -> MainForm_FormClosing"으로 설정 후 더블클릭 --> 'MainForm.cs'내에 더블클릭으로 생성된 이벤트핸들러 코드에 아래 형광펜으로 칠해진 부분으로 코드작성.





==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyWinForms.MainForm());
        }
    }
}




==============================================================================================




==> MainForm.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyWinForms.Sample;

namespace MyWinForms
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void miExit_Click(object sender, EventArgs e)
        {
            // 현재 프로그램 종료
            Application.Exit();
        }

        private void miAbout_Click(object sender, EventArgs e)
        {
            // 모달 폼 : 현재 창을 닫아야지만, 메인으로 이동 가능
            FrmAbout fa = new FrmAbout();
            fa.ShowDialog();
        }

        private void miButton_Click(object sender, EventArgs e)
        {
            // 모달리스 폼 : 독립적인 하나의 폼
            MyWinForms.Controls.FrmButton fb =
                new MyWinForms.Controls.FrmButton();
            fb.MdiParent = this; // MDI 컨테이너를 현재 폼(메인)으로 설정
            fb.Show();
        }


        #region 컨텍스트메뉴
        private void cmsAbout_Click(object sender, EventArgs e)
        {
            //FrmAbout fa = new FrmAbout();
            //fa.ShowDialog();
            miAbout_Click(null, null); // 재 사용
        }

        private void cmsExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

        private void miLable_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmButtonLableTextBox blt = new MyWinForms.Controls.FrmButtonLableTextBox();
            blt.MdiParent = this;
            blt.Show();
        }

        private void miCheckBoxRadioButton_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmCheckBoxRadioButton cbrb = new MyWinForms.Controls.FrmCheckBoxRadioButton();
            cbrb.MdiParent = this;
            cbrb.Show();
        }

        private void miTextBox_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmTextBox ftb = new MyWinForms.Controls.FrmTextBox();
            ftb.MdiParent = this;
            ftb.Show();
        }

        private void miMessageBox_Click(object sender, EventArgs e)
        {
            // 메시지 박스의 주요 모양
            // MSDN 온라인 적극 활용
            // 코드조각 : mbox
            MessageBox.Show("기본");
            MessageBox.Show("캡션", "제목");
            MessageBox.Show("버튼의 종류", "버튼", MessageBoxButtons.OKCancel);
            MessageBox.Show("아이콘의 종류", "아이콘"
                , MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void miComboListBox_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmComboListBox clb = new MyWinForms.Controls.FrmComboListBox();
            clb.MdiParent = this;
            clb.Show();
        }

        private void miGroupBox_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmGroupBox gb = new MyWinForms.Controls.FrmGroupBox();
            gb.MdiParent = this;
            gb.Show();
        }

        private void miDialogResult_Click(object sender, EventArgs e)
        {
            MyWinForms.Class.FrmDialogResult fdr = new MyWinForms.Class.FrmDialogResult();
            fdr.Show();
        }

        // 컨트롤 - 대화상자 - 폰트
        private void miFont_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmFontDialog ffd = new MyWinForms.Controls.FrmFontDialog();
            ffd.MdiParent = this;
            ffd.Show();
        }

        // 컨트롤 - 대화상자 - 파일 및 폴더
        private void miFileFolder_Click(object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmFileFolder fff = new MyWinForms.Controls.FrmFileFolder();
            fff.MdiParent = this;
            fff.Show();
        }

        // 초간단 노트패드
        private void miNotepad_Click(object sender, EventArgs e)
        {
            FrmNotepad fn = new FrmNotepad();
            fn.MdiParent = this;
            fn.Show();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // 스테이터스바의 3번째 레이블에 현재 시간 출력
            sslTime.Text =
                String.Format("{0}시 {1:0#}분 {2}초",
                    DateTime.Now.Hour
                    , DateTime.Now.Minute
                        , DateTime.Now.Second.ToString().PadLeft(2, '0'));
        }

        private void miExplorer_Click(object sender, EventArgs e)
        {
            FrmExplorer ie = new FrmExplorer();
            ie.Show();
        }

        #region 창 메뉴 관련
        private void miWindowClose_Click(object sender, EventArgs e)
        {
            Form frm = ActiveMdiChild; // 현재 열려있는 폼 가져오기
            if (frm != null)
            {
                frm.Close(); // 닫기
            }
        }
        private void miWindowCascade_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade); // 계단식
        }
        private void miWindowHorizontal_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal); // 수평 바둑판
        }
        private void miWindowVertical_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical); // 수직 바둑판
        }
        #endregion

        private void miCheckedListBox_Click(object sender, EventArgs e)
        {
            // 생성과 동시에 오픈
            (new MyWinForms.Controls.FrmCheckedListBox()).Show();
        }

        private void miImageViewer_Click(object sender, EventArgs e)
        {
            (new FrmImageViewer()).Show();
        }

        private void miTabControl_Click(object sender, EventArgs e)
        {
            (new MyWinForms.Controls.FrmTabControl()).Show();
        }

        private void miToolTip_Click(object sender, EventArgs e)
        {
            (new MyWinForms.Controls.FrmToolTip()).Show();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 폼을 닫을건지 취소할건지 결정
            DialogResult dr = MessageBox.Show("종료하시겠습니까?", "종료확인"
                                    , MessageBoxButtons.YesNo
                                    , MessageBoxIcon.Information);
            if (dr == DialogResult.No)
            {
                e.Cancel = true; // 취소
            }
        }
    }
}





< 실행결과 >

--> "MainForm"의 "닫기(X버튼)"버튼을 클릭하면... 





--> "폼"을 닫을지 확인하는 'MessageBox'가 나오고 "예(Y)"를 누르면 '폼'이 종료되고, '아니요(N)'를 누르면 멈춤.(= '폼 닫기' 취소 중지).





Posted by holland14
:


교재 623P. CurveList예제 참조(내가 마우스로 그렸던 그림이 캡쳐링되어 다시 패인팅(그려짐)) 되는 동작임. 눈으로 보기에는 폼에 내가 마우스로 그린 그림의 화면이 다른 폼에 의해 손실되지 않는 듯한 것으로 보이는 기능임.) "FrmMouseDown.cs" [디자인]에서 "폼"의 '속성' 중 이벤트 속성에서 "Paint -> FrmMouseDown_Paint"으로 설정하고 더블클릭 --> 생성된 "FrmMouseDown_Paint"이벤트핸들러 코드에 아래 "FrmMouseDown.cs"의 형광펜으로 칠해진 부분으로 코드작성.

* "ArrayList"형 객체 생성하여 좌표값(들)을 보관 / "foreach"문을 사용하여 저장된 좌표값 다시 그리기





==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Mouse.FrmMouseDown());
        }
    }
}



==============================================================================================




==> FrmMouseDown.cs




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace MyWinForms.Mouse
{
    public partial class FrmMouseDown : Form
    {
        private ArrayList al;
        public FrmMouseDown()
        {
            InitializeComponent();
            al = new ArrayList();
        }

        private void FrmMouseDown_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button== MouseButtons.Right)
            {
                // 그래픽 객체 생성
                Graphics g = CreateGraphics();
                // 원 그리기
                g.DrawEllipse(Pens.Red, e.X, e.Y, 10, 10);
                // 객체 해제
                g.Dispose();
            }
            p.X = e.X; p.Y = e.Y;
        }

        private Point p; // 좌표
        private void FrmMouseDown_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Graphics g = this.CreateGraphics();
                g.DrawLine(Pens.Blue, p.X, p.Y, e.X, e.Y);

                // 좌표값 보관
                al.Add(Rectangle.FromLTRB(p.X, p.Y, e.X, e.Y));

                p.X = e.X; p.Y = e.Y; // 재설정
                g.Dispose();
            }
        }

        private void FrmMouseDown_Paint(object sender, PaintEventArgs e)
        {
            // 저장된 좌표값 다시 그리기
            foreach (Rectangle r in al)
            {
                e.Graphics.DrawLine(Pens.Blue, r.Left, r.Top, r.Right, r.Bottom);
            }

        }
    }
}





< 실행결과 >

--> 마우스로 '폼'에 그림(선)을 그림 





--> "메모장"을 내가 그림을 그린 '폼' 위로 올려놓음.




--> 내가 그림을 그린 '폼'위의 "메모장" 치우면 그림이 손상되지 않고 원래 상태대로 보여진다.(좌표값(들)을 저장하였다가(캡쳐링같은 역할) 저장된 좌표값을 다시 그리는(Paint) 동작을 하여, 우리가 눈으로 보기에는 '폼'에 그린 그림이 손실되지 않고 그대로 있는 것으로 보이는 것이다. ) 




Posted by holland14
:


* "마우스다운(MouseDown)" 이벤트는 마우스 "우클릭" --> 폼(Form)에서 원 만들기
   "마우스무브(MouseMove)" 이벤트는 마우스 "좌클릭"하여 "드래그" --> 폼(Form)에서 선그리기
* 이 예제에서는 'MyWinForms'에 따로 폴더 추가하여 "Mouse"로 이름 지정한 후  이 폴더에 "FrmMouseDown.cs"를 만들었다.




==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Mouse.FrmMouseDown());
        }
    }
}



==============================================================================================




==> FrmMouseDown.cs




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Mouse
{
    public partial class FrmMouseDown : Form
    {
        public FrmMouseDown()
        {
            InitializeComponent();
        }

        private void FrmMouseDown_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button== MouseButtons.Right) // 마우스 우클릭
            {
                // 그래픽 객체 생성
                Graphics g = CreateGraphics();
                // 원 그리기
                g.DrawEllipse(Pens.Red, e.X, e.Y, 10, 10);
                // 객체 해제
                g.Dispose();
            }
            p.X = e.X; p.Y = e.Y;
        }

        private Point p; // 좌표
        private void FrmMouseDown_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) // 마우스 좌클릭
            {
                Graphics g = this.CreateGraphics();
                g.DrawLine(Pens.Blue, p.X, p.Y, e.X, e.Y);
                p.X = e.X; p.Y = e.Y; // 재설정
                g.Dispose();
            }
        }
    }
}





< 실행결과 >

--> 마우스 "우클릭"으로 "마우스다운(MouseDown)" 이벤트 실행하여 폼(Form)안에 빨간색 원을 그렸고 / 마우스 "좌클릭" 후 '드래그'해서 "마우스무브(MouseMove)"이벤트 실행하여 파란색 선을 그렸다.





Posted by holland14
:


==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Sample.FrmKeyDown());
        }
    }
}




==============================================================================================




==> FrmKeyDown.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Sample
{
    public partial class FrmKeyDown : Form
    {
        private Point p;
        public FrmKeyDown()
        {
            InitializeComponent();
            p.X = 10; p.Y = 10;
        }

        // 폼이 그려질 때 발생하는 이벤트
        private void FrmKeyDown_Paint(object sender, PaintEventArgs e)
        {
            // 원 그리기
            e.Graphics.FillEllipse(Brushes.Black, p.X - 8, p.Y - 8, 16, 16);
        }

        // 폼에서 키보드가 타이핑 될 때
        private void FrmKeyDown_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Left: p.X -= 10; Invalidate(); break;
                case Keys.Right: p.X += 10; Invalidate(); break;
                case Keys.Up: p.Y -= 10; Invalidate(); break;
                case Keys.Down: p.Y += 10; Invalidate(); break;
                default:
                    break;
            }
        }
    }
}





< 실행결과 >

--> 처음 실행 때 화면





--> "화살표 키"로 방향 이동





Posted by holland14
:


==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Sample.FrmKeyboard());
        }
    }
}




==============================================================================================




==> FrmKeyboard.cs




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Sample
{
    public partial class FrmKeyboard : Form
    {
        public FrmKeyboard()
        {
            InitializeComponent();
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 엔터키를 타이핑했을 때 다음 텍스트박스로 이동
            if (e.KeyChar == (char)Keys.Enter)
            {
                textBox2.Focus();
            }
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            // 엔터키 입력시 확인 버튼으로 포커스
            if (e.KeyCode == Keys.Enter)
            {
                button1.Focus();
            }
        }
    }
}





< 실행결과 >

--> '국어'점수의 "TextBox"에 텍스트(100) 입력 후, 엔터키를 타이핑했을 때 다음 텍스트박스로 이동





--> '영어'점수의 "TextBox"에 텍스트(90) 입력 후, 엔터키 입력시 "확인" 버튼으로 포커스() 맞춰짐.





Posted by holland14
:


Visual Studio 2008에서 파일 --> 새로만들기 --> 새 프로젝트 --> "새 프로젝트 추가"창에서 "Visual C# --> Windows"로 선택한 후 --> "Visual Studio에 설치되어 있는 템플릿"에서 "클래스 라이브러리"선택 후 이름(여기서는 "psh.Library"로 클래스 라이브러리의 이름 지정)과 저장위치 정한 후 프로젝트 만들기
--> '솔루션 탐색기'의 "psh.Labrary"에서 Class1.cs파일 삭제 후 다시 "psh.Labrary" 우클릭 --> 추가
--> 새항목 --> '새 항목 추가'창에서 "클래스"로 선택하고 파일명은 "Board.cs"(게시판)로 지정하여 클래스파일 생성함. --> "Board.cs"에 아래의 코드 입력하여 "나만의 라이브러리(Labrary)" 만들기(만들어 둔 나만의 라이브러리를 다른 클래스에 삽입하여 기능을 구현할 수 있다. 하지만 여기서 작성한 코드는 작성한 클래스인 "Board.cs"에서는 실행될 수는 없다. 왜냐면 이 코드들은 "클래스 라이브러리" 이므로... 나중에 다른 예제에서 여기서 만들어 둔 나만의 라이브러리를 활용할 수 있는 부분이 있으면 다른 클래스에서 적절히 활용하여 구현하면 된다.)



==> Board.cs



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

namespace psh.Library
{
    public class Board
    {
        /// <summary>
        ///  파일명(test.gif)을 넘겨주면 이미지 파일인지 아닌지를 결정
        /// </summary>
        /// <param name="fileName">.jpeg, .jpg, .png, .gif</param>
        /// <returns></returns>
        public static bool IsPhoto(string fileName)
        {
            // 완성해보세요~
            string temp = "";
            temp = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (temp == "jpeg" || temp == "jpg" || temp == "png" || temp == "gif")
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        ///  1048576 이 넘겨오면, 1MB 반환 : 즉, Byte, KB, MB, GB단위로...
        /// </summary>
        /// <param name="fileSize"></param>
        /// <returns></returns>
        public static string GetFileSize(long fileSize)
        {
            long temp = 0;
            long Byte = 0;
            long KB = 0;
            long MB = 0;
            long GB = 0;
            string total = "";
            temp = fileSize;
           
            if (temp >= 1073741824)
            {
                GB = temp / 1073741824;     // GB 단위
                temp -= GB * 1073741824;
                total += Convert.ToString(GB) + "GB ";
            }
            if (temp >= 1048576)
            {
                MB = temp / 1048576;        // MB 단위
                temp -= MB * 1048576;
                total += Convert.ToString(MB) + "MB ";
            }
            if (temp >= 1024)
            {
                KB = temp / 1024;           // KB 단위
                temp -= KB * 1024;
                total += Convert.ToString(KB) + "KB ";
            }
            if (temp > 0)
            {
                Byte = temp;
                total += Convert.ToString(Byte) + "Byte";   // Byte 단위
            }
            return total;
        }
    }
}





Posted by holland14
:

교재 14장


1. Visual Studio 2008을 사용해서 DLL 파일 만들기(프로젝트 단위)
 각각의 웹폼/ 윈폼/ 콘솔에서 DLL파일 복사해서 사용
  

2. GAC에 DLL파일 올려놓고, DLL파일을 따로 복사하지 않고 사용하기(여러 대 서버에서 관리)
 해당 서버에 딱 하나만 GAC영역에 올려놓고 모두 사용


3. 웹 서비스 : 서버 한대 올려놓고, 수백/수천대에서 접속해서 사용(한 곳에서 관리)
 로직/기능이 한곳에 있고, 여러 컴퓨터에서 접속해서 공통 사용


4. WCF : MS관련해서는 위와 같은 기능들의 최종점...(한 곳에서 관리)



 

Posted by holland14
:


'솔루션 탐색기'에서 "GAC사용하기"프로젝트에 마우스 우클릭 --> 추가 --> '새 웹 사이트' 클릭 --> '새 웹사이트 추가'창에서 'Visual Studio에 설치되어 있는 템플릿'에서 "ASP.NET 웹 서비스"로 선택하고 '언어 -> Visual C#'으로 선택하고 저장할 위치 선택하여 '확인'버튼 클릭하면 "APP_Code/Service.cs" 코드창이 뜨는데(여기서는 "APP_Code/MyCalculator.cs") 이 코드에서 "[WebMethod]"로 쓰여있는 아래부분의 코드인 " public string HelloWorld() { return "Hello World"; } "를 지우고 다시 씀.(여기서는 아래의 "App_Code/MyCalculator.cs"의 코드와 같이 "[WebMethod]"아래에 " public int Minus(int a, int b) { return (a - b); } } "로 수정했음. 뺄셈연산을 하는 (웹)메서드 임.)


 

==> App_Code/MyCalculator.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// MyCalculator의 요약 설명입니다.
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다.
// [System.Web.Script.Services.ScriptService]
public class MyCalculator : System.Web.Services.WebService
{

    public MyCalculator()
    {

        //디자인된 구성 요소를 사용하는 경우 다음 줄의 주석 처리를 제거합니다.
        //InitializeComponent();
    }

    [WebMethod]
    public int Minus(int a, int b)
    {
        return (a - b);
    }

}

 

 

--> "[WebMethod]"아래에 코드 수정한 "APP_Code/MyCalculator.cs"를 웹에 띄워야 함 --> 솔루션 탐색기에서 "Service.asmx"(여기서는 'C:\...\WebCalculator'에 속해있는 "MyCalculator.asmx") 마우스 우클릭 --> '브라우저에서 보기' 클릭(-> 이 작업은 웹에 내가 작성한 '코드("APP_Code/MyCalculator.cs")'를 띄운 것인데, 여기서는 "내가 작성한 코드를 웹에 띄우는 자가테스트"를 해볼 수 있도록 "Visual Studio에서 지원하는 Tool"로 '브라우저에서 보기'를 실행함으로서 웹에 띄우는 효과를 구현한 것이다. 실제로 웹에 띄우는 방식은 이 방법과는 다름.(-> 돈을 내고 ip주소나 도메인을 할당받아서 웹에 띄우는 방식 등등으로 웹서비스를 함.))



/* "MyCalculator.asmx" 마우스 우클릭 --> '브라우저에서 보기' 클릭하여 실행한 화면.
 "APP_Code/MyCalculator.cs"에서 작성한 코드를 웹에 띄우는 동작이다. */
 





--> 여기서는 "GAC사용하기"프로젝트에 속해있는 "(콘솔 응용 프로그램으로 만든)ConGAC"에서 마우스 우클릭 --> "서비스 참조 추가"클릭 --> "서비스 참조 추가"창에서 '검색'버튼 클릭(여기서는 '검색버튼'을 클릭하여 '주소(경로)'를 간단히 검색하였는데 이런 방법외에 실제상이라면 ip주소를 입력해서 검색하는 방법도 쓰면 된다.) --> "서비스" 탭에서 하위로 계속 클릭하면 "WebCalculator/MyCalculator.asmx\MyCalculator\MyCalculatorSoap"이 나오는데 "MyCalculatorSoap"을 클릭하면 옆의 '작업'탭에서 "Minus"라는 메서드가 뜨는 것을 볼수 있다. --> 그 다음에 여기서는 "서비스 참조 추가"창의 '네임스페이스'에 "Calc"로 이름을 지정한 후 '확인'버튼 클릭(이 작업은 "웹에서 서비스 참조"를 할 수 있도록 해당 웹(서버)의 주소를 지정해 준 작업이라고 할 수 있다.) 여기서 실행한 화면은 아래와 같다.








--> "GAC사용하기"프로젝트\"ConGAC"\"Program.cs"에서 웹에 올려진 "APP_Code/MyCalculator.cs"의 코드(메서드)를 참조(사용)하기 위한 코드를 아래와 같이 작성한다.("Calc.MyCalculatorSoapClient mcsc = new ConGAC.Calc.MyCalculatorSoapClient(); "코드와 
           "int r = mcsc.Minus(a, b); // 뉴욕에 있는 서버에서 가져오기" 코드를 타이핑 할 때 인텔리센스 되는지 확인할 것! "서비스 참조 추가"창에서 주소지정 및 이름입력 후 확인버튼 클릭하여 "(웹)서비스 참조 추가"가 올바로 되었다면 이 코드들을 타이핑할 때 인텔리센스 지원이 되어야 함. 인텔리센스가 지원이 안되고 있다면 다시 검토할 것!)


 

==> Program.cs

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

namespace ConGAC
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 5;

            Calc.MyCalculatorSoapClient mcsc = new ConGAC.Calc.MyCalculatorSoapClient();

            int r = mcsc.Minus(a, b); // 뉴욕에 있는 서버에서 가져오기

            Console.WriteLine(r);
        }
    }
}

 

--> "ConGAC('콘솔 응용 프로그램'이다.)"의 "Program.cs"에서 위와 같이 코드 작성 후 실행해보면(Ctl + F5)("ConGAC.Program"를 '속성'에서 "시작 개체"로 설정하고 실행.), 웹에 올려진 "APP_Code/MyCalculator.cs"의 코드(메서드)를 참조하여 실행한 결과, 콘솔창에 실행 결과가 '5'로 나온다.


< 실행결과 >

"ConGAC"의 "Program.cs"를 "시작페이지로 설정"하고 실행하면 콘솔창에 다음과 같이 출력된다.







* 참고화면
위에서 "ConGAC"에서 "서비스 참조 추가"를 한 결과 아래 그림과 같이 "ConGAC\Service References"에 "Calc"라는 이름의 '웹참조주소(경로)'가 생성된 것을 볼 수 있다.





Posted by holland14
:


Visual Studio 2008에서 파일 --> 새로만들기 --> 새 프로젝트 --> 기타프로젝트 형식 --> Visual Studio 솔루션에서 "빈솔루션"에 이름과 저장위치 정하고 "프로젝트" 생성하기 --> 솔루션 탐색기의 프로젝트(여기서는 "전역어셈블리캐시"로 프로젝트 이름지정)에서 마우스 우클릭 --> 추가 --> 새 프로젝트 추가에서 "프로젝트 형식 --> C#" --> "Visual Studio에 설치되어 있는 템플릿"에서 "클래스 라이브러리"선택 후 이름(여기서는 "Watch"로 클래스 라이브러리의 이름 지정)과 저장위치 정한 후 프로젝트 만들기 --> "Watch"클래스 라이브러리의 Class1.cs 삭제 --> "Watch"클래스 라이브러리 우클릭 --> 추가 --> 새항목 --> "클래스"로 선택하여 이름 지정후(여기서는 "Clock.cs"로 이름지정) "확인"버튼 클릭 --> "Clock.cs"에 현재시간을 출력하는 코드 작성 --> "Watch"에 마우스 우클릭하여 "빌드"하여 "C:\...\Watch\bin\Debug폴더에 생성된 "Watch.dll"파일 생성하기



==> "Watch" (클래스 라이브러리형식) 프로젝트의 Clock.cs

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

namespace Watch
{
    public class Clock
    {
        public static string NowTime()
        {
            return DateTime.Now.ToShortTimeString();
        }
    }
}


"Watch.dll파일"(여기서는 "Watch"클래스 라이브러리의 Clock.cs에서 코드작성 후 빌드해서 생성한 "Watch.dll")을 "C:\Windows\assembly"폴더에 복사하려고 하면 'MessageBox'에서 "어셈블리 Watch.dll에 강력한 이름이 필요합니다"라고 경고가 나오며 복사가 거부된다. 이를 복사하기 위해서는 우선 콘솔창에서 다음과 같이 '스트롱네임키'파일을 생성한다.("시작 -> 모든프로그램 ->Microsoft Visual Studio 2008 -> Visual Studio Tools -> Visual Studio 2008 명령 프롬프트 '클릭' --> "콘솔창에서 아래 화면과 같이 sn.exe -k WatchKey.snk를 입력하여 "WatchKey.snk"를 생성한다.) -->




--> C드라이브에 생성된 "WatchKey.snk"파일을 "복사"하여 C:\...\Watch 폴더 안에 "붙여넣기"한다.) --> "Watch"클래스 라이브러리 마우스 우클릭 --> 속성 --> "서명"탭 선택 --> "어셈블리 서명"체크박스 서명한 후 '찾아보기'에서 "WatchKey.snk"파일이 복사된 경로를 찾아서 "WatchKey.snk"파일 선택(=열기) 후 '속성'창 닫기--> "Watch"클래스 라이브러리 마우스 우클릭하여 "다시 빌드"하여 "WatchKey.snk"파일이 복사(추가)되어 다시 생성된 "Watch.dll"파일을 만든다. -->


/* C드라이브에 생성된 "WatchKey.snk"파일을 "복사"하여 C:\...\Watch 폴더 안에 "붙여넣기"하고 '속성'에서 "서명"에 '체크 및 경로 지정'후 "다시 빌드"하면 'Visual Studio'의 '솔루션 탐색기'에서도 "WatchKey.snk"파일이 "Watch"프로젝트에 복사(삽입)된 것을 볼 수 있다. */





--> "WatchKey.snk"파일을 복사하고 "다시 빌드"해서 재생성된 "C:\...\Watch\bin\Debug폴더의 "Watch.dll"파일을 "C:\Windows\assembly"폴더에 추가(=복사/드래그&드롭)하면 "assembly"폴더에 "Watch.dll파일"이 추가(복사)된다.(이는 재생성된 "Watch.dll"파일이 "공용(전역)어셈블리캐시(=GAC)"에 등록되어 다른 프로젝트들에서도 "Watch.dll"파일을 사용(참조) 할 수 있게 된 것이다.) -->


/* C드라이브에 생성된 "WatchKey.snk"파일을 '복사'하여 'C:\...\Watch' 폴더 안에 "붙여넣기"한 후 '서명'에서 "WatchKey.snk"의 경로를 찾아서 선택 후 '다시 빌드'하여 다시 만들어진 "Watch.dll"파일이 "C:\Windows\assembly"폴더에 '붙여넣기(드래그&드롭)'하여 추가 된 화면 */



--> 이제 "assembly"폴더에 추가된 "Watch.dll"파일을 사용하는 프로젝트를 새로 하나 만든다.('파일' -> '새로 만들기' -> '프로젝트'클릭 -> '새 프로젝트'창에서 '프로젝트 형식 : Visual C#\Windows'로 선택하고 'Visual Studio에 설치되어 있는 템플릿'에서 '콘솔 응용 프로그램'으로 선택 후 '이름'(여기서는 "UseWatch"로 이름 지정)과 위치 지정하고 '확인'버튼 클릭) --> 새로 만든 "UseWatch"프로젝트의 "Program.cs"에서 "Watch"클래스 라이브러리 형식 프로젝트의 "Clock.cs"를 사용(참조)할 코드를 아래와 같이 작성해.("Program.cs"를 '속성'에서 '시작페이지로 설정' 할 것!)


==> "UseWatch" (콘솔 응용 프로그램)프로젝트의 Program.cs

// 전용 어셈블리 : DLL 파일이 프로젝트에 복사됨.
// 공용 어셈블리: 참조만하고 복사되지 않음.

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

namespace UseWatch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Watch.Clock.NowTime());
        }
    }
}


/* Program.cs를 실행해보면 콘솔창에 현재 시간이 출력된다. "C:\...\UseWatch\bin\Debug"폴더 안에는 아래 그림처럼 "Watch.dll"파일이 존재하지 않는다. 하지만 "C:\Windows\assembly"폴더에 "Watch.dll"파일이 공용(전역)어셈블리캐시(GAC)로 들어있어서 이 파일을 이용(참조)하여 "UseWatch" (콘솔 응용 프로그램)프로젝트의 Program.cs를 실행하였다. 실행결과 "Clock.cs"가 동작(반환)하는 내용인 현재시간이 콘솔에 출력된다. */









< 실행결과 >

--> "UseWatch.Program"을 속성에서 '시작페이지로 설정'한 후 "Program.cs"를 실행(Ctl + F5)한 결과, 콘솔창에 현재시간이 출력된다.




Posted by holland14
: