serving the solutions day and night

Pages

Wednesday, April 17, 2013

CRM Plugin Code - Add/Update Entity, Connect WebService, Update Database

//Update Same Entity, Other entity, create new record in other entity  and connect to WebService
//Update to database  and
//Webservice update to database

using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;
using System.Xml;
using System.Net;
using GCEntity = CRMEnt.Entities;
using System.Text;
using System.ServiceModel;



namespace _CRMFYPlugin
{
    public class DNSPlugin : IPlugin
    {
        String WCFServiceURL = "";

        enum FoodCode
        {
            Act = 810520000,
            InAct = 810520001,
            Can = 810520002
        };

        public void Execute(IServiceProvider isProvider)
        {
            IPluginExecutionContext peContext = (IPluginExecutionContext)isProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory osFactory = (IOrganizationServiceFactory)isProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService oService = osFactory.CreateOrganizationService(peContext.UserId);

            //Extract the tracing service
            ITracingService itService = (ITracingService)isProvider.GetService(typeof(ITracingService));
            if (itService == null)
                throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");

            itService.Trace("DNS CRM Plugin has started..");
            itService.Trace("peContext.Depth " + peContext.Depth);
            //throw new InvalidPluginExecutionException("Plug-in Moved FROM CRM TO DNS :) ");

            //avoid infinite loop - updating same entity
            if (peContext.Depth > 1) return;
            String preVRSR = "", preVRSS = "", srReason = "", srCode = "", sFoodID = "", modifiedon = "";

            Entity eTarget, ePreImage, ePostImage;
            String logicalName = "";

            try
            {
//Read Pre Image values
                if (peContext.PreEntityImages.Contains("PrePostImageUpdate") && peContext.PreEntityImages["PrePostImageUpdate"] is Entity)
                {
                    ePreImage = (Entity)peContext.PreEntityImages["PrePostImageUpdate"];
                    preVRSS = GetOSetAttributeValue(ePreImage, GCEntity.Contact.AttrRCode);
                }

                // Check if the input parameters property bag contains a target
                // of the create operation and that target is of type Entity.
                if (peContext.InputParameters.Contains("Target") && peContext.InputParameters["Target"] is Entity)
                {
                    // Obtain the target business entity from the input parameters.
                    eTarget = (Entity)peContext.InputParameters["Target"];
                    logicalName = eTarget.LogicalName;
                    // Verify that the entity represents a Contact.
                    if (eTarget.LogicalName != "Contact") { return; }

//Read Post Image values
                    if (peContext.PostEntityImages.Contains("PrePostImageUpdate") && peContext.PostEntityImages["PrePostImageUpdate"] is Entity)
                    {
                        ePostImage = (Entity)peContext.PostEntityImages["PrePostImageUpdate"];
                        modifiedon = GetAttributeValue(ePostImage, GCEntity.Contact.AttrModifiedOn);

                        sFoodID = GetAttributeValue(ePostImage, GCEntity.Contact.AttrDNSFoodID);
                        srCode = GetOSetAttributeValue(ePostImage, GCEntity.Contact.AttrRCode);

                        string linkid = GetAttributeValue(ePostImage, GCEntity.Contact.AttrFoodLinkId);

                       
//Update same entity
//it is working for looping
                        var ContactUpdate = new GCEntity.Contact { Id = eTarget.Id, dns_laDate = DateTime.Parse(modifiedon) };
                        oService.Update(ContactUpdate);

                        UpdateFoodLink(oService, modifiedon, eTarget.Id, Int32.Parse(linkid), srReason);

                        StringBuilder sXML = new StringBuilder();
                        sXML.Append("<crm><una>" + GetLoginID(oService, peContext.UserId) + "</una>");
                        sXML.Append("<cdt>" + modifiedon + "</cdt>");
                        sXML.Append("<code>" + srCode + "</code>");
                        sXML.Append("<vids><id>" + sFoodID + "</id></vids></crm>");
                        WCFService(sXML.ToString());
                      
                      
                        
//Database Connection Part
/*itService.Trace("Database Start");
            itService.Trace("Database Start");
            StoredProcedure spList = new StoredProcedure("dbo.uspCRMDNSUpdateXML", sCon);

            spList.AddIn("@xml", sXML);
            spList.IUD();
            itService.Trace("Database End");*/
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteErrorLog("_CRMFYPlugin", ex.Message, this.GetType().ToString(), ex.StackTrace, ex.InnerException, new GCEntity.XrmServiceContext(oService));
            }
        }

//Get Attribute and Optionset value
        private string GetOSetAttributeValue(Entity eImage, String attName)
        {
            string attValue = "";
            if (eImage.Attributes.Contains(attName))
            {
                OptionSetValue osvValue = eImage.Attributes[attName] as OptionSetValue;
                if (osvValue != null)
                    attValue = osvValue.Value.ToString();
            }
            return attValue;
        }

        private string GetAttributeValue(Entity eImage, String attName)
        {
            string attValue = "";
            if (eImage.Attributes.Contains(attName))
            {
                attValue = eImage.Attributes[attName].ToString();
            }
            return attValue;
        }

//Read plugin secure and unsecure configuration
        public DNSPlugin(string unsecureConfig, string secureConfig)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(unsecureConfig);
            WCFServiceURL = PluginConfiguration.GetConfigDataString(doc, "WCFServiceURL");

            /*<Settings>
            <setting name="WCFServiceURL"><value>http://URL:1111/FolderName/ServiceName.svc</value></setting>
            </Settings>*/

        }

//CRM User Login ID
        private string GetLoginID(IOrganizationService orgService, Guid lid)
        {
            //LDAP User id      
            String domainName = String.Empty;
            GCEntity.XrmServiceContext crm = new GCEntity.XrmServiceContext(orgService);
            domainName = crm.SystemUserSet
                             .Where(vms => (vms.SystemUserId == lid))
                             .Select(vms => vms.DomainName).SingleOrDefault().ToString();
            return domainName;
        }

//Call Web Service
        private void WCFService(string xml)
        {
            BasicHttpBinding bhBinding = new BasicHttpBinding();
            bhBinding.Name = "BasicCRMDNSOperations";
            bhBinding.Security.Mode = BasicHttpSecurityMode.None;
            bhBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            bhBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            bhBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            EndpointAddress eAddress = new EndpointAddress(WCFServiceURL);

            FYServiceReference.CRMSVRSOperationsClient csoClient = new FYServiceReference.CRMSVRSOperationsClient(bhBinding, eAddress);
            csoClient.UpdateRegisterStatus(xml);
        }

//Update Food Link Entity
        private void UpdateFoodLink(IOrganizationService orgService, string modifiedon, Guid cid, int linkid, string srReason)
        {
            GCEntity.dns_foodlinks vm = new GCEntity.dns_foodlinks();
            vm.dns_rdate = DateTime.Parse(modifiedon);
            vm.dns_linktype = new OptionSetValue(12345);

            //Does food link already exist?
            GCEntity.XrmServiceContext crm = new GCEntity.XrmServiceContext(orgService);
            String vmid = crm.dns_foodlinksSet
                    .Where(vms => (vms.dns_dnslinkid == linkid) && (vms.dns_foodid == new EntityReference("Contact", cid))
                        && (vms.dns_name == "Fat Food"))
                    .Select(vms => vms.dns_foodlinksId).SingleOrDefault().ToString();

            if (vmid.Length > 0)
            {
                vm.dns_foodlinksId = new Guid(vmid);
                orgService.Update(vm);
            }
        }
    }

//Parse Plugin Configuration
    class PluginConfiguration
    {
        private static string GetValueNode(XmlDocument doc, string key)
        {
            XmlNode node = doc.SelectSingleNode(String.Format("Settings/setting[@name='{0}']", key));
            if (node != null)
            {
                return node.SelectSingleNode("value").InnerText;
            }
            return string.Empty;
        }

        public static Guid GetConfigDataGuid(XmlDocument doc, string label)
        {
            string tempString = GetValueNode(doc, label);
            if (tempString != string.Empty)
            {
                return new Guid(tempString);
            }
            return Guid.Empty;
        }

        public static bool GetConfigDataBool(XmlDocument doc, string label)
        {
            bool retVar;
            if (bool.TryParse(GetValueNode(doc, label), out retVar))
            {
                return retVar;
            }
            else
            {
                return false;
            }
        }

        public static int GetConfigDataInt(XmlDocument doc, string label)
        {
            int retVar;
            if (int.TryParse(GetValueNode(doc, label), out retVar))
            {
                return retVar;
            }
            else
            {
                return -1;
            }
        }

        public static string GetConfigDataString(XmlDocument doc, string label)
        {
            return GetValueNode(doc, label);
        }
    }

//Update Log Error
    class ErrorLog
    {
        public static void WriteErrorLog(Exception ex, GCEntity.XrmServiceContext peContext)
        {
            if (ex.InnerException != null)
                CreateLogRecord("", ex.Message, "", ex.StackTrace, ex.InnerException.ToString(), peContext);
            else
                CreateLogRecord("", ex.Message, "", ex.StackTrace, "", peContext);

        }
        public static void WriteErrorLog(string Source, string Message, string Application, string StackStrace, string InnerException, GCEntity.XrmServiceContext peContext)
        {
            CreateLogRecord(Source, Message, Application, StackStrace, InnerException, peContext);
        }

        public static void WriteErrorLog(string Source, string Message, string Application, string StackStrace, Exception InnerException, GCEntity.XrmServiceContext peContext)
        {
            if (InnerException != null)
                CreateLogRecord(Source, Message, Application, StackStrace, InnerException.ToString(), peContext);
            else
                CreateLogRecord(Source, Message, Application, StackStrace, "", peContext);

        }

        private static void CreateLogRecord(string Source, string Message, string Application, string StackStrace, string InnerException, GCEntity.XrmServiceContext peContext)
        {
            GCEntity.dns_errorlog ErrorLog = new GCEntity.dns_errorlog();
            ErrorLog.dns_ApplicationName = Application;
            ErrorLog.dns_Message =
            ErrorLog.dns_name = Message;
            ErrorLog.dns_StackTrace = StackStrace;
            ErrorLog.dns_InnerException = InnerException;
            peContext.AddObject(ErrorLog);
            peContext.SaveChanges();
        }
    }
}

//Entity Class Extend
//CRM Dynamics 2011 Code Generation Tool
namespace CRMEnt.Entities
{
    public partial class Contact : Microsoft.Xrm.Sdk.Entity
    {
        public const string AttrRCode = "dns_foodcode";
        public const string AttrModifiedOn = "modifiedon";
        public const string AttrDNSFoodID = "dns_foodID";
        public const string AttrFoodLinkId = "dns_linkid";

    }
}


http://msdn.microsoft.com/en-us/library/gg695782.aspx

No comments: