Thursday, May 28, 2015

Interface between systems - call to WS\ WCF service from CRM

Interface between systems - call to WS\ WCF service from CRM
The easy way to call WCF service using Plugin..
Invoke plugin from JS for instance by createing temp entity record
Write the next code in plugin:

public void Execute(IServiceProvider serviceProvider){
 IOrganizationService _srv = null;
 try
 {
  IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
 IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
 _srv = factory.CreateOrganizationService(context.InitiatingUserId);
  if (context.MessageName.ToLower() == "create"){
    HttpWebRequest httpWReq= HttpWebRequest)WebRequest.Create("https://service/lalala.asmx");
    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = "request";
    byte[] data = encoding.GetBytes(postData);
    httpWReq.Method = "POST";
    httpWReq.ContentType = "text/xml; charset=utf-8";
    httpWReq.Host = "iservices.service.example";
    httpWReq.ContentLength = data.Length;
    using (Stream stream = httpWReq.GetRequestStream()){
      Write(data, 0, data.Length);
      HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
      string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    }
                }
       }
 catch (FaultException<OrganizationServiceFault> ex){}
 Catch (Exception ez){}
        }



Enjoy,
Rami Heleg

No comments:

Post a Comment