Advertisement
Guest User

Untitled

a guest
Dec 1st, 2014
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.39 KB | None | 0 0
  1. // <copyright file="Plugin.cs" company="">
  2. // Copyright (c) 2014 All Rights Reserved
  3. // </copyright>
  4. // <author></author>
  5. // <date>11/20/2014 2:09:49 PM</date>
  6. // <summary>Implements the Plugin Workflow Activity.</summary>
  7. // <auto-generated>
  8. // This code was generated by a tool.
  9. // Runtime Version:4.0.30319.1
  10. // </auto-generated>
  11.  
  12. //http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addlistmemberslistrequest.aspx
  13. //http://gonzaloruizcrm.blogspot.com/2012/07/triggering-plugins-workflows-when.html
  14. //http://mileyja.blogspot.com/2011/11/add-multiple-entities-members-to.html
  15. //http://thecrmclub.blogspot.com/2013/08/How-to-programmatically-retrieve-Marketing-List-from-inside-Plugin-Dynamics-CRM.html
  16. //http://nishantrana.me/2012/08/18/sample-code-to-retrieve-all-the-members-of-a-static-marketing-list-in-crm-2011/
  17. //http://msdn.microsoft.com/en-us/library/hh372953.aspx
  18. //http://msdn.microsoft.com/en-us/library/gg309252.aspx
  19.  
  20. //http://mileyja.blogspot.com/2011/11/add-entity-member-to-marketing-list-in_16.html
  21. //https://community.dynamics.com/crm/b/mileyja/archive/2011/11/15/remove-an-entity-member-from-a-marketing-list-in-microsoft-dynamics-crm-2011-using-net-or-jscript.aspx
  22.  
  23. //https://social.microsoft.com/Forums/en-US/28d8b79f-fc27-4baa-82bc-9d5fe0fcbe16/update-delete-contacts-from-static-marketing-list-through-plugin-in-mscrm-2011?forum=crmdevelopment
  24. //http://www.koorb.co.nz/highlights-and-updates/how-to-integrate-with-dynamics-crm-marketing-lists-with-a-plug-in/
  25.  
  26.  
  27. namespace LansingMarketingList
  28. {
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Collections.ObjectModel;
  32. using System.Globalization;
  33. using System.Linq;
  34. using System.ServiceModel;
  35. using Microsoft.Crm.Sdk.Messages;
  36. using Microsoft.Xrm.Sdk;
  37. using Microsoft.Xrm.Sdk.Client;
  38. using Microsoft.Xrm.Sdk.Query;
  39. using Microsoft.Xrm.Sdk.Messages;
  40. using System.Collections;
  41.  
  42. /// <summary>
  43. /// Base class for all Plugins.
  44. /// </summary>
  45. public class Plugin : IPlugin
  46. {
  47. private IOrganizationService orgService;
  48. private TraceServiceWrapper tracingService;
  49.  
  50. //For some reason, the option set contains acct, contact and lead, 1 2 and 4. 3 is Skipped.
  51. public enum marketingListType { None = 0, Account = 1, Contact = 2, DUMMYDONOTUSETHISVALUEISBAD = 3, Lead = 4 };
  52.  
  53. /// <summary>
  54. /// Executes the plug-in.
  55. /// </summary>
  56. /// <param name="serviceProvider">The service provider.</param>
  57. /// <remarks>
  58. /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
  59. /// The plug-in's Execute method should be written to be stateless as the constructor
  60. /// is not called for every invocation of the plug-in. Also, multiple system threads
  61. /// could execute the plug-in at the same time. All per invocation state information
  62. /// is stored in the context. This means that you should not use global variables in plug-ins.
  63. /// </remarks>
  64.  
  65. private static object setValueSafely(AttributeCollection collection, string key, object val)
  66. {
  67. if (!collection.ContainsKey(key))
  68. {
  69. collection.Add(key, val);
  70. }
  71. else
  72. {
  73. collection[key] = val;
  74. }
  75.  
  76. return val;
  77. }
  78.  
  79. Entity getEntity(Guid id, string logicalname, IOrganizationService service)
  80. {
  81. Entity r = (Entity)service.Retrieve(logicalname, id,
  82. new ColumnSet { AllColumns = true });
  83. return r;
  84. }
  85.  
  86. /*
  87. * We are not going to include checking the Marketing Lists for Duplicates, because duplicate entries
  88. * are not allowed on the Data Grid.
  89. */
  90. public void Execute(IServiceProvider serviceProvider)
  91. {
  92. #region instantiation
  93. marketingListType listType = marketingListType.None; //Used for tracking purposes.
  94. Guid listGuid = new Guid(); //Holds the Guid of our marketing list.
  95. Guid relatedGuid = new Guid();//Holds the Guid of whatever related entity we're processing.
  96.  
  97. Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
  98. serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
  99.  
  100. //Create the services that will talk to CRM.
  101. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
  102. IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
  103. this.orgService = serviceFactory.CreateOrganizationService(context.UserId);
  104. OrganizationServiceContext ServiceContext = new OrganizationServiceContext(service);
  105.  
  106. // The trace wrapper is a CRMPoint.net custom library for matching logging and tracing to a custom entity.
  107. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
  108.  
  109. //Create our trace service wrapper for custom logging.
  110. var crmTracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
  111.  
  112. if (crmTracingService == null)
  113. {
  114. throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");
  115. }
  116. //This tells CRM which tracing configuration to log for.
  117. this.tracingService = new TraceServiceWrapper(this.orgService, crmTracingService, "AssociationTest");
  118. this.tracingService.Trace("This is a test. This is only a test.");
  119.  
  120. if (context.Depth > 2) { return; } //For recursion. Included and VERY strictly necessary or else the plugin will fire infinitely.
  121. #endregion
  122.  
  123. #region Complete logic block.
  124.  
  125. #region associate/disassociate
  126. if (context.MessageName == "Associate" || context.MessageName == "Disassociate")
  127. {
  128. #region validation
  129. if (!context.InputParameters.Contains("Relationship"))
  130. {
  131. this.tracingService.Trace("No relationship found. Exiting plugin.");
  132. this.tracingService.HandleSuccess();
  133. return;
  134. }
  135. else
  136. {
  137. this.tracingService.Trace("Found relationship.");
  138. }
  139. ////////////////////////////////////////////////////
  140. if (!context.InputParameters.Contains("Target"))
  141. {
  142. this.tracingService.Trace("No target found. Exiting plugin.");
  143. this.tracingService.HandleSuccess();
  144. return;
  145. }
  146. else
  147. {
  148. this.tracingService.Trace("Found target.");
  149. }
  150. ///////////////////////////////////////////////////
  151. if (!context.InputParameters.Contains("RelatedEntities"))
  152. {
  153. this.tracingService.Trace("No Related entities found. Exiting plugin.");
  154. this.tracingService.HandleSuccess();
  155. return;
  156. }
  157. else
  158. {
  159. this.tracingService.Trace("Related entity found.");
  160. }
  161. #endregion
  162. /*
  163. * Declare these variables here and not in instantiation region because they're of
  164. * no use if we don't have all of the correct context.InputParameters passed in.
  165. */
  166. EntityReference target = (EntityReference)context.InputParameters["Target"];
  167. EntityReferenceCollection related = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];
  168. Relationship relationship = (Relationship)context.InputParameters["Relationship"];
  169. this.tracingService.Trace("About to test for marketing list relationships: " + relationship.SchemaName);
  170.  
  171. /*We only want the plugin to fire if one of these 3 EXACT associations is created.
  172. * Otherwise, exit out of the plugin alltogether.
  173. */
  174. if (relationship.SchemaName != "new_new_consolidatedmarketinglist_account" &&
  175. relationship.SchemaName != "new_new_consolidatedmarketinglist_contact" &&
  176. relationship.SchemaName != "new_new_consolidatedmarketinglist_lead")
  177. {
  178. this.tracingService.Trace("Didn't find one of the 3 necessary associations.");
  179. this.tracingService.Trace(relationship.SchemaName);
  180. this.tracingService.HandleSuccess();
  181. return;
  182. }
  183. else
  184. {
  185. if (relationship.SchemaName == "new_new_consolidatedmarketinglist_account")
  186. {
  187. listType = marketingListType.Account;
  188. }
  189. else if (relationship.SchemaName == "new_new_consolidatedmarketinglist_contact")
  190. {
  191. listType = marketingListType.Contact;
  192. }
  193. else if (relationship.SchemaName == "new_new_consolidatedmarketinglist_lead")
  194. {
  195. listType = marketingListType.Lead;
  196. }
  197.  
  198. this.tracingService.Trace("listType set to: " + listType.ToString());
  199. }
  200.  
  201. #region Populate Related Guid
  202. //this.tracingService.Trace("Plugin Guid: " + context.OwningExtension.Id); //This is the GUID of the plugin.
  203. //this.tracingService.Trace("Consolidated Marketing List Guid: " + target.Id); //YES YES YES - Guid of the Consolidated Marketing List.
  204.  
  205. //This block was for validation of RemoveMEmber. The foreach below it was for validation on associate/disassociate.
  206. /*
  207. this.tracingService.Trace("XYZ: " + context.MessageName);
  208. foreach (KeyValuePair<string, object> x in context.InputParameters)
  209. {
  210. this.tracingService.Trace("PX: " + x.ToString());
  211. this.tracingService.Trace("AX: " + x.Key);
  212. this.tracingService.Trace("BX: " + x.Value);
  213. }
  214. */
  215. foreach (EntityReference relatedEnt in related)
  216. {
  217. //this.tracingService.Trace("Ent name: " + relatedEnt.Name);
  218. this.tracingService.Trace("Ent log: " + relatedEnt.LogicalName);
  219. this.tracingService.Trace("Ent id:" + relatedEnt.Id);
  220. relatedGuid = relatedEnt.Id;
  221. }
  222.  
  223. foreach (KeyValuePair<string, object> x in context.InputParameters)
  224. {
  225. //this.tracingService.Trace("PX: " + x.ToString());
  226. }
  227.  
  228. #endregion
  229.  
  230. try
  231. {
  232. #region associate
  233. if (context.MessageName == "Associate")
  234. {
  235. Entity thisList = getEntity(target.Id, "new_consolidatedmarketinglist", service);
  236. QueryExpression marketingList = new QueryExpression
  237. {
  238. EntityName = "list", //was crmp_policy
  239. ColumnSet = new ColumnSet { AllColumns = true }
  240. };
  241.  
  242. string entName = thisList.Attributes["new_name"] + "-" + listType.ToString();
  243. //Should look like: "Test-Line", etc...
  244.  
  245. marketingList.Criteria = new FilterExpression(LogicalOperator.And); //Was no LO.and
  246. marketingList.Criteria.AddCondition("listname", ConditionOperator.Equal, entName);
  247. marketingList.Criteria.AddCondition("new_consolidatedmarketinglist", ConditionOperator.Equal, new Guid(target.Id.ToString()));
  248.  
  249. EntityCollection mlCol = service.RetrieveMultiple(marketingList);
  250.  
  251. this.tracingService.Trace("Queried for marketing lists.");
  252.  
  253. if (mlCol.Entities.Count < 1) //No entities found.
  254. {
  255. Entity list = new Entity("list");
  256.  
  257. //OptionSetValue osv = new OptionSetValue((int)marketingListType.Lead);
  258. setValueSafely(list.Attributes, "listname", entName);
  259.  
  260. setValueSafely(list.Attributes, "type", false);//True for Dynamic, False for Static
  261. setValueSafely(list.Attributes, "createdfromcode", new OptionSetValue((int)listType));
  262. setValueSafely(list.Attributes, "new_consolidatedmarketinglist", new EntityReference("new_consolidatedmarketinglist", new Guid(target.Id.ToString())));
  263. //new EntityReference("new_consolidatedmarketinglist",new Guid(target.Id.ToString())));
  264.  
  265. listGuid = service.Create(list);
  266. //type - two option set - static or dynamic static = 0 dynamic = 1
  267. //createdfromcode - acct = 1, contact = 2, lead = 3
  268.  
  269. this.tracingService.Trace("No marketing list found. Created new one: " + entName);
  270.  
  271. addMember(listGuid, relatedGuid, service);
  272. this.tracingService.Trace("Added member to list:" + relatedGuid);
  273. }
  274. else
  275. {
  276. listGuid = mlCol.Entities[0].Id;
  277. addMember(listGuid, relatedGuid, service);
  278. this.tracingService.Trace("Added member to list:");
  279. }
  280.  
  281. this.tracingService.HandleSuccess();
  282. return; //No need to continue, we're done. :)
  283. }
  284. #endregion
  285.  
  286. #region disassociate
  287. if (context.MessageName == "Disassociate")
  288. {
  289. Entity thisList = getEntity(target.Id, "new_consolidatedmarketinglist", service);
  290. QueryExpression marketingList = new QueryExpression
  291. {
  292. EntityName = "list", //was crmp_policy
  293. ColumnSet = new ColumnSet { AllColumns = true }
  294. };
  295.  
  296. string entName = thisList.Attributes["new_name"] + "-" + listType.ToString();
  297. //Should look like: "Test-Line", etc...
  298.  
  299. marketingList.Criteria = new FilterExpression(LogicalOperator.And); //Was no LO.and
  300. marketingList.Criteria.AddCondition("listname", ConditionOperator.Equal, entName);
  301. marketingList.Criteria.AddCondition("new_consolidatedmarketinglist", ConditionOperator.Equal, new Guid(target.Id.ToString()));
  302.  
  303. EntityCollection mlCol = service.RetrieveMultiple(marketingList);
  304.  
  305. this.tracingService.Trace("Queried for marketing lists.");
  306.  
  307. if (mlCol.Entities.Count < 1) //No entities found.
  308. {
  309. this.tracingService.Trace("No Marketing List found to remove member from.");
  310. }
  311. else
  312. {
  313. //this.tracingService.Trace("h: " + mlCol.Entities[0].Id);
  314. //this.tracingService.Trace("i: " + relatedGuid);
  315.  
  316. try
  317. {
  318. string type = string.Empty;
  319. OptionSetValue code;
  320. bool found = false;
  321. ArrayList memberGuids = new ArrayList();
  322.  
  323. this.tracingService.Trace("About to query for list members.");
  324.  
  325. PagingInfo pageInfo = new PagingInfo();
  326. pageInfo.Count = 5000;
  327. pageInfo.PageNumber = 1;
  328.  
  329. QueryByAttribute query = new QueryByAttribute("listmember");
  330. query.AddAttributeValue("listid", new Guid(mlCol.Entities[0].Id.ToString())); //Query the marketing list to ensure our removed item is a member.
  331. query.ColumnSet = new ColumnSet(true);
  332. EntityCollection memberCollection = service.RetrieveMultiple(query);
  333. this.tracingService.Trace("Queried for list members.");
  334.  
  335. if (memberCollection.Entities.Count > 0)
  336. {
  337. code = (OptionSetValue)mlCol[0].Attributes["createdfromcode"];
  338. }
  339. else
  340. {
  341. this.tracingService.Trace("Unable to retrieve marketing list. Returning.");
  342. return;
  343. }
  344.  
  345. if (code.Value == 1) //act, cnt = 2, lead = 4
  346. {
  347. type = "account";
  348. }
  349. else if (code.Value == 2)
  350. {
  351. type = "contact";
  352. }
  353. else if (code.Value == 4)
  354. {
  355. type = "lead";
  356. }
  357.  
  358. foreach (Entity member in memberCollection.Entities)
  359. {
  360. memberGuids.Add(((EntityReference)member.Attributes["entityid"]).Id);
  361. }
  362.  
  363.  
  364. while (memberCollection.MoreRecords)
  365. {
  366. query.PageInfo.PageNumber += 1;
  367. query.PageInfo.PagingCookie = memberCollection.PagingCookie;
  368. memberCollection = orgService.RetrieveMultiple(query);
  369.  
  370. foreach (Entity member in memberCollection.Entities)
  371. {
  372. memberGuids.Add(((EntityReference)member.Attributes["entityid"]).Id);
  373. }
  374. }
  375.  
  376. //acct = name, else fullname //accountid, contactid, leadid
  377. //foreach (Entity member in memberCollection.Entities)
  378. foreach(Guid id in memberGuids)
  379. {
  380. //memberGuids.Add(((EntityReference)member.Attributes["entityid"]).Id);
  381.  
  382. if (id == relatedGuid)
  383. //if (memberGuids.Contains(relatedGuid))
  384. {
  385. try
  386. {
  387. removeMember(mlCol.Entities[0].Id, relatedGuid, service);
  388. this.tracingService.Trace("Removed member " + relatedGuid + " from list: " + mlCol.Entities[0].Id);
  389. }
  390. catch (Exception ex)
  391. {
  392. this.tracingService.Trace(ex.ToString());
  393. }
  394.  
  395. found = true;
  396. }
  397. }
  398.  
  399. if (found == false)
  400. {
  401. this.tracingService.Trace("Unable to find entity of type " + type + " with id of " + relatedGuid + "on marketing list: " + mlCol.Entities[0].Id);
  402. }
  403.  
  404. //removeMember(mlCol.Entities[0].Id, relatedGuid, service);
  405. //this.tracingService.Trace("Removed member from list:");
  406. }
  407. catch (Exception ex)
  408. {
  409. this.tracingService.Trace("Unable to remove member: " + ex);
  410. }
  411. }
  412.  
  413. this.tracingService.HandleSuccess();
  414. }
  415.  
  416. #endregion
  417. }
  418. catch (Exception ex)
  419. {
  420. this.tracingService.Trace("Failure for: " + relationship.SchemaName);
  421. this.tracingService.HandleException(ex);
  422. }
  423. }
  424. #endregion
  425.  
  426. #region RemoveMember block
  427. //this.tracingService.Trace("About to delve into REmoveMember code");
  428. else if (context.MessageName == "RemoveMember")
  429. {
  430. //throw new InvalidPluginExecutionException();
  431. Guid thisMarketListId = Guid.Empty;
  432. Guid removedEntityId = Guid.Empty;
  433. EntityReference consolidatedListRef = null;// = new EntityReference();
  434.  
  435. #region validation - just want to ensure our input parameters are all here.
  436. if (!context.InputParameters.Contains("ListId"))
  437. {
  438. this.tracingService.Trace("No ListId found. Exiting plugin.");
  439. this.tracingService.HandleSuccess();
  440. return;
  441. }
  442. else
  443. {
  444. this.tracingService.Trace("Found ListId.");
  445. }
  446. ////////////////////////////////////////////////////
  447. if (!context.InputParameters.Contains("EntityId"))
  448. {
  449. this.tracingService.Trace("No EntityId found. Exiting plugin.");
  450. this.tracingService.HandleSuccess();
  451. return;
  452. }
  453. else
  454. {
  455. this.tracingService.Trace("Found EntityId.");
  456. }
  457. #endregion
  458.  
  459. foreach (KeyValuePair<string, object> x in context.InputParameters)
  460. {
  461. if (x.Key == "ListId")
  462. {
  463. thisMarketListId = (Guid)x.Value;
  464. this.tracingService.Trace("Found Marketing List ID: " + thisMarketListId);
  465. }
  466.  
  467. if (x.Key == "EntityId")
  468. {
  469. removedEntityId = (Guid)x.Value;
  470. this.tracingService.Trace("Found removed entity ID: " + removedEntityId);
  471. }
  472. }
  473.  
  474. if (removedEntityId == Guid.Empty) //Unable to pull GUID out of context input.
  475. {
  476. this.tracingService.Trace("Unable to find removed entity. Exiting plugin.");
  477. return;
  478. }
  479.  
  480. if (thisMarketListId == Guid.Empty) //Unable to pull GUID out of context input.
  481. {
  482. this.tracingService.Trace("Unable to find marketing list. Exiting plugin.");
  483. return;
  484. }
  485.  
  486. this.tracingService.Trace("About to retrieve THIS marketing list as an entity.");
  487. Entity thisList = getEntity(thisMarketListId, "list", service);
  488.  
  489. /*foreach (KeyValuePair<string, object> x in thisList.Attributes)
  490. {
  491. this.tracingService.Trace(x.Key);
  492. this.tracingService.Trace(x.Value.ToString());
  493. }
  494. */
  495.  
  496. //Found our list, and have our deleted entity.
  497. consolidatedListRef = (EntityReference)thisList.Attributes["new_consolidatedmarketinglist"];
  498. Entity consolidatedList = getEntity(consolidatedListRef.Id, "new_consolidatedmarketinglist", service);
  499. this.tracingService.Trace("Consolidated list: " + consolidatedList.Id);
  500.  
  501. OptionSetValue val = (OptionSetValue)thisList.Attributes["createdfromcode"]; //act = 1, cnt = 2, ld = 4
  502.  
  503. string relationshipName = string.Empty;
  504. string entityTypeName = string.Empty;
  505.  
  506. //this.tracingService.Trace("Val.Value: " + val.Value);
  507.  
  508. if (val.Value == 1) //Account
  509. {
  510. entityTypeName = "account";
  511. relationshipName = "new_new_consolidatedmarketinglist_account";
  512. }
  513. else if (val.Value == 2)//Contact
  514. {
  515. entityTypeName = "contact";
  516. relationshipName = "new_new_consolidatedmarketinglist_contact";
  517. }
  518. else if (val.Value == 4) //Lead
  519. {
  520. entityTypeName = "lead";
  521. relationshipName = "new_new_consolidatedmarketinglist_lead";
  522. }
  523.  
  524. List<Entity> relationships = retrieveRelationships(service, "new_consolidatedmarketinglist", consolidatedList.Id, relationshipName, entityTypeName).ToList();
  525.  
  526. this.tracingService.Trace("Just pulled relationships.");
  527.  
  528. foreach (Entity ent in relationships)
  529. {
  530. if (ent.Id == removedEntityId)
  531. {
  532. EntityReferenceCollection erf = new EntityReferenceCollection();
  533. erf.Add(new EntityReference(ent.LogicalName, ent.Id));
  534. service.Disassociate(consolidatedList.LogicalName, consolidatedList.Id, new Relationship(relationshipName), erf);//was ent.id and not removedetc
  535. this.tracingService.Trace("Record" + ent.Id + " disassociated from Consolidated Marketing list: " + consolidatedList.Id);
  536. }
  537. else
  538. {
  539. //this.tracingService.Trace("");
  540. }
  541. }
  542.  
  543. this.tracingService.HandleSuccess();
  544. }
  545. #endregion
  546. #endregion
  547. }
  548.  
  549. /*
  550. * Add member to our "base" marketing list (not consolidated). We're passing in the list id,
  551. * the entity id, and the organization service.
  552. */
  553. public static void addMember(Guid listGuid, Guid relatedGuid, IOrganizationService service)
  554. {
  555. AddListMembersListRequest req = new AddListMembersListRequest();
  556. req.ListId = listGuid;
  557.  
  558. req.MemberIds = new System.Guid[1];
  559. req.MemberIds[0] = relatedGuid;
  560. AddListMembersListResponse resp = (AddListMembersListResponse)service.Execute(req);
  561. }
  562.  
  563. /*
  564. * Remove member from our "base" marketing list (not consolidated). We're passing in the list id,
  565. * the entity id, and the organization service.
  566. */
  567. public static void removeMember(Guid listGuid, Guid relatedGuid, IOrganizationService service) //waS VOID
  568. {
  569. try
  570. {
  571. RemoveMemberListRequest req = new RemoveMemberListRequest();
  572. req.EntityId = relatedGuid;
  573. req.ListId = listGuid;
  574. RemoveMemberListResponse resp = (RemoveMemberListResponse)service.Execute(req);
  575. }
  576. catch (Exception ex)
  577. {
  578. throw ex;
  579. }
  580. }
  581.  
  582. IEnumerable<Entity> retrieveRelationships(IOrganizationService service, string primaryEntity, Guid primaryEntityId, string relationshipName, string targetEntity)
  583. {
  584. //the related entity we are going to retrieve
  585. QueryExpression query = new QueryExpression();
  586. query.EntityName = targetEntity;
  587. query.ColumnSet = new ColumnSet { AllColumns = true };//("new_totalmonthlytext", "crmp_contract", "crmp_name");
  588.  
  589. //the relationship that links the primary to the target
  590. Relationship relationship = new Relationship(relationshipName);
  591. relationship.PrimaryEntityRole = EntityRole.Referenced; //important if the relationship is self-referencing
  592.  
  593. //the query collection which forms the request
  594. RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
  595. relatedEntity.Add(relationship, query);
  596.  
  597. //the request to get the primary entity with the related records
  598. RetrieveRequest request = new RetrieveRequest();
  599. request.RelatedEntitiesQuery = relatedEntity;
  600. request.ColumnSet = new ColumnSet { AllColumns = true };//("crmp_name");
  601. request.Target = new EntityReference(primaryEntity, primaryEntityId);
  602.  
  603. RetrieveResponse r = (RetrieveResponse)service.Execute(request); //was service.Execute
  604.  
  605. //query the returned collection for the target entity ids
  606. return r.Entity.RelatedEntities[relationship].Entities;//.Select(e => e.Id);
  607. }
  608. }
  609. }
  610. #region oldexecute
  611. /* //Old Execute method.
  612. public void Execute(IServiceProvider serviceProvider)
  613. {
  614. if (serviceProvider == null)
  615. {
  616. throw new ArgumentNullException("serviceProvider");
  617. }
  618.  
  619. // Construct the Local plug-in context.
  620. LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);
  621.  
  622. localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));
  623.  
  624. try
  625. {
  626. // Iterate over all of the expected registered events to ensure that the plugin
  627. // has been invoked by an expected event
  628. // For any given plug-in event at an instance in time, we would expect at most 1 result to match.
  629. Action<LocalPluginContext> entityAction =
  630. (from a in this.RegisteredEvents
  631. where (
  632. a.Item1 == localcontext.PluginExecutionContext.Stage &&
  633. a.Item2 == localcontext.PluginExecutionContext.MessageName &&
  634. (string.IsNullOrWhiteSpace(a.Item3) ? true : a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
  635. )
  636. select a.Item4).FirstOrDefault();
  637.  
  638. if (entityAction != null)
  639. {
  640. localcontext.Trace(string.Format(
  641. CultureInfo.InvariantCulture,
  642. "{0} is firing for Entity: {1}, Message: {2}",
  643. this.ChildClassName,
  644. localcontext.PluginExecutionContext.PrimaryEntityName,
  645. localcontext.PluginExecutionContext.MessageName));
  646.  
  647. entityAction.Invoke(localcontext);
  648.  
  649. // now exit - if the derived plug-in has incorrectly registered overlapping event registrations,
  650. // guard against multiple executions.
  651. return;
  652. }
  653. }
  654. catch (FaultException<OrganizationServiceFault> e)
  655. {
  656. localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));
  657.  
  658. // Handle the exception.
  659. throw;
  660. }
  661. finally
  662. {
  663. localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));
  664. }
  665. }
  666.  
  667. */
  668. #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement