Naz-Tek Services, Inc.

Writing Software To Provide Strategic Advantage

Home     Development Guidelines     Design Patterns     Knowledgebase     Trainingbase     Blog Feed     Events     Tools     About Us     Contact Us      
July 06

WCF Exception Handling

System.ServiceModel.FaultContractAttribute – Service Operation Interface Decorator


Public property

Specifies one or more SOAP faults that are returned when a service operation encounters processing errors.

Property Action – Gets or sets the action of the SOAP fault message that is specified as part of the operation contract.
Property DetailType – Gets the type of a serializable object that contains error information.
Property HasProtectionLevel – Gets a value that indicates whether the SOAP fault message has a protection level assigned.
Property Name – Gets or sets the name of the fault message in Web Services Description Language (WSDL).
Property Namespace – Gets or sets the namespace of the SOAP fault.
Property ProtectionLevel – Specifies the level of protection the SOAP fault requires from the binding.

Other references



7:15 PM GMT  |  Read comments(0)

WCF Messaging

System.ServiceModel.MessageContractAttribute – Strongly Typed SOAP Message


Public property

 
Property HasProtectionLevel – Gets a value that indicates whether the message has a protection level.
Property IsWrapped – Gets or sets a value that specifies whether the message body has a wrapper element.
Property ProtectionLevel – Gets or sets a value that specified whether the message must be encrypted, signed, or both.
Property WrapperName – Gets or sets the name of the wrapper element of the message body.
Property WrapperNamespace – Gets or sets the namespace of the message body wrapper element.


7:22 PM GMT  |  Read comments(0)

WCF Service Object Model

The Framework

WCF provides the framework to comprehensively manage and utilize the following 6 broad aspects of service orientation and development:

  1. Service – the core of the framework and an almost independent entity
  2. Host – independent of the service and is independently scalable
  3. Client – aware of the service API only via the proxy
  4. Communication – connects clients to service hosts via channels
  5. Security – tiers of out-of-the-box protection
  6. Debugging – tools and techniques

The Service

A WCF service promotes the separation of state and behavior.  It’s important for two main reasons:

  1. Behavior encapsulation and centralization – lower TCO in terms of maintainability and reusability as well as raising the potential scalability by orders of magnitude.
  2. State portability without much fear of unintentional or other malice.

The Object Model

Services are supported by the framework by a set of classes primarily from the System.ServiceModel namespace.

image

Figure 1 – core service framework object model

System.ServiceModel.ServiceContractAttribute – Service Interface Decorator


Property CallbackContract – Gets or sets the type of callback contract when the contract is a duplex contract.  Defaults to null.
Property ConfigurationName – Gets or sets the name used to locate the service in an application configuration file.  Defaults to fully qualified interface type name.
Property HasProtectionLevel – Gets a value that indicates whether the member has a protection level assigned.   Defaults to false.
Property Name – Gets or sets the name for the <portType> element in Web Services Description Language (WSDL).  Defaults to Managed type name.
Property Namespace – Gets or sets the namespace of the <portType> element in Web Services Description Language (WSDL).  Defaults to http://tempuri.org/.
Property ProtectionLevel – Specifies whether the binding for the contract must support the value of the ProtectionLevel property.  Defaults to None.
Property SessionMode – Gets or sets whether sessions are allowed, not allowed or required.  Defaults to Allowed.

System.ServiceModel.ServiceBehaviorAttribute – Service Implementation Decorator


Property Public propertyAddressFilterMode – Gets or sets the AddressFilterMode that is used by the dispatcher to route incoming messages to the correct endpoint.  Defaults to Exact.
    • Available options
      1. Any – Indicates a filter that matches on any address of an incoming message.  Using this value turns off the address filter check. Any message, no matter what its WS-Adressing:To identity is accepted
      2. Exact – Indicates a filter that does an exact match on the address of an incoming message
      3. Prefix – Indicates a filter does the longest prefix matches on the address of an incoming message
    • AddressFilterMode.Prefix
    • Understanding Address Filtering
    • WCF Addressing In Depth
Property Public propertyAutomaticSessionShutdown – Specifies whether to automatically close a session when a client closes an output session.  Defaults to true.
Property ConcurrencyMode – Gets or sets whether a service supports one thread, multiple threads, or reentrant calls.  Defaults to Single.
    • Available options
      1. Single – The service instance is single-threaded and does not accept reentrant calls. If the InstanceContextMode property is Single, and additional messages arrive while the instance services a call, these messages must wait until the service is available or until the messages time out.
      2. Reentrant – The service instance is single-threaded and accepts reentrant calls. The reentrant service accepts calls when you call another service; it is therefore your responsibility to leave your object state consistent before callouts and you must confirm that operation-local data is valid after callouts. Note that the service instance is unlocked only by calling another service over a channel. In this case, the called service can reenter the first service via a callback. If the first service is not reentrant, the sequence of calls results in a deadlock. For details, see ConcurrencyMode.
      3. Multiple – The service instance is multi-threaded. No synchronization guarantees are made. Because other threads can change your service object at any time, you must handle synchronization and state consistency at all times.
Property ConfigurationName – Gets or sets the value used to locate the service element in an application configuration file.  Defaults to fully qualified implementation type name.
Property IgnoreExtensionDataObject – Gets or sets a value that specifies whether to send unknown serialization data onto the wire.  Defaults to false.
Property IncludeExceptionDetailInFaults – Gets or sets a value that specifies that general unhandled execution exceptions are to be converted into a System.ServiceModel.FaultException<TDetail> of type System.ServiceModel.ExceptionDetail and sent as a fault message. Set this to true only during development to troubleshoot a service.  Defaults to false.
Property InstanceContextMode – Gets or sets the value that indicates when new service objects are created.  Defaults to PerSession.
    • Available options
      1. PerSession – A new InstanceContext object is created for each session.
      2. PerCall – A new InstanceContext object is created prior to and recycled subsequent to each call. If the channel does not create a session this value behaves as if it were PerCall.
      3. Single – Only one InstanceContext object is used for all incoming calls and is not recycled subsequent to the calls. If a service object does not exist, one is created.  For singleton lifetime behavior (for example, if the host application calls the ServiceHost constructor and passes an object to use as the service), the service class must set InstanceContextMode to InstanceContextMode.Single, or an exception is thrown when the service host is opened.
Property MaxItemsInObjectGraph – Gets or sets the maximum number of items allowed in a serialized object.  Defaults to 64KB.
Property Name – Gets or sets the value of the name attribute in the service element in Web Services Description Language (WSDL).  Defaults to service implementation class name.
Property Namespace – Gets or sets the value of the target namespace for the service in Web Services Description Language (WSDL).  Defaults to http://tempuri.org/.
Property ReleaseServiceInstanceOnTransactionComplete – Gets or sets a value that specifies whether the service object is released when the current transaction completes.  Defaults to true.
Property TransactionAutoCompleteOnSessionClose – Gets or sets a value that specifies whether pending transactions are completed when the current session closes without error.  Defaults to false.
Property TransactionIsolationLevel – Specifies the transaction isolation level for new transactions created inside the service, and incoming transactions flowed from a client.  Defaults to Unspecified.
    • Available options
      1. Serializable – Volatile data can be read but not modified, and no new data can be added during the transaction.
      2. RepeatableRead – Volatile data can be read but not modified during the transaction. New data can be added during the transaction.
      3. ReadCommitted – Volatile data cannot be read during the transaction, but can be modified.
      4. ReadUncommitted – Volatile data can be read and modified during the transaction.
      5. Snapshot – Volatile data can be read. Before a transaction modifies data, it verifies if another transaction has changed the data after it was initially read. If the data has been updated, an error is raised. This allows a transaction to get to the previously committed value of the data.  When you try to promote a transaction that was created with this isolation level, an InvalidOperationException is thrown with the error message "Transactions with IsolationLevel Snapshot cannot be promoted".
      6. Chaos – The pending changes from more highly isolated transactions cannot be overwritten.
      7. Unspecified – A different isolation level than the one specified is being used, but the level cannot be determined. An exception is thrown if this value is set.
Property TransactionTimeout – Gets or sets the period within which a transaction must complete.  Defaults to 0.
Property UseSynchronizationContext – Gets or sets a value that specifies whether to use the current synchronization context to choose the thread of execution.  Defaults to true.
Property ValidateMustUnderstand – Gets or sets a value that specifies whether the system or the application enforces SOAP MustUnderstand header processing.  Defaults to true.

Operation GetWellKnownSingleton – Retrieves an object that implements the service and that is used as the singleton instance of the service, or null if there is no singleton instance.
Operation SetWellKnownSingleton – Specifies an object that implements the service and that is used as the singleton instance of the service.
Operation ShouldSerializeConfigurationName – Returns a value that indicates whether the ConfigurationName property has changed from its default value and should be serialized.
Operation ShouldSerializeReleaseServiceInstanceOnTransactionComplete – Returns a value that indicates whether the ReleaseServiceInstanceOnTransactionComplete property has changed from its default value and should be serialized.
Operation ShouldSerializeTransactionAutoCompleteOnSessionClose – Returns a value that indicates whether the TransactionAutoCompleteOnSessionClose property has changed from its default value and should be serialized.
Operation ShouldSerializeTransactionIsolationLevel – Returns a value that indicates whether the TransactionIsolationLevel property has changed from its default value and should be serialized.
Operation ShouldSerializeTransactionTimeout – Returns a value that indicates whether the TransactionTimeout property has changed from its default value and should be serialized.

 

System.ServiceModel.OperationContractAttribute – Service Operation Interface Decorator


Property Action – Gets or sets the WS-Addressing action of the request message.
Property AsyncPattern – Indicates that an operation is implemented asynchronously using a Begin<methodName> and End<methodName> method pair in a service contract.
Property HasProtectionLevel – Gets a value that indicates whether the messages for this operation must be encrypted, signed, or both.
Property IsInitiating – Gets or sets a value that indicates whether the method implements an operation that can initiate a session on the server (if such a session exists).
Property IsOneWay – Gets or sets a value that indicates whether an operation returns a reply message.
Property IsTerminating – Gets or sets a value that indicates whether the service operation causes the server to close the session after the reply message, if any, is sent.
Property Name – Gets or sets the name of the operation.
Property ProtectionLevel – Gets or sets a value that specifies whether the messages of an operation must be encrypted, signed, or both.
Property ReplyAction – Gets or sets the value of the SOAP action for the reply message of the operation.

 

System.ServiceModel.OperationBehaviorAttribute – Service Operation Implementation Decorator


Public property
Property AutoDisposeParameters – Gets or sets whether parameters are to be automatically disposed.Public property  Defaults to true.
Property Impersonation – Gets or sets a value that indicates the level of caller impersonation that the operation supports.Public property  Defaults to NotAllowed.
Property ReleaseInstanceMode – Gets or sets a value that indicates when in the course of an operation invocation to recycle the service object.Public property  Defaults to None.
Property TransactionAutoComplete – Gets or sets a value that indicates whether to automatically complete the current transaction scope if no unhandled exceptions occur.  Defaults to true.
Public propertyProperty TransactionScopeRequired – Gets or sets a value that indicates whether the method requires a transaction scope for its execution.  Defaults to false.

 

System.Runtime.Serialization.DataContractAttribute – Service Payload Decorator


Property IsReference – Gets or sets a value that indicates whether to preserve object reference data.  Defaults to false.
Property Name – Gets or sets the name of the data contract for the type.  Defaults to class name.
Property Namespace – Gets or sets the namespace for the data contract for the type.  Defaults to class namespace.

 

System.Runtime.Serialization.DataMemberAttribute – Service Payload Member Decorator


  • Members must be both readable and writable otherwise System.Runtime.Serialization.InvalidDataContractException is raised.
Property EmitDefaultValue – Gets or sets a value that specifies whether to serialize the default value for a field or property being serialized.  Defaults to true.
Property IsRequired – Gets or sets a value that instructs the serialization engine that the member must be present when reading or deserializing.  Defaults to false. 
Property Name – Gets or sets a data member name.  Default is the actual member name.
    • Separates CLR member name from externally exposed contract member name, which bear security and versioning benefits.
    • Allows member names, otherwise not allowed in CLR
Property Order – Gets or sets the order of serialization and deserialization of a member.

Other references:

Professional WCF Programming



5:58 PM GMT  |  Read comments(0)

June 03

Legacy Migration – to .Net and Beyond

Unlike some of the legacy platforms, the .Net platform is a more thought out and strategically planned development platform, incorporating lessons learned and avoiding mistakes of earlier platforms.  It’s similar in concept to the Java platform in that both platforms rely on a virtual machines to accept intermediate language code compiled from diverse 3GL languages and to provide final execution environment.  Target of our analysis here is the .Net platform, so, let’s focus on some key areas that a migrating development team should carefully consider.

Follow migration objectives

Corporate objectives behind a migration should be explicitly identified and prioritized, because this will drive target platform choice, architecture and design decisions and mitigate among conflicting directives.  Some examples of general objectives are:

  • Extend application life – an older platform application may become progressively isolated and unsupported, yet still have business value to the organization, thus prompting migration rather than obsolescence
  • Reduce application TCO – enhancing and/or supporting an existing application written on an older platform may become progressively more expensive and eventually lead to a tipping point whereby leading to the decision to migrate.  This may occur for individual applications or a development environment as a whole encompassing a broader initiative
  • Remain competitive – aside from lowering TCO of application space, technology driven solutions have the potential to help business processes be more efficient at execution

Fundamental .Net concepts

Some of the building blocks of the .Net framework may be unfamiliar to development teams experienced in other platforms.  A solid understanding of some of these key concepts is crucial before majority of the .Net development begins, otherwise another beginning could also simultaneously occur, the maintenance and support nightmare especially pertaining to memory leaks and sluggish performance.  The single most fundamental concept of the .Net platform is the Common Language Runtime (CLR).  It is the virtual machine, mentioned earlier, that forms the core of the platform.  Some other key concepts are:

  • Full object orientation – everything in .Net inherits from object, some explicitly and others implicitly.  Only single inheritance is supported whereby a type may inherit from only one type but may implement multiple interfaces, which may be used to implement polymorphism.  An abstract type may be used to implement the most basic form of abstractionEncapsulation is supported in 5 access modifier scopes: public, protected internal/friend, internal/friend, protected, and private
  • Supported types – there are two high level types: value type and reference type.  Value types form the basis of primitives, such as Integer, Boolean, etc., which give the platform a substantial performance boost that lacked in older platforms like SmallTalk.  Value types are dynamically boxed/unboxed to support implicit inheritance from object
  • Garbage collection – out of scope object instances are garbage collected, eliminating the need to explicitly reset them, unless they implement the IDisposable interface, which identifies an object to be or aggregate unmanaged resource(s), e.g., non-CLR type(s) and that it must be explicitly disposed before it may be garbage collected.  Microsoft recommends a design pattern to cleanup disposable objects
  • Multiple concurrent language support – a .Net solution may contain multiple projects, each in it’s supported language of choice, e.g., one project may be in VB.NET while another in C# and yet another in F#
  • COM support – .Net supports a two way COM interoperability framework called the COM Interop.  Any .Net library may consume or be exposed to COM objects via the COM Interop framework.  Consumption is automatically handled by the IDE, which dynamically creates interoperability wrappers at the time of referencing, while exposure must be explicitly configured to avoid unintentional performance lags.  Keep in mind that COM Interop is very expensive and should be avoided when possible
  • Delegates – these are thread safe function pointers, e.g., c-style pointers with a strongly typed signature.  The .Net event model along with countless other framework aspects have delegates at the core
  • Generics – it’s the support for the use of templated types.  A generic server may declares one or more generic type(s) in the type/method declarations and use them as correspondingly scoped type instance and/or parameters

Migration steps

Easiest and the quickest solution may be to run the migration wizard and manually resolve any resulting errors and call it a migrated application.  However, that’s also potentially the most expensive approach, mainly because coding intentions are not accounted for and what may be a widely accepted good practice in one platform may be blasphemy in the other.  Depending on the specifics of the to and from application types and platforms, the entire end product may run against the grain and may raise nightmare support and maintenance scenarios until re-written.  A common migration scenario is moving from classic VB smart client application to ASP.NET web application.  Timely developer training is the high risk scenario here, because moving from a stated environment mindset to a stateless one requires a good training schedule and an elongated transient period to sync in.  Your context and exact scenario will dictate the specificity of your migration steps, but, here’s a rundown of the general steps:

  1. Prepare the source codebase – if it’s an option, it may be worthwhile to refactoring the codebase at the source and separate the model, view, and the controller tiers because it may be more expedient to do so in the source platform and because it reduces potential manual operations mainly centered around the UI (view)
    1. Label the codebase in source control
    2. Develop unit & integration test scripts, if not already available.  These scripts would likely be easily transferable to the target platform and be used to certify both the initial and the final product
    3. Execute all test scripts and archive reports in source control
    4. Refactor the codebase and move as much logic out of the UI tier and into the middle tier(s) as possible.  Note that this will have an impact on the overall application because the resultant public API will be altered and should be considered carefully for potential negative impact before refactoring
    5. Label the codebase in source control
  2. Prepare destination databases – the migrated product may or may not use the same databases as the pre-migration product.  If the databases are the same then skip this step otherwise backup the source database and restore it as the destination database, so, you have an exact snapshot replica with both data and schema
  3. Generate the destination codebase – if a wizard driven migration is applicable, e.g., same before and after application types, initiate the wizard by starting the legacy application with the appropriate .Net IDE
    1. Let the wizard drive.  If a wizard driven approach is not possible for the entire application, e.g., moving from classic VB to ASP.NET, consider migrating individual libraries one at a time using the wizard or using online language translators or manually typing, whichever is more expedient
    2. Review and resolve errors, there will generally be some conversion errors, review and resolve each as appropriate
    3. Add the project to source control
    4. Migrate all the test scripts to .Net using the migration wizard
    5. Execute all test scripts and verify expected behavior and archive reports in source control
    6. Label the codebase in source control
  4. Refactor the final product – this is likely to be the most time expensive part of the operation.  Depending on how the application was originally written, a complete rewrite may be in order
    1. Reverse engineer existing design artifacts and compare and map them to existing domain models.  Domain driven designs produce some of the lowest TCOs, as a general trend, regardless of migration
    2. Isolate different processes within the application to the extent possible with an eye on SOA, because that’s the upcoming and potentially prevalent platform, whereby, applications maybe rendered meaningless in its current sense and services interacting via discoverable interfaces (e.g., XML), regardless of their underlying platform, would form the basis of our software space
    3. Wrap service layers around the different and independently serviceable modules, if applicable

Every step of this potentially lengthy migration process, keep in mind the next migration for this very application and how it could be made more portable without sacrificing performance.



12:25 AM GMT  |  Read comments(0)

June 01

Legacy Migration – Motivation & Preparation

Motivations for migration

The primary motivation for migration is, as in most other cases, the bottom line.  Over time it becomes progressively more expensive to maintain and enhance legacy software developed in house due to some of the following reasons:

  • Limited vendor support – vendors move resources away from legacy platform support, reducing service pack release frequencies, which in turn:
    • Leaves thus discovered platform bugs and security gaps unattended for longer periods, requiring additional in-house development effort
    • Chokes the flow of more contemporary features, raising the opportunity cost, when compared to advances in RAD, for example
  • Higher integration cost – as systems are in ever increasing need of more integration to raise productive capacity, legacy platforms may be at a noticeable disadvantage in terms of additional development effort required to integrate with contemporary platforms and that gap only widens over time
  • Talent shortage – skilled and willing legacy developers become harder to find and retain, potentially raising turnover and training costs

Despite these and other reasons about 80% of production IT systems, according to developer.com, are running on legacy platforms.  At the heart of the issue again is the bottom line, mainly because identifying the actual cost of maintaining legacy code has challenges and disagreements, some of which are discussed in a 2009 article published by ITBusinessEdge.  Compare that to the highly visible and easily identifiable initial investment to migration projects and the management reluctance becomes obvious, until at least some TCO analysis is performed.

Pre-migration preparations

Once a decision has been made in favor of migration the first consideration should be the build versus buy analysis, each of which has many context specific pros and cons.  Should a full or partial build approach be taken, the following preparatory steps must be considered to minimize the total cost of the Endeavour and maximize the probability of success:

  • Identify concrete objectives and measurement units – list of business functionality, performance parameters, scalability ranges, and security measures, etc., in comparison to existing legacy application(s).  This list will be used for various aspects of project management, not the least of which is quantifying success
  • Select target platform – there are two heavy weights in the world of enterprise software development, .Net and Java as illustrated by Gartner.  Select one that minimizes TCO and is in sync with long term corporate objectives and directions

imageimage

  • Select deployment strategy – full migration versus partial and incremental migration.  Depending on you specific scenario, one option may be more cost effective than the other.  Generally, however, an incremental approach provides more flexibility, transparency, and adjustment opportunities
  • Train your team – devise a schedule for training to prepare your existing resources on the target platform.  It’s crucial to train your development team well on the target platform.  This single factor, if not properly managed, has the potential to substantially raise operational expenses, e.g., cost of support, maintenance, and enhancements over the life of the product while raising the necessity for rewrite

Developers coding on a platform they are not trained on codes for the platform they were trained on

  • Acquire expert review – subscribe to services whereby development artifacts produced by your team may be objectively and iteratively rated and guided, because higher quality translates to lower TCO

The old quote, “An ounce of prevention is worth a pound of cure”, is as applicable to migration projects as it is to any other aspect of software development.  Prepare well and you’ll pay less, both in monetary and political terms.  In the next article I’ll analyze some of the key considerations for migrating legacy codebase to the .Net platform.



10:38 PM GMT  |  Read comments(0)