Sunday, December 2, 2012

Consuming Oracle CRM OnDemand web services from .Net (C#)

Oracle CRM web services' documentation is not straight forward for implementation, at least I felt so. I had to figure it out the hard way but finally I was able to query and update. So here it is for anyone else embarking on the same path. 

1. Download the custom WSDL and NOT "Schema" after logging to CRM on demand website from the Admin > web services administration link. [Select Web Services 2.0 from the select services drop down box.]. Save it to a location on your drive and this is what you will reference from your "Add web reference" dialog box.

Note: This wsdl file will be huge (in tens of megs). 

2. In your project, select "Add web reference", type the path of the wsdl file on your drive. e.g. c:\oraclecrmsvc\contact.wsdl

You can find online examples of how to sign-in and make web service requests from this page - http://www.oracle.com/technetwork/indexes/samplecode/crmod-sample-522104.html. (R17Advsample1.zip - This has lot of examples about query, update, delete, etc., also to sign in).
 NOTE: Without signing in via the web service request, you cannot make request to query, update, delete or anything for that matter. 

Code: 


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using XeroxOracleCrm.Svc.ContactSvc;
using System.Net;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Reflection; 
 
namespace XeroxOracleCrm.Svc
{
    [WebService(Namespace = "http://abc.Svc/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class XeroxOracleCrmBridgeService : System.Web.Services.WebService
    {
        public string server = ConfigurationManager.AppSettings["CrmUrl"]; 
        public string username;
        public string password;
        public string sessionId;
        public Cookie cookie;
 
        [WebMethod]
        public string Contacts(string customerId)
        {
            if (!string.IsNullOrEmpty(customerId))
            { 
                customerId = customerId.Trim();
                if (string.IsNullOrEmpty(customerId))
                {
                    return "Invalid Customer ID"; 
                }
            }
 
            string errorObtainingSession = Establish();
            if (!string.IsNullOrEmpty(errorObtainingSession))
            {
                return "Error obtaining Oracle CRM On Demand's session. Message: " + errorObtainingSession; 
            }
 
            string response = GetContacts(customerId); 
 
            Destroy();
 
            return response; 
        }
 

        #region Private Methods
        //You have to instantiate the properties in the request, which you want in the
        // response.
        private string GetContacts(string customerId)
        {
            Contact c = new Contact();
 
            ContactQueryPage_Input cqi = new ContactQueryPage_Input();
 
            ContactQuery cq = new ContactQuery();
            cq.ContactFirstName = new queryType();
            cq.ContactLastName = new queryType(); 
            cq.ContactEmail = new ContactSvc.queryType();
            cq.ContactFullName = new ContactSvc.queryType();
            cq.ContactType = new queryType();
            cq.CustomerId = new queryType(); 
            cq.Id = new ContactSvc.queryType();
            cq.AccountId = new ContactSvc.queryType();
     
            cq.AssistantPhone = new ContactSvc.queryType();
            cq.HomePhone = new ContactSvc.queryType();
            
            cq.CustomText0 = new queryType();
            cq.CustomText1 = new queryType();
            cq.CustomText2 = new queryType();
            cq.CustomText3 = new queryType();
            cq.CustomText4 = new queryType();
            cq.CustomText5 = new queryType();
            cq.CustomText6 = new queryType();
            cq.CustomText7 = new queryType();
            cq.CustomText8 = new queryType(); 
            cq.QualifiedDate = new ContactSvc.queryType();
            cq.OwnerFullName = new ContactSvc.queryType();
            cq.LastCallDate = new ContactSvc.queryType();
            cq.LastActivityDate = new ContactSvc.queryType();
            cq.Gender = new ContactSvc.queryType();
            cq.CreatedDate = new ContactSvc.queryType();
            cq.ModifiedDate = new ContactSvc.queryType();
            cq.CreatedById = new ContactSvc.queryType();
            cq.CreatedByEMailAddr = new ContactSvc.queryType();
 
            cq.ExternalSystemId = new ContactSvc.queryType(); 
            cq.IndexedDate0 = new queryType();  
            cq.IndexedBoolean0 = new queryType();
            cq.IndexedCurrency0 = new queryType();
            cq.IndexedLongText0 = new queryType();
            cq.IndexedNumber0 = new queryType();
            cq.IndexedPick0 = new queryType();
            cq.IndexedPick1 = new queryType();  
            cq.IndexedPick2 = new queryType();
            cq.IndexedPick3 = new queryType();
            cq.IndexedPick4 = new queryType(); 
            cq.IndexedPick5 = new queryType();
            cq.IndexedShortText0 = new queryType(); 
            cq.IndexedShortText1 = new queryType(); 
            
            cq.ContactRole = new ContactSvc.queryType();
 
//You can use whatever query you want. Play with it. 
            cq.searchspec = "([ExternalSystemId] = '" + customerId +"')";
 
            ListOfContactQuery lcq = new ContactSvc.ListOfContactQuery();
            lcq.pagesize = "5";
            lcq.startrownum = "0";
            lcq.recordcountneeded = true;
            lcq.Contact = cq;
 
            cqi.ListOfContact = lcq;
 
            c.Url = GetURL();
            try
            {
                ContactQueryPage_Output co = c.ContactQueryPage(cqi);
                if(co.ListOfContact != null && co.ListOfContact.Contact != null && co.ListOfContact.Contact.Length > 0)
                {
                    ContactData cData = co.ListOfContact.Contact[0];
                    PropertyInfo[] properties = cData.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                    StringBuilder sbContactData = new StringBuilder(); 
                    foreach (PropertyInfo property in properties)
                    {
                        sbContactData.AppendLine(property.Name + ": " + property.GetValue(cData, null));
                    }
                    return sbContactData.ToString(); 
                }
                return string.Empty; 
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
  
        private string GetURL()
        {
            if (sessionId == null)
            {
                throw new Exception("No session has been established!");
            }
            
            return server + "/Services/Integration;jsessionid=" + sessionId;
        }
 
        private string GetLogInURL()
        {
            return server + "/Services/Integration?command=login";
        }
 
        private string GetLogOffURL()
        {
            return server + "/Services/Integration?command=logoff";
        }
 
        private string Establish()
        {
            try
            {
                // create a container for an HTTP request
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GetLogInURL());
 
                // username and password are passed as HTTP headers
                req.Headers.Add("UserName"ConfigurationManager.AppSettings["CrmUserName"]);
                req.Headers.Add("Password"ConfigurationManager.AppSettings["CrmPassword"]);
 
                // cookie container has to be added to request in order to 
                // retrieve the cookie from the response. 
                req.CookieContainer = new CookieContainer();
 
                // make the HTTP call
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    // store cookie for later...
                    cookie = resp.Cookies["JSESSIONID"];
                    if (cookie == null)
                    {
                        throw new Exception("No JSESSIONID cookie found in log-in response!");
                    }
                    sessionId = cookie.Value;
                }
            }
            catch (Exception ex)
            {
                return ex.Message; 
            }
            return ""; 
        }
 
        private void Destroy()
        {
            // create a container for an HTTP request
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GetLogOffURL());
 
            // reuse the cookie that was received at Login
            req.CookieContainer = new CookieContainer();
            req.CookieContainer.Add(cookie);
 
            // make the HTTP call
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("Logging off failed!");
            }
            // forget current session id
            sessionId = null;
        }
 
        #endregion
    }
}


Note: Use fiddler to see the requests and responses. 



Good luck!

No comments: