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;
        }
    }
}

Wednesday, September 10, 2014

Send Email using Plug in in CRM 2011 dynamics c#.net

Send Email using Plug in in CRM 2011 dynamics c#.net

 

Send Email using Plug in

This Plugin explains how to send email to user.

//send mail when ratin less than 20%
                                                Guid opprid = entity.Id;
                                                Entity Opprt = service.Retrieve("new_prospect", opprid, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
                                                Guid ownerId = ((EntityReference)Opprt.Attributes["ownerid"]).Id;
                                                Entity owner = service.Retrieve("systemuser", ownerId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
                                                String ownerName = (String)owner.Attributes["fullname"];
                                                Guid custId = ((EntityReference)Opprt.Attributes["ownerid"]).Id;
                                                String subject = "";
                                                subject = subject + "The following Prospect is Converted to Lead  with <b>Rating 10 %</b><br><br>";
                                                subject = subject + "<b>" + entity.Attributes["new_lastname"].ToString() + "   " + entity.Attributes["new_firstname"].ToString() + "</b>";

                                               // subject = subject + "<br>Kindly check/ensure availability of the required Products by " + dt + "<br><br>";

                                                Entity fromParty = new Entity("activityparty");
                                                fromParty["partyid"] = new EntityReference("systemuser", ownerId);
                                                Entity toParty = new Entity("activityparty");
                                                toParty["partyid"] = new EntityReference("systemuser", ownerId);

                                                Entity Email = new Entity("email");
                                                Email.Attributes["from"] = new Entity[] { fromParty };
                                                Email.Attributes["to"] = new Entity[] { toParty };
                                                Email.Attributes["subject"] = "Prospect to Lead with rating 10%";
                                                Email.Attributes["regardingobjectid"] = new EntityReference("new_prospect", opprid);
                                                Email.Attributes["description"] = subject;
                                                Email.Attributes["ownerid"] = new EntityReference("systemuser", ownerId);
                                               
                                                Guid EmailId = service.Create(Email);

                                                SendEmailRequest req = new SendEmailRequest();
                                                req.EmailId = EmailId;
                                                req.IssueSend = true;
                                                req.TrackingToken = "";
                                           
                                                SendEmailResponse res = (SendEmailResponse)service.Execute(req);


Here you CRM user should configure with Microsoft Outlook.

This will send email for who has logged in .
Please change code to get Manager of user or according to your requirement.