Thursday, July 10, 2008

 This is a Part 4 of the Interview articles.
Part 1: "BizTalk 2004, Questions for interview without answers" http://geekswithblogs.net/LeonidGaneline/archive/2006/05/22/79267.aspx  
Part 2: "BizTalk interview questions and principle" http://geekswithblogs.net/LeonidGaneline/archive/2007/07/03/113663.aspx
Part 3: "WCF: Questions for studing and interview" http://geekswithblogs.net/LeonidGaneline/archive/2008/01/07/wcf-questions-for-studing-and-interview.aspx  

Please, mark your skills in the table. 
I completely understand that nobody ever tried ALL the BizTalk features.    
   
Name                                                      Number of the Projects      Months             Skills Mark (1..10 or A,B...)

artifacts:
 applications   
ports, groups, locations   
FTP   
SOAP   
HTTP   
SQL   
WCF   
SMTP, POP3   
MSMQ   
SharePoint   
LOB: EDI base, Siebel, etc. (name them)   
pipelines
pipeline components   
schemas   
maps   
database functoids (or custom DB mapping)   
Xslt   
Xslt templates   
orchestrations   
transactions   
atomic scope  
long-running   
compensation scope    
exception scope     
persistent points   
correlations   
helper .NET classes   
SQL data bases (with relation to the BizTalk)   
hosts, instances   
adapters   
parties   
EDI, AS2 system   
policy, rules, vacabularies   
BAM   
BAS 
Development: 
orchestrations   
port-to-port   
helper .NET classes   
custom adapters   
custom pipeline components   
custom functoids   
rules…   
BAM   
BAS   
ESB  
 Debugging Tuning-Up:   
VS
Nunit   
BizUnit   
LoadGen   
stress testing   
performance metrics   
different utilities (name them)   
multi-server debugging   
MOM   
HAT   
Adm.Console   
PerfMon   
Deployment: 
BTSDeploy   
BTSTask   
MSI, Binding   
multi-server deployment   
clustered MessageBox   
WMI scripts  
   
Development techniques:   
   - correlation   
   - convoy parallel   
   - convoy sequential unified   
   - convoy sequential non unified   
   - long-running transaction   
   - transaction compensation   
  - FIFO   
   - send data to SQL   
   - receive data from SQL   
   - data validating   
 - error handling in the BizTalk applications   
  - BizTalk to/from WS/HTTP apps   
* test-driven development   
* .NET development tools   
   
Programming skills:   
* test-driven programming   
* VS.NET   
* script languages, utils   
* SQL: database normalization, programming   
 Web-programming   
low-end programming   
   
   

   
Several questions (sorry, no more than 2-3 min for answer):
 
  • How do you study BizTalk? what are the main sources of the information? 
  •  Describe creating the full-featured BizTalk application. Just the steps.   
  • Describe debugging the full-featured BizTalk application.   
  • Describe deploying the full-featured BizTalk application.   
  • Monitoring the BizTalk application:   
       


   
Skills Mark Legend:   
 can describe purpose and functionality 
 2 made Sample(s) 
 3 used in one project 
 used in one project recently  
 used in several projects 
 6 used advanced functionality 
 can show my answers in forums and articles in blog 
 8 used API (in code) 
 9 can teach other developers, can show pro and cons 
                 OR  
 A know something 
 B can use in standard cases 
 C can use advanced features, API 
 expert 

Wednesday, July 09, 2008

Interesting information in KB:
"How to use distinguished fields and promoted properties in a BizTalk Server project" http://support.microsoft.com/kb/942250
 
"...
  • A promoted property may not be available as a promoted property after you write a value into the message context. This situation can occur if the value that you write into the message context has the same name and namespace that was used to promote the property.
  • Properties that have a null value are not permitted in the message context. Therefore, if a null value is written into the message context, this value will be deleted.
    ..."
 
BTW What is it "a null value"?
  • Is it <shipDate xsi:nil="true"></shipDate> ?
  • Is it absence of the value <shipDate></shipDate> ?
  • Is it "closed tag <shipDate /> ?
  • Is it absence of the whole node?
 
In http://www.w3.org/TR/2004/REC-xmlschema-0-20041028/#Nils we have description of it. But frequently we've got different interpretation of this term. And I am not sure about interpretation in KB
 
 
And let me add one more, not obvious:
  • Distinguished fields and promoted properties have to always get Min/Max Occurs = 1. (Not 0, not "unbounded", only 1)

Tuesday, June 24, 2008

Notes

·         Bindings are spread across several namespaces.

·        DataContractAttribute is placed in the System.Runtime.Serialization namespace not in the System.ServiceModel namespace.

·         Configuration sections are spread across several namespaces.

·         ClientSection and ServicesSection: First has the structure client/endpoint, the second – services/service/endpoint. Asymmetric.


System.ServiceModel.dll

System.ServiceModel

·         ServiceHost

·         ChannelFactory<TChannel>

·         ClientBase<TChannel>

Contracts:

·         ServiceContractAttribute

·         OperationContractAttribute

·         MessageContractAttribute

·         FaultContractAttribute

Bindings:

·         BasicHttpBinding

·         NetMsmqBinding

·         NetNamedPipeBinding

·         NetPeerTcpBinding

·         NetTcpBinding

·         WS2007FederationHttpBinding

·         WS2007HttpBinding

·         WSDualHttpBinding

·         WSFederationHttpBinding

·         WSHttpBinding

Exceptions:

·         CommunicationException

·        

 

System.ServiceModel.Activation

·         ServiceHostFactory

·         WorkflowServiceHostFactory

System.ServiceModel.Activation.Configuration

·         DiagnosticSection

System.ServiceModel.Channels

Interfaces:

·         IChannel

·         IChannelFactory<TChannel>

·         IChannelListener<TChannel>

Abstract classes:

·         Binding

·         BindingContext

·         BindingElement

·         ChannelFactoryBase<TChannel>

·         ChannelListenerBase<TChannel>

·         CommunicationObject

·         Message

·         MessageHeader

·        

Bindings:

·         CustomBinding

Binding Elements:

·         TransportBindingElement

·         MessageEncodingBindingElement

·        

System.ServiceModel.Configuration

Sections:

·         BehaviorsSection

·         BindingsSection

·         ClientSection

·         DiagnosticSection

·         ServicesSection

Element: System.Configuration.ConfigurationElement

·         BaseAddressElement

·        

ElementCollection: System.ServiceModel.Configuration.ServiceModelEnhancedConfigurationElementCollection<ComMethodElement>

·         BaseAddressElementCollection

·        

System.ServiceModel.Description

·         ServiceEndpoint

Behavior interfaces:

·         IContractBehavior

·         IEndpointBehavior

·         IOperationBehavior

·         IServiceBehavior

Descriptions:

·         ContractDescription

·         FaultDescription

·         ServiceDescription

System.ServiceModel.Dispatcher

·         ChannelDispatcher

*     ClientOperation

*     ClientRuntime

·         EndpointDispatcher

Filters:

·         ActionMessageFilter

·         MatchAllMessageFilter

·         MessageFilter

·        

System.ServiceModel.MsmqIntegration

·         MsmqIntegrationBinding

System.ServiceModel.Security

Credentials:

Encoders:

System.ServiceModel.Security.Tokens

Tokens:

SecurityTokenParameters:


System.Runtime.Serialization.dll

System.Runtime.Serialization

Attributes:

·         CollectionDataContractAttribute

·         DataContractAttribute

·         DataMemberAttribute

·         EnumMemberAttribute

 

 

System.WorkflowServices.dll (v3.5)

System.ServiceModel

·         WorkflowServiceHost

Bindings:

·         BasicHttpContextBinding

·         NetTcpContextBinding

·         WSHttpContextBinding

 

 



Thursday, June 19, 2008

We should install the certificate to the server that hosts the services with Transport level security.

For tests we could use the self-made certificate, for production we recommend to use the certificate issued by the industrial certificate provider as the VeriSign.

1.       Install Microsoft .NET Framework 2.0 Software Development Kit (SDK) (x64) [http://www.microsoft.com/downloads/details.aspx?familyid=1AEF6FCE-6E06-4B66-AFE4-9AAD3C835D3D&displaylang=en]. It is installed by default to the "C:\Program Files\Microsoft.NET\SDK\v2.0 64bit\Bin " folder.

2.       [Optionally, only if you also have server certificate and want to refresh it]"C:\Program Files\Microsoft.NET\SDK\v2.0 64bit\Bin\certmgr.exe" -del -r LocalMachine -s My -c -n MyCompany-HTTPS-Server

3.       "C:\Program Files\Microsoft.NET\SDK\v2.0 64bit\Bin\makecert.exe" -sr LocalMachine -ss My -n CN= MyCompany-HTTPS-Server -sky exchange -sk MyCompany-HTTPS-Key

4.       Install the new certificate to the IIS by the Web Server Certificate Wizard. Open IIS Admin, choose the Web-site, Properties, Directory Security tab, Secure communicationServer Certificate… button, it starts the Web Server Certificate Wizard .

5. Check if the IIS / Web Site / Properties / tab Web Site - SSL Port set up to 443 (

 


To expose the service metadata by HTTPS and HTTP use:

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior_Name">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

To expose the service metadata by HTTPS or HTTP only, change attribute the httpsGetEnabled or httpGetEnabled to false.


Monday, June 02, 2008

After creating simple WCF service I've got strange errors (see below).
 
Th issue was in the names of the response messages.
I used the simple custom rule to name request and response messages (.NET DataContract classes):
<OperationName>Request and <OperationName>Response
For instance I created GetTokenResponse class for the response message of the GetToken operation.
 
And this is the wrong rule!
Why? Because the WCF creates these names for the WSDL metadata files:
 
For instance I've got:
...
<wsdl:message name="ITokenStore_GetToken_OutputMessage">
  <wsdl:part name="parameters" element="tns:GetTokenResponse" /> ...
 
....<wsdl:operation name="GetToken">
  <wsdl:input wsaw:Action=http://MyServices/TokenStore/2008-05-29/ITokenStore/GetToken message="tns:ITokenStore_GetToken_InputMessage" />
  <wsdl:output wsaw:Action=http://MyServices/TokenStore/2008-05-29/ITokenStore/GetTokenResponse message="tns:ITokenStore_GetToken_OutputMessage" />
 
 
When I changed the name to the GetToken_Response the errors disappeared.
It is not an error in the WCF it is just undocumented feature.
The problem is the error text gives us unhelpful and ambiguous information.
 
See the article in MSDN: http://msdn.microsoft.com/en-us/library/ms731045.aspx
Not a clue about these rules.
Conclusion:
Don't use the name convention for the request and response messages (.NET classes) like <OperationName>Request and <OperationName>Response !
 

Error in SoapUI
, when we've tried to get the metadata:
... ERROR:javax.wsdl.WSDLException: WSDLException (at /HTML): faultCode=INVALID_WSDL: Expected element '{http://schemas.xmlsoap.org/wsdl/}definitions'.
 

Error in IE: by address the <ServiceAddressURL>

The service encountered an error.

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
 contract: http://MyServices/TokenStore/2008-05-29:ITokenStore ----> System.Xml.Schema.XmlSchemaException: The global element 'http://MyServices/TokenStore/2008-05-29:GetTokenResponse' has already been declared.
   at System.Xml.Schema.XmlSchemaSet.InternalValidationCallback(Object sender, ValidationEventArgs e)
   at System.Xml.Schema.BaseProcessor.AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item)
   at System.Xml.Schema.Preprocessor.Preprocess(XmlSchema schema, String targetNamespace, ArrayList imports)
   at System.Xml.Schema.Preprocessor.Execute(XmlSchema schema, String targetNamespace, Boolean loadExternals)
   at System.Xml.Schema.XmlSchemaSet.PreprocessSchema(XmlSchema& schema, String targetNamespace)
   at System.Xml.Schema.XmlSchemaSet.Reprocess(XmlSchema schema)
   at System.ServiceModel.Description.MessageContractExporter.Compile()
   at System.ServiceModel.Description.DataContractSerializerMessageContractExporter.Compile()
   at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   --- End of inner ExceptionDetail stack trace ---
   at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
   at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
   at SyncInvokeGet(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

Error in IE: by address the <ServiceAddressURL>?wsdl

The service encountered an error.

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
 contract: http://MyServices/TokenStore/2008-05-29:ITokenStore ----> System.Xml.Schema.XmlSchemaException: The global element 'http://MyServices/TokenStore/2008-05-29:GetTokenResponse' has already been declared.
   at System.Xml.Schema.XmlSchemaSet.InternalValidationCallback(Object sender, ValidationEventArgs e)
   at System.Xml.Schema.BaseProcessor.AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item)
   at System.Xml.Schema.Preprocessor.Preprocess(XmlSchema schema, String targetNamespace, ArrayList imports)
   at System.Xml.Schema.Preprocessor.Execute(XmlSchema schema, String targetNamespace, Boolean loadExternals)
   at System.Xml.Schema.XmlSchemaSet.PreprocessSchema(XmlSchema& schema, String targetNamespace)
   at System.Xml.Schema.XmlSchemaSet.Reprocess(XmlSchema schema)
   at System.ServiceModel.Description.MessageContractExporter.Compile()
   at System.ServiceModel.Description.DataContractSerializerMessageContractExporter.Compile()
   at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   --- End of inner ExceptionDetail stack trace ---
   at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
   at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleMetadataRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
   at SyncInvokeGet(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)


Tuesday, May 13, 2008

WCF: Technique of debugging inconsistency between Wsdl and Response messages.

 

I was working with several web-services as a client and had several issues the same kind. WSDL of this services does not conform the Response messages (See below. I’ve bolded the text related to the issue.). I fixed this issue by changing proxy code. It is not a big issue but now we have to manually change proxy every time we have updated the proxy of this service.

 

Here the checklist how debugging this case:

[The proxy for the web-service could be created with any method in Visual Studio 2008 as “Add Service Reference”.]

1.       We have found that the client code cannot get all data from the service. Some data are lost.

2.       Using SoapUI make sure the Response returns all data. This is the sign of this inconsistency!

3.       Using debugger we have found that the data are lost exactly in
      response = client.Method(request)
line in the client code.

What does it mean? The data are successfully returned in the Response message. But the client proxy code could not process them. When the proxy code is deserializing the response message some data are lost. SoapUI does not process returned data, it just shows them as raw text. The proxy code is trying to deserialize this text, converting text to objects in memory. [The deserializer is the code in the Microsoft libraries in the System.Runtime.Serialization namespace. There are two of them in WCF: XmlSerializer and DataContractSerializer.] Some of returned data magically disappeared in the Deserializing process. Description of these cases is in article “WCF: values disappeared in response: derived classes and serialization/deserialization order error” [http://geekswithblogs.net/LeonidGaneline/archive/2008/05/01/wcf-values-disappeared-in-response-derived-classes-and-serializationdeseriazlization-order.aspx]

4.       Go to the proxy source code (maybe in Refeference.cs file) and fix code (see below). This make proxy inconsistent with Wsdl file and next time when you update this Web or Service reference you have to fix proxy code again. But the client deserializes the Response messages properly now!

5.       Document this fix! And do not make it in proxy code. J

You lucky if you have got inconsistency in Response messages. The worst situation if inconsistency is in Request messages. There are only two options: the service does not care about these inconsistencies and you are lucky again, or service reject your request with fault message. Moreover I make sure this message does not give you a clue what is going on.  Try to get the “correct” request from any source and follow the same debugging technique with it.

 

 


[WSDL ]

      <xsd:complexType name="ArrayOf_xsd_string">

        <xsd:sequence>

          <xsd:element minOccurs="0" maxOccurs="unbounded" name="item" type="xsd:string" />

        </xsd:sequence>

      </xsd:complexType>

      <xsd:complexType name="PromoDetails">

        <xsd:sequence>

          <xsd:element name="assetTypes" nillable="true" type="impl:ArrayOf_xsd_string" />

        </xsd:sequence>


[Response message]

               <assetTypes>

                  <assetTypes>Album</ assetTypes >

               </assetTypes>


[Response message How it should be with regard to WSDL]

               <assetTypes>

                  <item>Album</ item >

               </assetTypes>


[Auto generated Proxy code]

        private string[] assetTypesField;

 

        [System.Xml.Serialization.XmlArrayAttribute(IsNullable=true, Order=1)]

        [System.Xml.Serialization.XmlArrayItemAttribute("item", IsNullable = false)]

        public string[] assetTypes {

            get {

                return this.assetTypesField;

            }

            set {

                this.assetTypesField = value;

                this.RaisePropertyChanged("assetTypes");

            }

        }


[Fixed Proxy code]

        private string[] assetTypesField;

 

        [System.Xml.Serialization.XmlArrayAttribute(IsNullable=true, Order=1)]

        [System.Xml.Serialization.XmlArrayItemAttribute("assetTypes ", IsNullable = false)]

        public string[] assetTypes {

            get {

                return this.assetTypesField;

            }

            set {

                this.assetTypesField = value;

                this.RaisePropertyChanged("assetTypes");

            }

        }

 


Wednesday, May 07, 2008

The requirements look easy:
We need to monitor the health of the WCF services, availability of the WCF services. Are they up or down?
But we don't want to call operations of the service  because it sometime could change the service internal status and these changes are out of our control.
Some services have special Heartbeat() operation to make the health monitoring easily, but the most have not.
We don't have to check the work status of the web-method. That means we don't care if some underlying services, like SQL databases, don't work and the services available but response with errors. We just want to know are web-services up or down, could they response at all or not. It should be something really easy.
 
Let's start:
I thought this is quite routine task to the service consumers and there should be several routine decisions.
As I know the OpsMngr2007 use something  simple to measure the web-service health.
 
I've asked gurus on the MSDN forums about this.
 
Dan Rigsby proposed:
"A one way Ping() method on the server works well.  If there is an exception, then the channel is broken.  You can have a timer run Ping against the server at some interval.
If this is a duplex callback system you need to be careful.  The server might also need to check if the client is still alive.  You cant have both the servicecontract and callbackcontract have the same named methods, so you will have to rename one of them."
 
Thanks, Dan!
 
I've tried to
      >ping http://text.company.com/adfadfad/asdfadf/adfadfadf.asmx
and
     >ping http://text.company.com/adfadfad/asdfadf/adfadfadf.asmx?wsdl
 
The ping works only for the host name, like
      >ping text.company.com
not for web-service URL
 
It is not what I want.
 
It checks the health of the host, not the web-service.
It does not cover cases with several services on the one host.
It does not cover cases when the host is OK but the service is not response.
 

Islam Eldemery proposed:
"try to subscribe to the events of the communication object (in the client side), so if a service stopped or disconnected you may handle the fault event.. (remember that it can only fault once).

      proxy.InnerChannel.Faulted +=
new EventHandler(InnerChannel_Faulted);

or
      proxy.InnerDuplexChannel.Faulted += new EventHandler(InnerDuplexChannel_Faulted);

see my example of handling a service in a chat application
http://www.codeproject.com/KB/IP/WCFWPFChatRoot.aspx
if this is a duplex communication, to handle the service on the service side, try to check every time on each callback object you have, to see if someone has been aborted or not before you using it (may be a client disconnect for a network failure.. etc.)"

Islam, thanks for response!

 Unfortunately with this technique we can intercept only errors after we unsuccessfully call the service operation, right?
It is not our case. We want to check the availability not "post mortem" but proactively. For instance, click a button and get health of all services. And we cannot call the service operations, it's one of requirements.
 
Martin16 proposed:
"...
Additional ideas (for IIS/HTTP WCF Services) are 
1) a custom availability operation in your service which checks all resources and gives back a result your web application monitor can parse.
2) enable WCF performance counter and create a monitor on top of that.
3) buy Avicode MP (should provide native WCF Service support)"
 
Thanks for help, Martin16!
 
Yeah, 1) is the Heartbeat() operation. It doesn't work in my case where the services are out of mu control.
For 2) First, we want actively to request the health status not to listen how the service responses to the requests of the other clients.
Second, the WCF performance counters... OK I use them with OpsMng2007 I don't like them very-very much. (It's another story).
3) The third-part utils should use the same APIs we use, not something secret.  I also use OpsMngr2007. But I want to use simple and absolutely open (to me) source code.
 
...
So far so good.
Is it possible to use Mex endpoint or something like HttpRequest to <URL>?wsdl to make sure the service is up?
 
I've got one method from the book "Programming WCF Services" by Juval Lowy (page 71). 
Code Snippet:

   MetadataExchangeClient mexClient =

bool isServiceUp = true;
try
{
  
string address = "http://localhost/MyService.svc?wsdl";new MetadataExchangeClient(new Uri(address), MetadataExchangeClientMode.HttpGet);
   MetadataSet metadata = mexClient.GetMetadata();
// if service down I get the exception
}
   catch (Exception ex)
{
    isServiceUp =
false;
}
 
I catch the Exception like {"Metadata contains a reference that cannot be resolved: "http://localhost/MyService.svc?wsdl"} System.Exception {System.InvalidOperationException}
 
Easy and don't heavy load the service.
P.S.    Please, make sure you've read good comment by Islam Eldemery below.
========================================================================================

Thursday, May 01, 2008

WCF: values disappeared in response: derived classes and serialization/deserialization order error
 
This is a second article about errors with getting data from  the web-services.
"WCF: Deserialization error, the response elements disappeared" ( http://geekswithblogs.net/LeonidGaneline/archive/2008/04/01/wcf-deserialization-error-the-response-elements-disappeared.aspx )
First time the whole elements disappeared from the response messages without any errors. Now only values of the elements disappeared.
 
We got a very strange error.
 
Our client code to one of the third-part web-service could not get the values from the response message.
 
Investigation given us such picture:
The response class has a base class. And the disappeared values are exactly from properties of this class. See the client proxy code that was generated by Visual Studio (Pict.1). Nothing wrong with it.
If we look at the wsdl that was the source for this proxy code (Pict.2) there is nothing wrong too.
The most strange thing is we have the right values in the response message (Pict.3). The errorCode and errorMessage elements have values but then we lost them. We can get them in the code (Pict.4). The output is on Pict.5.
How? Why?
The base class properties are the errorCode and errorMessage, the derived class property is the crn.
The question is in what order those two kind of properties serialize to the elements of the Xml message and then deserialize back to the class properties?
If service and client make serialization and deserialization in the "stack-like" order then everything is OK.
We see that service serialize the derived class properties first and the base class properties last (See Pict.3.1). What about our client? The client is waiting the message with different order of elements (see Pict.3.2)
And this is the source of the problem!
 

In the "Data Member Order " article in the MSDN Library ( http://msdn.microsoft.com/en-us/library/ms729813.aspx ) we see:
 
"...The basic rules for data ordering include:
If a data contract type is a part of an inheritance hierarchy, data members of its base types are always first in the order..."
 
And there is no way to change this behaviour.
 
That's exactly how my client proxy is working. It is waiting the base class properties on the first place and have not get them, and because these properties have minOccurs="0" and nillable="true" attributes the proxy just decided that Xml message does not have properties at all and silently goes on to the first derived class property.
Unfortunately the third-part service uses the opposite order (it uses a java Axis2 service), data members of its base types are always last in the order in the serialized Xml messages.
BTW Here (http://www.onjava.com/pub/a/onjava/excerpt/JavaRMI_10/index.html?page=4) is mentioned that Java uses the same algorithm as WCF. Why does this consuming service use the opposite order? I have no idea.
Jeff W. Barnes in (http://jeffbarnes.net/portal/blogs/jeff_barnes/archive/2007/05/08/wcf-serialization-order-in-data-contracts.aspx) mentioned thet there is the solution but does not give it.
 
Is it possible to change the proxy code on my side to follow the service order? I don't know such options. Seems the WCF-classes where the whole deserialization occurs cannot be tuned up to change this order. Look one more time to the wsdl code (Pict.2). There is nothing about this order, ther is only the complexType the AddNewCreditCardResponse with the extension base="ax21:ResponseData".
Seems the only way to fix the problem is to change the auto generated code for the response message classes and force the right order. (Pict.6) OK from the point of view of WCF it is a wrong code, but what else we could do in this situation?
 
After these changes we've got the right result (see Pict.7).
 
 
 
=======================================================================
[Pict.1: autogenerated proxy code]
    [System.SerializableAttribute()]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://data.transaction.com/xsd")]
    public partial class AddNewCreditCardResponse : ResponseData {
       
        private string crnField;
        [System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=0)]
        public string crn {
            get {   return this.crnField; }
            set { this.crnField = value; }
        }
    }
 ...
    [System.Xml.Serialization.XmlIncludeAttribute(typeof(AddNewCreditCardResponse))]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://data.transaction.com/xsd")]
    public partial class ResponseData {
       
       private string errorCodeField;
       [System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=0)]
        public string errorCode{
            get { retu