private void PostData(CodeActivityContext context, string json, ITracingService trace) { var content = new StringContent(json, Encoding.UTF8, "application/json"); var webClient = new HttpClient(); var result = webClient.PostAsync(GetServiceUri(context), content).Result; trace?.Trace("Post status code:" + result.StatusCode); }
public Entity CopyRecord(ITracingService tracer = null) { var obj = new Entity(_logicalName) { Id = Guid.Empty }; obj.Attributes.AddRange(_values.ToArray()); tracer?.Trace("COPY RECORD: No. attributes: " + obj.Attributes.Count); obj.Attributes.Remove(_logicalName + "id"); return(obj); }
private bool SendToAi(string json) { try { HttpContent content = new StringContent(json, Encoding.UTF8, "application/x-json-stream"); HttpResponseMessage response = _httpClient.PostAsync(_loggingEndpoint, content).Result; if (response.IsSuccessStatusCode) { return(true); } _tracingService?.Trace( $"ERROR: Unable to write to Application Insights with response: {response.StatusCode.ToString()}: {response.ReasonPhrase}: Message: {CreateJsonDataLog(json)}"); return(false); } catch (Exception e) { _tracingService?.Trace(CreateJsonDataLog(json), e); return(false); } }
protected override void Execute(CodeActivityContext executionContext) { try { _tracingService = executionContext.GetExtension<ITracingService>(); IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); _service = serviceFactory.CreateOrganizationService(context.UserId); //Do stuff } catch (Exception ex) { _tracingService.Trace("Exception: {0}", ex.ToString()); } }
public async Task <APIResponse> CheckThirdPartyApi(string contactEmail) { tracingService?.Trace("CheckThirdPartyApi"); APIResponse resultObj = new APIResponse(); var client = new HttpClient(); string url = $"{ GetAPiUrl()}{contactEmail}"; var result = await client.GetAsync(url); if (result.StatusCode == HttpStatusCode.OK) { bool _flag = bool.Parse(result.Content.ReadAsStringAsync().Result); resultObj.APICallingResponse = true; resultObj.APICallingResponse = _flag; } return(resultObj); }
public static ConditionExpression GetCondition(this FilterExpression filter, string attribute, ConditionOperator?oper, ITracingService trace = null) { var result = filter?.Conditions?.FirstOrDefault(c => c.AttributeName.Equals(attribute) && (oper == null || oper == c.Operator)); if (result != null) { trace?.Trace($"Found condition: {result.Stringify()}"); return(result); } foreach (var subfilter in filter?.Filters) { if (subfilter.GetCondition(attribute, oper, trace) is ConditionExpression subresult) { return(subresult); } } return(null); }
public static void RemoveEmptyLinkEntities(this DataCollection <LinkEntity> linkEntities, ITracingService trace = null) { var i = 0; while (i < linkEntities.Count) { var sublink = linkEntities[i]; if (sublink.LinkEntities.Count == 0 && sublink.LinkCriteria.Conditions.Count == 0 && sublink.LinkCriteria.Filters.Count == 0) { trace?.Trace($"Removing link-entity: {sublink.Stringify()}"); linkEntities.Remove(sublink); } else { i++; } } }
public static void RemoveEmptyFilters(this DataCollection <FilterExpression> filters, ITracingService trace = null) { var i = 0; while (i < filters.Count) { var subfilter = filters[i]; if (subfilter.Conditions.Count == 0 && subfilter.Filters.Count == 0) { trace?.Trace($"Removing empty filter"); filters.Remove(subfilter); } else { i++; } } }
public static bool RemoveCondition(this FilterExpression filter, ConditionExpression condition, ITracingService trace = null) { if (filter?.Conditions?.Contains(condition) == true) { trace?.Trace($"Removing condition: {condition.Stringify()}"); filter.Conditions.Remove(condition); return(true); } var result = false; foreach (var subfilter in filter.Filters) { if (subfilter.RemoveCondition(condition, trace)) { result = true; } } filter.Filters.RemoveEmptyFilters(trace); return(result); }
private void TraceLog(string message) { _tracingservice.Trace(message); }
public EntityCollection getAssociations(string PrimaryEntityName, Guid PrimaryEntityId, string _relationshipName, string entityName, string ParentId) { // string fetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'> <entity name='" + PrimaryEntityName + @"'> <link-entity name='" + _relationshipName + @"' from='" + PrimaryEntityName + @"id' to='" + PrimaryEntityName + @"id' visible='false' intersect='true'> <link-entity name='opportunity' from='opportunityid' to='opportunityid' alias='ab'> <filter type='and'> <condition attribute='opportunityid' operator='eq' value='" + PrimaryEntityId.ToString() + @"' /> </filter> </link-entity> <link-entity name='" + entityName + @"' from='" + entityName + @"id' to='" + entityName + @"id' alias='ac'> <filter type='and'> <condition attribute='" + entityName + @"id' operator='eq' value='" + ParentId + @"' /> </filter> </link-entity> </link-entity> </entity> </fetch>"; tracingService.Trace(String.Format("FetchXML: {0} ", fetchXML)); EntityCollection relations = service.RetrieveMultiple(new FetchExpression(fetchXML)); return(relations); }
/// <summary> /// A plug-in that creates a follow-up task activity when a new account is created. /// </summary> /// <remarks>Register this plug-in on the Create message, account entity, /// and asynchronous mode. /// </remarks> public void Execute(IServiceProvider serviceProvider) { //Extract the tracing service for use in debugging sandboxed plug-ins. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); //<snippetFollowupPlugin1> // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); //</snippetFollowupPlugin1> //<snippetFollowupPlugin2> // The InputParameters collection contains all the data passed in the message request. if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { // Obtain the target entity from the input parameters. Entity entity = (Entity)context.InputParameters["Target"]; //</snippetFollowupPlugin2> // Verify that the target entity represents an account. // If not, this plug-in was not registered correctly. if (entity.LogicalName != "account") { return; } try { // Create a task activity to follow up with the account customer in 7 days. Entity followup = new Entity("task"); followup["subject"] = "Send e-mail to the new customer."; followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution."; followup["scheduledstart"] = DateTime.UtcNow.AddDays(7); followup["scheduledend"] = DateTime.UtcNow.AddDays(7); followup["category"] = context.PrimaryEntityName; // Refer to the account in the task activity. if (context.OutputParameters.Contains("id")) { Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString()); string regardingobjectidType = "account"; followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid); } //<snippetFollowupPlugin4> // Obtain the organization service reference. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); //</snippetFollowupPlugin4> // Create the task in Microsoft Dynamics CRM. tracingService.Trace("FollowupPlugin: Creating the task activity."); service.Create(followup); } //<snippetFollowupPlugin3> catch (FaultException <OrganizationServiceFault> ex) { throw new InvalidPluginExecutionException("An error occurred in the FollowupPlugin plug-in.", ex); } //</snippetFollowupPlugin3> catch (Exception ex) { tracingService.Trace("FollowupPlugin: {0}", ex.ToString()); throw; } } }
public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); tracingService.Trace("{0}", "CalculatePortableAdjustment Plug-in"); // The InputParameters collection contains all the data passed in the message request. if (context.InputParameters.Contains("Target") && (context.InputParameters["Target"] is Entity || context.InputParameters["Target"] is EntityReference)) { var facilitiesToUpdate = new EntityReferenceCollection(); if (context.MessageName == "Create" || context.MessageName == "Update") { Entity entity = (Entity)context.InputParameters["Target"]; if (entity.LogicalName != caps_Portable.EntityLogicalName) { return; } //Keep CRUD in mind, need to handle all scenarios //Get previous facility (if exists) and current facility if (context.MessageName == "Create" && entity.Contains("caps_facility")) { facilitiesToUpdate.Add(entity.GetAttributeValue <EntityReference>("caps_facility")); } if (context.MessageName == "Update") { Entity preImage = context.PreEntityImages["preImage"]; if (preImage.Contains("caps_facility")) { facilitiesToUpdate.Add(preImage.GetAttributeValue <EntityReference>("caps_facility")); } if (entity.Contains("caps_facility")) { facilitiesToUpdate.Add(entity.GetAttributeValue <EntityReference>("caps_facility")); } } } if (context.MessageName == "Delete") { EntityReference entity = (EntityReference)context.InputParameters["Target"]; if (entity.LogicalName != caps_Portable.EntityLogicalName) { return; } Entity preImage = context.PreEntityImages["preImage"]; if (preImage.Contains("caps_facility")) { facilitiesToUpdate.Add(preImage.GetAttributeValue <EntityReference>("caps_facility")); } } tracingService.Trace("{0}", "Line 66"); foreach (var facilityToUpdate in facilitiesToUpdate) { var kindergardenCount = 0; var elementaryCount = 0; var secondaryCount = 0; //For each facility, get all strong starts using (var crmContext = new CrmServiceContext(service)) { var portableRecords = crmContext.caps_PortableSet.Where(r => r.caps_Facility.Id == facilityToUpdate.Id && r.StateCode == caps_PortableState.Active); tracingService.Trace("{0}", "Line 75"); foreach (var portableRecord in portableRecords) { if (portableRecord.Contains("caps_classtype")) { if (portableRecord.GetAttributeValue <OptionSetValue>("caps_classtype").Value == (int)caps_ClassType.Kindergarten) { tracingService.Trace("{0}", "Line 82"); kindergardenCount += portableRecord.caps_Capacity.GetValueOrDefault(0); } if (portableRecord.GetAttributeValue <OptionSetValue>("caps_classtype").Value == (int)caps_ClassType.Elementary) { tracingService.Trace("{0}", "Line 88"); elementaryCount += portableRecord.caps_Capacity.GetValueOrDefault(0); } if (portableRecord.GetAttributeValue <OptionSetValue>("caps_classtype").Value == (int)caps_ClassType.Secondary) { tracingService.Trace("{0}", "Line 94"); secondaryCount += portableRecord.caps_Capacity.GetValueOrDefault(0); } } } tracingService.Trace("{0} - K:{1}; E:{2}; S:{3}", facilityToUpdate.Name, kindergardenCount, elementaryCount, secondaryCount); //Update the facility var recordToUpdate = new caps_Facility(); recordToUpdate.Id = facilityToUpdate.Id; recordToUpdate.caps_PortableCapacityElementary = elementaryCount; recordToUpdate.caps_PortableCapacityKindergarten = kindergardenCount; recordToUpdate.caps_PortableCapacitySecondary = secondaryCount; service.Update(recordToUpdate); } } } }
public static bool GetSecurityRoles(string securityRoleName, Guid userId, IOrganizationService service, ITracingService trace) { if (trace == null) { throw new InvalidPluginExecutionException("trace is null"); } if (securityRoleName == null || securityRoleName == "") { trace.Trace("SecurityRoleName is null"); throw new InvalidPluginExecutionException("SecurityRoleName is null"); } if (userId == Guid.Empty) { trace.Trace("userId is null"); throw new InvalidPluginExecutionException("userId is null"); } if (service == null) { trace.Trace("service is null"); throw new InvalidPluginExecutionException("service is null"); } trace.Trace("GetSecurityRoles - Start "); var response = false; QueryExpression query = new QueryExpression(); query.EntityName = EntityName.Role; //role entity name ColumnSet cols = new ColumnSet(); cols.AddColumn(Attributes.Role.Name); //We only need role name query.ColumnSet = cols; ConditionExpression systemUserIdCondition = new ConditionExpression(); systemUserIdCondition.AttributeName = Attributes.Role.SystemUserId; systemUserIdCondition.Operator = ConditionOperator.Equal; systemUserIdCondition.Values.Add(userId); ConditionExpression securityRoleNameCondition = new ConditionExpression(); securityRoleNameCondition.AttributeName = Attributes.Role.Name; securityRoleNameCondition.Operator = ConditionOperator.Equal; securityRoleNameCondition.Values.Add(securityRoleName); //system roles LinkEntity linkRole = new LinkEntity(); linkRole.LinkFromAttributeName = Attributes.Role.RoleId; linkRole.LinkFromEntityName = EntityName.Role; //FROM linkRole.LinkToEntityName = EntityName.SystemUserRoles; linkRole.LinkToAttributeName = Attributes.SystemUserRoles.RoleId; //system users LinkEntity linkSystemusers = new LinkEntity(); linkSystemusers.LinkFromEntityName = EntityName.SystemUserRoles; linkSystemusers.LinkFromAttributeName = Attributes.SystemUserRoles.SystemUserId; linkSystemusers.LinkToEntityName = EntityName.SystemUser; linkSystemusers.LinkToAttributeName = Attributes.SystemUser.SystemUserId; linkSystemusers.LinkCriteria = new FilterExpression(); linkSystemusers.LinkCriteria.Conditions.Add(systemUserIdCondition); linkRole.LinkEntities.Add(linkSystemusers); query.LinkEntities.Add(linkRole); query.Criteria.Conditions.Add(securityRoleNameCondition); EntityCollection collRoles = service.RetrieveMultiple(query); if (collRoles != null && collRoles.Entities.Count > 0) { foreach (Entity entity in collRoles.Entities) { if (entity.Contains(Attributes.Role.Name) && entity.Attributes[Attributes.Role.Name].ToString().ToLower() == securityRoleName) { return(response = true); } } } trace.Trace("GetSecurityRoles - End "); return(response); }
//Created By: Raphael Herrera, Created On: 8/31/2016 /*Purpose: Perform BL for receiving Vehicle In-Transit Transfer records * Registration Details: * Event/Message: * Post/Update: gsc_intransitstatus * Primary Entity: gsc_iv_vehicleintransittransferreceiving */ public void ReceiveTransfer(Entity vehicleTransferReceiving) { _tracingService.Trace("Started ReceiveTransfer Method..."); var inTransitTransferId = vehicleTransferReceiving.Contains("gsc_intransittransferid") ? vehicleTransferReceiving.GetAttributeValue <EntityReference>("gsc_intransittransferid").Id : Guid.Empty; //Retrieve Vehicle In-Transit Transfer EntityCollection inTransitCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_vehicleintransittransfer", "gsc_iv_vehicleintransittransferid", inTransitTransferId, _organizationService, null, OrderType.Ascending, new[] { "gsc_intransittransferstatus" }); _tracingService.Trace("Vehicle In-Transit Transfer records retrieved: " + inTransitCollection.Entities.Count); if (inTransitCollection.Entities.Count > 0) { Entity vehicleInTransit = inTransitCollection.Entities[0]; EntityCollection allocatedVehicleCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_allocatedvehicle", "gsc_vehicleintransittransferid", vehicleInTransit.Id, _organizationService, null, OrderType.Ascending, new[] { "gsc_inventoryid", "gsc_modelyear", "gsc_modelcode", "gsc_optioncode", "gsc_color", "gsc_csno", "gsc_vin", "gsc_productionno", "gsc_engineno", "gsc_destinationsiteid" }); _tracingService.Trace("AllocatedVehicle records retrieved: " + allocatedVehicleCollection.Entities.Count); if (allocatedVehicleCollection.Entities.Count > 0) { foreach (Entity allocatedVehicleEntity in allocatedVehicleCollection.Entities) { var inventoryId = allocatedVehicleEntity.Contains("gsc_inventoryid") ? allocatedVehicleEntity.GetAttributeValue <EntityReference>("gsc_inventoryid").Id : Guid.Empty; //Retrieve inventory EntityCollection inventoryCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending, new[] { "gsc_status", "gsc_productquantityid" }); _tracingService.Trace("Inventory records retrieved: " + inventoryCollection.Entities.Count); if (inventoryCollection.Entities.Count > 0) { Entity inventory = inventoryCollection.Entities[0]; var productQuantityId = inventory.Contains("gsc_productquantityid") ? inventory.GetAttributeValue <EntityReference>("gsc_productquantityid").Id : Guid.Empty; //Retrieve product quantity of Via Site EntityCollection viaQuantityCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_productquantity", "gsc_iv_productquantityid", productQuantityId, _organizationService, null, OrderType.Ascending, new[] { "gsc_available", "gsc_onhand", "gsc_productid", "gsc_vehiclemodelid" }); _tracingService.Trace("ProductQuantity records retrieved: " + viaQuantityCollection.Entities.Count); if (viaQuantityCollection.Entities.Count > 0) { Entity viaProdQuantity = viaQuantityCollection.Entities[0]; //Retrieve Product Quantity of Destination Site var destinationSite = vehicleTransferReceiving.Contains("gsc_destinationsiteid") ? vehicleTransferReceiving.GetAttributeValue <EntityReference>("gsc_destinationsiteid").Id : Guid.Empty; var productId = viaProdQuantity.Contains("gsc_productid") ? viaProdQuantity.GetAttributeValue <EntityReference>("gsc_productid").Id : Guid.Empty; var destinationConditionList = new List <ConditionExpression> { new ConditionExpression("gsc_siteid", ConditionOperator.Equal, destinationSite), new ConditionExpression("gsc_productid", ConditionOperator.Equal, productId) }; EntityCollection destinationQuantityCollection = CommonHandler.RetrieveRecordsByConditions("gsc_iv_productquantity", destinationConditionList, _organizationService, null, OrderType.Ascending, new[] { "gsc_onhand", "gsc_available" }); _tracingService.Trace("Destination ProductQuantity records retrieved: " + destinationQuantityCollection.Entities.Count); if (destinationQuantityCollection.Entities.Count > 0) { #region BL for Receiving Vehicle In-Transit Transfer Record Entity destinationQuantity = destinationQuantityCollection.Entities[0]; Int32 viaAvailable = viaProdQuantity.GetAttributeValue <Int32>("gsc_available"); Int32 viaOnHand = viaProdQuantity.GetAttributeValue <Int32>("gsc_onhand"); Int32 destinationAvailable = destinationQuantity.GetAttributeValue <Int32>("gsc_available"); Int32 destinationOnHand = destinationQuantity.GetAttributeValue <Int32>("gsc_onhand"); //Update Product Quantity of Via Site viaProdQuantity["gsc_available"] = viaAvailable - 1; viaProdQuantity["gsc_onhand"] = viaOnHand - 1; _organizationService.Update(viaProdQuantity); _tracingService.Trace("Updated Via Site Product Quantity..."); //Update Product Quantity of Destination Site destinationQuantity["gsc_available"] = destinationAvailable + 1; destinationQuantity["gsc_onhand"] = destinationOnHand + 1; _organizationService.Update(destinationQuantity); _tracingService.Trace("Updated Destination Site Product Quantity..."); //Update Inventory Status = Available inventory["gsc_status"] = new OptionSetValue(100000000); inventory["gsc_productquantityid"] = new EntityReference(destinationQuantity.LogicalName, destinationQuantity.Id); _organizationService.Update(inventory); _tracingService.Trace("Updated Inventory Status..."); //Update Vehicle In-Transit Transfer. Status = Received vehicleInTransit["gsc_intransittransferstatus"] = new OptionSetValue(100000002); _organizationService.Update(vehicleInTransit); _tracingService.Trace("Updated Vehicle In-Transit Transfer..."); #region Create Vehicle In-Transit Transfer Receiving Details Records Entity inTransitReceivingDetails = new Entity("gsc_iv_vehicleintransitreceivingdetail"); var baseModelId = viaProdQuantity.Contains("gsc_vehiclemodelid") ? viaProdQuantity.GetAttributeValue <EntityReference>("gsc_vehiclemodelid").Id : Guid.Empty; inTransitReceivingDetails["gsc_intransitreceivingid"] = new EntityReference(vehicleTransferReceiving.LogicalName, vehicleTransferReceiving.Id); inTransitReceivingDetails["gsc_inventoryid"] = new EntityReference(inventory.LogicalName, inventory.Id); inTransitReceivingDetails["gsc_modelid"] = new EntityReference("gsc_iv_vehiclebasemodel", baseModelId); inTransitReceivingDetails["gsc_productid"] = new EntityReference("product", productId); inTransitReceivingDetails["gsc_modelyear"] = allocatedVehicleEntity.Contains("gsc_modelyear") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_modelyear") : String.Empty; inTransitReceivingDetails["gsc_modelcode"] = allocatedVehicleEntity.Contains("gsc_modelcode") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_modelcode") : String.Empty; inTransitReceivingDetails["gsc_optioncode"] = allocatedVehicleEntity.Contains("gsc_optioncode") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_optioncode") : String.Empty; inTransitReceivingDetails["gsc_color"] = allocatedVehicleEntity.Contains("gsc_color") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_color") : String.Empty; inTransitReceivingDetails["gsc_csno"] = allocatedVehicleEntity.Contains("gsc_csno") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_csno") : String.Empty; inTransitReceivingDetails["gsc_vin"] = allocatedVehicleEntity.Contains("gsc_vin") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_vin") : String.Empty; inTransitReceivingDetails["gsc_productionno"] = allocatedVehicleEntity.Contains("gsc_productionno") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_productionno") : String.Empty; inTransitReceivingDetails["gsc_engineno"] = allocatedVehicleEntity.Contains("gsc_engineno") ? allocatedVehicleEntity.GetAttributeValue <string>("gsc_engineno") : String.Empty; inTransitReceivingDetails["gsc_destinationsiteid"] = vehicleTransferReceiving.Contains("gsc_destinationsiteid") ? vehicleTransferReceiving.GetAttributeValue <EntityReference>("gsc_destinationsiteid").Name : String.Empty; _organizationService.Create(inTransitReceivingDetails); _tracingService.Trace("Created Vehicle In-Transit Transfer Receiving Details record..."); #endregion //Delete Allocated Vehicle _organizationService.Delete(allocatedVehicleEntity.LogicalName, allocatedVehicleEntity.Id); _tracingService.Trace("Deleted Allocated Vehicle..."); #endregion } } } } } } _tracingService.Trace("Ending ReceiveTransfer Method..."); }
public void ExecutePluginLogic(IServiceProvider serviceProvider) { // Use a 'using' statement to dispose of the service context properly // To use a specific early bound entity replace the 'Entity' below with the appropriate class type using (var localContext = new LocalPluginContext <Entity>(serviceProvider)) { // Todo: Place your logic here for the plugin ITracingService tracingService = localContext.TracingService; tracingService.Trace("Plugin execution started"); bool success = false; string ResultMessage = "Unknown Error"; EntityReference leadReference = null; if (localContext.PluginExecutionContext.InputParameters.Contains("Target")) { leadReference = localContext.PluginExecutionContext.InputParameters["Target"] as EntityReference; } if (leadReference != null) { try { QualifyHelper qualify = new QualifyHelper(); tracingService.Trace("Qualifying Lead"); string quoteId = qualify.QualifyLead(leadReference, localContext.OrganizationService); if (quoteId != null) { tracingService.Trace("Lead qualified successfully"); success = true; localContext.PluginExecutionContext.OutputParameters["Success"] = success; localContext.PluginExecutionContext.OutputParameters["ResultMessage"] = "OK"; localContext.PluginExecutionContext.OutputParameters["ExecutionResult"] = quoteId; SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = leadReference.Id, LogicalName = leadReference.LogicalName, }, State = new OptionSetValue(1), Status = new OptionSetValue(3) }; localContext.OrganizationService.Execute(setStateRequest); tracingService.Trace("Plugin execution completed successfully"); } else { throw new InvalidPluginExecutionException("There was an issue creating the quote"); } } catch (Exception ex) { success = false; ResultMessage = ex.Message; throw new InvalidPluginExecutionException(ex.Message); } } else { localContext.PluginExecutionContext.OutputParameters["Success"] = success; localContext.PluginExecutionContext.OutputParameters["ResultMessage"] = ResultMessage; } } }
public void EntityAttachmentToEmail(string fileName, string parentId, EntityReference email, bool retrieveActivityMimeAttachment, bool mostRecent, int?topRecords = 0) { #region "Query Attachments" string fileNameCondition = string.IsNullOrEmpty(fileName) ? string.Empty : $"<condition attribute='filename' operator='like' value='{fileName}' />"; string fetchXML = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' {(topRecords > 0 ? $"top='{topRecords}'" : string.Empty)}>"; if (!retrieveActivityMimeAttachment) { fetchXML = $@"{fetchXML} <entity name='annotation'> <attribute name='filename' /> <attribute name='annotationid' /> <attribute name='subject' /> <attribute name='documentbody' /> <attribute name='mimetype' /> <order attribute='createdon' descending='true' /> <filter type='and'> {fileNameCondition} <condition attribute='isdocument' operator='eq' value='1' /> <condition attribute='objectid' operator='eq' value='{parentId} ' /> </filter> </entity> </fetch>"; } else { fetchXML = $@"{fetchXML} <entity name='activitymimeattachment'> <attribute name='filename' /> <attribute name='attachmentid' /> <attribute name='subject' /> <attribute name='body' /> <attribute name='mimetype' /> <filter type='and'> {fileNameCondition} <condition attribute='activityid' operator='eq' value='{parentId}' /> </filter> </entity> </fetch>"; } tracing?.Trace("FetchXML: {0} ", fetchXML); EntityCollection attachmentFiles = service.RetrieveMultiple(new FetchExpression(fetchXML)); if (attachmentFiles.Entities.Count == 0) { tracing?.Trace("No Attachment Files found."); return; } #endregion #region "Add Attachments to Email" int i = 1; List <Entity> attachedFiles = new List <Entity>(); foreach (Entity file in attachmentFiles.Entities) { tracing?.Trace("Entities Count: {0} ", i); Entity _Attachment = new Entity("activitymimeattachment"); _Attachment["objectid"] = new EntityReference("email", email.Id); _Attachment["objecttypecode"] = "email"; _Attachment["attachmentnumber"] = i; i++; if (file.Attributes.Contains("subject")) { _Attachment["subject"] = file.Attributes["subject"].ToString(); } if (file.Attributes.Contains("filename")) { _Attachment["filename"] = file.Attributes["filename"].ToString(); } if (file.Attributes.Contains("documentbody")) { _Attachment["body"] = file.Attributes["documentbody"].ToString(); } else if (file.Attributes.Contains("body")) { _Attachment["body"] = file.Attributes["body"].ToString(); } if (file.Attributes.Contains("mimetype")) { _Attachment["mimetype"] = file.Attributes["mimetype"].ToString(); } if (mostRecent) { tracing?.Trace("Is Most Recent"); Entity alreadyAttached = attachedFiles.Where(f => f["filename"].ToString() == file.GetAttributeValue <string>("filename")).FirstOrDefault(); if (alreadyAttached == null) { tracing?.Trace("not already attached"); service.Create(_Attachment); if (!file.Contains("filename")) { file["filename"] = ""; } attachedFiles.Add(file); } else { tracing?.Trace("already attached"); } } else { tracing?.Trace("Is Not Most Recent"); service.Create(_Attachment); } } #endregion }
public static InvalidPluginExecutionException BuildInvalidPluginExecutionException(Exception e, Type type, ITracingService tracingService) { if (tracingService != null) { tracingService.Trace(e.Message); tracingService.Trace(e.StackTrace); } var additionalInfo = new StringBuilder(); var executionException = e as InvalidPluginExecutionException; if (executionException != null) { var exc = executionException; return(exc); } var exception = e as FaultException <OrganizationServiceFault>; if (exception != null) { var exc = exception; additionalInfo.AppendFormat("\nTimestamp: {0}", exc.Detail.Timestamp); additionalInfo.AppendFormat("\nCode: {0}", exc.Detail.ErrorCode); additionalInfo.AppendFormat("\nMessage: {0}", exc.Detail.Message); additionalInfo.AppendFormat("\nTrace: {0}", exc.Detail.TraceText); if (exc.Detail.InnerFault != null) { additionalInfo.AppendFormat("\nInner Fault Message: {0}", exc.Detail.InnerFault.Message); additionalInfo.AppendFormat("\nInner Fault Trace: {0}", exc.Detail.InnerFault.TraceText); } } else { var timeoutException = e as TimeoutException; if (timeoutException != null) { var exc = timeoutException; additionalInfo.AppendFormat("\nMessage: {0}", exc.Message); additionalInfo.AppendFormat("\nTrace: {0}", exc.StackTrace); if (exc.InnerException != null) { additionalInfo.AppendFormat("\nInner Exception Message: {0}", exc.InnerException.Message); additionalInfo.AppendFormat("\nInner Exception Trace: {0}", exc.InnerException.StackTrace); } } else { additionalInfo.AppendFormat("\nMessage: {0}", e.Message); additionalInfo.AppendFormat("\nTrace: {0}", e.StackTrace); if (e.InnerException != null) { additionalInfo.AppendFormat("\nInner Exception Message: {0}", e.InnerException.Message); additionalInfo.AppendFormat("\nInner Exception Trace: {0}", e.InnerException.StackTrace); var exc = e.InnerException as FaultException <OrganizationServiceFault>; if (exc != null) { additionalInfo.AppendFormat("\nTimestamp: {0}", exc.Detail.Timestamp); additionalInfo.AppendFormat("\nCode: {0}", exc.Detail.ErrorCode); additionalInfo.AppendFormat("\nMessage: {0}", exc.Detail.Message); additionalInfo.AppendFormat("\nTrace: {0}", exc.Detail.TraceText); } } } } const string MessageFormatString = "An error occurred in the {0} plug-in. Exception: {1} Details: {2}"; var message = string.Format(MessageFormatString, type, e.Message, additionalInfo); tracingService?.Trace(message); var result = new InvalidPluginExecutionException(message, e); return(result); }
//Created By: Leslie Baliguat, Created On: 5/18/2016 /*Purpose: Update Order Status, Vehcicle Allocated Date and Inventory Id to Allocate fields of Sales Order to where Allocated vehicle is associated * Update Inventory Status of Inventory Record that is related to Allocated Vehicle * Update Available and Allocated fields of Product Quantity to where Inventory is associated * Registration Details: * Event/Message: * PreValidate/Delete: * Primary Entity: Allocated Vehicle */ public void RemoveAllocation(Entity allocatedEntity) { _tracingService.Trace("Started RemoveAllocation Method"); Entity salesOrderToUpdate = new Entity("salesorder"); if (allocatedEntity.GetAttributeValue <EntityReference>("gsc_orderid") != null) { _tracingService.Trace("Order Id not null"); var orderId = allocatedEntity.GetAttributeValue <EntityReference>("gsc_orderid").Id; EntityCollection orderRecords = CommonHandler.RetrieveRecordsByOneValue("salesorder", "salesorderid", orderId, _organizationService, null, OrderType.Ascending, new[] { "gsc_status", "gsc_vehicleallocateddate", "gsc_inventoryidtoallocate", "name" }); if (orderRecords != null && orderRecords.Entities.Count > 0) { _tracingService.Trace("Retrieved Related Order Details "); salesOrderToUpdate = orderRecords.Entities[0]; var status = salesOrderToUpdate.Contains("gsc_status") ? salesOrderToUpdate.GetAttributeValue <OptionSetValue>("gsc_status") : null; if (status.Value == 100000003) { salesOrderToUpdate["gsc_status"] = new OptionSetValue(100000002); salesOrderToUpdate["gsc_vehicleallocateddate"] = (DateTime?)null; salesOrderToUpdate["gsc_inventoryidtoallocate"] = null; _organizationService.Update(salesOrderToUpdate); } _tracingService.Trace("Related Order Updated"); } } /*************************************************************/ //Modified By: Raphael Herrera, Modified On: 8/14/2016 //Included cleanup for VehicleTransfer entity if (allocatedEntity.GetAttributeValue <EntityReference>("gsc_vehicletransferid") != null) { _tracingService.Trace("VehicleTransfer is not null"); var vehicleTransferId = allocatedEntity.GetAttributeValue <EntityReference>("gsc_vehicletransferid").Id; EntityCollection vehicleTransferCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_vehicletransfer", "gsc_iv_vehicletransferid", vehicleTransferId, _organizationService, null, OrderType.Ascending, new[] { "gsc_inventoryidtoallocate" }); _tracingService.Trace("Vehicle Transfer records retrieved: " + vehicleTransferCollection.Entities.Count); if (vehicleTransferCollection != null && vehicleTransferCollection.Entities.Count > 0) { Entity vehicleTransferEntity = vehicleTransferCollection.Entities[0]; vehicleTransferEntity["gsc_inventoryidtoallocate"] = null; _organizationService.Update(vehicleTransferEntity); _tracingService.Trace("Vehicle Transfer Record Updated"); } } /*************************************************************/ /*************************************************************/ //Modified By: Raphael Herrera, Modified On: 8/25/2016 //Included cleanup for Vehicle In-Transit Transfer Entity if (allocatedEntity.GetAttributeValue <EntityReference>("gsc_vehicleintransittransferid") != null) { _tracingService.Trace("Vehicle In-Transit Transfer is not null"); var vehicleInTransitId = allocatedEntity.GetAttributeValue <EntityReference>("gsc_vehicleintransittransferid").Id; EntityCollection vehicleInTransitCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_vehicleintransittransfer", "gsc_iv_vehicleintransittransferid", vehicleInTransitId, _organizationService, null, OrderType.Ascending, new[] { "gsc_inventoryidtoallocate", "gsc_intransittransferstatus" }); _tracingService.Trace("Vehicle In-Transit Transfer records retrieved: " + vehicleInTransitCollection.Entities.Count); if (vehicleInTransitCollection != null && vehicleInTransitCollection.Entities.Count > 0) { Entity vehicleInTransit = vehicleInTransitCollection.Entities[0]; //In-Transit Transfer Status != Picked if (vehicleInTransit.GetAttributeValue <OptionSetValue>("gsc_intransittransferstatus").Value != 100000000) { throw new InvalidPluginExecutionException("Unable to delete record that is already shipped."); } vehicleInTransit["gsc_inventoryidtoallocate"] = null; _organizationService.Update(vehicleInTransit); _tracingService.Trace("Vehicle Transfer Record Updated"); } } /*************************************************************/ if (allocatedEntity.GetAttributeValue <EntityReference>("gsc_inventoryid") != null) { _tracingService.Trace("Inventory Id not null"); var inventoryId = allocatedEntity.GetAttributeValue <EntityReference>("gsc_inventoryid").Id; EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending, new[] { "gsc_status", "gsc_color", "gsc_csno", "gsc_engineno", "gsc_modelcode", "gsc_optioncode", "gsc_productionno", "gsc_vin", "gsc_productquantityid", "gsc_modelyear", "gsc_siteid", "gsc_productid", "gsc_basemodelid" }); if (inventoryRecords != null && inventoryRecords.Entities.Count > 0) { _tracingService.Trace("Retrieved Related Inventory Details"); InventoryMovementHandler inventoryMovementHandler = new InventoryMovementHandler(_organizationService, _tracingService); inventoryMovementHandler.UpdateInventoryStatus(inventoryRecords.Entities[0], 100000000); Entity productQuantityEntity = inventoryMovementHandler.UpdateProductQuantity(inventoryRecords.Entities[0], 0, 1, -1, 0, 0, 0, 0, 0); // Create Inventory History Log inventoryMovementHandler.CreateInventoryQuantityAllocated(salesOrderToUpdate, inventoryRecords.Entities[0], productQuantityEntity, salesOrderToUpdate.GetAttributeValue <string>("name"), DateTime.UtcNow, "For Allocation", Guid.Empty, 100000003); } } _tracingService.Trace("Ended RemoveAllocation Method."); }
internal static void WriteToTrace(ITracingService traceService, string message) { if (traceService != null) traceService.Trace(message); }
public void Execute(IServiceProvider serviceProvider) { // Obtain the tracing service // The ITracingService enables writing to the tracing log ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. // The IPluginExecutionContext provides access to the context for the event that executed the plugin IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); // The InputParameters collection contains all the data passed in the message request. // The code verifies that the context InputParameters includes the expected parameters for the CreateRequest // that this plug-in will be registered for. If the Target property is present, the Entity that was passed to // the request will be available. if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { // Obtain the target entity from the input parameters. Entity entity = (Entity)context.InputParameters["Target"]; // Obtain the organization service reference which you will need for // web service calls. // The IOrganizationServiceFactory interface provides access to a service variable that implements the // IOrganizationService interface which provides the methods you will use to interact with the service to create the task. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { /* ***************************************** * Plug-in business logic goes here * *****************************************/ // Create a task activity to follow up with the account customer in 7 days. Entity followup = new Entity("task"); followup["subject"] = "Send e-mail to the new customer."; followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution."; followup["scheduledstart"] = DateTime.Now.AddDays(7); followup["scheduledend"] = DateTime.Now.AddDays(7); followup["category"] = context.PrimaryEntityName; // Refer to the account in the task activity. if (context.OutputParameters.Contains("id")) { Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString()); string regardingobjectidType = "account"; followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid); } // Create the task in Microsoft Dynamics CRM. tracingService.Trace("FollowupPlugin: Creating the task activity."); service.Create(followup); /* ***************************************** * END Plug-in business logic * *****************************************/ } catch (FaultException <OrganizationServiceFault> ex) { throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex); } catch (Exception ex) { tracingService.Trace("FollowUpPlugin: {0}", ex.ToString()); throw; } } }
protected override void Execute(CodeActivityContext executionContext) { ITracingService tracer = executionContext.GetExtension <ITracingService>(); IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { EntityReference emailWithAttachments = EmailWithAttachments.Get(executionContext); int deleteSizeMax = DeleteSizeMax.Get(executionContext); int deleteSizeMin = DeleteSizeMin.Get(executionContext); string extensions = Extensions.Get(executionContext); bool appendNotice = AppendNotice.Get(executionContext); if (deleteSizeMax == 0) { deleteSizeMax = int.MaxValue; } if (deleteSizeMin > deleteSizeMax) { tracer.Trace("Exception: {0}", "Min:" + deleteSizeMin + " Max:" + deleteSizeMax); throw new InvalidPluginExecutionException("Minimum Size Cannot Be Greater Than Maximum Size"); } EntityCollection attachments = GetAttachments(service, emailWithAttachments.Id); if (attachments.Entities.Count == 0) { return; } string[] filetypes = new string[0]; if (!string.IsNullOrEmpty(extensions)) { filetypes = extensions.Replace(".", string.Empty).Split(','); } StringBuilder notice = new StringBuilder(); int numberOfAttachmentsDeleted = 0; bool delete = false; foreach (Entity activityMineAttachment in attachments.Entities) { delete = false; if (activityMineAttachment.GetAttributeValue <int>("filesize") >= deleteSizeMax) { delete = true; } if (activityMineAttachment.GetAttributeValue <int>("filesize") <= deleteSizeMin) { delete = true; } if (filetypes.Length > 0 && delete) { delete = ExtensionMatch(filetypes, activityMineAttachment.GetAttributeValue <string>("filename")); } if (!delete) { continue; } DeleteEmailAttachment(service, activityMineAttachment.Id); numberOfAttachmentsDeleted++; if (appendNotice) { notice.AppendLine("Deleted Attachment: " + activityMineAttachment.GetAttributeValue <string>("filename") + " " + DateTime.Now.ToShortDateString() + "\r\n"); } } if (delete && appendNotice && notice.Length > 0) { UpdateEmail(service, emailWithAttachments.Id, notice.ToString()); } NumberOfAttachmentsDeleted.Set(executionContext, numberOfAttachmentsDeleted); } catch (Exception ex) { tracer.Trace("Exception: {0}", ex.ToString()); } }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(context.UserId); Entity postEmail = (Entity)context.PostEntityImages["emailPostImage"]; tracer.Trace("Executed Email Post Image "); CommonLib.Common common = new Common(); Entity email = common.RetrieveCrmRecord(service, "email", "activityid", postEmail.Id.ToString(), new string[] { "" }, true); string text = HTMLToText(email.Attributes["description"].ToString()); string subject = email.Attributes["subject"].ToString(); tracer.Trace("Email subject " + subject); tracer.Trace("Executed Email Post Image " + text); int startIndexCN = text.IndexOf("Client Name:"); int startIndexCP = text.IndexOf("Client Phone:"); int startIndexCE = text.IndexOf("Client Email:"); int startIndexSR = text.IndexOf("SR Number :"); //SR Number : mint_scrapedsrnumber int startIndexPN = text.IndexOf("Policy Number:"); //Policy Number: mint_scrapedpolicynumber int startIndexQN = text.IndexOf("Quote number:"); //Quote number: mint_scrapedquotenumber int startIndexSV = text.IndexOf("Quote Value:"); //mint_scrapedvalue tracer.Trace("startIndexCN " + startIndexCN); tracer.Trace("startIndexCP " + startIndexCP); tracer.Trace("startIndexCE " + startIndexCE); tracer.Trace("startIndexSR " + startIndexSR); tracer.Trace("startIndexPN " + startIndexPN); tracer.Trace("startIndexQN " + startIndexQN); tracer.Trace("startIndexSV " + startIndexSV); string nameC = ""; if (startIndexCN > 0) { nameC = text.Substring(startIndexCN + 12, startIndexCP - (startIndexCN + 12)); } string phoneC = ""; if (startIndexCN > 0) { phoneC = text.Substring(startIndexCP + 13, startIndexCE - (startIndexCP + 13)); } string emailC = ""; if (startIndexCN > 0) { emailC = text.Substring(startIndexCE + 13, startIndexSR - (startIndexCE + 13)); } string srNumber = ""; if (startIndexCN > 0) { srNumber = text.Substring(startIndexSR + 11, startIndexPN - (startIndexSR + 11)); } string policyN = ""; if (startIndexCN > 0) { policyN = text.Substring(startIndexPN + 14, startIndexQN - (startIndexPN + 14)); } string quoteN = ""; if (startIndexCN > 0) { quoteN = text.Substring(startIndexQN + 13, startIndexSV - (startIndexQN + 13)); } string quoteV = ""; Money quoteVm = new Money(0); if (startIndexCN > 0) { quoteV = text.Substring(startIndexSV + 13, text.Length - (startIndexSV + 13)); //string s2 = string.Format("{0:#,0.#}", float.Parse(s)); quoteVm = new Money(decimal.Parse(quoteV)); } tracer.Trace("name "); // tracer.Trace("name " + nameC); //mint_scrapedclientname tracer.Trace("phone " + phoneC); tracer.Trace("email " + emailC); tracer.Trace("srNumber " + srNumber); email.Attributes["mint_scrapedclientname"] = nameC; email.Attributes["mint_scrapedsrnumber"] = srNumber; email.Attributes["mint_scrapedpolicynumber"] = policyN; email.Attributes["mint_scrapedquotenumber"] = quoteN; email.Attributes["mint_scrapedclientemail"] = emailC; email.Attributes["mint_scrapedclientphone"] = phoneC; email.Attributes["mint_scrapedvalue"] = quoteVm; // Money mny = new Money(decimal.Parse(objCol.txt1)); service.Update(email); string srSubject = ""; int ind = 0; if (subject.Contains("SR")) // SR – 1234567 – RFQ { tracer.Trace("Contains SR "); ind = subject.IndexOf("SR"); tracer.Trace("ind " + ind.ToString()); if (ind > 0) { tracer.Trace("Contains SR f (ind > 0) "); srSubject = subject.Substring(ind, 18); // text.Substring(startIndexQN + 12, startIndexSV - (startIndexQN + 12)); } tracer.Trace("Contains SR srSubject " + srSubject); } //Entity regardingCase = common.RetrieveCrmRecord(service, "incident", "mint_srnumber1", srNumber, new string[] { "" }, true); ConditionExpression condition1 = new ConditionExpression(); condition1.AttributeName = "mint_srnumber1"; condition1.Operator = ConditionOperator.Equal; if (ind > 0) { condition1.Values.Add(srSubject.Trim()); } else { condition1.Values.Add(srNumber.Trim()); } FilterExpression filter1 = new FilterExpression(); filter1.Conditions.Add(condition1); QueryExpression query = new QueryExpression("incident"); query.ColumnSet.AddColumns("mint_srnumber1", "incidentid"); query.Criteria.AddFilter(filter1); EntityCollection regardingCase = service.RetrieveMultiple(query); tracer.Trace("regardingCase Count" + regardingCase.Entities.Count); tracer.Trace("regardingCase "); if (regardingCase.Entities.Count > 0) { tracer.Trace("regardingCase 1 "); tracer.Trace("regardingCase ID - " + regardingCase[0].Attributes["incidentid"].ToString()); Guid relatedCase = new Guid(regardingCase[0].Attributes["incidentid"].ToString()); email.Attributes["regardingobjectid"] = new EntityReference("incident", relatedCase); //(EntityReference)regardingCase.Attributes["incidentid"]; service.Update(email); } tracer.Trace("regardingCase ID"); tracer.Trace("regardingCase ID " + regardingCase[0].Id.ToString()); }
public void Execute(IServiceProvider serviceProvider) { // Extract the tracing service for use in debugging sandboxed plug-ins. // If you are not registering the plug-in in the sandbox, then you do // not have to add any tracing service related code. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); tracingService.Trace("In RSVPPlugin"); // The InputParameters collection contains all the data passed in the message request. if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { // Get the entity being operated om Entity entity = (Entity)context.InputParameters["Target"]; // Obtain the organization service reference which you will need for // web service calls. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { tracingService.Trace("Running for entity {0}", entity.LogicalName); // Should only run for the RSVP entity if (entity.LogicalName != CRMExtensions.ORM.msdev_rsvp.EntityLogicalName) { throw new InvalidPluginExecutionException("Unsupported registration"); } Dynamics365Context svc = new Dynamics365Context(service); var rsvp = entity.ToEntity <msdev_rsvp>(); // Need to ensure we do not exceed max attendance. If this RSVP is not attending, // no need to check if (rsvp.msdev_Attending.GetValueOrDefault(false)) { // Get max attendance for the event and compare against number of attending RSVPs var rsvpEvent = svc.msdev_meetupSet.First(e => e.msdev_meetupId == rsvp.msdev_MeetupId.Id); var eventAttendees = svc.msdev_rsvpSet.Where( r => r.msdev_MeetupId != null && r.msdev_MeetupId.Id == rsvpEvent.Id && r.msdev_Attending == true) .ToList(); if ((eventAttendees.Count + 1) > rsvpEvent.msdev_MaxAttendees.GetValueOrDefault(Int32.MaxValue)) { throw new InvalidPluginExecutionException("Maximum attendance exceeded"); } } } catch (FaultException <OrganizationServiceFault> ex) { throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex); } catch (Exception ex) { tracingService.Trace("MyPlugin: {0}", ex.ToString()); throw; } } }
protected void Trace_of(string method, List <string> parameters) { _tracingService.Trace($"{method}: {parameters.Aggregate("", (a, b) => a + ", " + b)}"); }
private static void HandleException(Exception e, ITracingService tracingService) { tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e)); tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "StackTrace: {0}", e.StackTrace)); var organizationServiceFault = new OrganizationServiceFault { Message = e.Message }; organizationServiceFault.ErrorDetails.Add("Original Exception", e); throw new FaultException<OrganizationServiceFault>(organizationServiceFault, e.Message); }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); try { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); //verify that this the correct event if (context.MessageName.ToUpper() != "UPDATE") { return; } if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity entity = (Entity)context.InputParameters["Target"]; //verify that this is the target entity if (entity.LogicalName.ToUpper() != "OPPORTUNITY") { return; } //the entity contains fields that have been updated //iterate through list to see if any airport fields have changed List <string> fields = new List <string>(); fields.Add("dev_departairport"); fields.Add("dev_arrive1"); fields.Add("dev_arrive2"); fields.Add("dev_arrive3"); fields.Add("dev_arrive4"); bool airportChange = false; foreach (KeyValuePair <string, object> item in entity.Attributes) { if (fields.Contains(item.Key)) { airportChange = true; break; } } //this keep the plugin code from recalculating data if (!airportChange) { return; } //organizational service reference for web service calls IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); TripInfo tripInfo = GetTripInfo(entity.Id, service); string distance1 = ""; if (tripInfo.TripLegs >= 1) { double distance = GetDistance(tripInfo.DepartAirport, tripInfo.Arrival1, service); distance1 = Math.Round(distance, 1).ToString() + " NM"; } string distance2 = ""; if (tripInfo.TripLegs >= 2) { double distance = GetDistance(tripInfo.Arrival1, tripInfo.Arrival2, service); distance2 = Math.Round(distance, 1).ToString() + " NM"; } string distance3 = ""; if (tripInfo.TripLegs >= 3) { double distance = GetDistance(tripInfo.Arrival2, tripInfo.Arrival3, service); distance3 = Math.Round(distance, 1).ToString() + " NM"; } string distance4 = ""; if (tripInfo.TripLegs == 4) { double distance = GetDistance(tripInfo.Arrival3, tripInfo.Arrival4, service); distance4 = Math.Round(distance, 1).ToString() + " NM"; } Entity updateOpportunity = new Entity("opportunity"); updateOpportunity.Id = entity.Id; updateOpportunity.Attributes["dev_distance1"] = distance1; updateOpportunity.Attributes["dev_distance2"] = distance2; updateOpportunity.Attributes["dev_distance3"] = distance3; updateOpportunity.Attributes["dev_distance4"] = distance4; service.Update(updateOpportunity); } } catch (Exception ex) { tracingService.Trace("Plugin: {0}, Error: {1}", "DistanceCalulator", ex.Message); } }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity)) { throw new InvalidPluginExecutionException("Target is not Entity"); } if (!context.PostEntityImages.Contains("image") || !(context.PostEntityImages["image"] is Entity)) { throw new InvalidPluginExecutionException("Context has no post entity images"); } Entity targetEntity = (Entity)context.InputParameters["Target"]; if (targetEntity.LogicalName != "al_order" && context.MessageName != "Create") { throw new InvalidPluginExecutionException("Target's logical name is not order or action is not create"); } try { IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); tracingService.Trace("PostOrderCreate: Get order object values"); Entity currentOrder = (Entity)context.InputParameters["Target"]; //EntityReference currentContact = currentDogovor.GetAttributeValue<EntityReference>("al_contact"); var orderValues = service.Retrieve(currentOrder.LogicalName, currentOrder.Id, new ColumnSet(new string[] { "al_facted", "al_summa", "al_dogovorid" })); tracingService.Trace("PostOrderCreate: Check if order is paid"); var isPaid = currentOrder.GetAttributeValue <bool>("al_facted"); // проверка статуса оплачено на объекте счет if (isPaid) { var contractId = currentOrder.GetAttributeValue <EntityReference>("al_dogovorid").Id; tracingService.Trace("PostOrderCreateUpdate: Get paid orders by contract and sums"); // поиск всех оплаченных счетов для данного договора QueryExpression queryExpression = new QueryExpression(); queryExpression.EntityName = "al_order"; queryExpression.ColumnSet = new ColumnSet(new string[] { "al_summa" }); queryExpression.Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "al_dogovorid", Operator = ConditionOperator.Equal, Values = { contractId } }, new ConditionExpression { AttributeName = "al_facted", Operator = ConditionOperator.Equal, Values = { true } } } }; var entityCollection = service.RetrieveMultiple(queryExpression); // общая сумма счетов var commonSum = 0; // подсчёт общей суммы счетов foreach (var ent in entityCollection.Entities) { commonSum = commonSum + (int)ent.Attributes["al_summa"]; } tracingService.Trace("PostOrderCreateUpdate: Set fact summa in contract object."); // объект договор связанный со счетами var contractValues = service.Retrieve("al_dogovor", contractId, new ColumnSet(new string[] { "al_summa" })); Entity contractToUpdate = new Entity("al_dogovor", contractId); // общая сумма в договоре var contractSum = contractValues.GetAttributeValue <Money>("al_summa"); // проверка не превышает ли общая сумма счетов общей суммы в договоре if ((decimal)commonSum > contractSum.Value) { throw new InvalidPluginExecutionException("Common sum of bills greater than contract sum"); } // обновление общей суммы в объекте договор contractToUpdate["al_factsumma"] = new Money((decimal)commonSum); service.Update(contractToUpdate); } } catch (Exception ex) { tracingService.Trace("PostOrderCreate: {0}", ex.ToString()); throw; } }
public void Execute(IServiceProvider serviceProvider) { ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); sharedMethods = new MShared(); try { // 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); // The InputParameters collection contains all the data passed in the message request. /*Esta validación previene la ejecución del Plugin de cualquier * transacción realizada a través del Web API desde Abox*/ if (context.InitiatingUserId == new Guid("7dbf49f3-8be8-ea11-a817-002248029f77")) { return; } EntityReference targetEntity = null; string relationshipName = string.Empty; EntityReferenceCollection relatedEntities = null; EntityReference doctorRelated = null; Entity contact = null; UpdatePatientRequest.Request updatePatientRequest = null; #region Associate & Disassociate // if (context.MessageName.ToLower() == "associate" || context.MessageName.ToLower() == "disassociate") if (context.MessageName.ToLower() == "associate" || context.MessageName.ToLower() == "disassociate") { contactEntity = new ContactEntity(); // Get the “Relationship” Key from context if (context.InputParameters.Contains("Relationship")) { // Get the Relationship name for which this plugin fired relationshipName = ((Relationship)context.InputParameters["Relationship"]).SchemaName; } // Check the "Relationship Name" with your intended one if (relationshipName != ContactFields.ContactxDoctorRelationship) { return; } else { productEntity = new ProductEntity(); updatePatientRequest = new UpdatePatientRequest.Request(); ContactMethods contactMethods = new ContactMethods(); #region -> Target if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference) { helperMethods = new RequestHelpers(); targetEntity = (EntityReference)context.InputParameters["Target"]; string[] columnsToGet = new string[] { ContactFields.IdAboxPatient, ContactFields.Country, ContactFields.UserType, ContactFields.IdType, ContactFields.Id, ContactFields.Firstname, ContactFields.SecondLastname, ContactFields.Lastname, ContactFields.Gender, ContactFields.Birthdate }; var columnSet = new ColumnSet(columnsToGet); contact = service.Retrieve(contactEntity.EntitySingularName, targetEntity.Id, columnSet); var relatedContacts = contactMethods.GetContactChildContacts(contact, service); if (relatedContacts != null) { if (relatedContacts.Entities.Count > 0) { Exception serviceEx = new Exception("No es posible realizar esta operación en usuarios que tienen pacientes bajo cuido registrados."); serviceEx.Data["HasFeedbackMessage"] = true; throw serviceEx; } } string userType = ""; if (contact.Attributes.Contains(ContactFields.UserType)) { EntityReference userTypeReference = null; userTypeReference = (EntityReference)contact.Attributes[ContactFields.UserType]; if (userTypeReference != null) { userType = sharedMethods.GetUserTypeId(userTypeReference.Id.ToString()); } } if (userType == "05") { Exception serviceEx = new Exception("Es necesario cambiar el tipo de usuario de este contacto para poder agregar médicos."); serviceEx.Data["HasFeedbackMessage"] = true; throw serviceEx; } //updatePatientRequest.personalinfo = new UpdatePatientRequest.Request.Personalinfo(); updatePatientRequest = helperMethods.GetPatientUpdateStructure(contact, service, trace); } #endregion -> Target #region -> Related doctorEntity = new DoctorEntity(); relatedEntities = context.InputParameters["RelatedEntities"] as EntityReferenceCollection; if (relatedEntities.Count > 0) { if (context.MessageName.ToLower() == "associate") { #region -> Associate int relatedEntitiesCount = relatedEntities.Count; int contactCurrentRelatedDoctors = 0; System.Collections.Generic.List <UpdatePatientRequest.Request.Medic> medicsToSave = new System.Collections.Generic.List <UpdatePatientRequest.Request.Medic>(); if (updatePatientRequest.medication == null) { updatePatientRequest.medication = new UpdatePatientRequest.Request.Medication(); updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[relatedEntitiesCount]; } else { if (updatePatientRequest.medication.medics == null) { updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[relatedEntitiesCount]; } else { contactCurrentRelatedDoctors = updatePatientRequest.medication.medics.Length; if (contactCurrentRelatedDoctors > 0) { for (int i = 0; i < contactCurrentRelatedDoctors; i++) { medicsToSave.Add(updatePatientRequest.medication.medics[i]); } updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[relatedEntitiesCount + contactCurrentRelatedDoctors]; } } } for (int i = 0; i < relatedEntitiesCount; i++) { doctorRelated = relatedEntities[i]; Entity doctor = service.Retrieve(doctorEntity.EntitySingularName, doctorRelated.Id, new ColumnSet(DoctorFields.DoctorIdKey)); if (doctor.Attributes.Contains(DoctorFields.DoctorIdKey)) { medicsToSave.Add(new UpdatePatientRequest.Request.Medic { medicid = doctor.GetAttributeValue <string>(DoctorFields.DoctorIdKey) }); } } int totalMedicsToSaveCount = updatePatientRequest.medication.medics.Length; for (int i = 0; i < totalMedicsToSaveCount; i++) { updatePatientRequest.medication.medics[i] = medicsToSave[i]; } #endregion -> Associate } else { #region -> Disassociate if (updatePatientRequest.medication != null) { if (updatePatientRequest.medication.medics != null) { System.Collections.Generic.List <UpdatePatientRequest.Request.Medic> medicsToSave = new System.Collections.Generic.List <UpdatePatientRequest.Request.Medic>(); //Recorrer la lista de medicos que se estan desasociando del contacto foreach (var relatedItem in relatedEntities) { //Obtener la entidad con el Id de Medico Entity doctorToRemove = service.Retrieve(doctorEntity.EntitySingularName, relatedItem.Id, new ColumnSet(DoctorFields.DoctorIdKey)); int medicsLength = updatePatientRequest.medication.medics.Length; //Buscar en la lista de medicos que tiene el usuario for (int i = 0; i < medicsLength; i++) { //Agregar a la lista de medicos a guardar, aquellos que no fueron desasociados if (updatePatientRequest.medication.medics[i].medicid != doctorToRemove.GetAttributeValue <string>(DoctorFields.DoctorIdKey)) { medicsToSave.Add(updatePatientRequest.medication.medics[i]); } } } //Enviar como null si no hay pacientes a guardar if (medicsToSave.Count == 0) { updatePatientRequest.medication.medics = null; } else { //Modificar el tamaño del array y agregar los médicos que se guardarán updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[medicsToSave.Count]; int length = updatePatientRequest.medication.medics.Length; for (int i = 0; i < length; i++) { updatePatientRequest.medication.medics[i] = medicsToSave[i]; } } } } #endregion -> Disassociate } } #endregion -> Related ///Request service POST /// DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UpdatePatientRequest.Request)); MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, updatePatientRequest); var jsonObject = Encoding.Default.GetString(memoryStream.ToArray()); memoryStream.Dispose(); //Valores necesarios para hacer el Post Request WebRequestData wrData = new WebRequestData(); wrData.InputData = jsonObject; wrData.ContentType = "application/json"; wrData.Authorization = "Bearer " + Configuration.TokenForAboxServices; wrData.Url = AboxServices.UpdatePatientService; var serviceResponse = sharedMethods.DoPostRequest(wrData, trace); UpdatePatientRequest.ServiceResponse serviceResponseProperties = null; if (serviceResponse.IsSuccessful) { DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UpdatePatientRequest.ServiceResponse)); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(serviceResponse.Data))) { deserializer = new DataContractJsonSerializer(typeof(UpdatePatientRequest.ServiceResponse)); serviceResponseProperties = (UpdatePatientRequest.ServiceResponse)deserializer.ReadObject(ms); } if (serviceResponseProperties.response.code != "MEMCTRL-1014") { trace.Trace(Constants.ErrorMessageCodeReturned + serviceResponseProperties.response.code); Exception serviceEx = new Exception(Constants.GeneralAboxServicesErrorMessage + serviceResponseProperties.response.message); serviceEx.Data["HasFeedbackMessage"] = true; throw serviceEx; } else { //contact.Attributes.Add("new_idaboxpatient", serviceResponseProperties.response.details.idPaciente); } } else { throw new InvalidPluginExecutionException(Constants.GeneralAboxServicesErrorMessage); } } } #endregion Associate & Disassociate } catch (Exception ex) { trace.Trace($"MethodName: {new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + ex.ToString()); try { sharedMethods.LogPluginFeedback(new LogClass { Exception = ex.ToString(), Level = "error", ClassName = this.GetType().ToString(), MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name, Message = "Excepción en plugin", ProcessId = "" }, trace); } catch (Exception e) { trace.Trace($"MethodName: {new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + e.ToString()); } if (ex.Data["HasFeedbackMessage"] != null) { throw new InvalidPluginExecutionException(ex.Message); } else { throw new InvalidPluginExecutionException(Constants.GeneralPluginErrorMessage); } } }
/// <summary> /// /// </summary> /// <param name="contact"></param> /// <returns></returns> internal static OracleResponse UpsertSupplierInOracle(Contact contact, string connString, ITracingService tracingService) { tracingService.Trace("Starting the UpsertSupplierInOracle"); OracleResponse oracleResponse = new OracleResponse(); OracleConnection conn = new OracleConnection(); conn.ConnectionString = connString; OracleCommand objCmd = new OracleCommand(); objCmd.Connection = conn; objCmd.CommandText = ConfigEntity.ORACLE_COMMAND_TEXT; //Upsert Supplier in Oracle objCmd.CommandType = CommandType.StoredProcedure; objCmd.Parameters.Add(ConfigEntity.SPParams.FIRST_NAME, OracleDbType.Varchar2, 100).Value = contact.First_Name; objCmd.Parameters.Add(ConfigEntity.SPParams.LAST_NAME, OracleDbType.Varchar2, 100).Value = contact.Last_Name; objCmd.Parameters.Add(ConfigEntity.SPParams.PAYMENT_METHOD, OracleDbType.Varchar2, 10).Value = contact.Payment_Method; //EFT or CHQ // Send EFT from code objCmd.Parameters.Add(ConfigEntity.SPParams.SIN, OracleDbType.Double, 100).Value = int.Parse(contact.SIN); objCmd.Parameters.Add(ConfigEntity.SPParams.ADDRESS1, OracleDbType.Varchar2, 1000).Value = contact.Address1; objCmd.Parameters.Add(ConfigEntity.SPParams.CITY, OracleDbType.Varchar2, 2000).Value = contact.City; objCmd.Parameters.Add(ConfigEntity.SPParams.POSTAL_CODE, OracleDbType.Varchar2, 10).Value = contact.Postal_Code; objCmd.Parameters.Add(ConfigEntity.SPParams.PROVINCE_CODE, OracleDbType.Varchar2, 20).Value = contact.Province_Code; objCmd.Parameters.Add(ConfigEntity.SPParams.COUNTRY_CODE, OracleDbType.Varchar2, 10).Value = contact.Country_Code; objCmd.Parameters.Add(ConfigEntity.SPParams.VALID_FROM, OracleDbType.Date, 2000).Value = DateTime.Today.Date; //Output Params if (contact.Party_Id > 0) //If an update request than send party ID { objCmd.Parameters.Add(ConfigEntity.SPParams.PARTY_ID, OracleDbType.Double, 2000).Value = contact.Party_Id; } else //Since Party ID is -1 i.e. the create request. { objCmd.Parameters.Add(ConfigEntity.SPParams.PARTY_ID, OracleDbType.Double, 2000).Direction = ParameterDirection.InputOutput; } objCmd.Parameters.Add(ConfigEntity.SPParams.TRANSACTION_CODE, OracleDbType.Varchar2, 1000).Direction = ParameterDirection.Output; objCmd.Parameters.Add(ConfigEntity.SPParams.TRANSACTION_MESSAGE, OracleDbType.Varchar2, 2000).Direction = ParameterDirection.Output; try { tracingService.Trace("Opening Connection"); conn.Open(); tracingService.Trace("Connection Opened"); objCmd.ExecuteNonQuery(); tracingService.Trace("Query Executed"); oracleResponse.PartyId = int.Parse(objCmd.Parameters[ConfigEntity.SPParams.PARTY_ID].Value.ToString()); oracleResponse.TransactionMessage = objCmd.Parameters[ConfigEntity.SPParams.TRANSACTION_MESSAGE].Value.ToString(); oracleResponse.TransactionCode = objCmd.Parameters[ConfigEntity.SPParams.TRANSACTION_CODE].Value.ToString(); tracingService.Trace("Populated Oracle Response"); } catch (Exception ex) { throw new InvalidPluginExecutionException(OperationStatus.Failed, new StringBuilder().Append(Strings.STORED_PROCEDURE_EXCEPTION) .Append(ConfigEntity.ORACLE_COMMAND_TEXT).AppendLine(" Exception:\n").AppendLine(ex.Message).ToString()); } finally { tracingService.Trace("Closing connection"); conn.Close(); tracingService.Trace("Connection closed"); } return(oracleResponse); }
public static void DoJob(IServiceProvider serviceProvider) { // var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); Entity entity = (Entity)context.InputParameters["Target"]; //entity = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet(new string[] { "eti_account", "eti_product" })); try { tracingService.Trace($"start"); var result = service.Retrieve("productassociation", entity.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("eti_productassociationrule", "productid")); //get pricelist var product = service.Retrieve("product", result.GetAttributeValue <EntityReference>("productid").Id, new ColumnSet("eti_associatedpricelist")); //get pricelevel var pricelevelQuery = new QueryExpression { EntityName = "productpricelevel", ColumnSet = new ColumnSet("amount"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "productid", Operator = ConditionOperator.Equal, Values = { product.Id } }, new ConditionExpression { AttributeName = "pricelevelid", Operator = ConditionOperator.Equal, Values = { product.GetAttributeValue <EntityReference>("eti_associatedpricelist").Id } } } } }; var pricelevel = service.RetrieveMultiple(pricelevelQuery).Entities[0]; tracingService.Trace($"pl {pricelevel.Id}"); var parentId = result.GetAttributeValue <EntityReference>("productid").Id; var associationsQuery = new QueryExpression { EntityName = "productassociation", ColumnSet = new ColumnSet("eti_productassociationrule", "eti_price"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "eti_requirementmode", Operator = ConditionOperator.Equal, Values = { 964820000 } }, new ConditionExpression { AttributeName = "productid", Operator = ConditionOperator.Equal, Values = { parentId } } } } }; var results = service.RetrieveMultiple(associationsQuery).Entities; tracingService.Trace($"found {results.Count}"); decimal sum = 0; foreach (Entity en in results) { sum += en.GetAttributeValue <Money>("eti_price").Value; //calculate sum } tracingService.Trace($"sum {sum}"); pricelevel.Attributes["amount"] = new Money(sum); service.Update(pricelevel); } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } }
public void Execute(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); if (tracingService == null) { throw new ApplicationException("Failed to initialize plugin tracing service"); } IPluginExecutionContext pluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); if (pluginExecutionContext == null) { throw new ApplicationException("Failed to initialize plugin execution context"); } IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); if (serviceFactory == null) { throw new ApplicationException("Failed to initialize plugin serviceFactory"); } try { var container = new Container(); container.Register <ITracingService>(() => tracingService); container.Register <IPluginExecutionContext>(() => pluginExecutionContext); container.Register <IOrganizationServiceFactory>(() => serviceFactory); container.Register <IRepositoryFactory>(() => new RepositoryFactory(container)); container.Register <IServicesFactory>(() => new ServicesFactory(container)); this.RegisterDependencies(container); if (this.IsContextValid(pluginExecutionContext)) { this.Execute(pluginExecutionContext, container); } else { tracingService.Trace($"Invalid plugin execution context detected (Plugin: {this.Name})"); tracingService.Trace("Plugin execution aborted"); throw new InvalidPluginExecutionException("Invalid plugin execution context detected"); } } catch (InvalidPluginExecutionException) { throw; } catch (OutOfMemoryException e) { throw new InvalidPluginExecutionException(OperationStatus.Failed, e.Message); } catch (StackOverflowException e) { throw new InvalidPluginExecutionException(OperationStatus.Failed, e.Message); } catch (ThreadAbortException e) { throw new InvalidPluginExecutionException(OperationStatus.Failed, e.Message); } catch (Exception e) { tracingService?.Trace($"Plugin failed unexpectedly: '{this.Name}'"); tracingService.Trace($"Exception: {e}"); throw new InvalidPluginExecutionException(OperationStatus.Failed, "Sorry, the action failed unexpectedly!"); } }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity)) { throw new InvalidPluginExecutionException("Target is not Entity"); } Entity targetEntity = (Entity)context.InputParameters["Target"]; if (targetEntity.LogicalName != "al_dogovor") { throw new InvalidPluginExecutionException("Target's logical name is not al_dogovor"); } try { IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // заполнение поля Дата первого договора на карточке объекта Контакт tracingService.Trace("SetFirstContractDate: Get first date by contact id"); // внешний ключ из договора на объект контакт //Entity dogovor = new Entity("al_dogovor"); Entity currentDogovor = (Entity)context.InputParameters["Target"]; Entity currentContact = currentDogovor.GetAttributeValue <Entity>("al_contact"); //EntityReference contactRef = dogovor.GetAttributeValue<EntityReference>("al_contact"); // дата договора var contractDate = currentDogovor.GetAttributeValue <DateTime>("al_date"); // поиск даты первого договора для заданного контакта QueryExpression queryExpression = new QueryExpression(); queryExpression.EntityName = "al_dogovor"; queryExpression.ColumnSet = new ColumnSet(new string[] { "al_date", "al_contact" }); queryExpression.Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "al_contact", Operator = ConditionOperator.Equal, Values = { /*contactRef*/ currentContact } } } }; queryExpression.AddOrder("al_date", OrderType.Ascending); queryExpression.TopCount = 1; var entityCollection = service.RetrieveMultiple(queryExpression); tracingService.Trace("SetFirstContractDate: Get query result"); // дата первого договора var date = entityCollection[0].GetAttributeValue <DateTime>("al_date"); tracingService.Trace("PostContractCreate: Set first contract date in contact object"); // обновление даты первого договора tracingService.Trace($"Current contact id = {currentContact?.Id} date = {date}"); Entity contactToUpdate = new Entity("contact", currentContact.Id); contactToUpdate["al_date"] = date; service.Update(contactToUpdate); //ContractService svc = new /*TestPlugins.*/ContractService(service, tracingService); //svc.SetFirstContractDate(); } catch (Exception ex) { tracingService.Trace("PreContact: {0}", ex.ToString()); throw; } }