잊지 않겠습니다.

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
,

System.Attribute

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

 Attribute에 대한 내용을 사용할때마다 찾아서 적어주도록 한다. 특별하게 크게 사용한 내용들이 아직까지 많지 않은지..;; 은근슬쩍 아는 attribute가 별로 없다는 생각이 든다.

  • CSLCompliant : 어셈블리에 있는 모든 형식들이 CLS를 준수하게 된다.
  • DllImport : 일반 Dll들의 참고시에 사용된다. 이는 native os에 대한 참고로 사용된다.
  • StructLayout : 구조체의 내부 표현을 구성하는데 이용된다.
  • Dispid : Com 디스패치 인터페이스에 있는 맴버들에 대한 Dispid를 지정한다.
  • Serializable : 클래스나 구조체를 직렬화할 수 있다는 것을 나타낸다.
  • NonSerialized : 클래스나 구조체가 직렬화될 수 없다는 것을 나타낸다.
  • WebMethod : HTTP 요청을 통해 호출 될 수 있다는 것을 나타낸다.
  • SoapHeader : Soap Header가 있어야지 되는 WebService를 지칭한다. 
  • Obsolete : 사용하지 않을 class나 method에 지정한다.
Posted by Y2K
,

System.AppDomain

.NET Framework 2009. 1. 7. 11:21
각 응용프로그램들의 프로세스내의 논리적 patition.

    논리적인 분할로 인하여 내부 운영체제가 로드된 실행 프로그램을 나타내는 방법을 추상화한다.
    완전한 프로세스보다 처리에 필요한 메모리나 Clock이 저렴하다.   
    이는, 응용된 프로그램을 호스팅하는데 있어서 독립성을 강화한다.
    AppDomain은 모든 프로세스 및 다른 AppDomain에게 완전히 독립된 형태를 갖게 된다.
    따라서, 각기 고유한 AppDomain에서 실행되는 응용프로그램들은 .NET Remoting Protocol이외에는 데이터와 정보를 공유할수 없다.

.NET에서의 Process, AppDomain, Context와의 관계
    Process >> AppDomain >> Context로 나뉘게 된다.
    하나의 Process는 여러개의 AppDomain을 가질 수 있으며, AppDomain은 여러개의 Context를 가지는 것이 가능하다.
Posted by Y2K
,
강력한 이름의 구성
  • Assembly의 문자열 이름(파일 확장자를 제외한 바이너리의 이름)
  • Assembly의 버젼 정보
  • Public Key
  • Culture 식별값

  

Assembly에 강력한 이름을 할당하는 과정
  • "sn.exe"를 이용 (-k flag)
  • .NET Framework에서 고유한 식별번호를 갖게하는 정보가 포함되게 된다.
  • [assembly : AssemblyKeyFile(@"C:\MyKey\MyKey.snk")] 로 assembly의 고유 키값을 설정
    • VS2003에서는 반드시 assembly를 수정해주는 것으로 해주어야지 된다.
    • VS2005에서는 프로젝트의 속성에서 지정이 가능하게 변경되었다.

  

Shared Assembly에서의 버젼 관리
  • Private Assembly와는 달리, private path를 이용하지 않는다.(config에서는 여전히 속성은 남아있으나, 사용하지 않는다.)
  • 여러 버젼의 동시에 Install이 가능하기 때문에, 문제가 발생하지 않는다. -> DLL 지옥의 해결 방안
Posted by Y2K
,

ASP.NET에서의 Logon/Logout을 구현하는 가장 일반적인 Forms authentication 방법.

   

web에서의 auth를 저장하는 방법으로 가장 주로 사용되는 것은 cookie를 사용, cookie와 auth에 대한 암호화를 이용해서 사용자 정보와 role을 저장할 수 있다.

   

Log-on (사용자 정보 저장)

1. web.config 설정

 authentication mode를 form으로 설정 

     <authentication mode="Forms">
      <forms loginUrl="~/NotLogOn" />
    </authentication>

   

2. Auth Cookie와 Authenticated user에 대한 정보 설정

LDAP, SQL Server를 이용한 Forms Authentication 이용 가능 (이에 대한 posting은 나중에...)

1) userName, password를 이용해서 정상적인 유저인 경우에 FormsAuthenticationTicket 생성

 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, 
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
roles )

  

* Role 정보 입력

 string role = string.concat("Senior Manager|Manager|Employee")

  

2) Cookie 암호화 & 저장

string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) 

Response.Cookie.Add(authCookie)

  

3. Auth 정보 확인 및 정보 검색

1) 암호화된 Cookie 값 얻기

string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(authCookie == null)
{
// there is no authentication cookie  
} 

  

2) Cookie 값 Decrypt

FormsAuthenticationTicket authTicket = null;

try 

{

authTicket = FormsAuthentication.Decrypt(authCookie.Value); 

  

3) UserData 얻기

string userName = authTicket.Name; //userName
string userData = authTicket.UserData; //userData : roles
DateTime issueDate = authTicket.IssueDate; //cookie created date
DateTime expiredDate = authTicket.Expiration; //cookie expired date
bool expired = authTicket.Expired;
Posted by Y2K
,
할당문 보다는 변수 초기화를 사용하는 편이 더 좋다.
  • 선언시 지정한 초기화 루틴은 본문보다 앞서 수행된다.
  • 각 맴버변수의 선언 순서에 따라서 초기화가 진행된다.
  • 초기화 구문을 사용하지 않으면 좋은 경우 
    • null이나 0로 초기화 하는 경우
    • 동일한 객체에 대해서 여러번 초기화 하는 경우가 되는 경우
  • 생성자 내부에서 할당을 수행하는 것이 원활하다.
static class 맴버의 경우, static 생성자를 사용해서 초기화하라.
  •  static member의 초기화 

    • 선언시 초기화 하는 방법
    • static 생성자를 이용하는 경우
  • static 생성자 : 접근할 class의 어떤 method, variable, property보다 먼저 수행되는 특별한 생성자 
    • Singleton 패턴으로 구현할 때 매우 자주 사용된다. 
  • 선언시에 초기화를 행하는 경우, 초기화 시에 에러가 발생할 경우가 생길때에(.NET Remoting에 연관) try~catch로 잡는 것이 불가능하다.
연쇄적인 생성자 호출을 이용하라.
  • 하나의 작은 생성자를 이용해서, 연쇄적인 생성자를 이용해서 coding의 양을 줄이고 안정적으로 만들어준다. 
  • 기본 인자값을 갖는 매서드를 언어적으로 지원하지 않기 때문에,  각각 정의해줘야지 된다.
자원 해제를 위해서 using과 try/finally를 이용하라.
  • Unmanagerd 자원의 경우, IDisposable interface의 Dispose() 메서드를 호출해서 명시적으로 자원을 해제해 주어야 한다.
  • using 구문 
    • 반드시 구문이 끝나는 경우에, 마치게 되는 내용을 이용해서 해지해주게 된다. 
    • 방어적인 Coding을 해주는 것이 가능하다.
  • try/finally 구문 
    • 오류가 발생하는 경우, 자원이 해지가 안되는 경우가 있다. 
    • 자원이 해지가 되는 것을 반드시 해주기 위해서 finally 구문으로 자원을 항시 해지시켜줘야지 된다.
  • 다수의 객체에 대해서 Dispose()가 호출되어야지 되는 경우라면, using 문장을 다수 배치하거나 try/finally 블록을 직접 구현하는 것이 좋다.
  • Dispose() : 메모리에서부터 객체를 제거하지는 않지만, GC에게 자원을 해제하는 것을 도와주는 시기를 제공한다. 
Garbage를 최소화 하라.
  • 지역 변수를 포함한 모든 Reference 타잎 객체는 Heap 공간에 할당된다.  
    • 지역 변수는 메서드를 빠져나오는 경우 바로 GC에 할당 된다.
    • OnPaint 등에서 사용하는 Font나 Brush의 경우에는 전역 변수로 만들어주고, 때에 따라서 사용하는 것이 좋다.
  •  string으로 문자열을 모으는 것보다도, StringBuilder를 이용해서 문자열을 다루어준다.
boxing과 unboxing을 최소화하라.
  • 복사과정을 거치는 것은 시스템이 큰 영향을 주기 때문에 최소한으로 피해야지 된다.
  • Array에서의 boxing과 unboxing (struct를 사용하는 경우)
    • ArrayList 상에 추가하기 위해서 boxing이 수행된다. : ArrayList 안에 들어가는 모든 형태는 Reference가 되어야지 되기 때문에
    • ArrayList에서 꺼내는 순간 다시 unboxing이 수행
    • ArrayList에서 값을 호출하는 순간 다시 unboxing이 수행된다.
    • 반드시 value type과 collection을 같이 사용하면 안된다.
  • .NET 2.0에서는 generic으로 이러한 결점을 많이 해결 되었다.
표준 Dispose 패턴을 구현하라
  • 비 메모리 자원을 제거하기 위하여 표준화된 패턴 
    • IDisposable Interface를 구현해서 unmanaged 자원을 해재
    • 명시적인 호출을 잊을 경우에 대비하기 위해서 finalizer에도 적절한 해재 코드를 넣는 것
    • protected virtual void Dispose(bool isDisposing) 을 반드시 구현해줘야지 된다. [상속에 대한 문제점 해결]
  • 자신이 IDisposable을 구현하고 있는 것을 알리는 것으로 사용하는 class에서 이것을 구현해야지 되는 것을 알린다.
  • Dispose나 finalizer에서의 주의점 
    • 자원의 해재 이외에 어떠한 다른 동작도 수행해서는 안된다.
    • 객체의 생존 주기에 대한 복잡한 문제가 발생할 수 있다. 
Posted by Y2K
,