Creating Services

  • The [OperationContract] attribute is applied to a method indicating that the method implements a service operation as part of a service contract. This attribute should be defined before each method specified in a WCF application code.
  • The TransactionTimeout property of the [ServiceBehavior] attribute gets or sets the time in the format “HH:MM:SS” within which a transaction must complete.
  • The [Service Contract] attribute is used to an interface or a class to define a service contract in a WCF application.
  • The TransactionFlowOption enumeration specifies the transaction flow policy for a service operation. It is used with the TransactionFlow attribute that specifies whether a service operation accepts incoming transactions from a client. The OperationBehaviorAttribute.TransactionAutoComplete property gets or sets a value to indicate whether the current transaction scope has been automatically completed if no unhandled exceptions occur.
  • Uploading the XML file in as a stream will work better for uploading large files. Streams can load large amounts of data, or large files that are read into most programs. Therefore, you should create the following operation contract:
    [OperationContract()] void UploadFile(Stream xmlData)
  • In order to handle complex data types, you should use the [KnownType(typeof())] attribute with the data contract. The [KnownType] attribute is specifically meant to be used with structures, classes, interfaces, and other complex data types.
  • Pass MCTS: Microsoft Visual Studio 2008 in a first attempt:

  • You must define a data contract for all complex data types that you require so that they can be serialized. A data contract can explicitly be created by using the DataContractAttribute (or [DataContract] qualifier) and DataMemberAttribute (or [DataMember] qualifier) attributes.
  • The [DataMember] attribute, when applied to a member of a type, it specifies that the member is part of a data contract. When this attribute is applied to a field or a property explicitly, it specifies that the member value will be serialized by an DataContractSerializer object.
  • In order to allow the interface to be passed to the clients, you should use the [KnownType(typeof())] attribute with your data contract. The [KnownType] attribute is specifically meant to be used with structures, classes, interfaces, and other complex data types.
  • Create code including the [DataContract] attribute with the [DataMember] attributes for using services both simple as well as complex data types.
  • The [DataMember] attribute, when applied to a member of a type, specifies that the member is part of a data contract. When this attribute is applied to a field or a property explicitly, it specifies that the member value will be serialized by an DataContractSerializer object.
  • If a WCF application makes extensive use of services and require data to be transferred from a client to the service and visa versa, then the [KnownType(typeof())] attribute should be used with the data contract.
  • The following steps should be taken if you wish to implement a service so that it can be used by applications:
    • Create a service contract and define it by using an interface.
    • Create a class that implements the interface.
    • Compile the code.
    • Run the service, which involves three steps namely configuring, hosting, and opening the service.
    • Then, deploy and implement the service to be used by applications.
  • The [ServiceContract(SessionMode=SessionMode.Required)] code statement specifies that the service contract requires a session-based binding and hence must be run within a session.
  • The TransactionScopeRequired property should be set to true to require the operation to execute within a transaction scope.
  • Setting the SessionMode to Required means that the service contract requires a session-based binding and hence must be run within a session.
  • The TransactionFlowOption enumeration is set to Allowed value to require the operation to execute within the scope of a transaction.
  • The TransactionTimeout property of the ServiceBehaviorAttribute class is used to get or set the period within which a transaction must complete. The transaction timeout should be set in the hours:minutes:seconds format.
  • Setting the TransactionFlowOption enumeration to Allowed and the ProtectionLevel property to ProtectionLevel.None ensures that the flow of a transaction is not blocked for security reasons such as authentication.
  • The [MessageContract] attribute creates a message contract enabling a user to use a type for a parameter or return value that serializes directly into a specified SOAP message structure.
  • A messaging operation contract has at most one parameter and one return value, where both the parameter value types and the return value types are either void or message types. A message type may be any type marked with the MessageContractAttribute or the Message type.
  • In a message contract, the [MessageBodyMember] attribute is applied to those members of the class type that you want to make into parts of the SOAP body of the message.
  • An Operation contract cannot return an integer return type, as this return type is not a message type.
  • The Action property of an operation contract is used to control the action of the method’s input message. Its property value is specified to “*” to indicate that a service operation will handle all messages received by the service, but cannot be directed to a service operation. Then, the operation contract should define a function (that returns a void) in order to process the message.

Exposing and Deploying Services

  • All communication with a WCF service occurs through service endpoints. An endpoint consists of four properties, namely an address, a binding, a contract and a set of behaviors.
  • If the includeExceptionDetailInFaults attribute in the element is set to true, it specifies that unhandled execution exceptions are to be converted into a FaultException of type ExceptionDetail and are sent as a fault message. Microsoft recommends you to set this attribute to true when debugging a WCF service.
  • Marshalling cannot be a requirement for configuring WCF endpoints. Marshalling is an older concept of COM and is not used in WCF services.
  • The following are the steps to configure service bindings:
    • Define a service contract for a user-defined WCF service.
    • Implement the service contract in a custom service class.
    • Create a Web.config file to configure a service endpoint for the service class. This service class uses the BasicHttpBinding class that represents a binding used by a WCF service to configure and expose endpoints.
    • Create a .svc file and place it in the Internet Information Services (IIS) virtual directory.
  • The AutomaticSessionShutdown should be set to false, when a custom control is used over the lifetime of the session. So, you must turn off the automatic shut down.
  • The System.ServiceModel.SessionMode.Required setting specifies that the service contract requires a sessionful binding.
  • The IsTerminating property of the [OperationContract] attribute gets or sets a value to indicate whether the service operation causes the server to close the session after a reply message is sent.
  • In the [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, ReleaseServiceInstanceOnTransactionComplete=true)] code, setting the ConcurrencyMode to Multiple will allow multiple threads to concurrently access the service. Secondly, setting the ReleaseServiceInstanceOnTransactionComplete to true will allow the instance to be released as soon as a transaction is complete.
  • Setting the AutomaticSessionShutdown property of the [ServiceBehavior] attribute to false prevents the server from automatically closing the session and also enables the custom control of the lifetime of a session.
  • The Required value of the SessionMode enumeration specifies that the service contract requires a sessionful binding.
  • The System.ServiceModel.SessionMode.Allowed setting specifies that the contract can support sessions if the incoming binding supports them. This setting simply let the service to use sessions optionally and not always use them.
  • In order to host a WCF service inside a managed application, you must take the following steps:
    • Embed the service code inside the managed application code.
    • Define a service endpoint for the service. This can be done either imperatively in code or declaratively through configuration.
    • Create an instance of the ServiceHost class that provides a host for services.
  • A WCF service is deployed inside a managed application, as it is the least robust hosting option and requires the least infrastructure to support deployment.
  • You need to call a constructor of the ServiceHost class in order to programmatically add the base address to a service.
  • The best deployment strategy would be to deploy the service inside a managed application, as it is the least robust hosting option and also requires the least infrastructure to deploy.
  • The following are the steps to host a WCF service within a managed Windows service:
    • Include a service implementation of the service contract, a Windows Service class, and an installer class for the WCF service code.
    • Implement the managed Windows service by inheriting it from the ServiceBase class.
    • Override the OnStart method of the ServiceBase class to create and open a ServiceHost object.
    • Override the OnStop method of the ServiceBase class to stop and dispose the ServiceHost object.
    • Inherit a custom installer class from the Installer class and allow the service to be installed by the Installutil.exe tool.
    • Provide a base address for the Windows service to be configured in application settings.
  • A WCF service that is hosted in IIS includes the following tasks during its deployment:
    • Guarantees that the IIS, WCF, and the WCF activation component are correctly installed and registered.
    • Reuses an existing ASP.NET application or creates a new IIS application.
    • Creates a .svc file for a WCF service.
    • Deploys the WCF service implementation to the IIS or ASP.NET application.
    • Configures the WCF service.
  • The @ServiceHost directive is used to associate the service host factory with the WCF service to be hosted. This directive is required to access or compile the service hosting code provided in a .svc file.
  • In order to host the WCF service on the IIS Web server, you have created a new folder for your application files. Then, you have used the IIS management tool to create a Web application in the new folder. Next, you need to perform the following actions:
    • Create a Web.config file that contains the appropriate configuration code. Place this file in the application folder.
    • Create a service file containing the @ServiceHost directive information for the service. Place this file in the application folder.
    • Create an App_Code folder within the application folder for your code files. Put the code file that defines and implements the service contract in this folder.
  • The aspNetCompatibilityEnabled attribute of the element should be set to true because the requests are made to WCF services that flow through the ASP.NET HTTP communication pipeline, and the communication over non-HTTP protocols is prohibited.
  • A new IIS application can be created for hosting WCF services. Alternatively, A WCF service can be deployed into an existing ASP.NET application. Before deploying a WCF service implementation to the IIS or ASP.NET application, it is necessary to create a .svc file for the WCF service. Then the WCF service can be configured.
  • The @ServiceHost directive is used to associate the service host factory with the WCF service to be hosted. This directive is required to access or compile the service hosting code provided in a .svc file.
  • In order to host the WCF service on the Web server, you must use the @ServiceHost directive information for the service.
  • The ServiceHost servicehost = new ServiceHost(/*Add Parameters */); servicehost.Description.Behaviors.Add(/*Add Service Behavior */); code instantiates the service and then uses the Description.Behaviors.Add method of the ServiceHost object in order to add custom behaviors to the service.
  • If you need to create a custom service behavior that throws an exception if the list of endpoints that are configured is not complete, you should write the following code segment:
    class CustomBehavior : IServiceBehavior
    {
    public void Validate(ServiceDescription desc, ServiceHostBase myservicehost)
    {
    MyValidationMethod();
    }
    }

Pass MCTS: Microsoft Visual Studio 2008 in a first attempt:

Instrumenting and Administering Services

  • The element of the
    element is used to specify a listener that collects, stores, and routes messages. This element directs the tracing output to an appropriate target. The sub-element of the element adds a listener to the Listeners collection.
  • WCF provides some namespaces (such as System.IO.Log, System.ServiceModel, System.ServiceModel.MessageLogging, and System.Runtime.Serialization) that define trace sources for each assembly. The traces generated within such an assembly are accessed by the listeners defined for that trace source.
  • The valid source levels of trace messages that are filtered by the source switch and event type filter are Off, Critical, Error, Warning, Information, Verbose, ActivityTracing, and All.
  • The valid values for the performanceCounters attribute are All, ServiceOnly, and Off.
  • Setting the performanceCounters attribute to All will enable all category counters such as ServiceModelService, ServiceModelEndpoint, and ServiceModelOperation.
  • The tracing levels from Verbose to Critical are stacked on top of each other except the Off level. Therefore, the Verbose tracing level can handle the Critical, Error, Warning, and Verbose trace events. The Verbose tracing level is useful for debugging purposes or for application optimization.
  • The logEntireMessage attribute of the element defines a Boolean value that specifies whether the entire message including the message header and body is logged.
  • The IClientMessageInspector.BeforeSendRequest method enables you to inspect or modify a message before a request message is sent to a WCF service. The IEndpointBehavior.ApplyClientBehavior method is implemented to view, modify, or add custom extension to the client runtime across all messages, which can be used with an endpoint or for specific operations such as including custom headers.
  • If the System.Diagnostics.XmlWriterTraceListener trace listener as its type is used in the configuration file, then the output file location and name must be specified in the service configuration file. This can be done by setting the initializeData attribute to the name of the log file. Otherwise, an exception will be thrown.
  • In order to identify the cause of the error that had occurred in the application, you must examine the application event log. One reason for logging application event is to help in debugging issues that arise in the application.
  • The valid sub elements of the element are , , , , , , , , and . Each of these sub elements determines a different item for the service model.
  • The IDispatchMessageInspector interface is used to implement the service side message inspection. It defines the methods that enable custom inspection modification of application messages for a WCF service.
  • Setting the isClientSide property to true establishes the client-side inspector.
  • The IClientMessageInspector interface implements the client-side message inspection and defines an instance of message inspector to be added to the MessageInspectors collection to view or modify messages.

Consuming Services

  • The following command line that uses the Service Model Metadata Utility Tool (SvcUtil.exe) tool with the appropriate switches (to create the client code) generates a code file and a configuration file for the service:
    svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
  • The Svcutil.exe utility tool is used to generate a service proxy. The output of this tool is a class that implements the service interface.
  • The ServiceModel Metadata Utility Tool (Svcutil.exe) is used to automatically create the service proxy class. Therefore, you do not have to manually create a class that implements the service interface.
  • The element of the main element specifies contract, binding, and address properties of the channel endpoint. The valid attributes of the element are address, binding, contract, name, bindingconfiguration, and behaviorconfiguration.
  • The required attributes of the element are address, binding and contract. The optional attributes of the element are bindingConfiguration, behaviorConfiguration, and name.
  • The name optional attribute is used to uniquely identify an endpoint for a given contract. Though, the name attribute is optional, it is required when it works with a ChannelFactory object. The ChannelFactory object uses this attribute in order to specify which endpoint in the client configuration is being targeted and must be loaded when a channel is created to service.
  • The address, behaviorConfiguration, and contract are valid endpoint attributes.
  • You do not use the binding and bindingConfiguration endpoint attributes when working with the ChannelFactory class, as a ChannelFactory object does not use these attributes to specify the endpoint.
  • The steps to use a WCF client are as follows:
    • Create an endpoint address and a WCF client object.
    • Call the service operations from within the client object.
    • Close the client connection once the operation call is completed.
  • In a scenario where you have already created the service proxy. Now, you should take the following steps to call the functions of the service:
    • Create a client class that implements the service interface.
    • Instantiate the class and call its methods.
    • Use the Svcutil.exe utility tool in order to create and use the client object.
  • You do not call the Open method on the client. Once you have instantiated the client proxy, you simply call its methods. You can call the Close method if you wish to end all communications with the client.
  • The CommunicationException class is used on the client or the server side to catch a communication related exception, such as address not found, or connectivity related exceptions between endpoints. In order to catch CommunicationException on the client side, you can use the traditional exception handling such as a try/catch block.
  • The TimeoutException exception is the best option to use, which will handle slow response time. This exception is thrown specially when the time allotted for a process or operation has expired.
  • If you have created a client for a WCF service and have appropriate error handling in the client for all expected exceptions. However, you find that if an exception occurs, the client is sometimes not usable after that. In order to rectify this problem, you should check the State property to verify if the client is still opened.
  • The ServiceActivationException class does not represent an expected WCF client exception, as this class represents an exception that is thrown when a service fails to activate.
  • The following are the steps to configure a WCF service endpoint to be interoperable with .NET Web service clients:
    • Create a new instance of the BasicHttpBinding class.
    • Optionally enable transport security for the WCF service endpoint binding by setting the security mode for the binding to Transport.
    • Add a new application endpoint to the service host by using the binding instance being created.
    • Enable an HTTP/GET metadata endpoint for the WCF service.
  • The valid contract types that can be specified with a COM Object are Typed contract, WSDL contract, and MEX contract.
  • You do not create contracts for .NET Web Service clients in order to configure a WCF service endpoint.

Securing Services

  • Transport level security is implemented using secure HTTP also called HTTPS.
  • An SSL can be implemented in a WCF application depending on how the application is hosted. The following are the methods in which SSL can be implemented:
    • Use the IIS infrastructure to set up an SSL service if IIS is used as the WCF host.
    • Bind an SSL certificate to the address using the HttpCfg.exe tool if a self-hosted WCF application is created.
  • Transport-level security is implemented using secure HTTP also called HTTPS and therefore uses SSL.
  • You will use the transport security mode, as it uses a transport-level protocol, such as HTTPS that would support all clients. This security mode is available on many platforms and less complex.
  • Message level security actually secures every single message and provides true end-to-end security.
  • Message security allows you to sign or encrypt only parts of the message, instead of the entire message.
  • The endpoint identity of a WCF service is a value that is generated from the service Web Services Description Language (WSDL). The endpoint identity that is propagated to any client is used to authenticate the service.
  • In order to configure the service identity, a service endpoint is created and its identity is set to the certificate’s DNS by using the WSHttpBinding object.
  • Security demands are used to ensure that only callers that have been granted a specified permission can call a user’s code.
  • In order to implement the Security Token Service (STS) authentication, you must use a WSFederationHttpBinding object with the default security mode.
  • The SupportingTokenParameters class is a collection of token properties and methods used to create security binding elements and a set of tokens of the same type.
  • You must enable the role manager in the application by setting the enabled attribute to true, as in the following code:
  • You will set the defaultProvider attribute of the element to SqlRoleProvider in order to match with the SQL Server roles.
  • You should not use the BasicHttpBinding class, as it does not use Windows authentication and creates a session in impersonating a client. Setting the Impersonation property to ImpersonationOption.Allowed will not cause a client impersonation, but it will merely allow the possibility of impersonation.
  • The following are the steps in impersonating a client on a WCF service:
    • Create a WCF service.
    • Use a binding class such as NetTcpBinding or WSHttpBinding that uses Windows authentication and creates a session.
    • Apply the [OperationBehavior] attribute (or the OperationBehaviorAttribute class) to a method that requires client impersonation, when implementing the interface of the service.
    • Set the Impersonation property of the [OperationBehavior] attribute to ImpersonationOption.Required.
  • The appropriate binding classes that uses Windows authentication and creates a session are NetTcpBinding and WSHttpBinding.
  • The following are the steps to set the allowed impersonation level on a client, after enabling the WCF client impersonation on a service:
    1. Create a service client code by using the ServiceModel Metadata Utility Tool (Svcutil.exe) utility tool to create the WCF client.
    2. Set the AllowedImpersonationLevel property of the WindowsClientCredential class to one of the TokenImpersonationLevel enumeration values that include None, Anonymous, Impersonation, Identification, and Delegation.

Managing the Service Life Cycle

  • Setting the value to PerSession of the InstanceContextMode property means that once the client connects, the same instance will be used for all calls from that client until the session ends.
  • Setting the value to PerCall of the InstanceContextMode means every single call from the client to the service gets a new instance of the service object.
  • The SessionMode.Required value specifies that the service contract requires always to use sessions.
  • The NetMsmqBinding class represents a queued binding suitable for cross-machine communication. This class provides support for queuing by leveraging Microsoft Message Queuing (MSMQ) as a transport.
  • A dead-letter queue contains messages that failed to reach the target queue, which may be due to reasons, such as expired messages and connectivity issues.
  • The following are the steps required to enable a reliable session to send messages:
    • Create the configuration element that contains the bindingConfiguration attribute. This attribute references a binding configuration by giving it a name say MyBinding1.
    • Reference the binding configuration name in the configuration element.
    • Enable the reliable session by setting the enabled attribute of the element to true.
  • The code statement enables the reliable session so that the messages should arrive in the same order in which they were sent.
  • The SessionMode.Allowed value will let the service contract to use sessions if possible and not always use them.
  • The properties of a transaction used in WCF are atomicity, consistency, isolation, and durability.
  • Setting the transactionFlow attribute to true and the transactionProtocol attribute of the configuration element to the specified transaction protocol is to configure the binding in a WCF service to accept incoming transactions.
  • The receiveTimeout and maxConnections attributes of the element are valid binding settings, but are irrelevant when a transaction is implemented in the binding.
  • The WsatConfig.exe -network:enable -port:443 -endpointCert: -accountsCerts: -restart command line is used to enable the WS-AT protocol service inside MSDTC by using port 443 and an X.509 certificate with a private key installed in the local computer.
  • The valid concurrency modes are single, multiple, and reentrant.
  • In the [ServiceBehavior( InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Multiple)] code, InstanceContextMode is set to Single to handle all the required client requests, and ConcurrencyMode is set to Multiple to have multiple threads processing messages concurrently.
  • You should set the instancing mode to PerCall, the session mode to Required, and the concurrency mode to Single, if you require to run a WCF service within a session, an instance for each client call, and also allow each instancing object to have one thread.
  • Setting the ConcurrencyMode to Multiple will allow multiple threads to concurrently access a WCF service. Secondly, setting the ReleaseServiceInstanceOnTransactionComplete to false will not allow the instance to be released as soon as a transaction is complete. Instead, this will allow the same instance to reuse for each call.

Pass MCTS: Microsoft Visual Studio 2008 in a first attempt:

One thought on “MCTS 70-503-CSHARP Short Notes: Exam Passing Tips

  1. Pingback: .Net upgrade Exam 70-523 – Exam Study Notes | tech2buzzy

Comments are closed.