locked
customized webservice issue. RRS feed

  • Question

  • Hi All,

    we have created on webservice that takes the data from lagecy system and create a record in MSCRM account entity.

    issue is when I runnning webserice in local host it is working fine and create a record in account enity,

    But when I consuming this webservice from other system not able to create record due to

    Code:


    using System.Web.Services;
    //using System;
    //using System.Collections.Generic;
    //using System.Linq;
    //using System.Web;
    //using System.Net;
    //using System.Configuration;
    //using System.Web.UI;
    //using System.Web.UI.WebControls;
    //using Microsoft.Xrm.Sdk;
    //using Microsoft.Xrm.Sdk.Messages;
    //using Microsoft.Xrm.Sdk.Query;
    //using Microsoft.Xrm.Sdk.Client;
    //using Microsoft.Crm.Sdk.Messages;
    //using Microsoft.Xrm.Sdk.Metadata;
    //using System.ServiceModel.Description;
    //using System.Security;
    //using System.Security.Cryptography;

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    //using Microsoft.Xrm.Sdk.DeviceCredential;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Discovery;
    using Microsoft.Xrm.Sdk.Messages;
    using System.Security.Principal;
    using System.Xml;
    using System.Runtime.InteropServices;
    using Microsoft.Xrm.Sdk;
    using System.Security.Cryptography;
    using System.Xml.Serialization;
    using Microsoft.Crm.Services.Utility;
    using System.IO;
    using McTools.Xrm.Connection;


    using log4net;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Net.Security;
    using Microsoft.Xrm.Client.Services;

     


    /// <summary>
    /// Summary description for CRMWebService
    /// </summary>
    [WebService(Namespace = "http://WebSite2/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {

       

        public WebService()
        {
           
            //Uncomment the following line if using designed components
            //InitializeComponent();
        }


        public void writeToText(string text)
        {
            string path = @"D:\logs\log.txt";
            if (!File.Exists(path))
            {
                File.Create(path);
                TextWriter tw = new StreamWriter(path);
                tw.WriteLine(text + "--" + DateTime.Now);
                tw.Close();
            }
            else if (File.Exists(path))
            {
                TextWriter tw = new StreamWriter(path, true);

                tw.WriteLine(text +"--" + DateTime.Now);
                tw.Close();
            }
        }


        //public string HelloWorld()
        //{
        //    return "Hello World";
        //}

     

        public class CreditInfo
        {
            private string customername;
            private string customernumber_1;
            private string customercreditlimit;
            private string totalreceivables;
            private string opendeliverycreditval;
            private string openbillingdocumentcredit;
            private string opensaleordercreditvalue;

          


            public string CustomerNumber1
            {
                get { return customernumber_1; }
                set { customernumber_1 = value; }
            }

            public string CustomerCreditLimit
            {
                get { return customercreditlimit; }
                set { customercreditlimit = value; }
            }

            public string CustomerName
            {
                get { return customername; }
                set { customername = value; }
            }

            //public string OpenDeliveryCreditValue
            //{
            //    get { return opendeliverycreditval; }
            //    set { opendeliverycreditval = value; }
            //}

            //public string OpenBillingDocumentCredit
            //{
            //    get { return openbillingdocumentcredit; }
            //    set { openbillingdocumentcredit = value; }
            //}

            //public string OpenSaleOrderCreditValue
            //{
            //    get { return opensaleordercreditvalue; }
            //    set { opensaleordercreditvalue = value; }
            //}
        }

      
      
        [WebMethod]
        [XmlInclude(typeof(CreditInfo))]
        public List<CreditInfo> GetCreditInfoData(List<CreditInfo> Creditvalues)
        {
            //log.Debug("Application loaded successfully.");
            writeToText("Application loaded successfully.");


            CreditInfo CreditInfoVal = new CreditInfo();
            List<CreditInfo> objCreditinfo = new List<CreditInfo>();
            foreach (var c in Creditvalues)
            {
                //CreditInfoVal.CustomerNumber1 = c.CustomerNumber1;
                //CreditInfoVal.CustomerCreditLimit = c.CustomerCreditLimit;
                CreditInfoVal.CustomerName = c.CustomerName;
                CreditInfoVal.CustomerNumber1 = c.CustomerNumber1;
                CreditInfoVal.CustomerCreditLimit = c.CustomerCreditLimit;

                //CreditInfoVal.CustomerName = c.CustomerName;
                //CreditInfoVal.TotalReceivables = c.TotalReceivables;
                //CreditInfoVal.OpenDeliveryCreditValue = c.OpenDeliveryCreditValue;
                //CreditInfoVal.OpenBillingDocumentCredit = c.OpenBillingDocumentCredit;
                //CreditInfoVal.OpenSaleOrderCreditValue = c.OpenSaleOrderCreditValue;
                objCreditinfo.Add(CreditInfoVal);
            }
            return objCreditinfo;

       

        }


       
          [WebMethod]
          [XmlInclude(typeof(CreditInfo))]
          public void PushCreditData(List<CreditInfo> Creditvalues)
          {
              log.Debug("Application loaded successfully.");
              log.Info("Entered to PushCreditData");

              writeToText("********************************************");

              writeToText("Entered Push Credit  data method.");

              try
              {
                  CreditInfo CreditInfoVal = new CreditInfo();
                  List<CreditInfo> objCreditinfo = new List<CreditInfo>();
                  foreach (var c in Creditvalues)
                  {


                      //CreditInfoVal.CustomerNumber1 = "c.CustomerNumber1";
                      //CreditInfoVal.CustomerCreditLimit = "c.CustomerCreditLimit";
                      //CreditInfoVal.CustomerName = "c.CustomerName";
                      //CreditInfoVal.CustomerNumber1 = c.CustomerNumber1;
                      //writeToText("Customer Number :" + CreditInfoVal.CustomerNumber1);
                      //CreditInfoVal.CustomerCreditLimit = c.CustomerCreditLimit;
                      //writeToText("Creditlimit :" + CreditInfoVal.CustomerCreditLimit);
                      CreditInfoVal.CustomerName = c.CustomerName;
                      writeToText("Customer Name :" + CreditInfoVal.CustomerName);
                      //CreditInfoVal.TotalReceivables = c.TotalReceivables;
                      //CreditInfoVal.OpenDeliveryCreditValue = c.OpenDeliveryCreditValue;
                      //CreditInfoVal.OpenBillingDocumentCredit = c.OpenBillingDocumentCredit;
                      //CreditInfoVal.OpenSaleOrderCreditValue = c.OpenSaleOrderCreditValue;
                      objCreditinfo.Add(CreditInfoVal);


                  }

                  CreateAccount(objCreditinfo);

                  //SaveData(objCreditinfo);
              }

              catch(Exception ex)
              {
                  log.Error("Push Credit Data : " + ex.Message);
                  writeToText("Exception in PushCreditDatamethod :" +ex.Message);

              }
          }

          [WebMethod]
          [XmlInclude(typeof(CreditInfo))]

          public void TestMethodPushCreditData()
          {

              writeToText("Entered TestMethod");
              //log.Debug("Application loaded successfully.");
              //log.Info("Entered to TestPushCreditData");
              CreditInfo CreditInfoVal = new CreditInfo();
              List<CreditInfo> objCreditinfo = new List<CreditInfo>();
              //CreditInfoVal.CustomerNumber1 = "2345";
              //CreditInfoVal.CustomerCreditLimit = "20000000";
              CreditInfoVal.CustomerName = "TestAccount";
              //CreditInfoVal.TotalReceivables = "xyz";
              //CreditInfoVal.OpenDeliveryCreditValue = "xyz";
              //CreditInfoVal.OpenBillingDocumentCredit = "xyz";
              //CreditInfoVal.OpenSaleOrderCreditValue = "xyz";
              objCreditinfo.Add(CreditInfoVal);
              PushCreditData(objCreditinfo);

         

          }

          private void SaveData(List<CreditInfo> CreditData)
          {
              try
              {
                  string path = System.Configuration.ConfigurationManager.AppSettings["Path"].ToString();
                  string FileName = path + "CInfo_" + DateTime.Now.ToString("MMddyyyhhmm") + ".xml";
                  using (TextWriter writer = new StreamWriter(FileName))
                  {
                      (new XmlSerializer(typeof(List<CreditInfo>))).Serialize(writer, CreditData);
                  }
              }
              catch (Exception ex)
              {
                  log.Error("error : " + ex.Message);


              }
          }


          public string CreateAccount(List<CreditInfo> CreditData)
        {

            OrganizationService Iservice;

            writeToText("****************************************************************");

            writeToText("Entered MSCRM CreatAccount Method");


            log.Info("Entered to CreateAccount");
            string message = string.Empty;
            try
            {


                //ConnectionManager connectionManager = new ConnectionManager(@"C:\Users\raghup\Documents\Visual Studio 2010\WebSites\WebSite2\Bin\mscrmtools2011.config");
                //Iservice = connectionManager.ConnectToServer(connectionManager.ConnectionsList.Connections[0]) as OrganizationService;

                var deviceCred = new System.ServiceModel.Description.ClientCredentials();
                var cred = new System.ServiceModel.Description.ClientCredentials();
                cred.UserName.UserName = "WindowsLivedID";
                cred.UserName.Password = "Password";
                cred.Windows.ClientCredential = new System.Net.NetworkCredential("WindowsLivedID", "Password");
             
               // Uri HomeRealmUri = new Uri(String.Format("https://disco.crm4.dynamics.com/XRMServices/2011/Discovery.svc", "crm4.dynamics.com"));

                //ServerConnection obj = new ServerConnection();
               // deviceCred = (System.ServiceModel.Description.ClientCredentials)obj.GetDeviceCredentials();
                OrganizationServiceProxy orgService = (OrganizationServiceProxy)GetCRMService("https://zuaricement-test.api.crm4.dynamics.com/XRMServices/2011/Organization.svc", cred, deviceCred);
              //  writeToText("OrgService Object Created");
                //orgService.EnableProxyTypes();
                Entity Account = new Entity("account");
                //Specify the attributes
               // contact.Attributes["lastname"] = "Raghu";

                //ITracingService tracingService =
                //    (ITracingService)serviceProvider.GetService(typeof(ITracingService));

     

                //Execute the service
                foreach (CreditInfo item in CreditData)
                {
                    try
                    {
                        //Entity entity = GetAccountBasedOnCustomerNumber(service, item.CustomerNumber1);

                        if (CreditData.Count > 0)
                        {

                            //if (item.CustomerCreditLimit != null)
                            //    Account.Attributes.Add("new_creditlimitamount", new Money(Convert.ToDecimal(item.CustomerCreditLimit)));
                            //writeToText("CreditLimit :" + item.CustomerCreditLimit + "  assigned");

                            //if (item.CustomerNumber1 != null)
                            //    Account.Attributes.Add("accountnumber", new String (Convert.ToDecimal(item.CustomerNumber1)));

                            //if (item.CustomerNumber1 != null)
                            //    Account.Attributes.Add("accountnumber", item.CustomerNumber1);
                            //writeToText("Customer Number :" + item.CustomerNumber1 + "   assigned");

                            if (item.CustomerName != null)
                                Account.Attributes.Add("name", item.CustomerName);

                            writeToText("Customer Name :" + item.CustomerName + "    assigned");

                            //if (item.OpenBillingDocumentCredit != null)
                            //    Account.Attributes.Add("new_creditlimitamount", new Money(Convert.ToDecimal(item.OpenBillingDocumentCredit)));

                            //if (item.OpenDeliveryCreditValue != null)
                            //    Account.Attributes.Add("new_creditlimitamount", new Money(Convert.ToDecimal(item.OpenDeliveryCreditValue)));

                            //if (item.OpenSaleOrderCreditValue != null)
                            //    Account.Attributes.Add("new_creditlimitamount", new Money(Convert.ToDecimal(item.OpenSaleOrderCreditValue)));

                            //if (item.TotalReceivables != null)
                            //    Account.Attributes.Add("new_creditlimitamount", new Money(Convert.ToDecimal(item.TotalReceivables)));
                           // return "error";

                            //Guid contactId = Iservice.Create(Account);
                        }

                       // Guid contactId = Iservice.Create(Account);


                    }
                    catch (Exception ex)
                    {

                        log.Error("Creat Account method exception : " + ex.Message);

                        writeToText("Exception in Assigning the values :" + ex.Message);

                        return "error";

                       

                    }
                }

               // Account.Attributes[""] = CreditData.

                Guid contactId = orgService.Create(Account);
                ///Guid contactId = orgService.Create(Account);

     

            }
            catch (Exception ex)
            {
                log.Error("Create Account method error: " + ex.Message);
                writeToText("Exception in CreateAccountMethod :" + ex.Message);

                message = ex.Message;
            }
            //returns the message
            return message;
        }


        protected virtual ClientCredentials GetCredentials(string username, string password)
        {
            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = username;
            credentials.UserName.Password = password;

           


            return credentials;
        }

        private static ClientCredentials GetDeviceCredentials()
        {
            return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();

        }

        private OrganizationServiceProxy GetCRMService(string crmServerUrl, System.ServiceModel.Description.ClientCredentials cred, System.ServiceModel.Description.ClientCredentials deviceCred)
        {

            try
            {
               
                writeToText("reached GetCRMService, before calling OrganizationServiceProxy constructor");
                OrganizationServiceProxy _service;
                _service = new OrganizationServiceProxy(new Uri(crmServerUrl), null, cred, deviceCred);
                _service.Timeout = System.TimeSpan.MaxValue;
                writeToText("reached GetCRMService, after calling OrganizationServiceProxy constructor");
                return _service;
        //        writeToText("Exception in CreateAccountMethod :" + _service);

        //        Uri oUri = new Uri("https://zuaricement-test.api.crm4.dynamics.com/XRMServices/2011/Organization.svc");
        //        //** Your client credentials   
        //        ClientCredentials clientCredentials = new ClientCredentials();
        //      

        //        //Create your Organization Service Proxy  
        //        OrganizationServiceProxy _service = new OrganizationServiceProxy(
        //            oUri,
        //            null,
        //            clientCredentials,
        //            null);
        //                        System.ServiceModel.Description.ClientCredentials credentials;
        //                       credentials = new ClientCredentials();

        //             If CRM On-Premise

        //             To use custom credentials pass user credentials


        //             To use Default Credentials; Uncomment below line and comment above

        //             credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

        //             If CRM Online

            //             Use “https” if CRM is SSL configured

        //            string orgUrl= "https://zuaricement-test.api.crm4.dynamics.com/XRMServices/2011/Organization.svc";

        //             Add this line if URL has “https” (i.e.,CRM is SSL configured)

        //            if (!string.IsNullOrEmpty(orgUrl) && orgUrl.Contains("https")) {

        //            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain,
        //            SslPolicyErrors sslPolicyErrors) { return true; };

        //            }
        //        Uri HomeURI =new Uri(homerealmUri);

        //            Uri organizationUri = new Uri(orgUrl);

        //            using (

        //            OrganizationServiceProxy serviceProxy =

        //            new OrganizationServiceProxy(organizationUri,null,credentials, null))

        //            {

        //                serviceProxy.EnableProxyTypes();

        //             To impersonate set the GUID of CRM user here

        //                Guid id;

        //               id= new Guid("201AE66E-6DD3-E211-8E40-AC162DB64AC6");

        //               serviceProxy.CallerId = id;


        //               IOrganizationService service;

        //            serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

        //            service = serviceProxy;

        //            serviceProxy.Timeout = new TimeSpan(0, 6, 0);
        //            return serviceProxy;
        //            }

     

     


            }

     

            catch (FaultException ex)
            {
                writeToText("fault exception: " + ex.Message);
                return null;
            }
            catch (Exception ex)
            {
                writeToText("General exception: " + ex.Message);
                return null;
            }
        }

        private static readonly ILog log = LogManager.GetLogger(
      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

     

     

        }

     

     

     

    Wednesday, September 4, 2013 8:29 AM

All replies

  • Hi,

    What exception are you getting - could you post the full exception with stack trace please.

    Thanks


    Scott Durow
    Blog www.develop1.net    Follow Me
    Rockstar365
    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

    Wednesday, September 4, 2013 9:01 AM
    Answerer
  • What is the exception message you are getting? Could be because of application pool. Try to change the 'Identity' property of the application pool you are using. But not sure without seeing the exception. 
    • Edited by jattscorpion Wednesday, September 4, 2013 10:50 AM
    Wednesday, September 4, 2013 10:49 AM
  • when initiating Organization Service proxy object getting this Exception.

    Metadata contains a reference that cannot be resolved: 'https://organization/XRMServices/2011/Organization.svc?wsdl'.--9/4/2013

    Thursday, September 5, 2013 5:07 AM
  • Hi,

    This usually means that have provided an incorrect Service Url to the OrganizationService - your original code shows https://zuaricement-test.api.crm4.dynamics.com/XRMServices/2011/Organization.svc

    Why line is your exception coming from  - there is a lot of commented out code!


    Scott Durow
    Blog www.develop1.net    Follow Me
    Rockstar365
    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

    Thursday, September 5, 2013 7:12 AM
    Answerer
  • Hi Thanks for help!

    but Acuvally code was not commented..

    The exact exception comming from

    The below line code is returns null..

    //_service = new OrganizationServiceProxy(new Uri(crmServerUrl), null, cred, deviceCred);

    Thursday, September 5, 2013 8:14 AM
  • But that line is commented out!!

    That line would never return null - it would either return an OrganizationServiceProxy or it would throw en exception.

    Could you post the exact line that is throwing the exception with the value of all the parameters and the complete stack trace please. I'm sure we can get it sorted from there. :)


    Scott Durow
    Blog www.develop1.net    Follow Me
    Rockstar365
    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

    Thursday, September 5, 2013 8:32 AM
    Answerer