Wednesday, September 26, 2012

Diagramming tools

Here's a quick list of simple and cool diagramming tools:





  • Yuml Class Diagrams. 
    Text based class diagrams.  The syntax can be a little awkward, but works well when you get your head around the syntax.




  • Web Sequence Diagrams
    Text based sequence diagramming web tool. Type some puesdo-code and the sequence diagram is drawn based on your text.





  • Gliffy free form diagrams.
    WYSIWYG style free form diagram tool.  Has templates for Sequence diagrams and others.  Pretty nice tool

    Saturday, September 15, 2012

    70-513 WCF Study Notes


    Skill measured in the exam

    http://www.microsoft.com/learning/en/us/exam.aspx?id=70-513

    This is my raw notes I made while studying for the exam.

    HOSTING

    Its valid to not specify any end-points. Adding base addresses will infer binding, contract is inferred by service name.

    DISCOVERY

    To discover a service:
    Create one FindCriteria object for each iterface and set their Duration properties to two seconds. Loop for 30 seconds total and invoke their Find methods.
    To implement a "logger" that recieves service start and stop announcments use the AnnouncementService class not the AnnouncementClient class.


    RSS CONSUMPTION FROM A CLIENT

    SyndicationFeed has an Items property : SyndicationItem
    TextSyndicationContent : SyndicationItem
    +Text : string


    CUSTOM BINDING - DEFINING THE ORDER OF ELEMENTS (TRSMTET)

    Transactions
    Reliability
    Security
    Message Patterns
    Transport upgrades/helpers
    Encoding
    Transport

    MESSAGE QUEUEING

    To deliver to Dead Letter queue use Reject enum value for receiveErrorHandling.
    Poison messages use the Move, or Drop
    Fault is the default value. (Throws an exception).
    Address of dead letter queue: net.msmq://localhost/system$;DeadLetter


    REST JSON SERVICES

    When using WebGet attrib must use a SVC file <%ServiceHost Service="TestService" Factory="System.ServiceModel.ActivationWebServiceHostFactory" %>
    or the WebHttpBehaviour on the service.
    Use webHttpBinding for Pox/Json and general WCF use from javascript.
    Use enableWebScript for Ms AJAX usage.


    ROUTING SERVICES

    ISimplexDatagramRouter = Reflects a one way message exchange.
    ISimplexSessionRouter  = Reflects a one way message exchange with a session aware channel.
    IRequestReplyRouter    = Reflects a request-reply message exchange.
    IDuplexSessionRouter   = Reflects a  duplex communication using a callback contract.
    Cannot mix message patterns when routing.  For contracts that do, use IDuplexSessionRouter and use callbacks to route the responses.


    PROXY USAGE

    Closing/Disposing a failed proxy might throw. Rather use .Abort in the exception handler or finalise block.
    Any Reuse of a closed proxy will result in ObjectDisposedException
    Proxy's should derive from ClientBase<T>, T = ServiceContract.


    SERVICE EXCEPTIONS

    Use serviceDebug element in web.config
    [FaultContract(typeof(FaultException<Order>))] is valid but received by client as FaultException.
    [FaultContract(typeof(ErrorInfo))              is best, received by client as FaultException<ErrorInfo>.


    PERFORMANCE MONITORING, LOGGING AND AUDTING

    Use serviceSecurityAudit element in a behaviour to audit to event log.
    setting <diagnostics performanceCounters="ServiceOnly"/> will only give service level counters (no endpoint or operation level counters are available).
    EventLogs are added to the security log by default in IIS7+ or Application in IIS6.
    Calls failed is talking about unhandled exceptions
    Calls faulted is when FaultExceptions are thrown.
    MessageLogging/Filters can contain operation level filters:
    <add xmlns:addr="http://www.w3.org/2005/08/addressing">addr:Action[text()='http://namespaceOfService/IServiceContract/OperationNameResponse']</add>
    Configuring Logging:
    <diagnostics>
    <messageLogging logEntireMessage="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"/>
    <sources>
    <source propagateActivity="true" name="System.ServiceModel" switchValue="Warning, ActivityTracing">
    <listeners>
    <add name="ServiceModelTraceListener"/>
    </listeners>
    </source>
    <sources>
    </diagnostics>

    mexHttpBinding is a valid binding. Useful when the same address is used for service call and metadata.


    SECURITY

    OperationContract has a protection level.
    ServiceContract has a protection level that enforces a Minimum.
    Message level security must be encrypted using a cert
    Don't use SecurityAction.Assert only use .Demand.
    Mulitple PrincipalPermission attributes allowed and are Or'ed.
    wsHTTPBinding defaults to message security and client credential type Windows.

    IMPERSONATION

    TokenImpersontationLevel.Impersonation
    Impersonates the user's credentials only on that service machine.
    TokenImpersonationLevel.Delegatioin
    Allows impersonation of the user's credentials on the service machine and other machines.
    When ImpersonateCallerForAllServiceOperations is false Allowed results in no impersonation.
    Required always results in impersonation.
    ServiceSecurityAuditBehavior adds to windows event log in security section.
    <machineSettings enableLoggingKnownPii="true"/> allows usernames and passwords to be logged in clear text in the WCF standard diagnostics logs. It is false by default.
    You can implement custom message level security binding with TransportSecurityBindingElement.
    Setting EstablishSecurityContext will not issue a token and require every call be re-authenticated.

    CERTIFICATES

    StoreName.My = Personal certs for logged in user
    StoreName.Root = Trust Root CA's
    StoreName.AuthRoot = Third party CA's


    STREAMING

    NetTcpBinding doesnt support message streaming with SessionMode=Required or with Reliable Sessions configured on.
    Use MTOM Message Transmission Optimization Mechanism for streaming large files; its more efficient than binary.


    CONTRACTS

    SERVICE BEHAVIOR ATTRIBUTE
    AutomaticSessionShutdown
    ConcurrencyMode
    ConfigurationName
    IncludeExceptionDetailsInFaults
    InstanceContextMode (PerSession Default)
    Name
    Namespace
    ReleaseServiceInstanceOnTransactionComplete
    TransactionAutoCompleteOnSessionClose
    TransactionIsolationLevel
    TransactionTimeout
    UseSynchronisationContext

    OPERATION BEHAVIOR ATTRIBUTE

    Impersonation
    RelaseInstanceMode
    TransactionAutoComplete
    TransactionScopeRequired

    TRANSACTION FLOW ATTRIBUTE 

    Used on an Operation Contract (Allows|Mandatory|NotAllowed)

    ORDER BEHAVIOURS ARE EVAL'D

    Most specific to most general
    Contract, Operation, Endpoint, Service
    Reliability should be turned on for Http bindings.


    MESSAGE CLASS

    A message instance can only be accessed or written to once.
    To eliminate duplicate xmlns in Message contracts, embed a datacontract as the sole messageBodyMember and declare the namespace on the datacontract.
    To read a message Use CreateBufferedCopy method of the Message class, use CreateMethod of the MessageBuffer class to make a copy.

    TOOLS

    SvcUtil.exe
    Generate a client side proxy from service metadata.
    Generate metadata from services
    WCFTestClient.exe
    Edit Client configuration
    Invoke service methods
    WSDL.exe
    Generate a client side proxy from service metadata.

    Saturday, September 1, 2012

    Which WCF Binding to use

    Ever wondered which binding to use and why?  Ever wondered what is the difference between wsHttpBinding and ws2007HttpBinding?

    For binding selection generally follow this:


    Common Binding Capability Matrix
    Name Transport Encoding Interop. With non-.Net Reliability Ordered Delivery Security
    BasicHttpBinding Http/Https Soap1.1*/Mtom Yes No No None*, Transport, Message, Mixed
    NetTcpBinding Tcp Binary No Yes (off*) Yes (on*) None, Transport*, Message, Mixed
    NetNamedPipeBinding IPC Binary No No (**) Yes (on*) None, Transport*
    WsHttpBinding Http/Https Soap1.2*/Mtom Yes Yes (off*) Yes (on*) None, Transport, Message*, Mixed
    NetMsMqBinding MsMq Binary No No No None, Transport*, Message, Both
    webHttpBinding Http/Https Xml*/Json Yes No No None*, Transport, Mixed
    * = The Default.
    ** = NetNamedPipeBinding doesn't support reliability but is classified as inherently reliable because its communicating within the same machine.

    Client Credentials Supported with Transport Security
    Name None Windows UserName Certificate
    BasicHttpBinding Yes* Yes Yes Yes
    NetTcpBinding Yes Yes* No Yes
    NetNamedPipeBinding No Yes* No No
    WsHttpBinding Yes Yes* Yes Yes
    NetMsMqBinding Yes Yes* No Yes
    WebHttpBinding Yes* Yes Yes Yes
    * = The Default.

    Client Credentials Supported with Message Security
    Name None Windows UserName Certificate Issued Token
    BasicHttpBinding No No No Yes* No
    NetTcpBinding Yes Yes* Yes Yes Yes
    NetNamedPipeBinding N/A N/A N/A N/A N/A
    WsHttpBinding Yes Yes* Yes Yes Yes
    NetMsMqBinding Yes Yes* Yes Yes Yes
    WebHttpBinding N/A N/A N/A N/A N/A

    Standard Behavior Defaults
    [ServiceBehavior(
        AutomaticSessionShutdown=true,
        ConcurrencyMode=ConcurrencyMode.Single,
        InstanceContextMode=InstanceContextMode.PerSession,
        IncludeExceptionDetailInFaults=false,
        UseSynchronizationContext=true,
        ValidateMustUnderstand=true)]

    [OperationBehavior(
            TransactionAutoComplete=true,
            TransactionScopeRequired=false,
            Impersonation=ImpersonationOption.NotAllowed)]

    http://msdn.microsoft.com/en-us/library/ms751438.aspx
    Of all the settings shown above InstanceContextMode is the most tricky.  Just because it defaults to PerSession, does not mean a session is always present.  If the binding does not support it or the service contract has been configured to not allow it (ServiceContract.SessionMode).

    Here's a table showing the resulting instance context mode as a result of binding, service cotract's session mode and service behavior's instance mode.
    Binding Service Behavior Session Mode Service Contract Context Mode Resulting Actual Instance Mode
    BasicHttp Allowed or Not Allowed Per Call or Per Session PerCall
    netTCP and netNamedPipes Allowed or Required Per Call PerCall
    netTCP and netNamedPipes Allowed or Required Per Session PerSession
    WsHttp (no message security and no reliability) Allowed or Not Allowed Per Call or Per Session PerCall
    WsHttp (with message secuity or reliability) Allowed or Required Per Session PerSession
    WsHttp (with message security or reliability) Not Allowed Per Call or Per Session PerCall
    WebHttpBinding Allowed or Not Allowed Per Call or Per Session PerCall
    Invalid configurations are not shown (invalid configurations will throw runtime exceptions such as InvalidOperationException: Contract requires Session, but Binding 'WebHttpBinding' doesn't support it).

    Using JSON
    I have little experience using JSON with the standard bindings, but my understanding is that you will be forced to use BasicHttpBinding or WebHttpBinding (not WsHttpBinding).  When doing so you will loose most of the support for other WCF features like security, reliability, ordered messages, and transactions.  With regard to security, SSL is supported by both Web and Basic, any other form of security (message and credentials) you'll be forced to hand craft service side extensions to support these.

    WTF is Ws2007HttpBinding?
    I came across this MSDN article that explains in detail the differences in a capability matrix between the Http bindings and W3C recommendations when to use which one.

    http://msdn.microsoft.com/en-us/library/ms730294.aspx

    Simply put, the difference with the newer 2007 Http binding is that is supports extensions to the Organization for the Advancement of Structured Information Standards (OASIS).  This means it supports minor changes to the WS Security standards. There is no real compelling reason for a developer to choose these bindings, there's no amazing new features to take advantage of, merely protocol level changes.  You might choose the 2007 binding if a client insists on a specific standard being used, or you're integrating into existing clients or services that use it.

    Further Reading