Quantcast
Channel: Microsoft Dynamics CRM Forum - Recent Threads
Viewing all articles
Browse latest Browse all 46379

Error in custom work flow: "The given key was not present in the dictionary".

$
0
0

Hi all 

I am created 3 records in my CRM as shown below

When I trigger my first created record which is "test" from the button. It will work fine. But when I trigger my second or third created record Test 1 or Lead Test from the button. It will giving me following error

My button code:

function CreateList() {
debugger;
var _return = window.confirm('Are you want to execute workflow.');

if (_return) {
var url = Xrm.Page.context.getServerUrl();
var entityId = Xrm.Page.data.entity.getId();
var workflowId = '214AB652-6AB4-4EE6-8891-ED3AD885FD5B'//;getWorkflowId();
var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
url = url + OrgServicePath;
var request;
request = "<s:Envelope xmlns:s=\"schemas.xmlsoap.org/.../envelope\">" +
"<s:Body>" +
"<Execute xmlns=\"schemas.microsoft.com/.../Services\" xmlns:i=\"www.w3.org/.../XMLSchema-instance\">" +
"<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"schemas.microsoft.com/.../Contracts\" xmlns:b=\"schemas.microsoft.com/.../Contracts\">" +
"<a:Parameters xmlns:c=\"schemas.datacontract.org/.../System.Collections.Generic\">" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>EntityId</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\"schemas.microsoft.com/.../Serialization\">" + entityId + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>WorkflowId</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\"schemas.microsoft.com/.../Serialization\">" + workflowId + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"</a:Parameters>" +
"<a:RequestId i:nil=\"true\" />" +
"<a:RequestName>ExecuteWorkflow</a:RequestName>" +
"</request>" +
"</Execute>" +
"</s:Body>" +
"</s:Envelope>";

var req = new XMLHttpRequest();
req.open("POST", url, true)
// Responses will return XML. It isn't possible to return JSON.
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "schemas.microsoft.com/.../Execute");
req.onreadystatechange = function () { assignResponse(req); };
req.send(request);
}

}

function assignResponse(req) {
if (req.readyState == 4) {
if (req.status == 200) {
alert('successfully executed the workflow');
}
}
}

My custom work flow activity code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;// use for web exception
using System.IO; // use for StreamReader
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System.Activities;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;

namespace CreateListMembers
{
public class ListMembers : CodeActivity
{
protected override void Execute(CodeActivityContext context)
{

string dataCenter = "14";
string apiKey = "abaff98b952ca886a92e5a";
string response = "";
ITracingService tracingService = context.GetExtension<ITracingService>();
IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);
// Retrieve all accounts owned by the user with read access rights to the accounts and
// where the last name of the user is not Cannon.
Guid MailChimpId = workflowContext.PrimaryEntityId;

string MailChimpQuery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
" <entity name='aw_mailchimp'>" +
" <attribute name='aw_mailchimpid' />" +
" <attribute name='aw_listid' />" +
" <order attribute='aw_listid' descending='false' />" +
" <filter type='and'>" +
" <condition attribute='aw_mailchimpid' operator='eq' uiname='test' uitype='aw_mailchimp' value='" + MailChimpId + "' />" +
" </filter>" +
" <link-entity name='list' from='aw_mailchimmarkettinglistid' to='aw_mailchimpid' alias='ag'></link-entity>" +
" </entity>" +
"</fetch>";

EntityCollection result = service.RetrieveMultiple(new FetchExpression(MailChimpQuery));

foreach (var columnsList in result.Entities)
{
string mailChimpListId = columnsList.Attributes["aw_listid"].ToString();
var aw_mailchimpid = columnsList.Attributes["aw_mailchimpid"];

string MarketingListQuery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
" <entity name='list'>" +
" <attribute name='createdfromcode' />" +
" <attribute name='listid' />" +
" <attribute name='aw_mailchimmarkettinglistid' />" +
" <order attribute='createdfromcode' descending='true' />" +
" <link-entity name='aw_mailchimp' from='aw_mailchimpid' to='aw_mailchimmarkettinglistid' alias='ac'>" +
" <filter type='and'>" +
" <condition attribute='aw_mailchimpid' operator='eq' uiname='test' uitype='aw_mailchimp' value='" + MailChimpId + "' />" +
" </filter>" +
" </link-entity>" +
" </entity>" +
"</fetch>";

EntityCollection MarketingListresult = service.RetrieveMultiple(new FetchExpression(MarketingListQuery));

foreach (var ColumnsMarketingList in MarketingListresult.Entities)
{
string MarketingListMemberType = ColumnsMarketingList.FormattedValues["createdfromcode"];

if (MarketingListMemberType == "Lead")
{
int MemberType = 4;
string LeadMembersQuery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
" <entity name='lead'>" +
" <attribute name='leadid' />" +
" <attribute name='lastname' />" +
" <attribute name='firstname' />" +
" <attribute name='emailaddress1' />" +
" <order attribute='lastname' descending='false' />" +
" <link-entity name='listmember' from='entityid' to='leadid' visible='false' intersect='true'>" +
" <link-entity name='list' from='listid' to='listid' alias='ay'>" +
" <filter type='and'>" +
" <condition attribute='createdfromcode' operator='eq' value='" + MemberType + "' />" +
" </filter>" +
" <link-entity name='aw_mailchimp' from='aw_mailchimpid' to='aw_mailchimmarkettinglistid' alias='az'>" +
" <filter type='and'>" +
" <condition attribute='aw_mailchimpid' operator='eq' uiname='test' uitype='aw_mailchimp' value='" + MailChimpId + "' />" +
" </filter>" +
" </link-entity>" +
" </link-entity>" +
" </link-entity>" +
" </entity>" +
"</fetch>";

EntityCollection LeadMemberResult = service.RetrieveMultiple(new FetchExpression(LeadMembersQuery));
foreach (var ColumnsLeadMembers in LeadMemberResult.Entities)
{
string emailAddress = ColumnsLeadMembers.Attributes["emailaddress1"].ToString();

var sampleListMember = JsonConvert.SerializeObject(
new
{
email_address = emailAddress,
merge_fields =
new
{
FNAME = ColumnsLeadMembers.Attributes["firstname"],
LNAME = ColumnsLeadMembers.Attributes["lastname"]
},
status_if_new = "subscribed"
});

var hashedEmailAddress = string.IsNullOrEmpty(emailAddress) ? "" : CalculateMD5Hash(emailAddress.ToLower());
var urii = string.Format("https://{0}.api.mailchimp.com/3.0/lists/{1}/members/{2}", dataCenter, mailChimpListId, hashedEmailAddress);
try
{
using (var webClient = new WebClient())
{
webClient.Headers.Add("Accept", "application/json");
webClient.Headers.Add("Authorization", "apikey " + apiKey);

response = webClient.UploadString(urii, "PUT", sampleListMember);
//Console.ReadLine();
}
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
}

}
}
}
private static string CalculateMD5Hash(string input)
{
// Step 1, calculate MD5 hash from input.
var md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);

// Step 2, convert byte array to hex string.
var sb = new StringBuilder();
foreach (var @byte in hash)
{
sb.Append(@byte.ToString("X2"));
}
return sb.ToString();
}
}
}

Please tell me. What is wrong here? Please....

Thank You


Viewing all articles
Browse latest Browse all 46379

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>