잊지 않겠습니다.

Visual Studio 2005, 2008을 설치할때마다 "이건 뭐하는 것일까.."하는 생각이 드는 내용이였는데, 잘가는 blog에서 포스팅 한 결과를 보고 구경중. 

Flow chart를 그리고, 그 flow chart에 따른 코드를 넣는 것으로 모든 내용이 다 만들어지고, 그에 따른 흐름이 가능해지는 방법으로 여러가지로 살펴볼 내용들이 많다는 생각이 든다. 

각 흐름에 따른 Flow를 만들어주고, 그 Flow에 맞는 code를 작성해주고..

마치 개발을 할때, PM들이 흐름도를 대강 작성하고, 프로그래머들이 코드를 채워넣기만 하면 되는 개발방향과도 너무나도 유사하게 개발을 할 수 있게 되지 않을까.. 하는 생각이 갑자기 든다. 

    

VS2008개발 발표회때 강연자가 했던 이야기가 기억이 난다. "이렇게 편한 툴이 생긴것 자체가 개발자들에게는 악몽이 되고 있습니다. 누구나 다 개발을 할 수 있게 된다면, 우리는 이제는 필요 없게 되어버릴수도 있습니다." 약간의 엄살이 들어가 있는 이야기이긴 하지만,  왠지 모르게 많은 공감이 되고 있는 이야기들. 

WF.png 


10월달에 볼 책이 결정이 난건가....  

(SYNCmail Background worker를 이걸로 한번 만들어볼까나.) 


sample code: 

public sealed partial class Workflow1: SequentialWorkflowActivity

{

        public string PostalCode

        {

            get;

            set;

        }

   

        public Workflow1()

        {

        InitializeComponent();

        }

   

        /// <summary>

        /// check code in IF-ELSE

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void EvaluatiePostalCode(object sender, ConditionalEventArgs e)

        {

            string USCode = @"^(\d{5}$)|(\d{5}$\-\d{4}$)";

            string CanadianCode = @"^[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d$";

   

            e.Result = ( Regex.IsMatch(PostalCode, USCode) || Regex.IsMatch(PostalCode, CanadianCode) );

        }

   

        /// <summary>

        /// method when true result from EvaluatiePostalCode

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void ValidatePostalCode(object sender, EventArgs e)

        {

            Console.WriteLine("Right Postal code");

        }

   

        /// <summary>

        /// method when false result from EvaluatiePostalCode

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void NotValidatePostalCode(object sender, EventArgs e)

        {

            Console.WriteLine("Wrong Postal code");

        }

}

   


Posted by Y2K
,

WCF Reliability

.NET Framework 2009. 1. 7. 11:30

 table1. Reliability and ordered message in bindings

 Name Support Reliability
 Default Reliability
 Supports ordered
 Default Ordered
 BasicHttpBinding No 
N/A 
No 
N/A 
 NetTcpBinding Yes
OFF
Yes
On
 NetPeerTcpBinding No
N/A
No
N/A
 NetNamedPipeBinding No
N/A (ON)
Yes
N/A (On)
 WSHttpBinding Yes
Off
Yes
On
 WSFederationHttpBinding Yes
OFF 
Yes
On
 WSDualHttpBinding Yes
On
Yes
On
 NetMsmqBinding No
N/A
No
N/A
 MsmqIntegrationBinding No
N/A
No
N/A

 

Reliability not supported binding

  • BasicHttpBinding : legacy ASMX service
  • NetPeerTcpBinding : designed for broadcast scenarios.
  • NetMsmqBinding, MsmqIntegrationBinding : this is not remote call. only disconnected calls.


Ordered Message

: WCF let you enable reliability but not ordered delivery.

: The default for all bindings that support reliability is that when reliability is enabled, ordered delivery is enabled as well.

: RequireOrderedDelivery property 

Posted by Y2K
,

WCF Elements

.NET Framework 2009. 1. 7. 11:29

1. Contracts

  • Service Contract
  • Data Contract
  • Fault Contracts
  • Message Contract 

OperationContract : 반드시 Method에서만 구현 가능하다. 이는 WCF Model에서의 제약조건으로 가지고 있으며, 동작에 의해서 구현되는 모델의 기본 사양이 된다. (property 또는 index, value에서는 절대로 구현할 수 없다.) 

1) Hosting

  • WCF Service는 반드시 Host Process 안에서 구현되어야지 된다.
  • Hosting 방법으로는 IIS를 이용하거나, Windows Application Service(WAS)를 이용하여 배포 가능하다.
A. IIS Hosting
  • ASMX web service와 유사한 방법. .svc를 만들어서, 배포(.asmx와 거의 동일하다.)
B. Self-Hosting
  • ServiceHost와 web.config(app.config)를 이용한 hosting. Program적으로 Hosting이 가능하다.
C. WAS Hosting

 

2. Binding

1) Basic binding
  • BasicHttpBinding 
  • legacy ASMX webservice
2) TCP binding
  • NetTcpBinding
  • Cross machine communication on the internet
  • optimized for WCF-WCF communication
3) Peer network binding
  • NetPeerTcpBinding
  • using all subscribe to the same grid and broadcast message
4) IPC binding
  • NetNamedPipeBinding
  • same machine communication
  • secure binding
5) Web Service binding
  • WSHttpBinding
  • http, https
6) Federated WS binding
  • WSFederationHttpBinding
  • supported federated security
7) Duplex WS binding
  • WSDualHttpBinding 
  • supported bidirectional communication
8) MSMQ binding
  • NetMsmqBinding 
9) MSMQ integration binding
  • MsmqIntegrationBinding
  • converts WCF message to and from MSMQ message
  • for legacy MSMQ client

3. EndPoints

  • an address : where the service is
  • binding : how to communicate with the service
  • contract : what the service does

The endpoint is the fusion of the address, contract and binding

Configuration : hosting process' config file.

              <endpoint
                address ="http://localhost/WCFProduct"
                binding="basicHttpBinding"
                contract="WCFProduct.IProduct"
                />

Programmatic Endpoint Configuration

      productsServiceHost = new ServiceHost(typeof(ProductServiceImpl));
      BasicHttpBinding binding = new BasicHttpBinding();
      productsServiceHost.AddServiceEndpoint(typeof(WCFProduct.IProduct), binding, "http://localhost:8000/WCFProduct");
      productsServiceHost.Open(); 

 

4. Metadata Exchange

HTTP-GET protocol을 이용한 metadata의 제공

WebService에서의 web browser를 이용한 Method view와 비슷한 내용을 제공한다.



Metadata Exchange Endpoint

기본적으로 제공되는 Metadata exchange endpoint가 아닌, special endpoint를 제공 가능.

 

5. Clint-Side Programming

1) IDE : Using "Add Service Reference" then add service url

2) SvcUtil : SvcUtil.exe (URL) /out:outputFileName.cs

  • make a class then make the client configuration file required to interact with a service
  • write service configuration with <system.serviceModel> <client> </client> </system.serviceModel> 
         <client>
            <endpoint address="http://localhost:8000/WCFProduct" binding="basicHttpBinding"
                bindingConfiguration="NewBinding0" contract="WCFProduct.IProduct"
                name="HttpHost">
                <identity>
                    <certificateReference storeName="My" storeLocation="LocalMachine"
                        x509FindType="FindBySubjectDistinguishedName" />
                </identity>
            </endpoint>
            <endpoint address="http://localhost:8000/WCFProduct" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IProduct" contract="WCFProduct.IProduct"
                name="BasicHttpBinding_IProduct" />
        </client>

3) Generating the client config file

svcutil.exe http://localhost:8002/MyService /out:proxy.cs /config:app.config 

4) Closing the proxy

      //Method 1 : Declare open and close
      client.Open(); //Open proxy
      client.ListProducts();
      client.Close(); //Close proxy

      //Method 2 : use using statement
      using ( client  = new WCFCLient.WCFProduct.ProductClient())
      {
        client.ListProducts();
      }

      //Method 3 : Use IDisposable interface
      IDisposable disposable = client as IDisposable;
      if ( disposable != null )
      {
        disposable.Dispose();
      }

5) Programmatic Client Configuration

      //Declare endpoint address with URL
      EndpointAddress endpointAddress = new EndpointAddress("http://localhost/WCFProduct/Service.svc");
      //Declare Binding method : http, https, tcp ....
      WSHttpBinding wsBinding = new WSHttpBinding();
      WCFProduct.ProductClient client = new WCFCLient.WCFProduct.ProductClient(wsBinding, endpointAddress);

 

6. Programmatic VS. Administrative Configuration

Administrative configuration

  • the option to change major aspects of the service and the clinet post-deployment
  • it's not type safe
  • configuration error will only be discovered at runtime

Programmatic configuration

  • be able to make an entire configurateion
  • decision is static and never changed. (it's hard-cording)
Posted by Y2K
,

Windows Communication Foundation was official released with .NET 3.0 a couple of months ago. For those people who're doing connected, distributed systems or are in any way interested in communication aspects of systems, this ought to be a God-send. WCF basically rolled all the different Microsoft messaging formats into one, making it extremely easy to architect the communication layer of simple to complex applications. This tutorial aims to explain the basic concepts behind the common terminology used in WCF development and design.

Below is a quick overview of the WCF architecture


WCF Programs

WCF programs are basically divided into 3 different types of programs. They are common known as

  • Clients
    Clients are program that consumes the services, they are normally the ones that initiate the messenging to the service. Depending on the designed architecture of your application, it is possible that a service behaves as a client as well.
  • Services
    Services are the programs that offers the services to the consumers. They are the ones that react and process the messages, similar to the backend of the application. They can be viewed as the equivalence of web services in .Net 2.0.

    All services have to have endpoints specified in order to work. A good way to remember proper endpoint configurations is ABC. A being Address, B being Binding and C being Contracts

    • Address
      Address are the expose points of services. Services have to tell the world that where they are via addresses.
    • Bindings
      Bindings will describe to the world on how they will communicate with the world. They contain information such as transport way, how they are encoded, are they reliable etc.
    • Contracts are of (but not necessary all have to be present) 3 different kinds

      • Service Contract
        Describes what the service does.
      • Data Contract
        Define custom messaging structure.
      • Message Contract
        Define the message format that is passed between services.

  • Intermediaries
    Intermediaries are programs that act as "middle-man", their basic roles can be similar to providing a firewall, routing, gateway etc. They are commonly invisible to the client and services.

Messages
All services and clients communicate via messages, which are made up of one body, and one or more header. All WCF messages are XML formatted and transport neutral. In other words, you can specify different forms of transport (HTTP, MSMQ, Named Pipes etc) for different messages. Within each application, you can specify different messaging transport depending on the communication needs of the system. Basically, messages can be divided into

  • Simplex
    One way messaging. Simplex in short means "fire and forget"
  • Duplex
    Asynchronous two-way messaging. In short this means that once fired, the application will carry on doing its own thing. Upon the return results, it will then handle it.
  • Request Reply
    Synchronous 2 way messaging. This is the common communicate method whereby you'll fire a request, and wait for the response before continuing.

 

Channels
Before a client and service can talk to each other, they have to go through a channel. Imagine a channel as a pipe, with one end being the input message and the other end with the results of the message. There're different channels that can be stacked onto each other, they are commonly known as Channel Stacks. They can be of these different types:

  • Reliable Sessions
  • TCP Transport
  • Binary Message Encoder
  • Windows Security
  • Request Reply

 The way in which messages are sent through the pipe (Channel) is known as a Transport and they way at which they are encoded are known as Encodings. Transport can be made up of the following:

  • HTTP
  • TCP
  • MSMQ
  • Named Pipes
Posted by Y2K
,

WCF Architecture

.NET Framework 2009. 1. 7. 11:28
Figure 1 illustrates the generic architecture WCF employs for all services.

Figure 1 - General WCF Architecture

Figure 1 - General WCF Architecture

The outer service represents the AppDomain of the service. A WCF service consists of contracts (data, fault and service contracts), a service instance (implementation) which is the implementation of a service contract, and configuration which contains the service endpoint information used at runtime to create the channel stack and the service instance.

A WCF service endpoint consists of two core elements: the service contract and a binding. A binding describes how the service will communicate with clients at runtime. WCF provides several default bindings out of the box, covering many common communication scenarios such as BasicHttpBinding and MsmqIntegrationBinding. In addition to creating bindings from scratch, you can also extend and customize the default bindings to work as you wish.

Service Instancing and opening communication

Figure 1 illustrates what happens when a WCF service is run. Ultimately, the aim of the service is to map messages from clients to operations within the service instance. The service instance requires a runtime host and the host must be opened for communication to occur. The ServiceHost<T> class represents this host in code. When the host's constructor is run, it uses the service endpoint configuration combined with the contracts defined in assemblies (retrieved using reflection) to create a ServiceDescription. Thus, the Service host description contains the complete description of the service, including what contracts to use, what service implementation to use for the service contract and how the service will communicate with the outside world (binding).

When the ServiceHost<T>.Open() method is run the Service Description is used to create a Channel Stack and a Service Instance. The Channel Stack is the runtime equivalent of the Binding information. The stack contains all the protocols required in order for the communication. As a minimum for any binding, this must contain at least a Transport and an Encoding. Additional protocols (such as Sessions and Transactions) can then be applied on top. For more information on the channel stack architecture, look at the following MSDN article: http://msdn2.microsoft.com/en-us/library/ms729840.aspx.

Once the service host is open, the service is ready to receive incoming requests from a client. The inbound message gets received through the channel stack and the Dispatcher is then responsible for assigning the message to the corresponding Service Instance operation, deserializing the message using the appropriate deserializer and executing the operation on the service instance. For more information on serialization , look at the following blog entry:http://blogs.conchango.com/simonevans/archive/2007/05/14/WCF-serialization-with-MSMQ.aspx.

Behaviors in WCF

Behaviors are a way of changing the default way in which either a service instance, or operation will execute when run. Behaviors either inherit from interface IServiceBehavior or IOperationBehavior. They are attached to the service description when the host is constructed, using a mixture of configuration, and/ or any additional code you choose to add. Whether you add a behavior in code or in configuration depends on whether you want the behavior to be configurable, or if you need to behavior to be permanently applied.

Examining runtime metadata using InstanceContext and OperationContext

Whilst the service instance is running, the InstanceContext class provides you with the ability to examine metadata about the instance at runtime, such as information about the channel stack and the host. The lifetime of the InstanceContext is aligned to the life time of the service instance. Likewise, the OperationContext provides you with runtime access to service operation metadata for the lifetime of the call to the service operation. OperationContext provides you with access to information such as message headers and properties for inbound and outbound messages, and the Dispatcher.

Handling Concurrency

InstanceContextMode and ConcurrencyMode are service behavior attributes applied to the Service Description when the host is constructed. Together, these two attributes are used to configure how a service will control the lifetime of service instances and how many messages a dispatcher will hand over to an instance.

The InstanceContextMode controls the lifetime of a service instance. By default, this is set to PerSession. This means the service instance will last for the lifetime of the corresponding Session (which equals PerCall if no session is available). PerCall instancing means the instance will be destroyed after the service operation completes. The final option here is Single, which means that the instance context will only be destroyed when the host is closed.

The ConcurrencyMode handles how many messages the dispatcher will hand over to the service instance. The default isSingle, which means the service instance runs single threaded, but this can be changed to run multi threaded by using the setting Multi.

Additional to InstanceContextMode and ConcurrencyMode, the ServiceThrottlingBehavior controls how many concurrent service instances will be run by the host at one time (the MaxConcurrentInstances property), and how many concurrent calls can be made to a single instance (the MaxConcurrentCalls property). It is worth noting with this final property that the channel stack will automatically ready the next inbound message even when concurrent calls are set to 1.

All of these behaviors together control how concurrency and threading will be handled within a WCF service. Figures 2 to 4 below show how these variables can affect threading and concurrency in WCF.

Figure 2

Figure 2 – PerCall instancing, Single Threaded with 2 concurrent instances

Figure 2 shows a service that allows two concurrent service instances to run, each of which is destroyed when the call to the operation is complete (PerCall). Each service instance is configured to only allow one thread to run at a time. This means that of the three inbound messages (shown on the left), the dispatcher will handle two currently using two service instances in the process. The third message will be made ready by the channel stack for handling by the dispatcher.

Figure 3

Figure 3 – PerCall instancing, Single Threaded with 1 concurrent instance

Figure 3 shows what happens when the concurrent instances property is set to 1. The result is only one service instance is created and runs single threaded. A second message is made ready for the dispatcher in the channel stack and is not processed until the service instance is destroyed at the end of the first operation call.

Figure 4

Figure 4 - Single Instance, Multi threaded with 2 concurrent calls

Figure 4 shows how using multi threaded concurrency with a single instance would affect how the service behaves with two concurrent calls allowed. The top two inbound messages from the channel stack would make a call to an operation on a single service instance concurrently. This service instance would not be destroyed at the end of the call to the operation. The third message would be waiting in the channel stack, and as soon as the service instance made a thread free for use, the dispatcher will call the operation for the third message against the same service instance.

Service Exceptions

When a service instance throws an unhandled exception, the InstanceContext is said to be in a Faulted state, and theFaulted event will be raised. This event can be handled in the service host. Once the host is in a faulted state, no further service instances will be created until the channel stack is taken out of a faulted state. This can be achieved by closing and reopening the host (services hosted in IIS automatically handled restarting the host).

Posted by Y2K
,

Service End Point

Host application(Service)은 클라이언트가 요청을 보낼 수 있는 End-Point를 제공함으로서 클라이언트 어플리케이션이 사용할 수 있는 서비스를 만든다.

Service Address

선택된 전송기법에 맞게 주소를 명시해야지 된다.

Service Binding

Service Binding에서는 서비스와 연결하는 방식과 서비스가 제공하는 데이터 포멧을 나타낸다.

  • 전송 프로토콜 : IIS의 지원시에는 전송프로토콜로 Http, Https를 설정, TCP 등의 전송 스킴에 대한 주소의 명세화
  • 메세지 엔트포인트 포멧 : 일반적으로 XML형태로 데이터 전송, 특별한 image등의 데이터를 보낼때는 다른 방식으로 encoding
  • 서비스 보안 요구사항 : 전송 레벨과 메세지 레벨에서의 보안의 구현
  • 서비스 트랜젝션 요구사항 : 트랜잭션 서비스의 구현
  • 서비스 커뮤니케이션의 신뢰성 : 데이터 교환의 무결성 확인
Service가 구현하는 계약

[ServiceContract] 속성의 인터페이스 구현

[OperationContract]의 동작에 대한 구현 : 반드시 직렬화가 가능한 형태로 만들어질 수 있어야지 된다.

  

Client process

WCF Runtime에서 보안, 신뢰성, 트랜젝션을 만족하는지에 대한 확인에 대한 채널 객체의 컬랙션 제공

WCF Runtime에서는 Channel과 Service Instance간의 연결 방법을 명시할 수 있다. 이는 서비스 계약을 구현한 Class에 [ServiceBehavior] 속성을 추가하는 것으로 WCF Runtime이 서비스를 초기화하는 방식을 수정할 수 있다. 

  • InstanceContextMode.PerCall : Method를 호출할 때마다 서비스의 새로운 Instance가 호출된다.
  • InstanceContextMode.PerSession : Session을 구현하면, Client의 Session별로 Instance가 생성된다. Session이 만료되면 Instance는 제거가 되며, Session이 유지되고 있는 도중에는 Instance는 계속 유지가 된다.
  • InstanceContextMode.Single : Service의 Instance는 하나만이 생성되며, 모든 client와 Session은 하나의 Instance에 의해서 공유가 되게 된다.
  [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
  public class ProductServiceImpl : IProduct

  

WCF Service Hosting

  • IIS를 이용 WebService를 이용한 WCF Service Hosting
  • Window Service를 이용한 WCF Service hosting
  • IIS 7.0을 이용한 Windows Activate Service(WAS) 이용
Posted by Y2K
,

WCF Attribute

데이터 계약에서 사용되는 Attribute : Class, structure, enum 형태에 모두 적용되어야지 된다.
  • [DataContract] : WCF 서비스에 사용될 데이터임을 명시한다.
  • [DataMember] : Serialization될 데이터들을 명시
  [DataContract]
  public class Product
  {
    [DataMember] public string Name;
    [DataMember] public string ProductNumber;
    [DataMember] public string Color;
    [DataMember] public string ListPrice;
  }
서비스 계약에서 사용되는 Attribute : interface로 제공된다.
  • [ServiceContract] : Service 계약에서 사용될 Interface를 명시
  • [OperationContract] : Service 계약에서 사용될 method를 명시

  [ServiceContract]
  public interface IProduct
  {
    [OperationContract]
    List<string> ListProducts();

    [OperationContract]
    Product GetProduct(string productNumber);

    [OperationContract]
    int CurrentStockLevel(string productNumber);

    [OperationContract]
    bool ChangeStockLevel(string productNumber, int newStockLevel, string shelf, int bin);
  }

interface와 데이터 계약에서 계약된 데이터를 이용해서, Service를 구현시켜준다.

  public class ProductServiceImpl : IProduct
  {
    private static WCFProduct.Datas.AdventureWorksDataContext dataContext;

    static ProductServiceImpl()
    {
      dataContext = new WCFProduct.Datas.AdventureWorksDataContext();
    }

    public List<string> ListProducts()
    {     
      return ( from p in dataContext.Products select p.ProductNumber ).ToList<string>();     
    }

    public Product GetProduct(string productNumber)
    {
      var productData = (from p in dataContext.Products where p.ProductNumber == productNumber select p).FirstOrDefault();
      Product product = new Product()
      {
        Name = productData.Name,
        ProductNumber = productData.ProductNumber,
        Color = productData.Color,
        ListPrice = productData.ListPrice.ToString()
      };
      return product;
    }

    public int CurrentStockLevel(string productNumber)
    {
      List<ProductInventory> productData = ( from p in dataContext.ProductInventories
                          join pr in dataContext.Products on p.ProductID equals pr.ProductID
                          select p ).ToList<ProductInventory>();

      return productData.Count;
    }

    public bool ChangeStockLevel(string productNumber, int newStockLevel, string shelf, int bin)
    {
      var productData = from p in dataContext.ProductInventories
                        join pr in dataContext.Products on p.ProductID equals pr.ProductID
                        where pr.ProductNumber == productNumber && p.Shelf == shelf &&
                        p.Bin == bin
                        select p;
      foreach ( ProductInventory p in productData )
      {
        p.Quantity = (short) newStockLevel;
      }

      dataContext.SubmitChanges();

      return true;
    }
  }

   

WCF Service의 구현 : WebService

*.svc 파일에 Service에 대한 연결 구현

<%ServiceHost Service = "Products.ProductsServiceImpl" %>

web.config에 Service에 대한 binding 옵션 추가
 <system.serviceModel>
  <services>
   <service name="WCFProduct.ProductServiceImpl" behaviorConfiguration="ProductsBehavior">
    <endpoint address="" binding="basicHttpBinding" contract="WCFProduct.IProduct"/>
   </service>
  </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ProductsBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
 </system.serviceModel>
  • Service에 대한 이름과 행동(behaviorConfiguration)을 추가시켜준다.
  • HttpGet을 얻기 위해 httpGetEnable을 true로 만들어주면, WebService와 동일하게 get을 통해 wsdl 문서를 얻을 수 있다.

   

SOA와 WCF

Network의 Resorce로 이루어지는 SOA는 독립적으로 서비스가 가능하며, 구현 기술에 관련없이 접근할 수 있다. 주된 장점은 특정 Platform이나 위치에 독립적인 solution을 만들수 있다는 것이다. 이를 지키기 위해서는 SOA의 4가지 원칙에 준수한 서비스를 만들어야지 된다.

경계가 뚜렷해야지 된다.

서비스가 요청을 어떻게 처리할지나 클라이언트가 요청에 대한 응답을 어떻게 다룰지에 대한 어떠한 가정을 해서는 안된다.

이 원칙은 서비스와 클라이언트간의 종속성을 최대한으로 줄일 수 있는 방법이 된다.

서비스는 자율적이 되어야지 된다.

하나 이상의 서비스가 사용될 수 없는 상황에서도 실행이 가능하도록 이러한 변화에 견딜 수 있도록 솔루션이 느슨하게 결합되도록 설계되어야지 된다.

서비스는 Class나 Type이 아닌 스키마와 계약으로 공유되어야지 된다.

서비스는 시간이 갈수록 변화되고 진화할 수 있다. 그리고 서비스의 새로운 버젼은 이전 버젼을 대신할 수 있어야지 된다. 서비스가 업데이트 되면 기존의 클라이언트와의 호환성을 유지하기 위해서 기존 계약을 계속 구현해야지 되고, 기존 스킴에 맞게 메세지를 보낼 수 있어야지 된다.

호환성은 정책에 기반한다.

서비스에 의해 드러나는 스킴과 계약은 서비스의 형태를 정의하지만 클라이언트가 서비스에 접근하기 위해서 만족시켜야지 되는 비기능적 요구사항은 반영하지 않는다. 보안 요구사항 등의 접속 방법들은 정책으로 구현하고, 정책 요구 사항이 구현 형태에 종속되지 않게 서비스를 설계해야지 하고 클라이언트는 서비스가 요구하는 어떤 정책이든 준수해야지 된다.   


WCF Attribute

데이터 계약에서 사용되는 Attribute : Class, structure, enum 형태에 모두 적용되어야지 된다.
  • [DataContract] : WCF 서비스에 사용될 데이터임을 명시한다.
  • [DataMember] : Serialization될 데이터들을 명시
  [DataContract]
  public class Product
  {
    [DataMember] public string Name;
    [DataMember] public string ProductNumber;
    [DataMember] public string Color;
    [DataMember] public string ListPrice;
  }
서비스 계약에서 사용되는 Attribute : interface로 제공된다.
  • [ServiceContract] : Service 계약에서 사용될 Interface를 명시
  • [OperationContract] : Service 계약에서 사용될 method를 명시

  [ServiceContract]
  public interface IProduct
  {
    [OperationContract]
    List<string> ListProducts();

    [OperationContract]
    Product GetProduct(string productNumber);

    [OperationContract]
    int CurrentStockLevel(string productNumber);

    [OperationContract]
    bool ChangeStockLevel(string productNumber, int newStockLevel, string shelf, int bin);
  }

interface와 데이터 계약에서 계약된 데이터를 이용해서, Service를 구현시켜준다.

  public class ProductServiceImpl : IProduct
  {
    private static WCFProduct.Datas.AdventureWorksDataContext dataContext;

    static ProductServiceImpl()
    {
      dataContext = new WCFProduct.Datas.AdventureWorksDataContext();
    }

    public List<string> ListProducts()
    {     
      return ( from p in dataContext.Products select p.ProductNumber ).ToList<string>();     
    }

    public Product GetProduct(string productNumber)
    {
      var productData = (from p in dataContext.Products where p.ProductNumber == productNumber select p).FirstOrDefault();
      Product product = new Product()
      {
        Name = productData.Name,
        ProductNumber = productData.ProductNumber,
        Color = productData.Color,
        ListPrice = productData.ListPrice.ToString()
      };
      return product;
    }

    public int CurrentStockLevel(string productNumber)
    {
      List<ProductInventory> productData = ( from p in dataContext.ProductInventories
                          join pr in dataContext.Products on p.ProductID equals pr.ProductID
                          select p ).ToList<ProductInventory>();

      return productData.Count;
    }

    public bool ChangeStockLevel(string productNumber, int newStockLevel, string shelf, int bin)
    {
      var productData = from p in dataContext.ProductInventories
                        join pr in dataContext.Products on p.ProductID equals pr.ProductID
                        where pr.ProductNumber == productNumber && p.Shelf == shelf &&
                        p.Bin == bin
                        select p;
      foreach ( ProductInventory p in productData )
      {
        p.Quantity = (short) newStockLevel;
      }

      dataContext.SubmitChanges();

      return true;
    }
  }

   

WCF Service의 구현 : WebService

*.svc 파일에 Service에 대한 연결 구현

<%ServiceHost Service = "Products.ProductsServiceImpl" %>

web.config에 Service에 대한 binding 옵션 추가
 <system.serviceModel>
  <services>
   <service name="WCFProduct.ProductServiceImpl" behaviorConfiguration="ProductsBehavior">
    <endpoint address="" binding="basicHttpBinding" contract="WCFProduct.IProduct"/>
   </service>
  </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ProductsBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
 </system.serviceModel>
  • Service에 대한 이름과 행동(behaviorConfiguration)을 추가시켜준다.
  • HttpGet을 얻기 위해 httpGetEnable을 true로 만들어주면, WebService와 동일하게 get을 통해 wsdl 문서를 얻을 수 있다.

   

SOA와 WCF

Network의 Resorce로 이루어지는 SOA는 독립적으로 서비스가 가능하며, 구현 기술에 관련없이 접근할 수 있다. 주된 장점은 특정 Platform이나 위치에 독립적인 solution을 만들수 있다는 것이다. 이를 지키기 위해서는 SOA의 4가지 원칙에 준수한 서비스를 만들어야지 된다.

경계가 뚜렷해야지 된다.

서비스가 요청을 어떻게 처리할지나 클라이언트가 요청에 대한 응답을 어떻게 다룰지에 대한 어떠한 가정을 해서는 안된다.

이 원칙은 서비스와 클라이언트간의 종속성을 최대한으로 줄일 수 있는 방법이 된다.

서비스는 자율적이 되어야지 된다.

하나 이상의 서비스가 사용될 수 없는 상황에서도 실행이 가능하도록 이러한 변화에 견딜 수 있도록 솔루션이 느슨하게 결합되도록 설계되어야지 된다.

서비스는 Class나 Type이 아닌 스키마와 계약으로 공유되어야지 된다.

서비스는 시간이 갈수록 변화되고 진화할 수 있다. 그리고 서비스의 새로운 버젼은 이전 버젼을 대신할 수 있어야지 된다. 서비스가 업데이트 되면 기존의 클라이언트와의 호환성을 유지하기 위해서 기존 계약을 계속 구현해야지 되고, 기존 스킴에 맞게 메세지를 보낼 수 있어야지 된다.

호환성은 정책에 기반한다.

서비스에 의해 드러나는 스킴과 계약은 서비스의 형태를 정의하지만 클라이언트가 서비스에 접근하기 위해서 만족시켜야지 되는 비기능적 요구사항은 반영하지 않는다. 보안 요구사항 등의 접속 방법들은 정책으로 구현하고, 정책 요구 사항이 구현 형태에 종속되지 않게 서비스를 설계해야지 하고 클라이언트는 서비스가 요구하는 어떤 정책이든 준수해야지 된다.   


Posted by Y2K
,

MS의 SOA에 대한 기본 Framework.

Solution의 설계 및 다양한 기술을 적용할 수 있는 지속적인 모델을 제시

  • WebService
  • COM+
  • MSMQ
  • .NET Framework remoting

과 같은 서비스의 일괄적인 통합 및 구축 개발 방법 

WCF 1.0
  • HTTP
  • TCp
  • Peer network
  • IPC(inter-process communication over named pipes)
  • MSMQ
Posted by Y2K
,
  1. lock
  2. Monitor
  3. System.Threading.Interlocked
    • Increment() : 증가
    • Decrement() : 감소
    • Exchange() : 교환
    • CompareExchange() : 같은지 검사후, 같은 경우 3번째의 값으로 값을 변경시켜준다.
  4. [Synchronization] 속성을 이용한 동기화
    • Class의 속성으로 설정
    • 해당 객체의 모든 맴버를 Thread에 안전하게 잠그게 된다.
    • 모든 맴머가 잠기게 되기 때문에 기능성이 심하게 저하될 수 있다
  5. AutoEvent, ManualEvent를 이용한 동기화
  6. Process간 통신을 위한 Mutex와 Semaphore
Posted by Y2K
,

# netstat -atn
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address          Foreign Address       State
... 생략 ...
tcp        0      0 0.0.0.0:25             0.0.0.0:*             LISTEN      <-- 포트가 열렸음
tcp        0      0 192.168.123.10:32799   207.46.106.141:1863   ESTABLISHED <-- 서로 연결중
tcp        0      0 192.168.123.10:32794   218.xxx.xx.xx:22      ESTABLISHED
tcp        0      0 192.168.123.10:32802   207.46.108.46:1863    CLOSE_WAIT  <-- 종료 대기중
tcp        0      0 192.168.123.10:33244   211.xxx.xx.x:80       ESTABLISHED


1)  TCP 연결관련 상태

  • RFC 793문서에 나온 기본적인 TCP 연결 과정


      TCP A                                                      TCP B
  1.  CLOSED                                                     LISTEN
  2.  SYN-SENT    --> < SEQ=100>< CTL=SYN>                   --> SYN-RECEIVED
  3.  ESTABLISHED <-- < SEQ=300>< ACK=101>< CTL=SYN,ACK>     <-- SYN-RECEIVED
  4.  ESTABLISHED --> < SEQ=101>< ACK=301>< CTL=ACK>         --> ESTABLISHED
  5.  ESTABLISHED --> < SEQ=101>< ACK=301>< CTL=ACK>< DATA>  --> ESTABLISHED

LISTEN      : 데몬이 요청을 발을 수 있도록 연결 요구를 기다리는 상태
  즉, 포트가 열려있음을 의미. http(80), mail(25), ftp(21), telnet(23) 등
  위에서 포트 25(mail)이 메일을 받을 수 있도록 열려 있는 상태
  윈도우즈에서는 LISTENING으로 표시
SYN_SENT    : 로컬에서 원격으로 연결 요청(SYN 신호를 보냄)을 시도한 상태
SYN_RECV    : 원격으로 부터 연결 요청을 받은 상태
  요청을 받아 SYN+ACK 신호로 응답은 한 상태이지만 ACK는 받지 못했다.
  netstat로 확인할 때 SYN_RECV가 상당히 많다면 TCP SYN 플러딩(Flooding) 공격일
  가능성이 있다.
  윈도우즈와 솔라리스에서는 SYN_RECEIVED으로, FreeBSD는 SYN_RCVD으로 표시
ESTABLISHED : 서로 연결이 되어 있는 상태
  위에서 192.168.123.10의 포트 32794과 218.xxx.xx.xx의 포트 22(ssh)이 서로
  연결되어 있는 상태

2) TCP 종료관련 상태

* 정상적인 연결 종료 과정

      TCP A                                                   TCP B

  1.  ESTABLISHED                                             ESTABLISHED
  2.  (Close)
      FIN-WAIT-1  --> < SEQ=100>< ACK=300>< CTL=FIN,ACK>  --> CLOSE-WAIT
  3.  FIN-WAIT-2  <-- < SEQ=300>< ACK=101>< CTL=ACK>      <-- CLOSE-WAIT
  4.                                                         (Close)
      TIME-WAIT   <-- < SEQ=300>< ACK=101>< CTL=FIN,ACK>  <-- LAST-ACK
  5.  TIME-WAIT   --> < SEQ=101>< ACK=301>< CTL=ACK>      --> CLOSED
  6.  (2 MSL)
      CLOSED                                                      

FIN_WAIT1   : 소켓이 닫히고 연결이 종료되고 있는 상태. 원격의 응답은 받을 수 있다.
  솔라리스에서는 FIN_WAIT_1로 표시
FIN_WAIT2   : 로컬이 원격으로 부터 연결 종료 요구를 기다리는 상태
  솔라리스에서는 FIN_WAIT_2로 표시
CLOSE_WAIT  : 원격의 연결 요청을 받고 연결이 종료되기를 기다리는 상태
  원격으로 부터 FIN+ACK 신호를 받고 ACK 신호를 원격에 보냈다.
TIME_WAIT   : 연결은 종료되었으나 원격의 수신 보장을 위해 기다리고 있는 상태
  이 상태를 특히 자주 보게되는 Apache에서 KeepAlive를 OFF로 해둔 경우,
  Tomcat 서버를 쓰는 경우 등
LAST_ACK    : 연결은 종료되었고 승인을 기다리는 상태
CLOSED      : 완전히 연결이 종료된 상태


※ 위의 FIN_WAIT1, FIN_WAIT2, CLOSE_WAIT 3개 상태는 연결 종료를 위해 서로간에
   신호를 주고받는 과정에 나타나는 상태로 이해하면 된다.
   종료 요청을 한 곳에서는 FIN_WAIT1, FIN_WAIT2, TIME_WAIT 상태가
   종료 요청을 받는 곳에서는 CLOSE_WAIT, LAST_ACK 상태가 표시된다.

3) 기타

CLOSING     : 연결은 종료되었으나 전송도중 데이타가 분실된 상태
UNKNOWN     : 소켓의 상태를 알 수 없음

솔라리스의 netstat 명령에서는 다음 2개의 상태를 더 표시한다.

IDLE        : 소켓이 열렸지만 binding 되지 않은 상태
BOUND       : listen이나 연결을 위한 준비 상태

※ 참고 문서  
- netstat 맨페이지(linux, solaris)
- RFC 793 ( http://www.ietf.org/rfc/rfc0793.txt )

Posted by Y2K
,