Where to set username and password in a Web Service client? - authentication

I was provided this WSDL, and I have to develop a client for it (I've been making questions here about it lol).
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="urn:ManterFornecedor" xmlns:s0="urn:ManterFornecedor" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<wsdl:types>
<xsd:schema elementFormDefault="qualified" targetNamespace="urn:ManterFornecedor">
<xsd:element name="Novo" type="s0:InputMapping1"/>
<xsd:complexType name="InputMapping1">
<xsd:sequence>
<xsd:element name="NO_FORNECEDOR" type="xsd:string"/>
<xsd:element name="DE_CONTRATO" type="xsd:string"/>
<xsd:element name="DH_INICIO" nillable="true" type="xsd:dateTime"/>
<xsd:element name="DH_FIM" nillable="true" type="xsd:dateTime"/>
<xsd:element name="NO_PRODUTO" type="xsd:string"/>
<xsd:element name="IC_STATUS" type="s0:IC_STATUSType" nillable="true"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="IC_STATUSType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Ativo"/>
<xsd:enumeration value="Inativo"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:element name="NovoResponse" type="s0:OutputMapping1"/>
<xsd:complexType name="OutputMapping1">
<xsd:sequence>
<xsd:element name="Id" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="AuthenticationInfo" type="s0:AuthenticationInfo"/>
<xsd:complexType name="AuthenticationInfo">
<xsd:sequence>
<xsd:element name="userName" type="xsd:string"/>
<xsd:element name="password" type="xsd:string"/>
<xsd:element minOccurs="0" name="authentication" type="xsd:string"/>
<xsd:element minOccurs="0" name="locale" type="xsd:string"/>
<xsd:element minOccurs="0" name="timeZone" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
</wsdl:types>
<wsdl:message name="NovoSoapOut">
<wsdl:part element="s0:NovoResponse" name="parameters"></wsdl:part>
</wsdl:message>
<wsdl:message name="ARAuthenticate">
<wsdl:part element="s0:AuthenticationInfo" name="parameters"></wsdl:part>
</wsdl:message>
<wsdl:message name="NovoSoapIn">
<wsdl:part element="s0:Novo" name="parameters"></wsdl:part>
</wsdl:message>
<wsdl:portType name="PortPortType">
<wsdl:operation name="Novo">
<wsdl:input message="s0:NovoSoapIn"></wsdl:input>
<wsdl:output message="s0:NovoSoapOut"></wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="PortSoapBinding" type="s0:PortPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="Novo">
<soap:operation soapAction="urn:ManterFornecedor/Novo" style="document"/>
<wsdl:input>
<soap:header message="s0:ARAuthenticate" part="parameters" use="literal"></soap:header>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="ManterFornecedorService">
<wsdl:documentation>Fornecedor</wsdl:documentation>
<wsdl:port binding="s0:PortSoapBinding" name="PortSoap">
<soap:address location="http://somewhere&webService=ManterFornecedor"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
I provided the full WSDL, but the important part for the question is
<soap:operation soapAction="urn:ManterFornecedor/Novo" style="document"/>
<wsdl:input>
<soap:header message="s0:ARAuthenticate" part="parameters" use="literal"></soap:header>
<soap:body use="literal"/>
</wsdl:input>
As you can see, input has a ARAuthenticate message in its header, which is
<wsdl:message name="ARAuthenticate">
<wsdl:part element="s0:AuthenticationInfo" name="parameters"></wsdl:part>
</wsdl:message>
<xsd:element name="AuthenticationInfo" type="s0:AuthenticationInfo"/>
<xsd:complexType name="AuthenticationInfo">
<xsd:sequence>
<xsd:element name="userName" type="xsd:string"/>
<xsd:element name="password" type="xsd:string"/>
<xsd:element minOccurs="0" name="authentication" type="xsd:string"/>
<xsd:element minOccurs="0" name="locale" type="xsd:string"/>
<xsd:element minOccurs="0" name="timeZone" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
I used Eclipse's Web Services Explorer to create a WS client to test this webservice, and it worked! This client has username and password fields to be set.
Ok, now I need to take this client exemple code, and implement a standalone (not web UI) solution that gathers info and uses the client to send it to the server. But it's failing, and I believe it's because authentication.
Only place I see username and password being set is in PortSoapBindingStub.createCall():
org.apache.axis.client.Call _call = super._createCall();
if (super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}
if (super.cachedUsername != null) {
_call.setUsername(super.cachedUsername);
}
if (super.cachedPassword != null) {
_call.setPassword(super.cachedPassword);
}
if (super.cachedEndpoint != null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}
if (super.cachedTimeout != null) {
_call.setTimeout(super.cachedTimeout);
}
if (super.cachedPortName != null) {
_call.setPortName(super.cachedPortName);
}
But, where are these cached stuff coming from? I tried to edit this code and manually set them, but keep receiving error:
Exception in thread "main" AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.lang.ArrayIndexOutOfBoundsException: -1
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}hostname:myhost
java.lang.ArrayIndexOutOfBoundsException: -1
at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:796)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at ManterFornecedor.PortSoapBindingStub.novo(PortSoapBindingStub.java:174)
at ManterFornecedor.PortPortTypeProxy.novo(PortPortTypeProxy.java:50)
at caixa.pedes.br.ManterFornecedor.main(ManterFornecedor.java:43)
Here's my code:
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import ManterFornecedor.*;
public class ManterFornecedor {
public static void main(String[] args) throws RemoteException, ServiceException, MalformedURLException {
InputMapping1 parameters = new InputMapping1(
"fornecedor","contrato",java.util.Calendar.getInstance(), java.util.Calendar.getInstance(),
"produto",IC_STATUSType.Ativo
);
java.net.URL endpoint = new java.net.URL("http://somewhere&webService=ManterFornecedor");
PortPortTypeProxy proxy = new PortPortTypeProxy();
ManterFornecedorServiceLocator locator = new ManterFornecedorServiceLocator();
ManterFornecedor.PortPortType port = locator.getPortSoap();
PortSoapBindingStub client = new PortSoapBindingStub(endpoint,locator);
ManterFornecedor.OutputMapping1 response = proxy.novo(parameters);
System.out.println(response);
}
}
Edit: as you can see, I'm new to Web Service and I'm kinda lost. I don't know exactally why, but the novo() method is available in Proxy, Locator and Stub. I'll read more about these design patterns because I'm new to them too, and using all 3 together is even more troublesome.
What's the best object to use to call WSDL generated operators? Unfortuntely, client code created in Eclipse uses JSP to receive parameters, and I'm not being able to properly isolate exemple code to real client so that I can develop my code and call client's operator.
It would be much easier if client was encapsulated in a unique class where I just had to provide its configs (endpoint, authentication, etc) and then call the operator.

You must put this code before to setRequestHeaders(_call); in the PortTypeSoapBindingStub class
try {
SOAPHeaderElement sopElement = new SOAPHeaderElement("urn:AuthenticationInfo","AuthenticationInfo") ;
sopElement.addChildElement("userName").addTextNode("XXXXX") ;
sopElement.addChildElement("password").addTextNode("XXXX");
sopElement.addChildElement("authentication").addTextNode("");
sopElement.addChildElement("locale").addTextNode("");
sopElement.addChildElement("timeZone").addTextNode("");
_call.addHeader(sopElement);
} catch (Exception e) {
e.printStackTrace();
}

I also struggled to achieve the same, later I found the NTLM Authentication wasn't enabled in the mac machine used at server
The following code worked for me
public static void testNavisionMicrosoft() {
static String baseURL = "file:C://locapath//customer.wsdl";
URL url = null;
try {
url = new URL(baseURL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url2 = null;
try {
url2 = new URL("http://localhost:8080/customer?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
final String username = "user";
final String password = "paswd";
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password
.toCharArray());
}
});
QName qname = new QName("search for soapActionin your wsdl file",
"search for service name in wsdl file");
Service service = Service.create(url, qname);
CRMCustomerPort proxy = service.getPort(CRMCustomerPort.class);
Map<String, Object> requestContext = ((BindingProvider) proxy)
.getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, username);
requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Timeout", Collections.singletonList("10000"));
requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
CRMCustomer data = proxy.read("AIL0003190");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(
"Error occurred in operations web service client initialization",
e);
}
}

Related

.NET Core - cannot find a simple soap request code

I need to send an xml like this
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="**************">
<soap:Header/>
<soap:Body>
<web:Open>
<web:username>USERNAME</web:username>
<web:password>PASSWORD</web:password>
</web:Open>
</soap:Body>
</soap:Envelope>
from this tutorial https://stackify.com/soap-net-core/
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(new Uri("http://server/PingService.svc"));
var channelFactory = new ChannelFactory(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var result = serviceClient.Ping("Ping");
channelFactory.Close();
but how do I modify this code to do my own request ?
I parsed microsoft documentation about WCF and svcutils and it appears infuriatingly complicated
I mean, all that, just to send an XML ?
how to I do a SOAP request in the simplest manner possible ?
thanks for helping me on this
The simplest way is to import the wsdl from the server side into your project. this will generate most of the required code. An example has been provided in the other question that you asked related to this.
It is also possible to do it completely manually. First you need create one or 2 xml schema's that describe your header and payload (the header is optional).
Open.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:web="http://bvdep.com/webservices/" targetNamespace="http://bvdep.com/webservices/" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:complexType name="OpenType">
<xs:sequence>
<xs:element name="username" type="xs:string"/>
<xs:element name="password" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="Open" type="web:OpenType"/>
</xs:schema>
header.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:head="http://bvdep.com/webservices/Header" targetNamespace="http://bvdep.com/webservices/Header" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="Header" type="head:HeaderType"/>
<xs:complexType name="HeaderType">
<xs:sequence>
<xs:element name="From" type="xs:string"/>
<xs:element name="To" type="xs:string"/>
<xs:element name="MsgType" type="xs:string"/>
<xs:element name="Datetime" type="xs:dateTime"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
then you use xsd.exe to generate class files. I use a bat file to do so.
#echo off
set exepad=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\xsd.exe
set sourcepad=..\..\
set xsdpad=%sourcepad%\ConsoleCore\xsd
set Outpad=%sourcepad%\ConsoleCore\generated
Set NameSpace=ConsoleCore.generated
"%exepad%" "%xsdpad%\Open.xsd" /c /n:%NameSpace% /o:%Outpad%
"%exepad%" "%xsdpad%\Header.xsd" /c /n:%NameSpace% /o:%Outpad%
In your vs core project you need to add 2 nuget packages
System.ServiceModel.Primitives and System.ServiceModel.Http
next you need to add an interface that describes the service an operation(s) that you want to invoke just as you found in the ping example
[ServiceContract(Namespace = "http://Open.webservice.namespace")]
public interface IOpenService
{
[XmlSerializerFormat()]
[OperationContract(IsOneWay = false, Action = "urn:#OpenOperation")]
OpenReturnMsg OpenOperation(OpenMsg msg);
}
[MessageContract(IsWrapped = false)]
public class OpenMsg
{
[MessageHeader(Name = "Header", Namespace = "http://bvdep.com/webservices/Header")] public HeaderType Header { get; set; }
[MessageBodyMember(Name = "Open", Namespace = "http://bvdep.com/webservices/")] public OpenType Open { get; set; }
}
[MessageContract(IsWrapped = false)]
public class OpenReturnMsg
{
[MessageBodyMember(Name = "ResponseMsg", Namespace = "http://Open.webservice.namespace")] public string ResponseMsg { get; set; }
}
And last the actual statements to invoke the service and get a response:
static void Main(string[] args)
{
Console.WriteLine("Start Program!");
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(new Uri("http://LOCALHOST:8085/mockOpenBinding"));
var channelFactory = new ChannelFactory<IOpenService>(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var msg = new OpenMsg
{
Header = new HeaderType
{
From = "source",
To = "dest",
MsgType = "open",
Datetime = DateTime.Now
},
Open = new OpenType
{
username = "user",
password = "pw"
}
};
var result = serviceClient.OpenOperation(msg);
channelFactory.Close();
Console.WriteLine(result.ResponseMsg);
}
i've tested this using a mock service from the below WSDL in SOAPUI.
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://Open.webservice.namespace" xmlns:web="http://bvdep.com/webservices/" xmlns:head="http://bvdep.com/webservices/Header" targetNamespace="http://Open.webservice.namespace">
<wsdl:types>
<xs:schema targetNamespace="http://Open.webservice.namespace" elementFormDefault="qualified">
<xs:import namespace="http://bvdep.com/webservices/Header" schemaLocation="Header.xsd"/>
<xs:import namespace="http://bvdep.com/webservices/" schemaLocation="Open.xsd"/>
<xs:element name="ResponseMsg" type="xs:string"/>
</xs:schema>
</wsdl:types>
<wsdl:message name="OpenMessageHeader">
<wsdl:part name="MsgHeader" element="head:Header"/>
</wsdl:message>
<wsdl:message name="OpenMessageRequest">
<wsdl:part name="Open" element="web:Open"/>
</wsdl:message>
<wsdl:message name="OpenMessageResponse">
<wsdl:part name="Response" element="tns:ResponseMsg"/>
</wsdl:message>
<wsdl:portType name="OpenPortType">
<wsdl:operation name="OpenOperation">
<wsdl:input message="tns:OpenMessageRequest"/>
<wsdl:output message="tns:OpenMessageResponse"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="OpenBinding" type="tns:OpenPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="OpenOperation">
<soap:operation soapAction="urn:#OpenOperation"/>
<wsdl:input>
<soap:body use="literal"/>
<soap:header message="tns:OpenMessageHeader" part="MsgHeader" use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="OpenService">
<wsdl:port name="OpenPort" binding="tns:OpenBinding">
<soap:address location="No Target Adress"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

Server was unable to process request. ---> Object reference not set to an instance of an object using Worklight 6.1.0?

I have WSDL stored on my local machine provided by Client, since its Sensitive data to publish in public i am posting modified version of it below.
<wsdl:definitions xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://www.Client.in/StoreLocator" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://www.Client.in/StoreLocator">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://www.Client.in/StoreLocator">
<s:element name="GetClientStore">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="fromLongitude" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="fromLatitude" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="GetClientStoreResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="GetClientStoreResult" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="AuthsoapHead" type="tns:AuthsoapHead"/>
<s:complexType name="AuthsoapHead">
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="FirstKey" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="SecondKey" type="s:string"/>
</s:sequence>
<s:anyAttribute/>
</s:complexType>
</s:schema>
</wsdl:types>
<wsdl:message name="GetClientStoreSoapIn">
<wsdl:part name="parameters" element="tns:GetClientStore"/>
</wsdl:message>
<wsdl:message name="GetClientStoreSoapOut">
<wsdl:part name="parameters" element="tns:GetClientStoreResponse"/>
</wsdl:message>
<wsdl:message name="GetClientStoreAuthsoapHead">
<wsdl:part name="AuthsoapHead" element="tns:AuthsoapHead"/>
</wsdl:message>
<wsdl:portType name="NearestStoreSoap">
<wsdl:operation name="GetClientStore">
<wsdl:input message="tns:GetClientStoreSoapIn"/>
<wsdl:output message="tns:GetClientStoreSoapOut"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="NearestStoreSoap" type="tns:NearestStoreSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="GetClientStore">
<soap:operation soapAction="http://www.Client.in/StoreLocator/GetClientStore" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
<soap:header message="tns:GetClientStoreAuthsoapHead" part="AuthsoapHead" use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:binding name="NearestStoreSoap12" type="tns:NearestStoreSoap">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="GetClientStore">
<soap12:operation soapAction="http://www.Client.in/StoreLocator/GetClientStore" style="document"/>
<wsdl:input>
<soap12:body use="literal"/>
<soap12:header message="tns:GetClientStoreAuthsoapHead" part="AuthsoapHead" use="literal"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="NearestStore">
<wsdl:port name="NearestStoreSoap" binding="tns:NearestStoreSoap">
<soap:address location="https://www.Client.in/StoreLocator/neareststore.asmx"/>
</wsdl:port>
<wsdl:port name="NearestStoreSoap12" binding="tns:NearestStoreSoap12">
<soap12:address location="https://www.Client.in/StoreLocator/neareststore.asmx"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
I am using Worklight Back-end Service to get results from this SOAP.
Find below the Store Locator Service URL to fetch the nearest stores based on latitude(fromLatitude) and longitude(fromLongitude) i.e. https://www.Client.in/StoreLocator/neareststore.asmx and Also look the test keys for Client Store Locator Service URL(Pass values in Request header) i.e. FirstKey:FTG8F535DFGDFGER8GFDGG4FG8DGS, SecondKey:password.
---------------------------------SoapAdapter1-impl.js--------------------------------------
function NearestStore_GetClientStore(params, headers){
var soapEnvNS;
soapEnvNS = 'http://www.w3.org/2003/05/soap-envelope';
var request = buildBody(params, 'xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:tns="http://www.Client.in/StoreLocator" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" ', soapEnvNS);
return invokeWebService(request, headers);
}
function invokeWebService(body, headers){
var input = {
method : 'post',
returnedContentType : 'xml',
path : '/StoreLocator/neareststore.asmx',
body: {
content : body.toString(),
contentType : 'text/xml; charset=utf-8'
}
};
//Adding custom HTTP headers if they were provided as parameter to the procedure call
headers && (input['headers'] = headers);
return WL.Server.invokeHttp(input);
}
Now, i am directly Invoking Procedure from eclipse with below detail:
{
"GetClientStore": {
"fromLatitude": "18.9750",
"fromLongitude": "72.8258"
}
},{"soapAction": "http://www.Client.in/StoreLocator/GetClientStore","FirstKey":"FTG8F535DFGDFGER8GFDGG4FG8DGS","SecondKey":"password"}
And i am getting error now as below:
{
"Envelope": {
"Body": {
"Fault": {
"Code": {
"Value": "soap:Receiver"
},
"Detail": "",
"Reason": {
"Text": {
"CDATA": "Server was unable to process request. ---> Object reference not set to an instance of an object.",
"lang": "en"
}
}
}
},
"soap": "http:\/\/www.w3.org\/2003\/05\/soap-envelope",
"xsd": "http:\/\/www.w3.org\/2001\/XMLSchema",
"xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance"
},
"errors": [
],
"info": [
],
"isSuccessful": true,
"responseHeaders": {
"Cache-Control": "private",
"Connection": "Keep-Alive",
"Content-Length": "508",
"Content-Type": "application\/soap+xml; charset=utf-8",
"Date": "Wed, 09 Jul 2014 11:57:13 GMT",
"X-Frame-Options": "SAMEORIGIN",
"X-MS-InvokeApp": "1; RequireReadOnly"
},
"responseTime": 158,
"statusCode": 500,
"statusReason": "Internal Server Error",
"totalTime": 159,
"warnings": [
]
}
Finally, i got Answer to my own Question. I had to develop a simple HTTP Adapter as below
function getLocation(latVar, longVar) {
var request =
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:stor="http://www.client.in/StoreLocator">
<soap:Header>
<stor:AuthsoapHead>
<stor:FirstKey>FTG8F535DFGDFGER8GFDGG4FG8DGS</stor:FirstKey>
<stor:SecondKey>password</stor:SecondKey>
</stor:AuthsoapHead>
</soap:Header>
<soap:Body>
<stor:GetclientStore>
<stor:fromLongitude>{longVar}</stor:fromLongitude>
<stor:fromLatitude>{latVar}</stor:fromLatitude>
</stor:GetclientStore>
</soap:Body>
</soap:Envelope>;
var input = {
method : 'post',
returnedContentType : 'xml',
path : '/StoreLocator/neareststore.asmx',
body: {
content: request.toString(),
contentType: 'text/xml; charset=utf-8'
},
};
var result = WL.Server.invokeHttp(input);
var filteredData = result.Envelope.Body.GetclientStoreResponse;
return filteredData;
}
Javascript will show red error mark for request but ignore and deploy and invoked it and i can see data coming as below:
{
"GetclientStoreResult":
"<Response>
<StatusCode>200<\/StatusCode>
<StoresCount>3<\/StoresCount>
<Stores>
<StoreDetails>
<StoreName>client Store<\/StoreName>
<AddressLine1>Fatehabad Road<\/AddressLine1>
<AddressLine2>Khasra No.-76, Mauja Rajpur, Near Amar Hotel, Fatehabad Road, Agra<\/AddressLine2>
<City>Agra<\/City>
<State>Uttar Pradesh<\/State>
<countryCode>IN<\/countryCode>
<Postalcode>282001<\/Postalcode>
<MainPhone>09x 1x 0x71x0<\/MainPhone>
<MobilePhone>09x 1x9 x97x9x<\/MobilePhone>
<MobilePhone2><\/MobilePhone2>
<HomePage>http:\/\/www.client.in<\/HomePage>
<EMail>clientcare.upw#client.com<\/EMail>
<Timings>1:10:30:19:30,2:10:30:19:30,3:10:30:19:30,4:10:30:19:30,5:10:30:19:30,6:10:30:19:30,7:10:30:19:30<\/Timings>
<PaymentType><\/PaymentType>
<Category>Mobile Service Provider Company<\/Category>
<Description>Service & Sales Store for client<\/Description>
<Latitude>27.164696<\/Latitude>
<Longitude>78.038031<\/Longitude>
<Distance>1.21778962564819<\/Distance>
<\/StoreDetails>
<StoreDetails>
<StoreName>client Store<\/StoreName>
<AddressLine1>VS Pratap Pura<\/AddressLine1>
<AddressLine2>client Store G1 & G2 Ground floor Hotel Usha Kiran Complex Pratap Pura MG Road Agra<\/AddressLine2>
<City>Agra<\/City>
<State>Uttar Pradesh<\/State>
<countryCode>IN<\/countryCode>
<Postalcode>282001<\/Postalcode>
<MainPhone>09x 19 x971x0<\/MainPhone>
<MobilePhone>0x7 19 x7190<\/MobilePhone>
<MobilePhone2><\/MobilePhone2>
<HomePage>http:\/\/www.client.in<\/HomePage>
<EMail>clientcare.upw#client.com<\/EMail>
<Timings>1:10:30:19:30,2:10:30:19:30,3:10:30:19:30,4:10:30:19:30,5:10:30:19:30,6:10:30:19:30,7:10:30:19:30<\/Timings>
<PaymentType><\/PaymentType>
<Category>Mobile Service Provider Company<\/Category>
<Description>Service & Sales Store for client<\/Description>
<Latitude>27.15356<\/Latitude>
<Longitude>78.007565<\/Longitude>
<Distance>4.1715187443831<\/Distance>
<\/StoreDetails>
<StoreDetails>
<StoreName>client Store<\/StoreName>
<AddressLine1>Sanjay Place<\/AddressLine1>
<AddressLine2>Shop No. G-1, Block No. 38\/4B, Sanjay Place, Agra<\/AddressLine2>
<City>Agra<\/City>
<State>Uttar Pradesh<\/State>
<countryCode>IN<\/countryCode>
<Postalcode>282002<\/Postalcode>
<MainPhone>0x7 1x 097x90<\/MainPhone>
<MobilePhone>0x7 19 0xx190<\/MobilePhone>
<MobilePhone2><\/MobilePhone2>
<HomePage>http:\/\/www.client.in<\/HomePage>
<EMail>clientcare.upw#client.com<\/EMail>
<Timings>1:10:30:19:30,2:10:30:19:30,3:10:30:19:30,4:10:30:19:30,5:10:30:19:30,6:10:30:19:30,7:10:30:19:30<\/Timings>
<PaymentType><\/PaymentType>
<Category>Mobile Service Provider Company<\/Category>
<Description>Service & Sales Store for client<\/Description>
<Latitude>27.198541<\/Latitude>
<Longitude>78.006023<\/Longitude>
<Distance>4.4289447148507<\/Distance>
<\/StoreDetails>
<\/Stores>
<\/Response>",
"isSuccessful": true,
"xmlns": "http:\/\/www.client.in\/StoreLocator"
}

JAXB Eclipse Link Moxy: ClassCastException while Unmarshalling JSON using schema validation

I am using eclipse link(v2.5.1) Dynamic JAXB to convert XML to JSON and viceversa using a multiple schemas. While umarshalling the JSON to XML,I want to validate the JSON(against the XSD) and Dynamic Moxy is unable to validate the generated JSON and results in classcast exception.
emp.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:emp="Employee:2:0" targetNamespace="Employee:2:0"
elementFormDefault="unqualified" attributeFormDefault="unqualified"
version="2.0">
<xsd:element name="searchManager" type="emp:SearchManager" />
<xsd:complexType name="SearchManager">
<xsd:sequence>
<xsd:element name="CompanyName" type="xsd:string" />
<xsd:element name="objects" type="emp:Employee" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Employee">
<xsd:complexContent>
<xsd:extension base="emp:Organization">
<xsd:sequence>
<xsd:element name="EmpId" type="xsd:string" minOccurs="0" />
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="Projects">
<xsd:complexContent>
<xsd:extension base="emp:Organization"/>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="Organization">
<xsd:annotation>
<xsd:documentation>Abstract base class </xsd:documentation>
</xsd:annotation>
</xsd:complexType>
</xsd:schema>
Manager.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="Manager:1:0" xmlns:emp="Employee:2:0"
xmlns:manager="Manager:1:0" xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="unqualified" attributeFormDefault="unqualified"
version="1.0">
<!-- schema imports -->
<xs:import namespace="Employee:2:0" schemaLocation="emp.xsd" />
<xs:complexType name="Manager">
<xs:annotation>
<xs:documentation>
Definition of class Employee
</xs:documentation>
</xs:annotation>
<xs:complexContent>
<xs:extension base="emp:Employee">
<xs:sequence>
<xs:element name="teamSize" type="xsd:int" minOccurs="0" />
<xs:element name="project1" type="manager:Project1"
minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Project1">
<xs:complexContent>
<xs:extension base="manager:Developement">
<xs:sequence>
<xs:element name="type" type="xsd:int" minOccurs="0" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Developement">
<xs:annotation>
<xs:documentation>
Abstract base class for an Development
</xs:documentation>
</xs:annotation>
<xs:complexContent>
<xs:extension base="emp:Projects"/>
</xs:complexContent>
</xs:complexType>
</xs:schema>
sample.xml
<emp:searchManager xmlns:emp="Employee:2:0"
xmlns:manager="Manager:1:0">
<CompanyName>Test</CompanyName>
<objects xmlns:ns2="Manager:1:0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:Manager">
<EmpId>123456</EmpId>
<teamSize>10</teamSize>
<project1>
<type>1</type>
</project1>
</objects>
</emp:searchManager>
The driver program to test is as follows
public class XMLToJSON {
/**
* #param args
*/
public static void main(String[] args) {
FileInputStream xsdInputStream;
try {
xsdInputStream = new FileInputStream("Manager.xsd");
DynamicJAXBContext jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdInputStream, new MyEntityResolver(), null, null);
FileInputStream xmlInputStream = new FileInputStream("sample.xml");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<DynamicEntity> manager = (JAXBElement) unmarshaller.unmarshal(xmlInputStream);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//input xml to print
marshaller.marshal(manager, System.out);
Map namespaces = new HashMap();
namespaces.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
namespaces.put("Employee:2:0", "ns1");
namespaces.put("Manager:1:0", "ns2");
// XML to JSON
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER, namespaces);
FileOutputStream jsonOutputStream = new FileOutputStream("sample.json");
marshaller.marshal(manager, jsonOutputStream);
marshaller.marshal(manager, System.out);
//JSON to XML
JAXBUnmarshaller jsonUnmarshaller = jaxbContext.createUnmarshaller();
jsonUnmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
jsonUnmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespaces);
jsonUnmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, true);
jsonUnmarshaller.setProperty(UnmarshallerProperties.JSON_ATTRIBUTE_PREFIX, "#");
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("Manager.xsd"));
jsonUnmarshaller.setSchema(schema);
StreamSource json = new StreamSource("sample.json");
JAXBElement<DynamicEntity> myroot = (JAXBElement) jsonUnmarshaller.unmarshal(json);
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
m.marshal(myroot, System.out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Generated Sample JSON
{
"ns1.searchManager" : {
"CompanyName" : "Test",
"objects" : [ {
"xsi.type" : "ns2.Manager",
"EmpId" : "123456",
"teamSize" : 10,
"project1" : [ {
"type" : 1
} ]
} ]
}
}
While unmarshalling the below exception was seen
Exception in thread "main" java.lang.ClassCastException: org.eclipse.persistence.internal.oxm.record.XMLReaderAdapter$ExtendedContentHandlerAdapter cannot be cast to org.eclipse.persistence.internal.oxm.record.UnmarshalRecord
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.isTextValue(JSONReader.java:454)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:350)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:244)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:430)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:299)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parseRoot(JSONReader.java:166)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:125)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:140)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:778)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:666)
at org.eclipse.persistence.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:593)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:287)
at XMLToJSON.main(XMLToJSON.java:74)
EDIT:Corrected the generated sample json
Question
The intention is to check whether JSON conforms to the XML schema. Does Dynamic JAXB support JSON Validation while unmarshalling? Is this a bug in Dynamic JAXB Moxy?
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
You are hitting the following issue which was fixed in the 2.5.1 (and 2.6.0) streams.
http://bugs.eclipse.org/407498
The fix is available in EclipseLink 2.5.1 (and 2.6.0) in the nightly builds starting September 11, 2013 from the following link:
http://www.eclipse.org/eclipselink/downloads/nightly.php
Schema Validation and JSON Unmarshalling
Due to how we need to process the JSON document, validating the JSON input against an XML schema is not guaranteed to work. Below is the exception you will get for your use case once you get the ClassCastException fix.
javax.xml.bind.UnmarshalException
- with linked exception:
[Exception [EclipseLink-25004] (Eclipse Persistence Services - #VERSION#.#QUALIFIER#): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred unmarshalling the document
Internal Exception: org.xml.sax.SAXParseException; cvc-complex-type.2.4.d: Invalid content was found starting with element 'teamSize'. No child element is expected at this point.]
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:980)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:290)
at forum18824990.XMLToJSON.main(XMLToJSON.java:63)
Caused by: Exception [EclipseLink-25004] (Eclipse Persistence Services - #VERSION#.#QUALIFIER#): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred unmarshalling the document
Internal Exception: org.xml.sax.SAXParseException; cvc-complex-type.2.4.d: Invalid content was found starting with element 'teamSize'. No child element is expected at this point.
at org.eclipse.persistence.exceptions.XMLMarshalException.unmarshalException(XMLMarshalException.java:115)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:144)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:784)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:666)
at org.eclipse.persistence.internal.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:566)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:287)
... 1 more
Caused by: org.xml.sax.SAXParseException; cvc-complex-type.2.4.d: Invalid content was found starting with element 'teamSize'. No child element is expected at this point.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:453)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3232)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1795)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:741)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(ValidatorHandlerImpl.java:565)
at org.eclipse.persistence.internal.oxm.record.XMLReader$ValidatingContentHandler.startElement(XMLReader.java:431)
at org.eclipse.persistence.internal.oxm.record.XMLReaderAdapter$ExtendedContentHandlerAdapter.startElement(XMLReaderAdapter.java:178)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:302)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:436)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:418)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:244)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:436)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:303)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parseRoot(JSONReader.java:166)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:125)
at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:140)
... 5 more

generate wcf server code from wsdl files

Greetings, I would like to generate some contract based on wsdl file. I used svcutil but I suspect it generated it wrong as all contract methods have void returned type. Is there any tool for this purpose?
EDIT:
here is the wsdl file:
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:tns="http://dantek.com.pl/EDItEUR/EDItX/LibraryBookSupply/WebService/CustomerService/20100611/ServiceContract" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" targetNamespace="http://mytargetNamespace/ServiceContract" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<wsdl:types>
<xsd:schema targetNamespace="http://mytargetNamespace/ServiceContract/Imports">
<xsd:import namespace="http http://mytargetNamespace/ServiceContract/ServiceContract" />
</xsd:schema>
</wsdl:types>
<wsdl:message name="CustomerService_ProcessMethod_InputMessage">
<wsdl:part name="parameters" element="tns:ProcessMethod" />
</wsdl:message>
<wsdl:message name="CustomerService_ProcessMethod_OutputMessage">
<wsdl:part name="parameters" element="tns:ProcessMethodResponse" />
</wsdl:message>
>
<wsdl:portType name="CustomerService">
<wsdl:operation name="ProcessShipNotice">
<wsdl:input wsaw:Action=" http://mytargetNamespace/ServiceContract/ProcessMethod" message="tns:CustomerService_ProcessMethod_InputMessage" />
<wsdl:output wsaw:Action=" http://mytargetNamespace/ServiceContract/ProcessMethod" message="tns:CustomerService_ProcessMethod_OutputMessage" />
</wsdl:operation>
</wsdl:portType>
</wsdl:definitions>
And the contract created
[ServiceContract]
public interface CustomerService
{
[System.ServiceModel.OperationContractAttribute(Action = "http://mytargetNamespace/ServiceContract/CustomerService/ProcessMethod”, ReplyAction = " http://mytargetNamespace/ServiceContract/CustomerService/ProcessMethodResponse")]
[System.ServiceModel.XmlSerializerFormatAttribute()]
void ProcessMethod(ProcessMethodRequest request);
I don't want to have ProcessMethod returned type void but rather ProcessMethodResponse type. How can I achieve it?
EDIT2: Here's my schema:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://myTargetNamespece/ServiceContract" elementFormDefault="qualified"
targetNamespace="http://myTargetNamespace/ServiceContract" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="ProcessMethod">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="request" type="tns:ProcessMethodRequest" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="ProcessMethodRequest" abstract="true" />
<xs:complexType name="ProcessMethodRequestWithPayload"/>
<xs:element name="ProcessMethodResponse">
<xs:complexType />
</xs:element>
</xs:schema>
Generated operation contract is correct. You WSDL specifies request/response operation (= two-way) with empty response. ProcessMethodResponse element is wrapper element for the response message but it does not contain any subelements = void response.
If you want to return ProcessMethodResponse you have to use message contracts. You can instruct svcutil to use message contracts by /mc or /messageContract switch.

svcutil soap fault namespace problem

I'm generating client side web service code using svcutil. The wsdl contract I'm using contains a soap fault. When the code is generated the fault seems to be wrapped in the namespace it was defined in the contract.
Can anyone explain why?
I'm simply running svcutil [filename]
Example WSDL:
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://tempuri.org/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://tempuri.org/">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/">
<s:element name="HelloFault">
<s:complexType/>
</s:element>
<s:element name="HelloWorld">
<s:complexType/>
</s:element>
<s:element name="HelloWorldResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="HelloWorldResult" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</wsdl:types>
<wsdl:message name="HelloWorldSoapIn">
<wsdl:part name="parameters" element="tns:HelloWorld"/>
</wsdl:message>
<wsdl:message name="HelloWorldSoapOut">
<wsdl:part name="parameters" element="tns:HelloWorldResponse"/>
</wsdl:message>
<wsdl:message name="NewMessage">
<wsdl:part name="detail" element="tns:HelloFault"/>
</wsdl:message>
<wsdl:portType name="Service1Soap">
<wsdl:operation name="HelloWorld">
<wsdl:input message="tns:HelloWorldSoapIn"/>
<wsdl:output message="tns:HelloWorldSoapOut"/>
<wsdl:fault name="FaultName" message="tns:NewMessage"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="Service1Soap12" type="tns:Service1Soap">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="HelloWorld">
<soap12:operation soapAction="http://tempuri.org/HelloWorld" soapActionRequired="" style="document"/>
<wsdl:input>
<soap12:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal"/>
</wsdl:output>
<wsdl:fault name="FaultName">
<soap12:fault name="FaultName" use="literal"/>
</wsdl:fault>
</wsdl:operation>
</wsdl:binding>
Generates:
namespace tempuri.org
{
using System.Runtime.Serialization;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="HelloFault", Namespace="http://tempuri.org/")]
public partial class HelloFault : object, System.Runtime.Serialization.IExtensibleDataObject
{
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
public System.Runtime.Serialization.ExtensionDataObject ExtensionData
{
get
{
return this.extensionDataField;
}
set
{
this.extensionDataField = value;
}
}
}
}
But other types declared in the contract are declared without a namespace?
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class HelloWorldRequest
{
...
You have to use the /UseSerializerForFaults attribute on svcutil, this will cause the XmlSerializer to be used for reading and writing faults (but only those), instead of the default DataContractSerializer (which will still be used for the rest of the stuff).
This seems to be a genuine bug - more info on my blog post.
I'm not sure I understand what the problem is... can you clarify?
From the looks of it, it would seem WCF is doing the right thing... the generated class has the right namespace URI in the [DataContract] attribute according to the schema in the WSDL fragment you showed.
What were you expecting?
Update: OK, I see what you're saying, but in this specific case, it's not unexpected either. If you look closely, notice that the other class you mention (HelloWorldRequest) is a Message Contract, not a DataContract. Message Contracts don't have namespaces themselves, though they can specify a namespace for the wrapper element around the message body (see the WrapperNamespace property).
In your case, the message contract specifies that it is not wrapped, so the WrapperNamespace wouldn't apply anyway.
Update #2: Regarding the CLR namespace (and not the XML namespace URI), SvcUtil does give you a way to control that; check out the /namespace: argument in the documentation.