17 April, 2015

How to generate a WCF service from the WSDL file?

Why we need to generate WCF service using WSDL?

Usually we create our own webservices, but sometimes we need to create a mock of the webservice from which WSDL we have obtained. This situation may happen if we have to create a client of the third-party service to which the access is restricted. In that case it is easier to create our own service, than use the real one. It is especially useful when we shoot the data to the service and we do not really need the response except possible exceptions.

How to do it?

Firstly we need to have w WSDL file which will be a base for our mock. Then we need to generate the interface, which will be a contract in our new service. To do this, we need to use small application called wsdl.exe. It is a part of the Windows SDK and it can be found e.g. here: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools>wsdl.exe. To generate the interface in C#, you should use the following command:

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools>wsdl.exe "C:\WsdlToGenerateInterfaceFrom.wsdl" /l:CS /serverInterface

After execution of this command, the interface will be generated in a folder, where the wsdl.exe is placed. Sometimes there may be some warnings like:

Warning: This web reference does not conform to WS-I Basic Profile v1.1.
R2706: A wsdl:binding in a DESCRIPTION MUST use the value of "literal" for the use attribute in all soapbind:body, soapbind:fault, soapbind:header and soapbind: headerfault elements.

Hopefully, usually the warnings are not danger. Now you can create new VS WCF library (service) project and implement the interface (your contract).

After implementing of the interface it is good to run the web service and look into the WSDL file generated by it. Unfortunately sometimes, some of the types may be missing. It happens due to the fact, that there are some attributes added automatically to the generated classes. We need to be aware that some of them may be removed or sometimes, we need to add some attributes (like DataContract or OperationContract)

Finally we can use our webservice as a mock for other applications. This is very useful for quick tests of some behaviors.

0 comments:

Post a Comment