Pages
Calender
<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910
Blogroll
    Pradeep Patel , Created On 10. June 2010, 19:05

     

    One of the unique features of C# is the concept of Partial, extendable to definition of a Class or a Struct, an Interface or a method.
    Using this, the definition of any class, struct, interface of method can exist in two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

    To split a class definition, partial keyword modifier is used.

    For Example:

       1:      public partial class Pradeep
       2:      {
       3:          public void OnLeave()
       4:          {
       5:          }
       6:      }
       7:   
       8:      public partial class Pradeep
       9:      {
      10:          public void InMeeting()
      11:          {
      12:          }
      13:      }

    Here, it is valid to use the same name for the class and implement desired functionality separately.
    Finally, when compiled, the code is auto merged , giving a Final class named Pradeep, with the two methods that were defined separately.

    The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace.
    Following are the points that need to be taken care of while working with Partial keyword.

    • All the parts must use the partial keyword.
    • All the parts must have the same accessibility, such as public, private, and so on.
    • All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
    • If any part is declared abstract, then the whole type is considered abstract.
    • If any part is declared sealed, then the whole type is considered sealed.
    • If any part declares a base type, then the whole type inherits that class.
    • Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations.
    • Nested types can be partial, even if the type they are nested within is not partial itself

    For Example:

        class LeaveReachTimings
        {
            partial class Residence
            {
                void TimetoReach() { }
            }
            partial class Office
            {
                void TimeToLeave() { }
            }
        }


    Here the Class LeaveReachTimings is not partial, but it is completely valid to declare partial classes Residence and Office as nested classes in it.

    • Attributes of partial-type definitions are merged

    For Example

        [SerializableAttribute]
        partial class CurrentCompany { }
    
        [Obsolete Attribute]
        partial class CurrentCompany { }
    
        These two attributes will finally merge and are equivalent to the following.
    
        [SerializableAttribute]
        [Obsolete Attribute]
        partial class CurrentCompany { }

    Enough of Theory Let us now create one partial Class to verify the concepts covered so far.

    Partial Class:

     

        public partial class Record
        {
            private int x;
            private int y;
    
            public Record(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }
    
        public partial class Record
        {
            public int PrintSum()
            {
                return x + y;
            }
    
        }

    Partial Methods:

    Similar to Partial Classes, Partial Methods are also allowed. These are allowed in partial classes or struct.
    One part of class contains the signature and the same or other part of the partial class can contain its implementation.
    If no implementation is provided, then the method and all calls made to it are removed at compile time.

    Therefore, any code in the partial class can use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.

    A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part.

    If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

    Following are the considerations with Partial Methods.

    • Partial method declarations must begin with the partial keyword
    • Return Type is always void.
    • out parameters are not allowed , however ref can be used.
    • Partial methods cannot be virtual as they are implicitly private.

    It means they have access modifiers such as public, private or internal. Hence, they cannot be called from outside the partial class, and cannot be declared as virtual.

    • Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
    • Partial methods can use static and unsafe modifiers.
    • Partial methods can be generic.
    • A delegate to a partial method which has an implementation, can be made. But, the partial method which has just a signature and no implementation can not have a delegate.


    Example:

        public partial class PartialClassTest
        {
            private string mytest = string.Empty;
    
            partial void MyPartialMethodTest();
    
        }
    
    
        public partial class PartialClassTest
        {
            partial void MyPartialMethodTest()
            {
                mytest = "Partial Method call Succeded!!";
    
            }
    
            public string returnstring()
            {
                MyPartialMethodTest();
                return mytest;
    
            }
        }

    Here the partial methods, always return void and to get the value of mytest string I have to declare yet another method(return string), which finally prints the string on the webpage if called as per the following code.

        protected void Page_Load(object sender, EventArgs e)
        {
            PartialClassTest ptest = new PartialClassTest();
            Response.Write(ptest.returnstring());
        }

    Please note: Delegate or Enumeration declarations can not use partial keyword.

    Hope this discussion was helpful.

    Till Next time we connect, Happy Coding!!!




    WCF (Basics..for building effective Services)


    WCF:  Windows Communication Foundation
    It includes a collection of .NET distributed technologies that have existed for long , but never got grouped under one name.
    WCF can be considered as collection of the following technologies.

    1. Web Services(ASMX)
    2. NET Enterprise Services
    3. MSMQ
    4. .NET Remoting


    Code written in WCF can interact across components, applications and systems.
    WCF is in accordance with SOA (Service Oriented Architecture).

    Following Sections provide the details of these ABCs.

    Addresses

    In WCF, every service has a unique address. The address provides two important elements
    A)   Location of the service.
    B)   Transport protocol or transport schema used to communicate with the service.

     The location indicates the name of the target machine, site, or network; a communication port, pipe, or queue; and an optional specific path or URI.
    WCF supports the following transport schemas:
       A)   HTTP
       B)   TCP
       C)   Peer network
       D)   IPC (Inter-Process Communication over named pipes)
       E)   MSMQ

    Addresses have the following format:
    [base address]/[URI]
    (Note: URI is optional and can be omitted, however when it is present it gets merged with the base address to provide the final address, where the service can be located).

     base address format:
    [transport]:// [machine or domain][:optional port]

    Following section is meant only to make you familiar with the various formats thatare used with specific type of transport protocol.
    It can be skipped if desired.

    Using different available address formats.

    TCP Addresses

    TCP addresses use net.tcp for the transport and generally uses a port:
    net.tcp ://{ machine or domain}/ServiceName
    e.g. Net.tcp//localhost/PService
    (Note: If a port number is not specified, Port 808 is used as default)

    HTTP Addresses

    HTTP addresses use httpfor transport, and https can be used if secure transport is required.
    e.g.http://localhost:8001
    When the port number is not mentioned, it defaults to 80.

    IPC Addresses

    IPC addresses use net.pipe for transport.
    Note: If a service uses this (i.e. named pipes, it can accept call only from thesame machine).
    e.g. net.pipe://localhost/PrPipe

     MSMQ Addresses

    MSMQ addresses use net.msmq for transport
    When private queues are used, queue type needs to be mentioned and is  omittedfor public queues:
    net.msmq://localhost/private/PService (using private queue)
    net.msmq://localhost/PService             (usingPublic Queue)

    Peer Network Address

    Peer network addresses use net.p2p for transport peer network name, path and port needs to be specified.....

    Bindings

    The Standard Bindings Following 9 types of Bindings are defined for WCF:

    Basic Binding

    BasicHttpBinding class provides this type of binding.
    It  exposes a WCF service as a legacy ASMX web service.
    This binding is extremely useful when the intent is to design a WCF service that should provide backward compatibility with WebServices.

    TCP binding

    NetTcpBinding class provides this type of binding.
    It uses TCP for cross-machine communication on the intranet.
    It supports a variety of features, including reliability, transactions, andsecurity, and is optimized for WCF-to-WCF communication.
    Restriction: It requires both the client and the service to use WCF.

    Peer network binding

    NetPeerTcpBinding class provides this type of binding and  uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it....

    IPC binding

    NetNamedPipeBinding class provides this type of binding and uses named pipes as a transport for same-machine communication. It is the most secure binding as it cannot accept calls from outside the machine and it supports a number of features similar to the TCP binding.

    Web Service (WS) binding

    WSHttpBinding class provides this type of binding, and  uses HTTP or HTTPS for transport....

    Federated WS binding

    WSFederationHttpBinding class provides this type of binding, this is a specializationof the WS binding, offering support for federated security......

    Duplex WS binding

     WSDualHttpBinding class provides this type of binding. It is similar to the WS binding except it also supports bi-directional communication from the service to the client.

    MSMQ binding

    NetMsmqBinding class provides this type of binding and uses MSMQ for transport and is suitable for  disconnected queued calls...

    MSMQ integration binding

    MsmqIntegrationBinding class provides this type of binding and converts WCF messages to and from MSMQ messages. This is most suitable for usage when Service legacy MSMQ clients interoperability is critical.

    Message Transfer Patterns
    WCF use the following three messaging patterns:

    1. Simplex,
    2. Duplex
    3. Request-Reply.

    Simplex communication is commonly referred to as one-way communication. This approachis used when asynchronous write-only services are required. It simply means if onlyone directional (client to Service) communication is required, use this pattern.

         Duplex communication provides true asynchronous two-way communications. (using callback  operations).

         In simplex and duplex communication, the consumer is not locked into waiting for a reply.
         Request-Reply: General enough not to provide any details

    Defining Bindings is one the most critical stages in WCF Service development. Service development.
    Correct type of binding can save a lot of time and effort need to build an effective service.
    As an effort to make you comfortable in Service development below is the checklist that needs to be referred before finalizing bindings for your service.

    Interoperability Level:
    Make sure  if communication will only be in  a .NET to .NET scenario,or legacy ASMX service, or if it is to be used by a consumer that adheres to the WS* specifications.

    Encoding:
        Select correct type of encoding, from among
        Text
        Message TransmissionOptimization Mechanism (MTOM) 
        Binary.

        Transport Protocols
               Select from  transport options TCP, HTTP, Named Pipe, and MSMQ.

        Messaging patterns : simplex, duplex, and request-reply.
        Security Considerations: WinTransactions and reliable sessions.

    Contracts:
    The contract is a platform-neutral and standard way of describing what the service does.
    WCF defines four types of contracts.

    Service contracts

    Describe which operations the client can perform on the service.

    Data contracts

    Define which data types are passed to and from the service.

    Fault contracts

    Define which errors are raised by the service, and how the service hand Allow the service to interact directly with messages. Message contracts can be typed or untyped.

    Service Type Support e.g. Message contract The following are the three types of services that can be written with WCF.

    1. Typed Services: These services use exact parameterization(passingthe required parameters in the correct order, format and type) when calling a servicemethod and respond with a well-defined type(as expected by the caller).
    2. Un-Typed Services: XML is the core of this type as it is used totransport the input parameters and the response output is also in XML. These servicesare the most flexible, but provide very little value back to the consumer.
    3. Typed Message Services: A custom type is defined that will containthe required input parameters and one more type that will wrap up the output parameters.

    This approach is generallyknown as Request Object / Response Object, since these are the types of objects that are result ofthese types of services.

    This  tutorial is just meant as a base for understanding the nitty-gritties of WCF.
    Next tutorial will cover the detailed implementation of the theoretical sections discussed here.

    Till then, Happy Coding...