Dynamics 365





Tuesday, December 16, 2014

Sequence Number Generator for Custom Entity In MS CRM 2011



Sequence Number Generator for Custom Entity In MS CRM 2011
Create a custom entity to store starting number , Max number(last generated number) and prefix.
Physical Name: Auto Number , Logical Name: new_autonumber
Create the folloing Attributes:
PhysicalName : EntityLogName, Logical Name : new_EntityLogName DType :SingleLine
PhysicalName:StartNumber, Logical Name : new_ StartNumber DType :INT
PhysicalName:LastAllocatedNumber, Logical Name: new_LastAllocatedNumber DType :INT
PhysicalName:Prefix, Logical Name: new_Prefix, DType :Single Line
PhysicalName:Suffix, Logical Name: new_Suffix DType :Single Line
PhysicalName:Seperator, Logical Name: new_Seperator DType :Single Line
PhysicalName:Attribute, Logical Name: new_Attribute DType :Single Line

Once Cutsom Entity created Add the fields to form of custom entity .
It should look like below.
new_seqnumber   This filed should be there in lead  form(Create new_seqnumber Filed in lead form)
Name is on which entity you want to generate auto sequence number.
PreFix  : you can pass any value if you want to give prefix to number.
lastAllocatedNumber is max number or last generated number of lead entity.




Here is the Plugin code to generate auto seq number .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
namespace AutoSeqNumber
{
    public class GenAutoSql:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            if (context.Depth == 1 && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {

                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName == "lead")
                {
                    try
                    {
                        QueryExpression expression = new QueryExpression("new_autonumber");

                        expression.ColumnSet.AllColumns = true;

                        expression.Criteria.AddCondition("new_name", ConditionOperator.Equal, entity.LogicalName);

                        EntityCollection coll = service.RetrieveMultiple(expression);

                        foreach (Entity auto in coll.Entities)
                        {

                            if (coll != null && coll.Entities.Count > 0)
                            {

                                int startNumber = 0;

                                int number;

                                string prefix = string.Empty; ;

                                string suffix = string.Empty;

                                string seperator = string.Empty;

                                string attribute = string.Empty;

                                int lastAllocated;

                                string seqNumber = string.Empty;

                                string requestType = string.Empty;                               

                                DateTime today = DateTime.Now;

                                if (auto.Attributes.Contains("new_startnumber"))
                                {

                                    startNumber = (int)auto.Attributes["new_startnumber"];

                                }

                                if (auto.Attributes.Contains("new_lastallocatednumber"))
                                {

                                    number = (int)auto.Attributes["new_lastallocatednumber"];

                                    lastAllocated = number;

                                    lastAllocated++;

                                }

                                else
                                {

                                    number = startNumber;

                                    lastAllocated = number;

                                }

                                if (auto.Attributes.Contains("new_prefix"))
                                {

                                    prefix = auto.Attributes["new_prefix"].ToString();

                                }

                                if (auto.Attributes.Contains("new_suffix"))
                                {

                                    suffix = auto.Attributes["new_suffix"].ToString();

                                }

                                if (auto.Attributes.Contains("new_seperator"))
                                {

                                    seperator = auto.Attributes["new_seperator"].ToString();

                                }

                                if (auto.Attributes.Contains("new_startnumber"))
                                {

                                    attribute = auto.Attributes["new_attribute"].ToString();

                                }

                                if (attribute == "new_seqnumber")
                                {

                                    seqNumber = prefix + seperator + lastAllocated.ToString();

                                    entity.Attributes[attribute] = seqNumber;

                                }

                                if (attribute == "new_seqnumber")
                                {

                                    seqNumber = prefix + seperator + lastAllocated.ToString() + seperator + suffix;

                                    entity.Attributes[attribute] = seqNumber;

                                }

                                seqNumber = prefix + seperator + lastAllocated.ToString() + seperator + suffix;

                                auto.Attributes["new_lastallocatednumber"] = lastAllocated;

                                service.Update(auto);

                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidPluginExecutionException(
                           "An error occurred in the Generating Sequence Number" + ex.Message, ex);
                    }

                }
                else
                {
                    throw new InvalidPluginExecutionException(
                                       "Seq number should be on lead");
                }

            }
          

        }
    }
}


Once Pulg in has been completed register assemble .
And add step on pre-Operation.
Now create new Lead it will generate seq number .

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.