Advertisement
Guest User

SearchPlots

a guest
Feb 22nd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.91 KB | None | 0 0
  1. using Microsoft.Crm.Sdk.Messages;
  2. using Microsoft.Xrm.Sdk;
  3. using Microsoft.Xrm.Sdk.Client;
  4. using Microsoft.Xrm.Sdk.Query;
  5. using Sb.Common;
  6. using Sb.Helpers;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12.  
  13. namespace GlobalActions
  14. {
  15.     public class SearchPlots : IPlugin
  16.     {
  17.         private IOrganizationService _service;
  18.         private ITracingService tracingService;
  19.  
  20.         public void Execute(IServiceProvider serviceProvider)
  21.         {
  22.             try
  23.             {
  24.                 var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
  25.                 var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
  26.                 tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
  27.                 _service = factory.CreateOrganizationService(context.UserId);
  28.  
  29.                 //tracingService.Trace("SearchPlots action started at: {0}", DateTime.Now);
  30.  
  31.                 var target = (EntityReference)context.InputParameters["Target"];
  32.  
  33.                 //tracingService.Trace("TargetId: {0}", target.Id);
  34.  
  35.                 var plotlist = GetPlots(target.Id);
  36.  
  37.                 //tracingService.Trace("Plots count: {0}", plotlist.Count());
  38.  
  39.                 var searchTemplateId = CreateSearchTemplate(target.Id);
  40.                 AssociatePlots(searchTemplateId, plotlist);
  41.  
  42.                 //tracingService.Trace("SearchTemplateId: {0}", searchTemplateId);
  43.  
  44.                 context.OutputParameters["SearchTemplateId"] = searchTemplateId;
  45.  
  46.                 tracingService.Trace("SearchPlots action finished at: {0}", DateTime.Now);
  47.  
  48.             }
  49.             catch (InvalidPluginExecutionException ex)
  50.             {
  51.                 throw ex;
  52.             }
  53.         }
  54.        
  55.         private  Guid CreateSearchTemplate(Guid targetId) =>
  56.             CreateSearchTemplate(new EntityReference(Helper.Lead.LogicalName, targetId));
  57.  
  58.         private Guid CreateSearchTemplate(EntityReference targetRef)
  59.         {
  60.             var initializeFormRequest = new InitializeFromRequest
  61.             {
  62.                 EntityMoniker = targetRef,
  63.                 TargetEntityName = Helper.SearchTemplate.LogicalName
  64.             };
  65.  
  66.             var initializedEntity = ((InitializeFromResponse)_service.Execute(initializeFormRequest)).Entity;
  67.  
  68.             return _service.Create(initializedEntity);
  69.         }
  70.  
  71.         private void AssociatePlots(Guid searchTemplateId, IEnumerable<Guid> plotList)
  72.         {
  73.             if (plotList.Count() == 0)
  74.             {
  75.                 return;
  76.             }
  77.  
  78.             var entityReferenceCollection = new EntityReferenceCollection();
  79.             foreach (var id in plotList)
  80.             {
  81.                 entityReferenceCollection.Add(new EntityReference(Helper.Plot.LogicalName, id));
  82.             }
  83.  
  84.             _service.Associate(Helper.SearchTemplate.LogicalName, searchTemplateId,
  85.                 new Relationship(Helper.SearchTemplate.Relationships.SearchTemplatePlots), entityReferenceCollection);
  86.         }
  87.  
  88.         private IEnumerable<Guid> GetPlots(Guid leadId)
  89.         {
  90.             var targetLead = _service.Retrieve(Helper.Lead.LogicalName, leadId,
  91.                 new ColumnSet(
  92.                     Helper.Lead.Fields.City,
  93.                     Helper.Lead.Fields.NumberOfBedRooms,
  94.                     Helper.Lead.Fields.FloorFrom,
  95.                     Helper.Lead.Fields.FloorTill,
  96.                     Helper.Lead.Fields.AreaFrom,
  97.                     Helper.Lead.Fields.AreaTill,
  98.                     Helper.Lead.Fields.BudgetAmount,
  99.                     Helper.Lead.Fields.RealtyType
  100.                 ));
  101.  
  102.             var houseModels = RetrieveHouseModels(leadId);
  103.             var projects = RetrieveProjects(leadId);
  104.  
  105.             var plotsQuery = new QueryExpression(Helper.Plot.LogicalName)
  106.             {
  107.                 Criteria = new FilterExpression(LogicalOperator.And)
  108.             };
  109.  
  110.             if (houseModels.Any())
  111.                 plotsQuery.Criteria.AddCondition(Helper.Plot.Fields.HouseModels,
  112.                     ConditionOperator.In, houseModels.Cast<object>().ToArray());
  113.  
  114.             if (projects.Any())
  115.                 plotsQuery.Criteria.AddCondition(Helper.Plot.Fields.ProjectId,
  116.                     ConditionOperator.In, projects.Cast<object>().ToArray());
  117.  
  118.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.City,
  119.                 Helper.Plot.Fields.City, ConditionOperator.Equal);
  120.  
  121.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.NumberOfBedRooms,
  122.                 Helper.Plot.Fields.NumberOfBedrooms, ConditionOperator.Equal);
  123.  
  124.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.FloorFrom,
  125.                 Helper.Plot.Fields.FloorNumber, ConditionOperator.GreaterEqual);
  126.  
  127.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.FloorTill,
  128.                 Helper.Plot.Fields.FloorNumber, ConditionOperator.LessEqual);
  129.  
  130.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.AreaFrom,
  131.                 Helper.Plot.Fields.ProjectArea, ConditionOperator.GreaterEqual);
  132.  
  133.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.AreaTill,
  134.                 Helper.Plot.Fields.ProjectArea, ConditionOperator.LessEqual);
  135.  
  136.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.BudgetAmount,
  137.                 Helper.Plot.Fields.BasePrice, ConditionOperator.LessEqual);
  138.  
  139.             ApplyConditionIfContains(targetLead, plotsQuery, Helper.Lead.Fields.RealtyType,
  140.                 Helper.Plot.Fields.HouseType, ConditionOperator.Equal);
  141.  
  142.             var plots = _service.RetrieveMultipleByQuery(plotsQuery).Select(item => item.Id);
  143.            
  144.             return plots;
  145.         }
  146.  
  147.         private static void ApplyConditionIfContains(Entity entity, QueryExpression query,
  148.             string sourceAttribute, string targetAttribute, ConditionOperator @operator)
  149.         {
  150.             if (!entity.Contains(sourceAttribute)) return;
  151.             var value = entity[sourceAttribute];
  152.  
  153.             if (value is EntityReference entityReference)
  154.                 query.Criteria.AddCondition(targetAttribute, @operator, entityReference.Id);
  155.             else
  156.                 if (value is Money money)
  157.                 query.Criteria.AddCondition(targetAttribute, @operator, money.Value);
  158.             else
  159.                 if (value is OptionSetValue optionSet)
  160.                 query.Criteria.AddCondition(targetAttribute, @operator, optionSet.Value);
  161.             else
  162.                 query.Criteria.AddCondition(targetAttribute, @operator, value);
  163.         }
  164.  
  165.         private List<Guid> RetrieveHouseModels(Guid leadId)
  166.         {
  167.             var houseModelsQuery = new QueryExpression(Helper.HouseModel.LogicalName);
  168.             var leadRelationshipLink = houseModelsQuery.AddLink(Helper.Lead.Relationships.LeadHouseModel,
  169.                 Helper.HouseModel.Fields.Id, Helper.HouseModel.Fields.Id);
  170.             leadRelationshipLink.LinkCriteria.AddCondition(Helper.Lead.Id, ConditionOperator.Equal, leadId);
  171.             return _service.RetrieveMultipleByQuery(houseModelsQuery).Select(item => item.Id).Distinct().ToList();
  172.         }
  173.  
  174.         private List<Guid> RetrieveProjects(Guid leadId)
  175.         {
  176.             var projectsQuery = new QueryExpression(Helper.Project.LogicalName);
  177.             var leadRelationshipLink = projectsQuery.AddLink(Helper.Lead.Relationships.LeadProject,
  178.                 Helper.Project.Fields.Id, Helper.Project.Fields.Id);
  179.             leadRelationshipLink.LinkCriteria.AddCondition(Helper.Lead.Id, ConditionOperator.Equal, leadId);
  180.             return _service.RetrieveMultipleByQuery(projectsQuery).Select(item => item.Id).Distinct().ToList();
  181.         }
  182.        
  183.     }
  184. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement