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();
token.setCallerId("00000000-0000-0000-0000-000000000000");
token.setOrganizationName(OrganizationName);
//token.setAuthenticationType(0);

CrmServiceSoapStub bindingStub = (CrmServiceSoapStub) new CrmServiceLocator().getCrmServiceSoap(new URL(endpointURL));
bindingStub.setHeader("http://schemas.microsoft.com/crm/2007/WebServices",
"CrmAuthenticationToken", token);

bindingStub.setUsername(username);
bindingStub.setPassword(password);

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

40 comments:

  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.

    regards,
    Praneeth

    ReplyDelete
  2. which are the wsdl files you converted ?

    ReplyDelete
  3. CrmDiscoveryService.wsdl
    CrmService.wsdl
    MetadataService.wsdl

    ReplyDelete
  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 ?

    ReplyDelete
  5. thank you dave,

    Microsoft Dynamics CRM Online.

    should i send you the wsdl's ?

    - Praneeth

    ReplyDelete
  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.

    ReplyDelete
  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

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

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

    ReplyDelete
  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).

    ReplyDelete
  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.

    ReplyDelete
  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

    ReplyDelete
  13. Hi Wojciech,

    yes , we have to modify the client-config.wsdd file inside the Axis jar to enable NTLM. This helped me
    http://tjordahl.blogspot.com/2007/03/apache-axis-and-commons-httpclient.html

    ReplyDelete
  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 ?

    ReplyDelete
  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.

    ReplyDelete
  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.

    ReplyDelete
  17. sent to your mail address. check mail

    ReplyDelete
  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)


    Regards,
    Subhash
    subhash.lingampally@gmail.com

    ReplyDelete
  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

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

    ReplyDelete
  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 ?

    ReplyDelete
  22. Hi David,

    1)I generated the classes using wsdl
    2)Edited the client-config wsdd file and trying to connect.

    Unfortunately i get the following errors

    - 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
    at org.apache.commons.httpclient.auth.NTLMScheme.authenticate(NTLMScheme.java:331)
    at org.apache.commons.httpclient.HttpMethodDirector.authenticateHost(HttpMethodDirector.java:281)
    at org.apache.commons.httpclient.HttpMethodDirector.authenticate(HttpMethodDirector.java:233)
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:169)
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
    at org.apache.axis.transport.http.CommonsHTTPSender.invoke(CommonsHTTPSender.java:196)
    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:13094)
    at Axis14TestCRM.main(Axis14TestCRM.java:65)
    - Failure authenticating with NTLM @usalvicrmbw2k84.pmm.com:80
    - Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
    AxisFault
    faultCode: {http://xml.apache.org/axis/}HTTP
    faultSubcode:
    faultString: (401)Unauthorized
    faultActor:
    faultNode:
    faultDetail:
    {}:return code: 401
    HTTP Error 401 - Unauthorized: Access is denied

    {http://xml.apache.org/axis/}HttpErrorCode:401

    (401)Unauthorized
    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:13094)
    at Axis14TestCRM.main(Axis14TestCRM.java:65)


    Can you help on this?

    Regards,
    Subhash

    ReplyDelete
  23. 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?

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

    Thanks.

    ReplyDelete
  25. 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!

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

    ReplyDelete
  27. 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!

    ReplyDelete
  28. 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!

    ReplyDelete
  29. 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

    ReplyDelete
  30. Got it!!! Thanks a lot, mate!!

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

    ReplyDelete
  32. 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!!

    ReplyDelete
  33. Are you sure you got the ticket using jLive?

    ReplyDelete
  34. Hi,
    When I execute the above sample program to connect MS Dynamics CRM online, I got the following error:

    AxisFault
    faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
    faultSubcode:
    faultString: org.xml.sax.SAXParseException: The string "--" is not permitted within comments.
    faultActor:
    faultNode:
    faultDetail:
    {http://xml.apache.org/axis/}stackTrace:org.xml.sax.SAXParseException: The string "--" is not permitted within comments.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    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.XMLScanner.scanComment(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanComment(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.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 javax.xml.parsers.SAXParser.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.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)
    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:10600)
    at com.emailforce1.test.TestMicrosoftCRM.main(TestMicrosoftCRM.java:66)


    How can we fix this?

    Thanks
    Aravintha J

    ReplyDelete
  35. 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.

    ReplyDelete
  36. 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?

    thx

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

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

    ReplyDelete
  38. 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

    Regards
    Yadesh Kasaramoni

    ReplyDelete
  39. 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.

    ReplyDelete