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.
 


Monday, August 18, 2014

Inactivate quote usin EntityMoniker Dynamics CRM 2011.

private SetStateRequest inactiveQuote(Entity entSuspect)
        {
            //to set prospect record inactive

            SetStateRequest setState = new SetStateRequest();

            setState.EntityMoniker = new EntityReference();

            //Pass GUID of the record to be activated or Deactivated
            WinOpportunityRequest oppState = new WinOpportunityRequest();
            oppState.OpportunityClose.EntityState = 0;

            setState.EntityMoniker.Id = entSuspect.Id;

            setState.EntityMoniker.Name = "quote";

            setState.EntityMoniker.LogicalName = entSuspect.LogicalName;

            //Setting ‘State’ i.e., (0 – Active ; 1 – InActive)

            setState.State = new OptionSetValue();

            setState.State.Value = 1;

            oppState.Status = new OptionSetValue(3);

            //Setting ‘Status’ i.e., (1 – Active ; 2 – InActive)

            setState.Status = new OptionSetValue();

            setState.Status.Value = 3;


            return setState;
            //
        }

Tuesday, July 29, 2014

Generate proxy file using CrmSvcUtil.exe from command prompt


Generate proxy file using CrmSvcUtil.exe from command prompt sample.
try below command in cmd


C:\Program Files\Microsoft Dynamics CRM\Tools>CrmSvcUtil.exe /url:http://dynamics/ABCdev/XRMServices/2011/Organization.svc /domain:SP /username:murthy /password:xxxxx  /out:c:\CRMSamples\Xrm.cs /namespace:Microsoft.Crm.Sdk.Samples /serviceContextName:XrmServiceContext

Friday, April 18, 2014

CRM 2011 - Hide or Disable Button from ribbon

CRM 2011   Hide or Disable Button from ribbon

 

 Source:http://mscrmshop.blogspot.com/2011/07/step-by-step-hiding-add-existing-button.html

Here are the steps

  • Create a new solution.
  • Add the contact entity to the solution. Do not include any required components or dependent components to the solution.
  • Export the solution and unzip the solution file.
  • Open the customizations file and look for “<RibbonDiffXml>” tag.
  • Replace the <CustomActions /> with
<CustomActions>
  <HideCustomAction Location="Mscrm.SubGrid.contact.AddExistingAssoc" HideActionId="Mscrm.SubGrid.contact.AddExistingAssoc.HideAction" />
  <HideCustomAction Location="Mscrm.SubGrid.contact.AddExistingStandard" HideActionId="Mscrm.SubGrid.contact.AddExistingStandard.HideAction" />
</CustomActions>
  • Save the file.
  • Replace the customizaions.xml file in your zip solution with this file.
  • Import the solution and publish the changes.
Note: Replace the highlighted "contact” text with your entity name. It can be “opportunity” or a custom entity like “new_entity” etc.

 

Monday, January 20, 2014

Set Notification error messsage in CRM 2011


Please try below code instead of alert box it will be displayed on form.

set_Notification(2, 'source', 'Business Phone must contain 10 numbers.');

Tuesday, January 7, 2014

CRM 2011 - change Ribbon Button Name



Change button Name in ribbon - CRM 2011 dynamics.


Hi,
When we have relationship between two entities, the child entity link add to the left navigation of parent.
For example,
  • “Contacts” link add to the left navigation of “Accounts”
Contacts Associated View In Account Contacts Associated View In Account
The view we call it as “Associate View” and it contains buttons with below naming convention
  • “Add {Display name of child}” (i.e., “Add Contact” in above screen)
  • “Add Existing {Display name of child}” (i.e., “Add Existing Contact” in above screen)
To rename the “Add & Add existing” buttons below are the steps
  • Create a new solution
  • Add child entity (i.e., Contact) in above example
  • Export & Save solution in local folder
  • Extract folder and open “Customizations.XML” in Visual Studio
  • Find <RibbonDiffXml><CustomActions> node
  • Add below XML
          <CustomAction Id=”Mscrm.SubGrid.{Entity Name}.AddNewStandard.CustomAction” Location=”Mscrm.SubGrid.{Entity Name}.AddNewStandard” Sequence=”210″>
<CommandUIDefinition>
<!–New Button Id – AddNewStandard; Existing Button Id – AddExistingStandard–>
<Button Id=”Mscrm.SubGrid.{Entity Name}.AddNewStandard
Command=”Mscrm.AddNewRecordFromSubGridStandard”
Sequence=”20″
LabelText=”My Custom Text
Alt=”My Custom Text
Image16by16=”/_imgs/ribbon/NewRecord_16.png” Image32by32=”/_imgs/ribbon/newrecord32.png”
TemplateAlias=”o1″ ToolTipTitle=”Add New Contact”
ToolTipDescription=”$Resources(EntityDisplayName):Mscrm_SubGrid_EntityLogicalName_MainTab_Management_AddNewStandard_ToolTipDescription” />
</CommandUIDefinition>
</CustomAction>
  • Save, zip & Export solution