RSS

WCF Web API

The API targets the REST starter kit but is more broadly scoped, both on the client and on the server.  It enhances WCF offering but is not intended as a replacement of it.  Figure 1 depicts high level architecture of the concept, note that it still follows core WCF service model.

image

Figure 1 – Web API architecture

With Web API, REST has come ways to within striking distance of becoming a first class service model within the WCF platform.  It’s a set of libraries that enhance WCF’s REST offering, which may be downloaded directly at CodePlex or via NuGet (recommended).

To install the Web API package:

  1. Download and install NuGet
  2. Create new or open existing Visual Studio application
  3. Reference Web API package

image 

Figure 2 – NuGet context menu for project references

image

Figure 3 – NuGet reference management dialog

When a package is installed (e.g., referenced via NuGet) the following steps occur:

  1. A subfolder named packages is created at the solution root
  2. Libraries, with dependencies, are placed underneath it
  3. Project references, to the libraries in step 2, are made
  4. A configuration file, packages.config, is added to the project, identifying installed components

image

Figure 4 – WebApi.All component model

WebApi.All installs 4 components.  Full list of (Preview 4) components, libraries, namespaces, & classes are listed below:

  • HttpClient
    • Microsoft.Net.Http
      • System.Net.Http
        • ByteArrayContent
        • DelegatingChannel
        • FormUrlEncodedContent
        • HttpClient
        • HttpClientChannel
        • HttpCompletionOption
        • HttpContent
        • HttpException
        • HttpMessageChannel
        • HttpMethod
        • HttpRequestMessage
        • HttpResponseMessage
        • MessageProcessingChannel
        • MultipartContent
        • MultipartFormDataContent
        • StreamContent
        • StringContent
        • WebRequestChannel
      • System.Net.Http.Headers
        • AuthenticationHeaderValue
        • CacheControlHeaderValue
        • ContentRangeHeaderValue
        • EntityTagHeaderValue
        • HttpContentHeaders
        • HttpHeaders
        • HttpRequestHeaders
        • HttpResponseHeaders
        • MediaTypeHeaderValue
        • MediaTypeWithQualityHeaderValue
        • NameValueHeaderValue
        • NameValueWithParametersHeaderValue
        • ProductHeaderValue
        • ProductInfoHeaderValue
        • RangeConditionHeaderValue
        • RangeHeaderValue
        • RangeItemHeaderValue
        • RetryConditionHeaderValue
        • StringWithQualityHeaderValue
        • TransferCodingHeaderValue
        • TransferCodingWithQualityHeaderValue
        • ViaHeaderValue
        • WarningHeaderValue
  • JasonValue
    • Microsoft.Runtime.Serialization.Json
      • System.Json
        • JsonArray
        • JsonObject
        • JsonObjectValidation
        • JsonPrimitive
        • JsonType
        • JsonValue
        • JsonValueChange
        • JsonValueChangeEventArgs
        • JsonValueLinqExtensions
      • System.Runtime.Serialization.Json
        • JsonValueExtensions
    • Microsoft.ServiceModel.Web.jQuery
      • Microsoft.ServiceModel.Activation
        • WebServiceHostFactory3
      • Microsoft.ServiceModel.Configuration
        • WebHttpElement3
      • Microsoft.ServiceModel.Web
        • FormUrlEncodedExtensions
        • WebHttpBehavior3
        • WebServiceHost3

  • WebApi.Core (installs dependencies: HttpClient & JsonValue)
    • Microsoft.ApplicationServer.Common
      • Microsoft.ApplicationServer.Common
        • ChainedBeginHandler : MulticastDelegate
        • ChainedEndHandler : MulticastDelegate
      • Microsoft.ApplicationServer.Common.Notification
        • INotificationService
        • NotificationEvent
        • NotificationReceiver
        • NotificationSender
    • Microsoft.ApplicationServer.Http
      • Microsoft.ApplicationServer.Http
        • FormUrlEncodedMediaTypeFormatter
        • HttpBinding
        • HttpBindingSecurity
        • HttpBindingSecurityMode
        • HttpContentExtensionMethods
        • HttpRequestMessage<T>
        • HttpResponseMessage<T>
        • HttpServiceHost
        • IQueryComposer
        • JsonMediaTypeFormatter
        • JsonValueMediaTypeFormatter
        • MediaRangeMapping
        • MediaTypeFormatter
        • MediaTypeFormatterCollection
        • MediaTypeFormatterExtensionMethods
        • MediaTypeMapping
        • ObjectContent
        • ObjectContent<T>
        • QueryCompositionAttribute
        • QueryCompositionMessageProperty
        • QueryStringMapping
        • TrailingSlashMode
        • UriPathExtensionMapping
        • UrlQueryComposer
        • XmlMediaTypeFormatter
      • Microsoft.ApplicationServer.Http.Activation
        • HttpServiceHostFactory
      • Microsoft.ApplicationServer.Http.Channels
        • HttpMessageEncodingBindingElement
        • HttpMessageExtensionMethods
        • HttpMessageHandlerBindingElement
        • HttpMessageHandlerFactory
      • Microsoft.ApplicationServer.Http.Configuration
        • HttpBehaviorElement
        • HttpBindingCollectionElement
        • HttpBindingElement
        • HttpBindingSecurityElement
        • HttpEndpointCollectionElement
        • HttpEndpointElement
      • Microsoft.ApplicationServer.Http.Description
        • HttpBehavior
        • HttpEndpoint
        • HttpOperationDescription
        • HttpOperationDescriptionExtensionMethods
        • HttpOperationHandlerFactory
        • HttpParameter
        • HttpParameterExtensionMethods
      • Microsoft.ApplicationServer.Http.Dispatcher
        • HttpErrorHandler
        • HttpInstanceProvider
        • HttpMessageFormatter
        • HttpMessageInspector
        • HttpOperationHandler
        • HttpOperationHandler<T,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,T9,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,T8,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,T7,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,T6,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,T5,TOutput>
        • HttpOperationHandler<T1,T2,T3,T4,TOutput>
        • HttpOperationHandler<T1,T2,T3,TOutput>
        • HttpOperationHandler<T1,T2,TOutput>
        • HttpOperationSelector
        • HttpResponseException
        • RequestContentHandler
        • ResponseContentHandler
        • UriAndMethodOperationSelector
        • UriTemplateHandler
    • Microsoft.ApplicationServer.Serialization
      • Microsoft.ApplicationServer.Serialization
        • IDataContractSurrogate
      • Microsoft.ApplicationServer.Serialization.Configuration
        • TypeElementExtensionMethods
    • Microsoft.ApplicationServer.ServiceModel
      • Microsoft.ApplicationServer.ServiceModel.Configuration
        • ServiceModelConfigurationElement
        • ServiceModelConfigurationElementCollection<ConfigurationElementType>
        • ServiceModelEnhancedConfigurationElementCollection<TConfigurationElement>
    • Microsoft.QueryComposition
      • Microsoft.QueryComposition.Client
        • ALinqExpressionVisitor
        • CountOption
        • DataServiceALinqExpressionVisitor
        • Evaluator
        • ExpressionNormalizer
        • InputReferenceExpression
        • ProjectionQueryOptionExpression
        • QueryOptionExpression
        • ReferenceEqualityComparer
        • ReferenceEqualityComparer<T>
        • ResourceBinder
        • ResourceExpression
        • ResourceSetExpression
        • UriWriter
      • Microsoft.QueryComposition.Server
        • DataServiceProviderMethods
        • OpenTypeMethods
        • QueryTranslator
    • WebApi.Enhancements (installs dependencies: Core)
    • Microsoft.ApplicationServer.HttpEnhancements
      • Microsoft.ApplicationServer.Http
        • HtmlForamtter
        • PlainTextFormatter
      • Microsoft.ApplicationServer.Http.Activation
        • HttpConfigurableServiceHost
        • HttpConfigurableServiceHost<TService>
        • HttpConfigurableServiceHostFactory
        • IConfigurableServiceHostFactory
        • RouteCollectionExtensions
      • Microsoft.ApplicationServer.Http.Description
        • HttpBehaviorWithErrorHandler
        • HttpErrorHandlerBehavior
        • HttpHostConfiguration
        • IContractConfiguration
        • IEndpointConfiguration
        • IEndpointFactory
        • IHttpHostConfigurationBuilder
        • InstanceProviderBehavior
        • IOperationConfiguration
        • IResourceFactory
        • IServiceConfiguration
        • ResourceFactoryProvider

To develop a Web API MVC service (source):

  1. Create empty MVC 3 app
  2. Reference WebApi
  3. Add DTO (POCO Data Transfer Object)
  4. Add & register service contract
  5. Add service operation
  6. Expose operation over http
  7. Consume operation (verification)
 
1 Comment

Posted by on July 4, 2011 in .Net WCF

 

Hosting WCF Services

Hosting Options

There are two main options to hosting WCF services:
  • Self host – explicitly controlled lifetime, e.g., hosted within an executable
  • Long running host – “implicitly” controlled lifetime, e.g., IIS, WAS, Windows Service, etc., although lifetime must be explicitly controlled within windows services other than WAS

How To Host WCF Services

There are four basic steps to hosting a WCF service within a .Net environment:
  1. Create a host project, e.g., website, web app, console app, etc.
  2. Reference relevant libraries, e.g., ServiceModel and appropriate service libraries and dependencies
  3. Configure EndPoints to accept requests, unless factories are used
  4. Appropriately instantiate a ServiceHost object or a subclass

The Object Model

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

Figure 1 – partial WCF 4 runtime object model

System.ServiceModel.ServiceHost – default host


Hosts and exposes services and allows interaction with them.

Figure 2 – ServiceHost class

ServiceHost() – Initializes a new instance of the ServiceHost class.
ServiceHost(Object, Uri[]) – Initializes a new instance of the ServiceHost class with the instance of the service and its base addresses specified.
ServiceHost(Type, Uri[]) – Initializes a new instance of the ServiceHost class with the type of service and its base addresses specified.
 
SingletonInstance – Gets the singleton instance of the hosted service.


 
AddServiceEndpoint(Type, Binding, String) – Adds a service endpoint to the hosted service with a specified contract, binding, and endpoint address.
AddServiceEndpoint(Type, Binding, Uri) – Adds a service endpoint to the hosted service with a specified contract, binding, and URI that contains the endpoint address.
AddServiceEndpoint(Type, Binding, String, Uri) – Adds a service endpoint to the hosted service with a specified contract, binding, an endpoint address, and a URI on which the service listens.
AddServiceEndpoint(Type, Binding, Uri, Uri) – Adds a service endpoint to the hosted service with a specified contract, binding, a URI that contains the endpoint address, and a URI on which the service listens.
CreateDescription – Creates a description of the service hosted. (Overrides ServiceHostBase.CreateDescription(IDictionary<String, ContractDescription>).)
InitializeDescription(Object, UriSchemeKeyedCollection) – Initializes a description of the service hosted based on its instance and specified base addresses.
InitializeDescription(Type, UriSchemeKeyedCollection) – Initializes a description of the service hosted based on its type and specified base addresses.

System.ServiceModel.ServiceHostBase – abstract base


Provides base object for the default and custom hosts

Figure 3 – ServiceHostBase class

ServiceHostBase – Initializes a new instance of the ServiceHostBase class.
 
BaseAddresses – Gets the base addresses used by the hosted service.
CloseTimeout – Gets or sets the interval of time allowed for the service host to close.
DefaultCloseTimeout – Gets the default interval of time allowed for the service host to close. (Overrides CommunicationObject.DefaultCloseTimeout.)
DefaultOpenTimeout – Gets the default interval of time allowed for the service host to open. (Overrides CommunicationObject.DefaultOpenTimeout.)
ManualFlowControlLimit – Gets or sets the flow control limit for messages received by the service hosted.
OpenTimeout – Gets or sets the interval of time allowed for the service host to open.
 
 AddBaseAddress – Adds a base address to the service host.
AddDefaultEndpoints – Adds service endpoints for all base addresses in each contract found in the service host with the default binding.
AddServiceEndpoint(ServiceEndpoint) – Adds the specified service endpoint to the hosted service.
AddServiceEndpoint(String, Binding, String) – Adds a service endpoint to the hosted service with a specified contract, binding, and endpoint address.
AddServiceEndpoint(String, Binding, Uri) – Adds a service endpoint to the hosted service with a specified contract, binding, and a URI that contains the endpoint address.
AddServiceEndpoint(String, Binding, String, Uri) – Adds a service endpoint to the hosted service with a specified contract, binding, endpoint address and URI that contains the address at which it listens.
AddServiceEndpoint(String, Binding, Uri, Uri) – Adds a service endpoint to the hosted service with the specified contract, binding, and URIs that contain the endpoint and listening addresses.
 ApplyConfiguration – Loads the service description information from the configuration file and applies it to the runtime being constructed.
 CreateDescription – When implemented in a derived class, creates the description of the hosted service.
IncrementManualFlowControlLimit – Increases the limit on the flow rate of messages to the hosted service by a specified increment.
 InitializeDescription – Creates and initializes the service host with the contract and service descriptions.
 InitializeRuntime – Initializes the runtime for the service host.
 LoadConfigurationSection – Loads the service element from the configuration file of the hosted service.
 OnAbort – Aborts the service. (Overrides CommunicationObject.OnAbort().)
 OnBeginClose – Begins an asynchronous operation invoked on the close of the service host. (Overrides CommunicationObject.OnBeginClose(TimeSpan, AsyncCallback, Object).)
 OnBeginOpen – Begins an asynchronous operation invoked on the opening of the service host. (OverridesCommunicationObject.OnBeginOpen(TimeSpan, AsyncCallback, Object).)
 OnClose – Closes down the hosted service, including their channel dispatchers and associated instance contexts and listeners. (OverridesCommunicationObject.OnClose(TimeSpan).)
 OnClosed – Releases resources used by the service host. (Overrides CommunicationObject.OnClosed().)
 OnEndClose – Completes an asynchronous operation invoked on the closing of the service host. (OverridesCommunicationObject.OnEndClose(IAsyncResult).)
 OnEndOpen – Completes an asynchronous operation invoked on the opening of the service host. (OverridesCommunicationObject.OnEndOpen(IAsyncResult).) OnOpen – Opens the channel dispatchers. (Overrides CommunicationObject.OnOpen(TimeSpan).)
 OnOpened – Gets the service credentials,service authentication and authorization behavior for the hosted service. (OverridesCommunicationObject.OnOpened().)
 ReleasePerformanceCounters – Releases the service and channel dispatcher performance counters for the hosted service.
SetEndpointAddress – Sets the endpoint address of the specified endpoint to the specified address.


UnknownMessageReceived
– Occurs when an unknown message is received.

 
Leave a comment

Posted by on August 2, 2010 in .Net WCF

 

WCF Messaging

System.ServiceModel.MessageContractAttribute – Strongly Typed SOAP Message




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

 
Leave a comment

Posted by on July 6, 2010 in .Net WCF

 

WCF Exception Handling

System.ServiceModel.FaultContractAttribute – Service Operation Interface Decorator


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

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

Other references

 
Leave a comment

Posted by on July 6, 2010 in .Net WCF

 

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.

Figure 1 – core service framework object model

System.ServiceModel.ServiceContractAttribute – Service Interface Decorator


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

System.ServiceModel.ServiceBehaviorAttribute – Service Implementation Decorator


 AddressFilterMode – 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
 AutomaticSessionShutdown – Specifies whether to automatically close a session when a client closes an output session.  Defaults to true.
 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.
 ConfigurationName – Gets or sets the value used to locate the service element in an application configuration file.  Defaults to fully qualified implementation type name.
 IgnoreExtensionDataObject – Gets or sets a value that specifies whether to send unknown serialization data onto the wire.  Defaults to false.
 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.
 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.
 MaxItemsInObjectGraph – Gets or sets the maximum number of items allowed in a serialized object.  Defaults to 64KB.
 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.
 Namespace – Gets or sets the value of the target namespace for the service in Web Services Description Language (WSDL).  Defaults to http://tempuri.org/.
 ReleaseServiceInstanceOnTransactionComplete – Gets or sets a value that specifies whether the service object is released when the current transaction completes.  Defaults to true.
 TransactionAutoCompleteOnSessionClose – Gets or sets a value that specifies whether pending transactions are completed when the current session closes without error.  Defaults to false.
 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.
 TransactionTimeout – Gets or sets the period within which a transaction must complete.  Defaults to 0.
 UseSynchronizationContext – Gets or sets a value that specifies whether to use the current synchronization context to choose the thread of execution.  Defaults to true.
 ValidateMustUnderstand – Gets or sets a value that specifies whether the system or the application enforces SOAP MustUnderstand header processing.  Defaults to true.

 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.
 SetWellKnownSingleton – Specifies an object that implements the service and that is used as the singleton instance of the service.
 ShouldSerializeConfigurationName – Returns a value that indicates whether the ConfigurationName property has changed from its default value and should be serialized.
 ShouldSerializeReleaseServiceInstanceOnTransactionComplete – Returns a value that indicates whether the ReleaseServiceInstanceOnTransactionComplete property has changed from its default value and should be serialized.
 ShouldSerializeTransactionAutoCompleteOnSessionClose – Returns a value that indicates whether the TransactionAutoCompleteOnSessionClose property has changed from its default value and should be serialized.
 ShouldSerializeTransactionIsolationLevel – Returns a value that indicates whether the TransactionIsolationLevel property has changed from its default value and should be serialized.
 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


 Action – Gets or sets the WS-Addressing action of the request message.
 AsyncPattern – Indicates that an operation is implemented asynchronously using a Begin<methodName> and End<methodName> method pair in a service contract.
 HasProtectionLevel – Gets a value that indicates whether the messages for this operation must be encrypted, signed, or both.
 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).
 IsOneWay – Gets or sets a value that indicates whether an operation returns a reply message.
 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.
 Name – Gets or sets the name of the operation.
 ProtectionLevel – Gets or sets a value that specifies whether the messages of an operation must be encrypted, signed, or both.
 ReplyAction – Gets or sets the value of the SOAP action for the reply message of the operation.

 

System.ServiceModel.OperationBehaviorAttribute – Service Operation Implementation Decorator




 AutoDisposeParameters – Gets or sets whether parameters are to be automatically disposed.  Defaults to true.
 Impersonation – Gets or sets a value that indicates the level of caller impersonation that the operation supports.  Defaults to NotAllowed.
 ReleaseInstanceMode – Gets or sets a value that indicates when in the course of an operation invocation to recycle the service object.  Defaults to None.
 TransactionAutoComplete – Gets or sets a value that indicates whether to automatically complete the current transaction scope if no unhandled exceptions occur.  Defaults to true.
 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


 IsReference – Gets or sets a value that indicates whether to preserve object reference data.  Defaults to false.
 Name – Gets or sets the name of the data contract for the type.  Defaults to class name.
 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.
 EmitDefaultValue – Gets or sets a value that specifies whether to serialize the default value for a field or property being serialized.  Defaults to true.
 IsRequired – Gets or sets a value that instructs the serialization engine that the member must be present when reading or deserializing.  Defaults to false. 
 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
 Order – Gets or sets the order of serialization and deserialization of a member.

Other references:

Professional WCF Programming

 
Leave a comment

Posted by on July 6, 2010 in .Net WCF

 

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.

 
Leave a comment

Posted by on June 3, 2010 in Software Engineering

 

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

  • 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.

 
Leave a comment

Posted by on June 2, 2010 in Software Engineering

 

Developing World-Class Software Development Environment

Developing any product requires the 3 Bs:

  • Builders
  • Building processes
  • Building blocks & tools

Let’s analyze in more detail these three aspects of development in the context of technology.  Progressively, over the past couple of decades, it has become common place for organizations to have an IT department, which may still be perceived as a necessary evil by the business side due primarily to less than readily available statistical quantitative reporting on their value add, but that’s a topic for another discussion.  IT departments often have to help decide between build versus buy, which may not always be as rigorous a process as it should due to political considerations and management leaning in one direction or another.  That’s also topic for another discussion.  So, let’s analyze the echo system for in-house software development.

Builders are the most important of the 3B’s, simply because the blocks and the processes are not yet autonomous.  There are several aspects to software development that require various combinations of specific training, knowledge, and experience.  These skill-sets requirements may be consolidated into the following 8 functional areas:

  • [BA] Analyze the business process to produce concrete and transferable (parameters and constraints hand-off) requirements
  • [Arch] Architect a relevant solution with, at the very least, a data flow and a components model
  • [Tech lead] Design the constituent components, their relationships, and public interfaces and lead the development effort
  • [Developer] Develop, deploy, enhance, and maintain the codebase
  • [Tester] Test the codebase and the product against the parameters and constraints identified in the business analysis
  • [Technical writer] Develop help documentation and support specification
  • [UX] Progressively improve all aspects of the process and the product, focusing primarily on product usage efficiency
  • [PM] Manage the process instance, e.g., the project, quantitatively with sponsor directives, communications, tasks, risks, etc.

There’s a tendency in the industry to delegate large portions of the process components requiring special skills to developers with certain levels of exposure to pre-identified tools and platforms.  Development cost containment is by far the most frequently identified underlying cause for such inclinations.  However, a minor analysis takes that argument apart and obviates such to be a misconception.  It’s true that developers are generally highly intelligent individuals and can deduce and acquire sufficient expertise to cover all of the 8 identified functional areas.  It is also true that the overall hourly development cost of a non-ideal team (say, 3 developers with the help of some actual or sample end users) developing a software is less than that of an ideal team (team of 8+ specialists, 1 or more specialist from each of the 8 identified functional areas) doing so.  While hourly development cost is an important piece of information highly visible and easily attained and plugged into cost justification reporting, other less quantifiable expenses must be quantitatively/statistically analyzed or extrapolated into account at the very least, because the costs are present whether they are measured or not.  Consider for example, the negative impact of a non-ideal development team:

  • Developers managing projects without specific training
    • Lower the quality of project management output (easy to learn, requires sustained training to master), proportionally raising timeline and corresponding development hours
    • Raise the risk of task failure, because one of the most important, although frequently skipped, responsibilities of a PM is to progressively breakdown tasks until associated risks may be quantified and used to project estimated development hours, which would be negatively impacted
    • Raise the risk of project failure, potentially due to reactive management and communication lapses
  • Developers architecting/designing solutions without specific training
    • May be unable to form sound basis for reasonable component models and/or well encapsulated interfaces contributing negatively to the 4 pillars of software: security, scalability, performance, and maintainability, consequently raising TCO by orders of magnitude at multiple levels
  • Developers moonlighting as BAs (testers, technical writers, or usability experts) without specific training
    • Raise the unit cost of business analysis, because they generally have higher hourly rate
    • Lower the quality of analysis output (BA is easy to learn but takes sustained training to master), proportionally raising development timeline and TCO

Having ideal teams alone is no guarantee for success, they must be accompanied by continuous training focused corporate strategy and a solid development process.

A better trained team member makes better decisions, resulting in better product quality, resulting in lowered TCO and higher productivity, contributing directly to corporate bottom-line.

The second leg of a team building strategy is the development methodology (building process), which must be strictly managed and continuously improved.  The main argument for having a methodology (e.g., an established process) is that it reduces unknown entities and thus limiting risk to producing the end product.  It also simplifies project management by tightly scoping tasks thus simplifying estimations and projecting release dates well in advance.  Couple of notable methodologies are flavors of Agile and Six Sigma, where the later originally developed by Motorola for manufacturing and has been retrofitted to software development with some success.  The methodology selection process must analyze corporate culture, mid to long term objectives, industry trends, available skill sets and tools support, as well as other relevant parameters and constraints. 

Any selected methodology must accommodate the 6 key process elements:

  1. Analyze
  2. Architect
  3. Design
  4. Develop
  5. Deploy
  6. Test

Other supplemental elements, such as code review, design approval, TDD (test module development must precede target development), refactor, etc. are highly recommended and raise general product quality.  Not all of the selected process elements will be necessary for a given iteration, but, should be in place and analyzed for relevancy at each iteration.  Development cycle iteration length should be moderately scoped to raise manageability and lower risk.

Implementation of a methodology must be scoped in a limited fashion to weed out potential risks and stumbling blocks as well as to tune the process to corporate culture and stated objectives.  Once widely in place, the methodology must be monitored and analyzed regularly (complete the feedback loop) for continuous improvement.

Your A team without a fitting toolbox is on queue to become someone else’s team.  The final leg of the team building strategy is selecting the building blocks and tools, most appropriate for the organization based on corporate culture, available skill sets, stated objectives, business model, and availability of the tools and platforms as well as reliability of respective vendors.   Currently the two main competing platforms are .Net and Java, each with pros and cons.  Selecting a development platform is only the beginning, a complement of tools must be built or licensed to support in-house development effort.  Tools for configuration management, project management, various user interface components, bug tracking, etc. are commonly used supplementals and generally raise development efficiency.  However, tools must be used cautiously and must be reviewed regularly for best-fit analysis, mainly because development aid tools such as CodeGen and CSLA may facilitate ease of use and abuse alike.

Development guidelines must be in place as well to fit the development platform, toolsets, and corporate objectives.  Having the guidelines in place is not enough, it must be closely accompanied by enforcement mechanism, otherwise the guidelines run the risk of being ignored.  A commonly used argument against following guidelines is that it raises development timelines.  The argument may only be tactically valid but weighs in strongly against tight deadlines.  However, the cost of not following standards is distributed across SDLC iterations and the old adage, “An ounce of prevention is worth a pound of cure” applies.

Select your team, process, and tools actively and as an organization or they will be implemented in some fashion by individual members which may not necessarily align with broader corporate objectives, raising potentially hard to detect costs.

 
Leave a comment

Posted by on May 19, 2010 in Software Engineering

 

Software Development Standards

Having standards are one of the most important aspects of the development process.  Whatever the standards may be, having them is important.  Enforcing corporate software development standards may be a little more challenging, check-in rules and regular code reviews can help with having processes around standards enforcements.  Here are some concrete and easily applicable guidelines:

Class

  • Name
    • Pascal case, e.g., MemberCode
    • No trailing "Type" or "Class", e.g., MemberType, MemberClass, etc.
    • Trailing collection type identifier, e.g., MemberCollection : Collection<Member>, MemberList : List<Member>, etc.
  • Sealed, unless otherwise necessary
  • Scoped with most restrictive priority, e.g., begin with private and then broaden as necessary
  • Should implement state pattern whenever state is relevent to business logic at the class level, e.g., database persistance, etc.
  • Should implement as singleton whenever the class state is equally relevent throughout the library, code collection classes, etc.
  • Should implement generics instead of using object whenever possible
  • Collection classes should inherit from generic collection
  • Must implement IDisposable if either a native or an IDisposable .net object is refrenced at the class level
  • Should not exceed 200 lines of code, re-evaluate and/or refactor code coherency otherwise
  • Exception handling
    • Wrap exceptions if desired
    • Allow exceptions to bubble up to the UI.  Do not handle, supress, or log them below the UI, unless absolutely necessary
  • Field
    • Name
      • Preceeding underscore, e.g., _id
      • Camel cased, e.g., _memberName
      • No type information, e.g., _sMemberName
      • No scope information, e.g., _mMemberName
  • Property
    • Name
      • Pascal case
    • Local variables
      • Camel case
      • Include type information, e.g., string sData, int iData, Member oMember, etc.
    • Setters should perform comparison test and ignore call if value is unchanged, otherwise set dirty state
  • Method
    • Name
      • Pascal case
      • Should preceed with Get whenever applicable, e.g., GetValue()
    • Parameters
      • Name
        • Camel case
        • Preceed with a ‘p’, e.g., pArg
        • No type information, e.g., _pArg
      • Must be 4 or less
      • Should pass an object reference instead of multiple values from it
    • Stateless actions and functions should be static
    • Dispose localy referenced native and IDisposable .net objects, unless the object is included in the return in which case it must be disposed before going out of scope
    • Should wrap native and IDisposable .net objects in the using block
    • Should wrap persistable blocks in a transaction block only at the highest applicable level
    • Event handlers should follow the ObjectName_EventName(object, EventArgs) pattern
    • Should not exceed 20 lines of code, re-evaluate and/or refactor code coherency otherwise
  • Event
    • Name
      • Should identify an action, e.g., Save, Click, etc.
      • Callback handler should identify the instance or type (for static events) name and the event name seperated by underscore, e.g., MyUser_Save, etc.
    • Use generic EventHandler(of T)
    • Should have standard signature, e.g., (object, EventAgrs), (object, MyEventAgrs), etc., note that generic EventHandler supplies standard signature

General

  • Constants and variables must be localized to most common scope
  • Calls should be limited to 4 levels or less deep
  • Have a singular exception handling mechanism and implement wrapping and logging within it

Pre-checkin checklist:

  1. Get latest from solution context menu
  2. Rebuild solution
  3. Verify that everything compiles
 
Leave a comment

Posted by on March 6, 2010 in Software Design

 

Code for Security

The basic premise behind security is protection against targeted or accidental malice.  The principle applies to the software industry just as readily as it does to any other.  Just like in the real world security in the software world revolves around various authorization models implemented in tiers and degrees of granularity.  At the bottom of the chain there’s data encapsulated by information which in turn is encapsulated by resources, all up for CRUD operations leading to effect in the non-virtual world. 

Currently the primary motivation for cyber attacks appear to be to steal information for financial gain and some common means to achieve that end are:

  • Phishing
  • Hacking
  • Malware – spyware, bots, etc.
  • Password Cracking
  • Social Engineering
  • Computer Viruses / Worms / Trojans

All of these threat templates have a life cycle that begin with malicious intent and end with some gain relevant to the perpetrator and loss to the victim.  Authorization abuse is heavily involved at almost all cyber threat life cycle, so, from a software development perspective, we need to design our software based on authorization models.  Unfortunately, that’s not enough, simply because authorizations may be hijacked, unless the model is perfect!  Although this is only a very small play in a very large battlefield, it’s a fundamental one and plays an ever increasingly central role to threat neutralization.  We should be mindful of some of the following precautionary measures in our development environments:

  • Secure development environment
    • Run with minimal privileges
    • Secure local IIS
    • Secure local database engine
  • Secure production environment
    • Avoid inserting test data in production database
    • Avoid creating backdoors to production environment
  • Code to protect
    • Don’t trust user input – can lead to buffer overruns, cross-site scripting attacks, SQL injection attacks, etc.
    • Protect against buffer overruns – generally c/c++ problem
    • Prevent cross-site scripting – secure query string parameters
    • Don’t require sa permissions – prevent sql injection
    • Don’t write your own encryption algorithm
    • Reduce attack profile – don’t install features you don’t use
    • Employ the principle of least privilege – separate and run code requiring additional privileges in a different process
    • Pay attention to failure modes – have exception handling framework and fall back to most secure mode
    • Impersonation is fragile, avoid heavy reliance on it
    • Write apps for non-admins
    • Centralize authorization models in design and at every level, e.g., class level, library level, application level, communication level, platform level, department level, and corporate level
 
Leave a comment

Posted by on November 10, 2009 in Software Design - Security

 
 
Follow

Get every new post delivered to your Inbox.