Search This Blog

Showing posts with label CRM Plugin. Show all posts
Showing posts with label CRM Plugin. Show all posts

Tuesday, January 2, 2018

Create a child record by copying mapping fields data from Parent – Using CRM SDK

Create a child record by copying mapping fields data from Parent – Using CRM SDK


InitializeFromRequest initialize = new InitializeFromRequest();

// Set the target entity (i.e.,Contact)
initialize.TargetEntityName = “contact”;

// Create the EntityMoniker of Source (i.e.,Account)
initialize.EntityMoniker = new EntityReference(“account”, new Guid(“D4CBEE74-B5E3-E611-8109-C4346BDD8041”));

// Execute the request
InitializeFromResponse initialized = (InitializeFromResponse)orgService.Execute(initialize);

// Read Intitialized entity (i.e.,Contact with copied attributes from Account)
if (initialized.Entity != null)
{
// Get entContact from the response
Entity entContact = initialized.Entity;

// Set the additional attributes of the Contact
entContact.Attributes.Add(“firstname”, “Rajeev”);
entContact.Attributes.Add(“lastname”, “Pentyala”);

// Create a new contact
orgService.Create(entContact);

Thanks to Rajeev, please find URL below to the original post

Friday, October 6, 2017

Dynamically add Embeded/attach image in Email body in Dynamics CRM

IS it possible to Embeded/attach image in Email body in Dynamics CRM 

Embeded image in email body:

To add dynamically image in the email, usually we write code to create email.

There are three ways our image will add in the CRM

  • Public images hosted in external website
  • Webresource
  • Notes( add through attachment)

The below code is for "Public images hosted in external website" and "Webresource"
//Uploaded image in the Webresource .
string webresource = "<html> <img  src='~/WebResources/new_image'  width='205' height='150'></html>";

//published Image Url Link
string crmModule = "<html> <img  src='http://images.all-free-download.com/images/graphiclarge/beautiful_nature_landscape_05_hd_picture_166223.jpg'  width='150' height='150'></html>";


 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//CRM SDK Namespace
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;

namespace Sample
{
    public class Email : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context =
            (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

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

                Entity Lead = (Entity)context.InputParameters["Target"];
                string Emailid = Lead.GetAttributeValue<string>("emailaddress1");
                string Name = Lead.GetAttributeValue<string>("lastname");

                //From Current User
                Entity from = new Entity("activityparty");
                from["partyid"] = new EntityReference("systemuser", context.UserId);

                
                Entity to = new Entity("activityparty");
                to["partyid"] = new EntityReference("lead", Lead.Id);

                //Uploaded Crm webresource Url.
                string webresource = "<html> <img  src='~/WebResources/new_image'  width='205' height='150'></html>";

                //published Image Url Link

                string crmModule = "<html> <img  src='http://images.all-free-download.com/images/graphiclarge/beautiful_nature_landscape_05_hd_picture_166223.jpg'  width='150' height='150'></html>";

                //Hyperlink (or) Re-Direct Url link
                string Hyper = String.Format("<a href='https://google.com/'> Click Here</a>");

                //Create Email
                Entity Email = new Entity("email");
                Email["from"] = new Entity[] { from };
                Email["to"] = new Entity[] { to };
                Email["subject"] = "welcome Mr : " + Name;
                Email["description"] = "<h3> Dear  " + Name + "</h3>" + "<br/>" + "Microsoft Dynamics CRM 365 Module" + "<br/>" 
                    + crmModule + "<br/>" +  Hyper + "<br/>" + webresource;

                //SendEmailRequest
                Guid _emailId = service.Create(Email);
                SendEmailRequest reqSendEmail = new SendEmailRequest();
                reqSendEmail.EmailId = _emailId;
                reqSendEmail.TrackingToken = "";
                reqSendEmail.IssueSend = true;
                SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail);

            }
        }
    }
}



The below code is for "Notes"
string crmModule = "<html> <img src='data: image/jpeg; base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw /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xTsMwEIbpIzDA6FaMMPYJkDKzVYU + QFeEGPIKfYU8AETkCYI6wANkZQwIKRNDB1hA0Jrf0rk6WXZ8BvWkb4kv99vn89kDrfVexBSYgVNwDA7AN + jAK3gEd + AlGMGIBFDgFvzouK3JV / lihQTOwLtOtw9wIRG5pJn91Tbgqk9kSk7GViADrTD4HCyZ0NQnomi51sb0fUyCMQEbp2WpU67IjfNjwcYyoUDhjJVcZBjYBy40j4wXgaobWoe8Z6Y80CJBwFpunepIzt2AUgFjtXXshNXjVmMh + K + zzp / CMs0CqeuzrxSRpbOKfdCkiMTS1VBQ41uxMyQR2qbrXiiwYN3ACh1FDmsdK2Eu4J6Tlo31dYVtCY88h5ELZIJJ + IRMzBHfyJINrigNkt5VsRiub9nXICdsYyVd2NcVvA3ScE5t2rb5JuEeyZnAhmLt9NK63vX1O5Pe8XaPSuGq1uTrfUgMEp9EJ + CQvr + BJ / AAKvAcCiAR + bf9CjAAluzmdX4AEIIAAAAASUVORK5CYII ='></html>";


Usually this code works in normal page but here image is not embedded with email after send. It says harmful in the email.

When I check with how inserting signature in the email works in the CRM. I have checked through sent email description column through web API and found they URL in the image tag

Check the selected item








Wednesday, August 9, 2017

Date Time value in Plugin

In the plugin values are retrieved from CRM are in "UTC" format.

Value set in the plugin or console application are based on the date time property. If the date time property is not set as 
"UTC" then values converted as UTC and saved in the database.

If  the date time property is set as "UTC" then it will save as "UTC".



Thursday, December 22, 2016

Plugin Message in Dynamics CRM

Plugin Message in Dynamics CRM




Message

Description

Create

This message will trigger when-ever primary entity record is created

Update

This message will trigger when-ever primary entity record is updated

Retrieve

This message will trigger when-ever primary entity record is retrieve( entity form open).

Eg: In the Active account grid, double click any one of the record this message will trigger.

Retrieve Multiple

This message will trigger when-ever primary entity records are viewed from grid.

Publish All customization

This message will trigger when-ever you click "PublishAll"

Publish

This message will trigger when-ever you click "Publish" on webresource and entity form.

Grant Access

This message will trigger when-ever record is shared 

Revoke Access

This message will trigger when-ever record is unshared

AddMember
This message will trigger and primary entity is "list" when-ever add member in the marketing  list through UI.

RemoveMember

This message will trigger and primary entity is "list"  
when-ever remove/delete member in the marketing
  list through UI.

AddListMember

This message will trigger and primary entity is "list" when-ever add member in the marketing  list through AddListMembersListRequest class(console application.

AddItem

This message will trigger whenever you add marketing list in the campaign activity
Remove Item

This message will trigger whenever you add marketing list in the campaign activity







Thursday, December 15, 2016

Pass parameters to Plugin Using Secure or Unsecure Configuration Using Plugin Registration Tool in MS CRM

Pass parameters to Plugin Using Secure or Unsecure Configuration to Plugin:
When you start developing plugins, you often need an input parameter or a configuration for the plugin execution which can be easily updated without having to re-compile and/or re-register the plugin.
For example , i want to read some of the data which may change every time. Rather than creating the custom entity to read the Configuration kind of thing better to use this method to read the Parameters.
Use the plugin step “Configuration”
When you register a plugin step, there is a field where you can specify some configuration parameters for the plugin execution as below:Image
Then in the Constructor of your plugin class you will get the configuration value which you can use later in the Execute method:
Image2

In the Quickwatch you can watch the total configuration as follows:
Image1

have a glance below for plugin code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using System.Xml;
namespace ReadPluginConfgInPlugins
{
public class PluginConfg : IPlugin
{
private readonly string _unsecureString;
private readonly string _secureString;
public PluginConfg(string unsecureString, string secureString)
{
if (String.IsNullOrWhiteSpace(unsecureString) || String.IsNullOrWhiteSpace(secureString))
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(unsecureString);
Guid DefaultQueueGuid = PluginConfiguration.GetConfigDataGuid(doc, “Contact Guid”);
string ContactFullName = PluginConfiguration.GetConfigDataString(doc, “Full Name”);
int MobileNumber = PluginConfiguration.GetConfigDataInt(doc, “Mobile Number”);
bool Gender = PluginConfiguration.GetConfigDataBool(doc, “Gender 0 refer to Male”);
}
catch (Exception ex)
{
throw new Exception(“SoapException” + ex.Message + “########” + ex.StackTrace + “$$$$Inner Exception” + ex.InnerException);
}
}
}
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// For this sample, execute the plug-in code only while the client is online.
tracingService.Trace(“AdvancedPlugin: Verifying the client is not offline.”);
if (context.IsExecutingOffline || context.IsOfflinePlayback)
return;
// The InputParameters collection contains all the data passed
// in the message request.
if (context.InputParameters.Contains(“Target”) &&
context.InputParameters[“Target”] is Entity)
{
Entity entity = (Entity)context.InputParameters[“Target”];
}
}
}
}
For this approach also have a Pros and Cons.
PROS:
  • The step configuration is solution-aware so it will be automatically transported with the plugin step.
CONS:
  • You need to use the plugin registration tool or another application to update the step configuration.
  • The configuration is step-specific so you have to provide it and/or update it for every step even if the value is the same for all the steps (the configuration is on each step instead of the assembly or plugin type).
  • the configuration is just an attribute of the plugin step so you cannot control privileges on the configuration independently from privileges on plugin step entity.
*. Use the plugin step “Secure Configuration”
This is similar to the step Configuration except that the configuration data is stored in a separate entity which can be secured.
PROS:
  • The configuration data can be secured as any other entity using the CRM security model. This is useful when the configuration contains sensitive information such as passwords.
CONS:
  • Secure configuration is not solution aware so you will need to configure it for each environment.
  • You need to use the plugin registration tool or another application to update the step configuration.
  • The configuration is step-specific so you have to provide it and/or update it for every step even if the value is the same for all the steps (the configuration is on each step instead of the assembly or plugin type).
*. Use a Web Resource
You can store configuration information in web resources, for example you might have some XML configuration stored in a web resource and have your plugin read the web resource each time it executes.
PROS:
  • Web resources are solution aware and the GUID is preserved across environments so you can hardcode the web resource GUID in your plugin code. You can transport the web resource and the plugin in the same solution.
  • Can be easily updated using the CRM UI.
CONS:
  • You cannot secure the configuration since it depends on the web resource access privileges and most users will need at least read access to web resources.
Hope this may help you.

Thanks to the below site
https://srmscrm.wordpress.com/category/ms-crm-2011/ms-crm-2011-plugins/

Retrieve more than 5000 record in Query expression or Limit number of result record in query expression

 https://msdn.microsoft.com/en-us/library/gg327917.aspx


// Query using the paging cookie.
// Define the paging attributes.
// The number of records per page to retrieve.
int queryCount = 3;

// Initialize the page number.
int pageNumber = 1;

// Initialize the number of records.
int recordCount = 0;

// Define the condition expression for retrieving records.
ConditionExpression pagecondition = new ConditionExpression();
pagecondition.AttributeName = "parentaccountid";
pagecondition.Operator = ConditionOperator.Equal;
pagecondition.Values.Add(_parentAccountId);

// Define the order expression to retrieve the records.
OrderExpression order = new OrderExpression();
order.AttributeName = "name";
order.OrderType = OrderType.Ascending;

// Create the query expression and add condition.
QueryExpression pagequery = new QueryExpression();
pagequery.EntityName = "account";
pagequery.Criteria.AddCondition(pagecondition);
pagequery.Orders.Add(order);
pagequery.ColumnSet.AddColumns("name", "emailaddress1");                   

// Assign the pageinfo properties to the query expression.
pagequery.PageInfo = new PagingInfo();
pagequery.PageInfo.Count = queryCount;
pagequery.PageInfo.PageNumber = pageNumber;

// The current paging cookie. When retrieving the first page, 
// pagingCookie should be null.
pagequery.PageInfo.PagingCookie = null;
Console.WriteLine("Retrieving sample account records in pages...\n");
Console.WriteLine("#\tAccount Name\t\tEmail Address"); 

while (true)
{
    // Retrieve the page.
    EntityCollection results = _serviceProxy.RetrieveMultiple(pagequery);
    if (results.Entities != null)
    {
        // Retrieve all records from the result set.
        foreach (Account acct in results.Entities)
        {
            Console.WriteLine("{0}.\t{1}\t{2}", ++recordCount, acct.Name,
                               acct.EMailAddress1);
        }
    }

    // Check for more records, if it returns true.
    if (results.MoreRecords)
    {
        Console.WriteLine("\n****************\nPage number {0}\n****************", pagequery.PageInfo.PageNumber);
        Console.WriteLine("#\tAccount Name\t\tEmail Address");

        // Increment the page number to retrieve the next page.
        pagequery.PageInfo.PageNumber++;

        // Set the paging cookie to the paging cookie returned from current results.
        pagequery.PageInfo.PagingCookie = results.PagingCookie;
    }
    else
    {
        // If no more records are in the result nodes, exit the loop.
        break;
    }
}

Wednesday, March 16, 2016

Executing Messages in a Single Transaction in Dynamics CRM 2015

Executing Messages in a Single Transaction in Dynamics CRM 2015
In CRM 2015, you can now execute multiple CRM requests in a single transaction. This gives developers the ability to easily rollback or cancel transactions if one of the CRM requests within the transaction fail.

We can now use the "ExecuteTransactionRequest" message which will automatically rollback the entire transaction if any of the associated requests fail.

Example:
We are going to create a record in three different entity.

1.Create a instance of sales order,invoice and email
2.Form a create request
{
{
{
{
{
{
{
{
}
}
}
{
}
{
 I have created a plugin which will force the Invoice to fail during creation, so we can see what happens.
The entire transaction rollback no record is created. 

Monday, January 4, 2016

Guid conversion in plugin


If you have any doubt in the post please post comments. I will try to solve your problem.

Guid objCarrierId = new Guid();
 string strValue = (string)objEntity.Attributes["new_carrierid"];                            
  Guid.TryParse(strValue, out objCarrierId);