'Programming'에 해당되는 글 64건

  1. 간단한 WCF 서비스 생성
  2. 이클립스 C++ 설치기 (Eclipse C++ Install)
  3. 이클립스 설치기 (자바)
  4. Strongly Typed Dataset의 테이블에 데이터 로드하기
  5. [javascript] Scope-safe constructor
  6. 정해진 시간후에 텍스트 자동으로 감추기
  7. Callback 함수의 예 - GetCallbackEventReference
  8. SOAP Envelope Sample
  9. ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer
  10. LINQ in MSDN

간단한 WCF 서비스 생성

WCF는 SOA(Service-oriented application)기반의 어플리케이션을 위한 프레임워크이다. WCF의 개발을 위해서는 닷넷3.0 이상이 필요하다
WCF는 분산 어플리케이션을 구축하는 수단이다
WCF는 Enterprise Services처럼 트랜젝션을 처리할 수 있다
WCF는 .NET remoting과 같이 SOAP메시지의 바이너리 작용을 생성할 수 있다
WCF는 같은 장비 또는 다른 장비에 있는 다른 컴포넌트와 통신할 수 있다

SOA는 메시지 기반의 서비스 아키텍춰이다
- 경계가 명확하다
- 서비스는 자율적이다
- 서비스는 계약, 스키마 그리고 정책에 기반한다
- 서비스 호환성은 정책에 기반한다


WCF 서비스는 다음의 3가지로 구성된다
1. 서비스
2. 하나이상의 endpoint
3. 서비스를 제공할 환경

Endpoint는 다음의 3가지로 구성된다
A is for address(where)
B is for binding(how)
C is for contract(what)

** WCF서비스 생성
서비스를 생성하기 위한 2가지 주요 절차가 있다. 첫번째는  Service Contract를 생성하는 것이고, 두번째는 Data Contract를 생성하는 것이다.

다음의 순서에 의하여 WCF를 서비스하는 console 어플리케이션을 만들것이다.
1. Console application을 생성한다

사용자 삽입 이미지

2. System.ServiceModel.dll를 참조 추가한다
사용자 삽입 이미지

3. Calculator.vb를 추가 생성
4. 다음과 같이 ICalculator 인터페이스를 추가한다
Imports System.ServiceModel

<ServiceContract()> _
Public Interface ICalculator
    <OperationContract()> _
    Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
    <OperationContract()> _
    Function Subtract(ByVal a As Integer, ByVal b As Integer) As Integer
    <OperationContract()> _
    Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer
    <OperationContract()> _
    Function Divide(ByVal a As Integer, ByVal b As Integer) As Integer
End Interface

Public Class Calculator

End Class

<ServiceContract()> 속성은 서비스 클래스로써의 인터페이스 또는 클래스임을 설정한다
<OperationContract()> 속성은 WCF서비스로서의 메서드임을 정의한다


5. 서비스를 호스팅할 코드를 Module1.vb에 생성한다. 다음의 두개의 네임스페이스는 서비스를 호스팅하기 위해서 필요하다
Imports System.ServiceModel
Imports System.ServiceModel.Description

6. Module1.vb의 코딩
Imports System
Imports System.ServiceModel
Imports System.ServiceModel.Description
Module Module1
    Sub Main()

        Using serviceHost As ServiceHost = New ServiceHost(GetType(Calculator))

serviceHost.AddServiceEndpoint(GetType(ICalculator), New WSHttpBinding, New Uri("http://localhost:8000/Calculator/"))


            Dim smb As New ServiceMetadataBehavior()
            smb.HttpGetEnabled = True
            smb.HttpGetUrl = New Uri("http://localhost:8000/docs")

            serviceHost.Description.Behaviors.Add(smb)

            serviceHost.Open()

            Console.WriteLine("Press the <ENTER> key to close the host.")
            Console.ReadLine()
        End Using

    End Sub
End Module

-  Using serviceHost As ServiceHost = New ServiceHost(GetType(Calculator)): 서비스 호스트를 새엇ㅇ한다
- Dim ntb As NetTcpBinding = New NetTcpBinding(SecurityMode.None): 바인딩을 생성하며 시큐리티는 없다

7. Console 어플리케이션을 실행하면 다음과 같이 된다


8. Console 어플리케이션을 실행한 상태에서 http://localhost:8000/docs를 웹브라우져에서 보면 WSDL 문서를 볼 수 있다



** WCF서비스 호스팅
- Console applications
- Windows Forms applications
- Windows Presentation Foundation applications
- Managed Windows Services
- Internet Information Services (IIS) 5.1
- Internet Information Services (IIS) 6.0
- Internet Information Services (IIS) 7.0 and the Windows Activation Service (WAS)

** WCF 바인딩의 종류
System.ServiceModel.BasicHttpBinding
System.ServiceModel.Channels.CustomBinding
System.ServiceModel.MsmqBindingBase
System.ServiceModel.NetNamedPipeBinding
System.ServiceModel.NetPeerTcpBinding
System.ServiceModel.NetTcpBinding
System.ServiceModel.WSDualHttpBinding
System.ServiceModel.WSHttpBindingBase


WCF를 사용할 클라이언트는 http://youbeen.tistory.com/entry/간단한-WCF서비스의-클라이언트-생성 에서 참조한다

0. 자바 런타임 설치
http://www.java.com

1. eclipse 다운로드
http://www.eclipse.org/downloads/

2. GCC, MAKE 설치
http://sourceforge.net/projects/mingw/files/

간편한 설치를 위해서 Automated MinGW Installer의 MinGW 5.1.4.exe를 다운로드 받습니다.
사용자 삽입 이미지

다운로드 받은 파일을 실행하여 설치를 시작합니다.

사용자 삽입 이미지

3.  g++ objective c, MinGW Make를 선택합니다.
사용자 삽입 이미지

다음의 화면이 나타나면서 설치를 계속 진행합니다.

사용자 삽입 이미지


4. gcc의 실행을 위하여 전역 경로를 설정합니다.방법은 내컴퓨터의 속성을 클릭하여 시스템 등록 정보의 환경변수를 선택합니다.

다음의 그림 처럼 선택하여 시스템 변수 Path에 C:\MinGW\Bin\을 추가합니다. 그리고 도스모드에서 gcc를 실행하여 확인합니다.

5. MinGW의 Make파일로 교체합니다. 다음의 그림을 참조하여 수정합니다.


-- 이상 끝~~ --

이클립스 설치기 (자바)

이클립스 설치 및 설정입니다.

1. Java Runtime을 설치합니다. http://developers.sun.com/downloads/ 에서 파일을 다운받아서 JVM을 설치합니다

2. http://developers.sun.com/downloads/ 에 접속하여 아래와 같이 JDK를 다운로드 받습니다.

JDK 윈도우 버전을 선택합니다.



3. 환경변수를 설정합니다. 시스템 변수의 Path에 c:\Program files\Java\jdk1.6.0_14\bin을 추가합니다. 그리고 다시 JAVA_HOME\bin을 더 추가합니다.




새시스템 변수를 추가합니다. (CLASSPATH)

새시스템 변수를 추가합니다 (JAVA_HOME)


다음과 같이 도스모드에서 테스트합니다.



4. 다음의 링크에서 다운로드를 받습니다. (윈도우 버전 JEE Java developer 입니다.)
http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/R/eclipse-java-galileo-win32.zip

5. 다운로드 받은 eclipse-java-galileo-win32.zip의 압출을 풉니다.

사용자 삽입 이미지



** Strongly Typed Dataset 생성
1. Strongly Typed DataSet을 생성한다.
2. 생성된 DataSet에 DataTable을 추가한다

** 데이터셋에 데이터 로드하기
1. DataSet.DataTable.Load(DataReader)
ex) regCardDS.RegCardQuestions.Load(cmd.ExecuteReader)
      [DataSet].[DataTable].Load(DataReader)

function Student(name, grade, age){
    this.name = name;
    this.grade = grade;
    this.age = age;
}

var student = Student("Woody Choi", 1, 20);
alert(student.name);
alert(student.grade);
alert(student.age);

new 생성자 없이 Student를 선언을 하면 에러가 발생하게 된다. 왜냐하면, this를 window로 인식을 하게 되기 때문이다. 이를 해결하기 위해서 다음과 같은 처리를 할 수 있다.

Self-scope 생성자는 먼저 this가 Student type인지를 확인하고, 그렇지 않으면 new 를 이용하여 객체를 생성한다.

function Student(name, grade, age){
 if (this instanceof Student){
  this.name = name;
  this.grade = grade;
  this.job = job;  
 }
 else{
  return new Student(name, grade, age);
 }
}

        var student = Student("Woody", 1, 34);
        alert(student.name);
        alert(student.grade);
        alert(student.age);


 

        setTimeout(infoTimeout, 1000)

        function hideTextTimeout() {
            timeout = timeout - 1;
            if (timeout > 0) {
                // show message to say that saving is completed
                document.getElementById(_messageDiv).innerHTML = "message";
                setTimeout(hideText, 1000); // call reculsively
            }
            else {
                // clear message
                document.getElementById(_messageDiv).innerHTML = "";
            }
        }


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>WEb Service CallBack</title>
    <script type="text/javascript">
        function GetTemp() {
            var zipcode = document.forms[0].TextBox1.value;
            UseCallback(zipcode, "");
        }

        function GetTempFromServer(TextBox2, context) {
            document.forms[0].TextBox2.value = "Zipcode: " +
            document.forms[0].TextBox1.value + " | Temp: " + TextBox2;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <input id="Button1" type="button" value="Get Temp" onclick="GetTemp()" />       
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <br />
    </div>
    </form>
</body>
</html>
=====================================================================================
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SingleParam : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
    private string _callbackResult = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetTempFromServer", "context");
        string cbScript = "function UseCallback(arg, context)" + "{" + cbReference + ";" + "}";

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cbScript, true);
    }

    public void RaiseCallbackEvent(string eventArg)
    {
        _callbackResult = "zzzzzzzzzzzzzz";
    }

    public string GetCallbackResult()
    {
        return _callbackResult;
    }
}

SOAP Envelope Sample


Client Windows applicaton
------------------------------------------------------------
Public Class frmMain

    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
        TextBox1.Text = String.Empty

        Dim obj As New wsSampleSoap.AuthHeader
        Dim ws As New wsSampleSoap.Service1

        obj.UserName = "admin"
        obj.Password = "dotnet"

        ws.AuthHeaderValue = obj
        TextBox1.Text = ws.GetCustomerList()
    End Sub
End Class
-----------------------------------------------------------

** SOAP Web Service

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

using System.Web.Services.Protocols;
using System.Xml.Serialization;


namespace SampleSoapMessage
{

    public class AuthHeader : System.Web.Services.Protocols.SoapHeader
    {
        public string UserName;
        public string Password;
    }

    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/", Description="SOAP Header Example")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class Service1 : System.Web.Services.WebService
    {
        public AuthHeader curUser;  // header item

        [WebMethod]
        [SoapHeader("curUser")]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod(Description = "authenticates a user")]
        [SoapHeader("curUser")]
        bool Login()
        {
            if (curUser != null)
            {
                if (Authenticate(curUser.UserName, curUser.Password))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
                return false;
           
        
        }

        bool Authenticate(string user, string pwd)
        {
            return user == "admin" && pwd == "dotnet";
        }

        [WebMethod(Description = "returns the current time")]
        [SoapHeader("curUser")]
        public string GetCustomerList()
        {
            string customerList = string.Empty;

            if (Login())
                customerList = "OK";
            else
                customerList = "Fail";

            return customerList;
        }

    }
}

PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Article ID : 312629
Last Review : August 1, 2003
Revision : 2.5
This article was previously published under Q312629

SYMPTOMS

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.

Back to the top

CAUSE

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

Back to the top

RESOLUTION

To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
  Response.Redirect ("nextpage.aspx", false);
						
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Execute method instead.

Back to the top

STATUS

This behavior is by design.

Back to the top

LINQ in MSDN