Dynamics 365





Thursday, September 18, 2014

Copy lead entity attacment to Opportunity entity - CRM 2011

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.CSharp;
using System.Data;
using System.Runtime.Serialization;
using Microsoft.Crm.Sdk.Messages;
using System.IO;

namespace CopyLeadAttachToOpp
{
    public class PluginCopyAttach:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));


            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity && context.Depth < 2)
            {
                Entity entity = context.InputParameters["Target"] as Entity;

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(new Guid?(context.UserId));


                OrganizationServiceContext orgContext = new OrganizationServiceContext(service);

               
                    if (context.MessageName.ToUpper() == "QUALIFYLEAD")
                    {

                        if (entity.LogicalName == "lead")
                        {

                            try
                            {
                               // string regardingprospect = "opportunity";


                                var Lquery = new QueryExpression("opportunity");
                                    Lquery.ColumnSet = new ColumnSet(true);
                                    Lquery.Criteria.AddCondition(new ConditionExpression("pmax_parentopportunity", ConditionOperator.Equal, entity.Id));

                                    //var Lentitys = service.RetrieveMultiple(Lquery).Entities;
                                    var Lentitys = service.Retrieve("pmax_parentopportunity", entity.Id, Lquery.ColumnSet);
                               
                               
                                    //Guid qid = new Guid();
                                    if (Lentitys!=null)
                                    {

                                        //copy notes
                                        var query = new QueryExpression("annotation");
                                        query.ColumnSet = new ColumnSet(true);
                                        query.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, entity.Id));




                                        var activities = service.RetrieveMultiple(query).Entities;
                                        //remove email activities because emails which are sent already when rating is less thn 20% giving error in below code
                                        foreach (var activity in activities)
                                        {
                                            // activity.LogicalName = activity.Attributes["objecttypecode"].ToString();
                                            //activity.Attributes.Remove("activityid");
                                            //activity.Attributes.Remove("instancetypecode");

                                            Entity entNote = (Entity)activity;



                                            //array to remove from notes record
                                            string[] strAttributesNotestoRemove = new string[] { "createdon", "createdby", "modifiedon", "modifiedby", "annotationid", "objecttypecode", "objectid" };
                                            //Clone new notes object from existing notes record
                                            Entity entNewAnnotation = CloneRecordForEntity("annotation", entNote, strAttributesNotestoRemove);
                                            //Add object id to attach this new notes to Invoice sponsor item record
                                            entNewAnnotation["objectid"] = new EntityReference("opportunity", Lentitys.Id);
                                            entNewAnnotation["objecttypecode"] = "opportunity";
                                            service.Create(entNewAnnotation);



                                        }
                                        //
                                    }
                            }
                            catch (Exception ex)
                            {
                                throw new InvalidPluginExecutionException(
                                   "An error occurred in the CopyLeadAttachToOpp.PluginCopyAttach Plug-in" + ex.Message, ex);
                            }
                        }
                    }
               
            }
        }
        private Entity CloneRecordForEntity(string targetEntityName, Entity sourceEntity, string[] strAttributestoRemove)
        {
            //Initiate target entity (cloned copy)
            Entity clonedEntity = new Entity(targetEntityName);
            //read the attributes from source entity
            AttributeCollection attributeKeys = sourceEntity.Attributes;
            //Loop through each of the key and check and add that in the target entity
            foreach (string key in attributeKeys.Keys)
            {
                //Check if key is not there in the list of removed keys
                if (Array.IndexOf(strAttributestoRemove, key) == -1)
                {
                    //add key from source in the destination
                    clonedEntity[key] = sourceEntity[key];
                } //end if checking removed attributes
            }//end foreach keys
            return clonedEntity;
        }
    }
}

No comments:

Post a Comment