Interact Wcf Service With Microsoft Dynamics Crm Plugin


Hi ,

in my previous post I have explained how to interact WCF Services with Microsoft Dynamics CRM.
In this post I would like to explain how to invoke the Wcf services with CRM service using plugin c#.

• For calling external wcf services within our crm service, we can generate WCF Client Class similar to our early bound class generation.

Goto Visual Studio Tools –> Developer Command

• Use Svcutil.exe and map to the desired location where your client code has to get generated.

Type the following command : svcutil.exe followed by language type , Early Bound class Name.cs , Hosted Url of your WCF Application
svcutil.exe /language:cs /out:CreateLead.cs http://****:8081/Service1.svc

Generate WCF

Add the generated CreateLead.cs class in your application and the namespace reference in your plugin class file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Net;
using System.ServiceModel;
using CreateLead;  // Generated WCF Class
namespace Crm_Plugin
{
    public class WCF_Integration : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            //<snippetFollowupPlugin1>
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));
            //</snippetFollowupPlugin1>

            //<snippetFollowupPlugin2>
            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
            Entity entity = (Entity)context.InputParameters["Target"];

               // Invoke  WCF SERVICE
                BasicHttpBinding myBinding = new BasicHttpBinding();
                myBinding.Name = "BasicHttpBinding_IService1";
                myBinding.Security.Mode = BasicHttpSecurityMode.None;
                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                EndpointAddress endPointAddress = new EndpointAddress("http://******:8080/Service1.svc");

                ChannelFactory<IService1> SerFactor = new ChannelFactory<IService1>(myBinding, endPointAddress);
                IService1 chanl = SerFactor.CreateChannel();

// Passing Parameter to the Wcf Class CreateLead
string Result =chanl.CreateLead(entity.GetAttributeValue<string>("firstname").ToString(), entity.GetAttributeValue<string>("lastname").ToString(), entity.GetAttributeValue<string>("emailaddress1").ToString());
                SerFactor.Close();
            }
        }
    }
}

* Note ,
i have registered my plugin in pre create Contact Entity .
Passing [ First Name , Last Name , Email Address ] 3 parameters to out CreateLead WCF Method .

Advertisements

Invoke WCF Service Using Microsoft Dynamics Crm


Hi ,
In this post I would like to share how to config , Wcf service with Crm service
Before starting Have a look  how to interact WCF Services.

Create WCF Application .
Refer Bellow Sample Code :


IService1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
    [OperationContract]
    string CreateLead(string FirstName , string LastName , string EmailId);
}

 


Service1.cs
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class Service1 : IService1
{
    /// <summary>
    ///   username = Declaring Organization credential User Name (Online / on premis)
    ///   url = Organization Service Url
    /// </summary>

    #region Organization Credential
    OrganizationServiceProxy _oService;
    string username = "parthiban@dyn.onmicrosoft.com";
    string password = "********";
    string url = "https://dyn.api.mscrm.dynamics.com/XRMServices/2011/Organization.svc";
    #endregion

    #region Create Lead Record
    /// <summary>
    /// Create Lead Record
    /// </summary>
    /// <param name="FirstName"></param>
    /// <param name="LastName"></param>
    /// <param name="EmailId"></param>
    /// <returns>New Created Lead Guid </returns>
    public string CreateLead(string FirstName, string LastName, string EmailId)
    {

        Guid newContactId = Guid.Empty;
        //Check Weather Crm Authentication
        if (InitializeCRMService(username, password, url))
        {
            Entity LeadEntity = new Entity("lead");
            LeadEntity["firstname"] = FirstName;
            LeadEntity["lastname"] = LastName;
            LeadEntity["emailaddress1"] = EmailId;
            LeadEntity["subject"] = "Lead Created From Web Service";
            newContactId = _oService.Create(LeadEntity);

            return "New Lead Created Id : " + newContactId.ToString();
        }

        else
        {
            return "Record Could Not Be Created :" + newContactId.ToString();
        }
    }
    #endregion

    #region check for CRM Authentication Service
    /// <summary>
    /// Checking For Client Credential
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="passWord"></param>
    /// <param name="Url"></param>
    /// <returns>Bool Value Either True / False </returns>
    private bool InitializeCRMService(string userName, string passWord, string Url)
    {
        bool isSuccess = false;
        Uri organizationUrl = new Uri(Url);
        ClientCredentials credentials = new ClientCredentials();
        credentials.UserName.UserName = userName;
        credentials.UserName.Password = passWord;
        _oService = new OrganizationServiceProxy(organizationUrl, null, credentials, null);
        _oService.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
        //Validate Users Credential
        if (_oService != null)
            isSuccess = true;
        return isSuccess;
    }
    #endregion
}

Run Your Application Service1.svc

 

WCF Output Image