Tuesday, 13 May 2014

plugin to call externalWebservice

 public class PushToFacebook : IPlugin
    {

        /// <summary>
        /// Standard execute method of a plugin.
        /// </summary>
        /// <param name="serviceProvider">Service Provider containing CRM endpoints</param>
        public void Execute(IServiceProvider serviceProvider)
        {
            string message = string.Empty;
            string postId = string.Empty;
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
            serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "new_post")
                {
                    if (entity.Attributes.Contains("new_message") && entity.Attributes.Contains("new_commentid"))
                    {
                        message = entity.Attributes["new_message"].ToString();
                        postId = entity.Attributes["new_commentid"].ToString();
                        this.Process(message, postId);
                    }
                    else
                    {
                        throw new Exception("The comment has not been logged ");
                    }
                }
            }
        }

        /// <summary>
        /// Method for posting back post to CRM
        /// </summary>
        /// <param name="message">Message to be posted</param>
        /// <param name="postId">Postid which is to be posted</param>
        private void Process(string message, string postId)
        {
            try
            {
                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://b3d1b7d74b504ecda951f061bff5e17c.cloudapp.net/PostToFacebookService.svc");
                PushToFacebookService.FacebookServiceClient client = new PushToFacebookService.FacebookServiceClient(myBinding, endPointAddress);
                client.SendToFacebook(postId, message);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

No comments:

Post a Comment