Tuesday, June 29, 2010

Connecting MS CRM 4.0 using Java webservices

Continue from connecting with MS CRM 3.0

The following is the sample code to connect MSCRM 4.0

String password = "password";

String username = "user";
String OrganizationName = "orgname";  //Whats Org Name

String endpointURL = "http://server:port/MSCrmServices/2007/CrmService.asmx"

CrmAuthenticationToken token = new CrmAuthenticationToken();

CrmServiceSoapStub bindingStub = (CrmServiceSoapStub) new CrmServiceLocator().getCrmServiceSoap(new URL(endpointURL));
"CrmAuthenticationToken", token);


WhoAmIRequest whoRequest = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse)bindingStub.execute(whoRequest);
String userid = whoResp.getUserId();
System.out.println("userid = "+userid );

I will provide the sample code for connecting MS CRM Services for all types of deployment


  1. hi dave,

    i'm trying to connect to mscrm 4.0 ondemand.

    when i converted wsdl to stub classes, i'm not getting the class "CrmServiceSoapStub " which u mentioned in the sample code.

    is it the same code useful to connect to mscrm ondemand.


  2. which are the wsdl files you converted ?

  3. CrmDiscoveryService.wsdl

  4. There are three types of deployments:

    * Microsoft Dynamics CRM 4.0 - On-premise deployment
    * Microsoft Dynamics CRM 4.0 – Internet-facing deployment (IFD)
    * Microsoft Dynamics CRM Online

    Which one is yours ?

  5. thank you dave,

    Microsoft Dynamics CRM Online.

    should i send you the wsdl's ?

    - Praneeth

  6. Please check this link to convert wsdl to java http://davidbits.blogspot.com/2009/09/microsoft-dynamic-crm-30-java.html

    But the above Code will not work for CRM-online

    To connect CRM-online from java, It needs a lot of work.

    But to connect CRM-IFD or CRM-AD is easy. WE only need to just modify the above code.

  7. Hi David,

    I have to access to Dynamics CRM 4.0 CrmService from Java client. I was trying to use AXIS2 and WSDL2Java tool, but unfortunately my generated stub differs from examples which I have seen on network. For example I do not have some classes generated ( for example there is no class AllColumns which should derive from ColumnSetBase - this is needed in querying). After generation, WSDL2Java tool throws me following warning "WARN: Type {http://schemas.microsoft.com/crm/2006/Query} Value missing!" I think that this may be a reason for my problem (but I'm not sure). And now I'm wondering how it is possible that my stub differs from that one found on the network

  8. Have you used all jar files in the classpath of the command for wsdl2java specified here

  9. To connect CRM-online from java , we have to create a service in .net to get the ticket

  10. I havent used those jar files because I was trying to use a tool called Wsdl2Java.bat of Axis2 (exactly version 1.5 this is not the same Axis as used in the David's post) and I think this bat contains all needed jars (which are different since it is Axis2).

  11. Hi David,

    I've created the code exaclty as You made it in this tutorial, but still I'm getting error 401 Unauthorized. What is more WhoAmIRequest needs optionalParameters to be set in other case it throws an error saying that optionalParameters are not nillable or sth like that...
    One more question.. In the case of MS CRM 4.0 do we have to modify the file "client-config.wsdd" to enable ntlm authentication ? Please answer me because I had to make it work.

  12. HI Wojciech,
    are you getting nonnillable element ? then just set "elemField.setMinOccurs(0)" property for that field.

    inside static block, find that field in that class

  13. Hi Wojciech,

    yes , we have to modify the client-config.wsdd file inside the Axis jar to enable NTLM. This helped me

  14. Hi David,

    I'd like to thank You for Your help and for this blog entry. I'm now able to call CrmService. I can retrieve entities and create a new one. But recently I've faced another issue. I've spent too much time on it and again asking You for help.. Here is the thing: I'm using Axis 1.4, When I want to create entity with Lookup attribute (to make relation between entities)I can not do that because my CrmReference doesn't contain "value" attribute. This attribute I assume should be of type "com.microsoft.wsdl.types.Guid" but this package is not present in my workspace - it wasn't generated from CrmServiceWsdl + MetadataService. So I'd like to now how it is on Your side ? Do You have this Guid class after generating stubs ?

  15. yes, I too faced this issue after converting to java classes. To solve this add a String variable and create its getter and setter also included this variable in equals(), hashCode() methods and create attributeDesc and addto typeDesc in static block.

  16. Hmm thank You, but I'd be grateful If You send me this "CrmReference.java" file on wojmak@gmail.com. I have tried your solutions many time, before your answer and after it, but with no success. In crm server log there is a message that there were some problems during reading soap, I think this can be the problem :

    attrField.setXmlName(new javax.xml.namespace.QName("", "value"));

    Because in CrmService Wsdl file there is no such type "value" in CrmReference definition.

  17. sent to your mail address. check mail

  18. Hi David,

    I followed the code above but still get the following error. Could you please help on this?

    org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized
    at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:307)
    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:200)
    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:76)
    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:400)
    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:225)
    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:438)
    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:402)
    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
    at com.microsoft.schemas.crm._2007.webservices.CrmServiceStub.retrieveMultiple(CrmServiceStub.java:1608)


  19. Getting the following error
    - Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachment support is disabled.
    - ntlm authentication scheme selected
    - Credentials cannot be used for NTLM authentication: org.apache.commons.httpclient.UsernamePasswordCredentials
    org.apache.commons.httpclient.auth.InvalidCredentialsException: Credentials cannot be used for NTLM authentication: org.apache.commons.httpclient.UsernamePasswordCredentials

    Can anyone help on this? Quick response is appreciable

  20. I am trying to connect MSCRM services from java using axis 1.4

  21. Hi, this post is the continuation of "connecting with MS CRM 3.0" . please check the first line of this post and click the link.
    1. Verify you have all jar files.
    2. Edit the the wsdd file inside the axis.jar
    3. try now.
    any results ?

  22. Hi I've followed your example and was able to get the WhoAmI request working correctly, but I am still encountering a few strange issues. When I try to use dynamic entities to create a contact record in CRM I get an error "expected start of entity element". Have you ever tried using Dynamic entities with Java? I know my code is correct because I tried the equivalent code using .NET and it created the contact successfully.

    Also I am experiencing the same issue as Wojciech regarding missing value field in UniqueIdentifier, CrmReference, etc classes. could you possibly send me the same code you sent Wojciech?

  23. oh i forgot to add my email is craig.schulte@forethought.com.


  24. nevermind, upgraded from axis 1.3 to 1.4 and it eliminated the issues with Dynamic Entities. I also figured out how to add the missing _value properties for the broken classes. Everything appears to be working perfectly now. Thanks for the blog!

  25. Hi Craig, Its pleasure to hear that you solved the issues by yourself. good work ..!

  26. Hi David,
    I've trying to connect to CRM using your instructions, but it keeps crashing when calling "new CrmServiceLocator()" throwing the following exception:

    - Exception:
    org.apache.axis.ConfigurationException: org.xml.sax.SAXException: Fatal Error: URI=null Line=7: The element type "parameter" must be terminated by the matching end-tag "".
    org.xml.sax.SAXException: Fatal Error: URI=null Line=7: The element type "parameter" must be terminated by the matching end-tag "".
    at org.apache.axis.utils.XMLUtils$ParserErrorHandler.fatalError(XMLUtils.java:723)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(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.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at org.apache.axis.utils.XMLUtils.newDocument(XMLUtils.java:369)
    at org.apache.axis.utils.XMLUtils.newDocument(XMLUtils.java:388)
    at org.apache.axis.configuration.FileProvider.configureEngine(FileProvider.java:179)
    at org.apache.axis.AxisEngine.init(AxisEngine.java:172)
    at org.apache.axis.AxisEngine.(AxisEngine.java:156)
    at org.apache.axis.client.AxisClient.(AxisClient.java:52)
    at org.apache.axis.client.Service.getAxisClient(Service.java:104)
    at org.apache.axis.client.Service.(Service.java:197)
    at Pack.com.microsoft.schemas.crm._2007.WebServices.CrmServiceLocator.(CrmServiceLocator.java:21)
    at Main.main(Main.java:48)

    Have you got any idea what this might be about? I believe it must be related to the wsdd file. If this is the case, could you please elaborate on it a little bit more?

    Thanks a lot for your time, mate!

  27. Hi Craig,
    I've just sorted the previous issue out. It was the wsdd file. Now, I'd need to Authenticate using either Kerberos or Digest. Could you please tell me how to do that?
    Thanks a lot again!

  28. Hi fretwio,

    This is David not Craig .. :-)

    Now you are connecting with Basic authentication right ?

    Kerberos means mscrm ntlm authentication ok
    To work with ntlm aythentication , we have to change the pivot value
    of http transport in client-config.wsdd file inside the axis jar.
    I have mentioned this in the first post, please check the first line of this post or go to http://davidbits.blogspot.com/2009/09/microsoft-dynamic-crm-30-java.html

  29. Got it!!! Thanks a lot, mate!!

  30. Thanks frewio.. :) The Lord's holy name be praised !..

  31. David, now I'm trying to connect to CRM 2011 Online. I'm using jLive to connect to passport, and then I'm using the token it returns in the CrmAuthenticationToken. Still, I'm not being able to connect as it's trying to connect using NTLM instead of passport.
    Any thoughts on this?
    Thanks again, mate!!

  32. Are you sure you got the ticket using jLive?

  33. I am usiing the IBM RAD to generate the client code of MS CRM webservice. bindingStub.setHeader() method is missing in the generation. Thanks for your help.

  34. Hi David,

    i'm having some problems in dealing with some of the objects generated by the axis2 framework with wsdl2java. i'm having difficulties in dealing with objects like picklists and lookups or associating accounts with contacts.
    Do you have any example of how to deal with that?


    1. Can you explain in detail or can I see the source what you tried already ..

  35. Hi David,

    I'm using ur sample code to connect to CRM 4.0 server, but I get error response :

    - ntlm authentication scheme selected
    - Failure authenticating with NTLM @XXX.XXX.XXX:443
    faultCode: {http://xml.apache.org/axis/}HTTP
    faultString: (401)Unauthorized
    {}:return code: 401
    HTTP Error 401.1 - Unauthorized: Access is denied


    at org.apache.axis.transport.http.CommonsHTTPSender.invoke(CommonsHTTPSender.java:218)
    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 com.microsoft.schemas.crm._2007.WebServices.CrmServiceSoapStub.execute(CrmServiceSoapStub.java:10675)
    at com.eprotea.crm.TestCRM.CRM(TestCRM.java:117)
    at com.eprotea.crm.TestCRM.runJob(TestCRM.java:199)
    at com.eprotea.crm.TestCRM.main(TestCRM.java:213)

    Below is my source code :

    CrmAuthenticationToken token = new CrmAuthenticationToken();

    CrmServiceSoapStub adminBinding = (CrmServiceSoapStub) new CrmServiceLocator().getCrmServiceSoap(new URL("https://XXX.XXX.XXX/MSCrmServices/2007/CrmService.asmx"));

    adminBinding.setHeader("http://schemas.microsoft.com/crm/2007/WebServices","CrmAuthenticationToken", token);


    WhoAmIRequest whoRequest = new WhoAmIRequest();
    whoRequest.setOptionalParameters(new OptionalParameter[] {});
    WhoAmIResponse whoResp = (WhoAmIResponse) adminBinding.execute(whoRequest);

    String UserId = whoResp.getUserId();

    System.out.println("userid = "+ UserId);

    Could you tell me what is the problem?
    Thank you.

  36. Are you able to connect using SoapUI ? We can try if you give the username/password and the url.. meyilto:jpulikkottil gmail -- com

  37. Hi David,

    I m trying to connect to MSCRM on premise using java client generated using (axis2 1.6 and XMLBEANS binding) but i was unable to call the Execute method of metadataService.
    Can you please some throw some light or if you can provide any code(for authentication or retrieve or execute) that will be very grateful my mail id is yadesh.kasaramoni@gmail.com

    Yadesh Kasaramoni

  38. Hi David,
    I am trying to create account entity on dynamics crm side, through java code.
    I am getting error "An error occurred when verifying security for the message.". So, after googling the issue I found that the client and server time should be in sync. My timezone is "IST", so I guess the urn I should be using is "crmapac:dynamics.com" (correct me if I am wrong). The wsdl provides "crmna:dynamics.com", so I changed it to the "crmapac". I also made changes in the stubs generated through the wsdl.
    Still this error persists. Also, this error is not consistent. Sometimes I do get '401 Unauthorized'.
    I need to do this urgently.
    Kindly, help me with this.