Showing posts with label Crm_Plugins. Show all posts
Showing posts with label Crm_Plugins. Show all posts

Sunday 8 December 2013

Creste Email using CRM 2011 Plug In

private void SendEmail(IOrganizationService service, Guid recieverUserId, Guid senderUserId, Guid regardingObjectId, string emailBody, string emailSubject)
{
Entity email = new Entity();
email.LogicalName = “email”;
//Set regarding object property (i.e. The entity record, which u want this email associated with)
EntityReference regardingObject = new EntityReference(“{entity_name}”, regardingObjectId);
email.Attributes.Add(“regardingobjectid”,regardingObject);
//Defining Activity Parties (starts)
EntityReference from = new EntityReference(“systemuser”, senderUserId);
EntityReference to = new EntityReference(“systemuser”,recieverUserId);
//Derive from party
Entity fromParty = new Entity(“activityparty”);
fromParty.Attributes.Add(“partyid”,from);
//Derive to party
Entity toParty = new Entity(“activityparty”);
toParty.Attributes.Add(“partyid”, to);
EntityCollection collFromParty = new EntityCollection();
collFromParty.EntityName = “systemuser”;
collFromParty.Entities.Add(fromParty);
EntityCollection collToParty = new EntityCollection();
collToParty.EntityName = “systemuser”;
collToParty.Entities.Add(toParty);
email.Attributes.Add(“from”,collFromParty);
email.Attributes.Add(“to”, collToParty);
//Defining Activity Parties (ends)
//Set subject & body properties
email.Attributes.Add(“subject”,emailSubject);
email.Attributes.Add(“description”, emailBody);
//Create email activity
Guid emailID = service.Create(email);
//Sending email
SendEmailRequest reqSendEmail = new SendEmailRequest();
reqSendEmail.EmailId = emailID;//ID of created mail
reqSendEmail.TrackingToken = “”;
reqSendEmail.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail);
}

Thursday 28 November 2013

How to get the Contact Guids from a PartyList in a Plugin?

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

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
Content = entity.GetAttributeValue<String>("subject");
Recipients = entity.GetAttributeValue<EntityCollection>("to");
for (int i = 0; i < Recipients.Entities.Count; i++)
        {
            ActivityParty ap = Recipients[i].ToEntity<ActivityParty>();
            string contactid = ap.PartyId.Id.ToString(); 
            Contact c = (Contact) service.Retrieve(Contact.EntityLogicalName,ap.PartyId.Id,new ColumnSet(new string[]{"mobilephone"}));
            string mobilephone = c.MobilePhone;
              //Do something with the mobile phone nr

}

Thursday 10 October 2013

Parsing Whole Number value while Setting in MSCRM 2011

Int i;
if (Int32.TryParse(TextBox_Employees.Text, out i))
{
 mylead["numberofemployees"] = i;
}

Get selected Option Set value label in mscrm 2011 C#

                      RetrieveAttributeRequest request = new RetrieveAttributeRequest();
                       request.EntityLogicalName = targetEntity.LogicalName;
                       request.LogicalName = optionsetLogicalName;
                       request.RetrieveAsIfPublished = true;          

                      RetrieveAttributeResponse response = (RetrieveAttributeResponse)service.Execute(request);
                       PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;

                       var query = from option in picklist.OptionSet.Options
                                   where option.Value == int.Parse(Statusvalue.ToString())
                                   select option.Label.UserLocalizedLabel.Label;
                        SselectedOptionSetlLabel = query.FirstOrDefault().ToString();

Monday 23 September 2013

Clone an Opportunity in MS CRM 2011 with Plugin by Mohammad Yusuf Ansari

Below is a Plugin to create an Opportunity Clone [Cloning opportunity products as well].It uses early bound approach.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Entities = Pes.My.Configurations.Entities;
using System.ServiceModel;
using Pes.My.Configurations.Entities;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Client;
 
namespace My.Crm.Plugins.Opportunity
{
    public class PostUpdate : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            Entities.Opportunity oppRec;
 
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
 
            // This plug-in was fired from the playback queue after the user selected to go online within Microsoft Dynamics CRM for Outlook.
            if (context.IsExecutingOffline || context.Depth > 1)
                return;
 
 
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"is Entity)
            {
 
                //Verify that the entity represents an Opportunity
                if (((Entity)context.InputParameters["Target"]).LogicalName != Pes.My.Configurations.Entities.Opportunity.EntityLogicalName || context.MessageName != "Update")
                    return;
                else
                    oppRec = ((Entity)context.InputParameters["Target"]).ToEntity<Pes.My.Configurations.Entities.Opportunity>();
            }
            else
            {
                return;
            }
 
            try
            {
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
 
 
                using (var MyContext = new MyContext(service))
                {
 
                    if (oppRec.My_IsCloned == true)
                    {
                        if (context.Depth == 1)
                        {
 
                            Entity opportunity = null;
 
                            opportunity = service.Retrieve(Entities.Opportunity.EntityLogicalName, oppRec.Id, new ColumnSet(true));
 
                            Entity cloneopportunity = new Entity();
 
                            opportunity.Attributes.Remove("opportunityid");
                            opportunity.Id = Guid.NewGuid();
 
                            cloneopportunity = opportunity;
                            Guid ClonedOppId = service.Create(cloneopportunity);
 
 
                            List<Entities.OpportunityProduct> listoppproduct = MyContext.OpportunityProductSet
                                      .Where(acp => acp.OpportunityId.Id == oppRec.Id).ToList<Entities.OpportunityProduct>();
                            foreach (OpportunityProduct objoppproduct in listoppproduct)
                            {
                                cloneOppProduct((Guid)objoppproduct.Id, ClonedOppId, service);
                            }
 
 
                        }
 
                    }
 
                }
 
 
            }
            catch (InvalidPluginExecutionException)
            {
                throw;
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
            }
 
        }
 
        private void cloneOppProduct(Guid guid, Guid Opp, IOrganizationService service)
        {
 
            Entity opportunityproduct = null;
            opportunityproduct = service.Retrieve(Entities.OpportunityProduct.EntityLogicalName, guid, new ColumnSet(true));
 
            Entity cloneopportunityproduct = new Entity();
 
            opportunityproduct.Attributes.Remove("opportunityproductid");
            opportunityproduct.Attributes.Remove("opportunityid");
            opportunityproduct.Id = Guid.NewGuid();
            opportunityproduct.Attributes["opportunityid"] = new EntityReference(Entities.Opportunity.EntityLogicalName, Opp);
            cloneopportunityproduct = opportunityproduct;
            service.Create(cloneopportunityproduct);
 
        }
    }
}



Note: I run this plugin from ribbon button "Clone Opportunity".Here I am setting Custom field "My_IsCloned " to true and saving the form using javaScript.And On post update it triggers this plugin.


Also you have to create an early bound class using CrmSvcUtil  below is an example

CrmSvcUtil.exe /out:MyEntities.cs /url:https://Mydev1.api.crm.dynamics.com/XRMServices/2011/Organization.svc /username:name@My.com /password:pass123 /namespace:Pes.My.Configurations.Entities /serviceContextName:MyContext 

Use the class generated i.e MyEntities [here] in your project and accomplish the same.

Hope this helps.

LINQ query to get all the N:N custom entity records for the above Account.



 string accountId = "CC572EC9-01E3-E211-AC62-984BE173A384";
  var customEntities = (from NtoN in makeUseOfContext.new_customentity_accountSet
                        where NtoN.accountid.Value == new Guid(accountId) && 
                        NtoN.new_customentityid != null
                         select new { 
                                    customentityid = NtoN.new_customentityid.Value 
                                   }).ToList();

C# code to create a email record in MSCRM 2011


                    Entity email = new Entity();
                    email.LogicalName = "email";

                    //Set regarding object property (i.e. The entity record, which u want this email associated with)

                    EntityReference regardingObject = new EntityReference("quote", targetEntity.Id);
                    email.Attributes.Add("regardingobjectid", regardingObject);

                    //Defining Activity Parties (starts)
                    //Derive ccparty

                  EntityReference cc1 = new EntityReference("systemuser", preparedById);
                    EntityReference cc2 = new EntityReference("systemuser", salesContactId);


                    Entity ccParty = new Entity("activityparty");
                    ccParty.Attributes.Add("partyid", cc1);
                    Entity ccParty1 = new Entity("activityparty");
                    ccParty1.Attributes.Add("partyid", cc2);

                    EntityCollection collccParty = new EntityCollection();
                    collccParty.EntityName = "systemuser";
                    collccParty.Entities.Add(ccParty);
                    collccParty.Entities.Add(ccParty1);
                    EntityCollection collToParty = new EntityCollection();
                    collToParty.EntityName = "contact";
                    collToParty.Entities.Add(toParty);
      //Derive to party
                    email.Attributes.Add("cc", collccParty);
                    Entity toParty = new Entity("activityparty");
                    EntityCollection contacts = GetContactsRelatedTOQuote(service, targetEntity.Id);
                    if (contacts.Entities.Count > 0)
                    {
                        foreach (Entity e in contacts.Entities)
                        {
                            toParty.Attributes.Add("partyid", new EntityReference("contact", e.Id));
                        }

                    }

                    email.Attributes.Add("to", collToParty);

                    //Defining Activity Parties (ends)

                    //Set subject & body properties
                    email.Attributes.Add("subject", "xxxxxx " + postMessageImage["name"].ToString());
                    email.Attributes.Add("description", "Test");

                    //Create email activity

                    Guid emailID = service.Create(email);

Calling On Demand Workflow through a Button in Ribbon (launchOnDemandWorkflow) in CRM 2011 by Nishanth Rana

l had to call  an on demand workflow through a custom button click inside the ribbon. I thought of using launchOnDemandWorkflow function.
But couldn’t really find a way of calling that function.
So thought of calling it through its url, which would be something like this

iObjType=10004
&iTotal=1
&sIds=%7b4BEBDCAF-8F66-E011-A475-00155D045711%7d%3b
&wfId=%7bF0ED25C7-5129-4297-8515-69DFFA0739FF%7d

function CallOnDemandWorkflow() {

var recordID = crmForm.ObjectId;

var url = http://server/org/_grid/cmds/dlg_runworkflow.aspx?iObjType=10004&iTotal=1&sIds={“+ recordID + “}&wfId={F0ED25C7-5129-4297-8515-69DFFA0739FF}”;
window.open(url);
}
However I keep getting some JavaScript Error.
Finally found out the correct way of doing so.
function CallOnDemandWF() {
var a = new Array(crmFormSubmit.crmFormSubmitId.value);
var sIds = crmFormSubmit.crmFormSubmitId.value+“;”;
var sEntityTypeCode = “10004″//Replace this with your entity type code
var sWorkflowId = “{F0ED25C7-5129-4297-8515-69DFFA0739FF}”//Replace this with your actual workflow ID
var iWindowPosX = 500; //Modal dialog position X
var iWindowPosY = 200; //Modal dialog position Y
var oResult = openStdDlg(prependOrgName(“/_grid/cmds/dlg_runworkflow.aspx”)+“?iObjType=” + CrmEncodeDecode.CrmUrlEncode(sEntityTypeCode) + “&iTotal=” +
CrmEncodeDecode.CrmUrlEncode(a.length) + “&wfId=” + CrmEncodeDecode.CrmUrlEncode(sWorkflowId)+ “&sIds=” + CrmEncodeDecode.CrmUrlEncode(sIds) , a, iWindowPosX, iWindowPosY);
}
Check out the thread
Final Output

Extracting the SSRS Report in PDF programmatically using Plugin or Wokflow in mscrm 2011

Extracting the Report in PDF programmatically.
Code snippet:
ReportGenerator rg = new ReportGenerator("http://crm/Reportserver/ReportExecution2005.asmx",
                new NetworkCredential("administrator", "Password", "contoso"));

            ParameterValue[] parameters = new ParameterValue[1];
            parameters[0] = new ParameterValue();
            parameters[0].Name = "P1";
            parameters[0].Value = string.Format("Select * From FilteredQuote Where QuoteId = '{0}'",
                context.PrimaryEntityId);

            byte[] reportresult = rg.Render("/contoso_mscrm/quote", FormatType.PDF, parameters);

            Entity attachment = new Entity("activitymimeattachment");
            attachment["objectid"] = Email.Get<EntityReference>(executionContext);
            attachment["objecttypecode"] = "email";
            attachment["filename"] =
            attachment["subject"] = "Quote.pdf";
            attachment["body"] = System.Convert.ToBase64String(reportresult);

Ref Links:




Tuesday 10 September 2013

MSCRM 2011 Plugin in user context to avail configured filed level security

var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
var target = new Entity("account");
target["name"] = "test 3";
target["new_secretcode"] = "1234";
var sf = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
var service = sf.CreateOrganizationService(Guid.Empty);
service.Create(target);

var service = sf.CreateOrganizationService(Guid.Empty);
To execute plugin in user context: The Create OrganizationService call that we pass Guid.Empty. Passing Guid.Empty instructs the method to give back an organization service configured to run in the context of the user


var service = sf.CreateOrganizationService(null);
To execute plugin in System context : we passed null to that method the organization service would be configured to run in the system context and the plugin would be able to update the secured field.


Thursday 5 September 2013

Retrieve OptionSet Text in CRM 2011 using C# in Plugin

Retrieve Normal(Local) Option Set Text


// Get Normal option set Text
string optionsetText = entity.FormattedValues["new_optionset"];

or

string optionsetText = entity.GetFormattedAttributeValue("new_optionset");

Retrieve Global Option Set Text

int OptionsetValue = ((Microsoft.Xrm.Sdk.OptionSetValue)entity["new_localoptionset"]).Value;
string GlobaloptionsetText= GetOptionsetText(entity, service, "new_globaloptionset", OptionsetValue );



   // Retrieves Global Option set Selected Text
        // Parameters: 1. Entity Name   2. Service  3. Global Option Set Name   4. optionset selected value
        public string GetOptionsetText(Entity entity, IOrganizationService service,string  optionsetName,int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;
            try
            {


                RetrieveOptionSetRequest retrieveOptionSetRequest =
                    new RetrieveOptionSetRequest
                    {
                        Name = optionsetName
                    };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse =
                    (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);

                // Access the retrieved OptionSetMetadata.
                OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                // Get the current options list for the retrieved attribute.
                OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
                foreach (OptionMetadata optionMetadata in optionList)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
break;
                    }
                }
            }
            catch (Exception)
            {


                throw;
            }
            return optionsetSelectedText;
        }

Tuesday 6 August 2013

Parsing MSCRM Retrieved Data values in Plugin

Entity _Account = service.Retrieve(“account”, new Guid(“XXXXX”), new ColumnSet(new string[] { “name”, “accountcategorycode”, “new_collectiondate”, “creditlimit”, “parentaccountid”, “new_executivecommission”, “new_isbilled” }));
//To fetch string value
string Name = _Account["name"].ToString();
//To fetch optionset selected value
int OptionSetValue = ((OptionSetValue)_Account["accountcategorycode"]).Value;
//To fetch date time field value
DateTime CollectionDate = ((DateTime)_Account["new_collectiondate"]).Date;
//To fetch money field value
decimal Creditlimit = ((Money)_Account["creditlimit"]).Value;
//To fetch decimal field value
decimal Executivecommission = (decimal)_Account["new_executivecommission"];
//To fetch lockup field
Guid ParentAccountID = ((EntityReference)_Account["parentaccountid"]).Id;
//To fetch Boolean field
Boolean IsBilled=(Boolean)_Account["new_isbilled"];

BY Mahendarpal

Tuesday 26 March 2013

MSCRM  Fetch XML 5000 Records Limitation:


Have you ever tried to write a code which will get you all records from a specific entity? It's harder then you think it is! Everybody who is a bit aware of the CRM SDK thinks it should be a fetch statement like this:

<fetch mapping='logical'><entity name='account'><attribute name='accountid'/></entity>

WRONG!
This would only give you the first 5000 records in the database! It is written down in the SDK with small letters, but it could drive you crazy..

There are two solutions for this issue.
1) Add a registery setting to specify not to implement MaxRowsPerPage
2) Modify the fetch statement and merge several results

Here are the details for each solution
1st solution
Search in the SDK for the word "TurnOffFetchThrottling". You should add this as DWORD registery setting to HKLM\Software\Microsoft\MSCRM. Set the value to 1. You will now not have the 5000 records limit.

2nd solution
Modify your fetch statement to include paging and count numbers. Store all the data in an DataSet and perform that series of code over and over again as long as there is data coming.

Here's the script you should use to get all accountid's (for clarity and the ease of use I have added a function called "FetchDataSet").


private DataSet FetchAllAccountIds(){
int i=1;
bool bFinished = false;
DataSet dsAllData = new DataSet();
while (bFinished == false)
{
StringBuilder sbFetch = new StringBuilder();
sbFetch.AppendFormat("<fetch mapping='logical' page='{0}' count='5000'>", i);
sbFetch.Append("<entity name='account'>");
sbFetch.Append("<attribute name='accountid'/>");
sbFetch.Append("<attribute name='new_12_accountid'/>");
sbFetch.Append("</entity>");
sbFetch.Append("</fetch>");
DataSet dsTempResult = FetchDataSet(sbFetch.ToString());
dsAllData.Merge(dsTempResult);
if (dsTempResult.Tables[0].Rows[0]["morerecords"].ToString() == "0")
{
bFinished = true;
}
else
{
i++;
}
}
return dsAllData;
}

private DataSet FetchDataSet(string fetchXml)
{
string strResult = service.Fetch(fetchXml);
DataSet ds = new DataSet();
System.IO.StringReader reader = new System.IO.StringReader(strResult);
ds.ReadXml(reader);
return ds;
}