/// <summary> /// Execute /// </summary> /// <param name="serviceProvider"></param> public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(context.UserId); try { if ((context.InputParameters == null) || (!context.InputParameters.Contains("Target"))) { return; } else if (context.MessageName == "Update" && context.Depth > 1) { return; } Entity serviceRequest = (context.PostEntityImages != null && context.PostEntityImages.Contains("PostImage")) ? (Entity)context.PostEntityImages["PostImage"] : null; EntityCollection configurationCollection = ServiceRequestHelper.GetConfigurationValueCollection(service); Provider provider = ServiceRequestHelper.GetProviderDetails(service, ((EntityReference)serviceRequest["customerid"]).Id, configurationCollection, trace); int caseOrigin = ((OptionSetValue)serviceRequest["caseorigincode"]).Value; //// Check if provider is not updated, if not updated no action is desired. if (!provider.IsProviderUpdated) { ServiceRequestHelper.SetProviderCriteriaMissingFields(service, serviceRequest); return; } string currentStatusCode = ServiceRequestHelper.GetStatusCodeFromValue(service, ((OptionSetValue)((Entity)context.InputParameters["Target"])["statuscode"]).Value); string priorityName = serviceRequest.Attributes.Contains("smp_priorityid") ? ((EntityReference)serviceRequest["smp_priorityid"]).Name : string.Empty; string invalidIntegrationCodes = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("NoCmmsIntegrationActionCodes")).First()["smp_value"].ToString(); int preStatus = context.PreEntityImages.Contains("PreImage") ? ((OptionSetValue)context.PreEntityImages["PreImage"]["statuscode"]).Value : -1; var configurationList = from val in configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals(CRMAttributesResource.RoutingPriorities8By8)).First()["smp_value"].ToString().Split(',') select val; if (caseOrigin == 3 && currentStatusCode.ToLower() == "open" && configurationList.Contains(priorityName) && preStatus != 180620012) { trace.Trace("Aborting Integration....."); } else if (preStatus == 1 && (currentStatusCode.ToLower() == "cncl" || currentStatusCode.ToLower() == "clsd" || currentStatusCode.ToLower() == "comp")) { trace.Trace("Aborting Integration as Pre status is :{0} and Current Status :{1}", preStatus, currentStatusCode.ToLower()); } else if (!string.IsNullOrWhiteSpace(currentStatusCode) && !string.IsNullOrWhiteSpace(invalidIntegrationCodes) && (!invalidIntegrationCodes.ToUpperInvariant().Contains(currentStatusCode.ToUpperInvariant()))) { //// Call integration if status code doesnot falls in invalid integration codes or //// current status is "Dispatched" and previous status is "Pending CSR Dispatched" DoIntegration(service, serviceRequest, provider, trace, caseOrigin, configurationCollection); } else { trace.Trace("The Status is Invalid"); } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
/// <summary> /// Retrieves the users settings. /// </summary> /// <param name="service">The service.</param> /// <returns></returns> public static int?RetrieveUsersSettings(IOrganizationService service, Guid userId, int caseorigin, bool portalSubmit, int prevStatusCode, int statusCode, ITracingService trace) { Entity currentUserSettings = null; try { trace.Trace("caseorigin : " + caseorigin); trace.Trace("portalSubmit : " + portalSubmit); trace.Trace("statusCode : " + statusCode); trace.Trace("prevStatusCode : " + prevStatusCode); if ((caseorigin != (int)ServiceRequestEnum.ServiceRequestOrigin.Web && portalSubmit == false) || (caseorigin == (int)ServiceRequestEnum.ServiceRequestOrigin.Web && portalSubmit == false && statusCode != (int)ServiceRequestEnum.StatusCode.Draft) || (portalSubmit == true && prevStatusCode == (int)ServiceRequestEnum.StatusCode.PendingCSRDispatch)) { currentUserSettings = service.RetrieveMultiple( new QueryExpression("usersettings") { ColumnSet = new ColumnSet("timezonecode"), Criteria = new FilterExpression { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, userId) } } }).Entities[0].ToEntity <Entity>(); } else { string fromUserDomainName = ServiceRequestHelper.GetConfigurationValue(service, "EmailSenderDomainName"); Guid systemId = ServiceRequestHelper.GetCrmUserId(service, fromUserDomainName); currentUserSettings = service.RetrieveMultiple( new QueryExpression("usersettings") { ColumnSet = new ColumnSet("timezonecode"), Criteria = new FilterExpression { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, systemId) } } }).Entities[0].ToEntity <Entity>(); } } catch (Exception e) { trace.Trace("error"); trace.Trace("In Exception :" + e.Message); throw e; } return((int?)currentUserSettings.Attributes["timezonecode"]); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostServiceRequestsmp_CopySR(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } // TODO: Implement your custom Plug-in business logic. IPluginExecutionContext context = localContext.PluginExecutionContext; ITracingService trace = localContext.TracingService; trace.Trace("In Copy SR"); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference) { EntityReference entity = (EntityReference)context.InputParameters["Target"]; var service = localContext.OrganizationService; if (entity.LogicalName == "incident") { Entity serviceRequest = serviceRequest = ServiceRequestHelper.GetServiceRequestDetails(service, entity.Id); string[] strAttributesServiceRequestToRemove = new string[] { "ticketnumber", "title", "statuscode", "customerid", "smp_referencesr", "incidentid", "createdon", "createdby", "modifiedon", "modifiedby", "smp_issurveyservicerequest", "smp_cancelledforreclassification", "smp_slamet", "smp_priorityid", "smp_submitteddatetime", "smp_problemoccureddatetime", "smp_duedate", "smp_tier1workcompletiondatebybuildingtimezone", "smp_completeddate", "smp_completeddatebybuildingtimezone", "smp_requestedduedate", "smp_createddatetimebybuildingtimezone", "smp_submitteddatetimebybuildingtimezone", "smp_occureddatetimebybuildingtimezone", "smp_duedatebybuildingtimezone", "smp_providerduedatebybuildingtimezone", "ownerid", "smp_duedatetimebybuildingtimezone", "smp_statusonhold", "smp_problemtypedescriptionid", "smp_answer" }; Entity entNewIncident = this.CloneRecordForEntity("incident", serviceRequest, strAttributesServiceRequestToRemove); entNewIncident["customerid"] = new EntityReference(CRMAttributesResource.AccountEntity, this.GetProviderId(service, "Not Assigned")); entNewIncident["caseorigincode"] = new OptionSetValue(1); entNewIncident["smp_flag"] = false; entNewIncident["smp_createdfrom"] = new OptionSetValue(3); entNewIncident["smp_problemoccureddatetime"] = Convert.ToDateTime(DateTime.UtcNow, CultureInfo.CurrentCulture); entNewIncident["smp_portalsubmit"] = false; Guid cloneId = service.Create(entNewIncident); EntityCollection dynamicProblemTypeNotes = GetServiceRequestDynamicProblemTypeNotes(service, entity.Id); foreach (Entity dynamicProblemTypeEntity in dynamicProblemTypeNotes.Entities) { Entity newDynamicProblemTypeNotes = new Entity(); newDynamicProblemTypeNotes.LogicalName = "smp_servicerequestproblemtypedesc"; if (dynamicProblemTypeEntity.Attributes.Contains("smp_problemtypedescriptionid")) { newDynamicProblemTypeNotes["smp_problemtypedescriptionid"] = new EntityReference("smp_problemtypedescription", ((Microsoft.Xrm.Sdk.EntityReference)dynamicProblemTypeEntity.Attributes["smp_problemtypedescriptionid"]).Id); } if (dynamicProblemTypeEntity.Attributes.Contains("smp_answer")) { newDynamicProblemTypeNotes["smp_answer"] = dynamicProblemTypeEntity.Attributes["smp_answer"]; } newDynamicProblemTypeNotes["smp_servicerequestid"] = new EntityReference("incident", cloneId); service.Create(newDynamicProblemTypeNotes); } EntityReference serviceRequestId = new EntityReference("incident", cloneId); context.OutputParameters["CloneEntity"] = serviceRequestId; } } }
public ActionResult Create(CreateServiceRequestViewModel iModel) { if (!ModelState.IsValid) { ModelState.AddModelError("", ErrorResource.FormFieldNotValid); iModel = ServiceRequestHelper.GenerateCreateServiceRequestViewModel(); return(View(iModel)); } var chosenScenarioTupple = GenerateScenarioTupple(iModel.Scenarios.PostData); return(RedirectToAction(chosenScenarioTupple.Item1, chosenScenarioTupple.Item2)); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePreServiceRequestUpdateSetIntegrationStatus(LocalPluginContext localContext) { if (localContext == null) { return; } IPluginExecutionContext context = localContext.PluginExecutionContext; ITracingService trace = localContext.TracingService; if (context == null) { return; } Entity serviceRequest = context.InputParameters.Contains("Target") ? context.InputParameters["Target"] as Entity : null; Entity preImage = (context.PreEntityImages != null && context.PreEntityImages.Contains("PreImage")) ? (Entity)context.PreEntityImages["PreImage"] : null; var service = localContext.OrganizationService; if (service != null && serviceRequest != null && preImage != null) { try { int statusCode = -999; statusCode = serviceRequest.Attributes.Contains("statuscode") ? ((OptionSetValue)serviceRequest["statuscode"]).Value : ((OptionSetValue)preImage["statuscode"]).Value; if (statusCode != -999 && (statusCode == 5 || statusCode == 6)) { return; } EntityCollection configurationCollection = ServiceRequestHelper.GetConfigurationValueCollection(service); string currentStatusCode = ServiceRequestHelper.GetStatusCodeFromValue(service, statusCode); string draftStatusCode = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("DraftStatusCode")).First()["smp_value"].ToString(); SetIntegrationStatus(serviceRequest, preImage, service, currentStatusCode, draftStatusCode, trace, configurationCollection); } catch (CustomServiceManagementPortalException) { Logger.Write("Updating integration status field failed", ExceptionType.SendServiceRequestToProviderFailed, service, "incident", "smp_servicerequestid", serviceRequest.Id, string.Empty); } } }
/// <summary> /// Sets the integration status. /// </summary> /// <param name="context">The context.</param> /// <param name="serviceRequest">The service request.</param> /// <param name="service">The service.</param> /// <param name="currentStatusCode">The current status code.</param> /// <param name="draftStatusCode">The draft status code.</param> private static void SetIntegrationStatus(Entity serviceRequest, Entity preImage, IOrganizationService service, string currentStatusCode, string draftStatusCode, ITracingService trace, EntityCollection collection) { int statusCode = serviceRequest.Attributes.Contains("statuscode") ? ((OptionSetValue)serviceRequest["statuscode"]).Value : ((OptionSetValue)preImage["statuscode"]).Value; if (!string.IsNullOrWhiteSpace(currentStatusCode) && !string.IsNullOrWhiteSpace(draftStatusCode) && (currentStatusCode.ToUpperInvariant() != draftStatusCode.ToUpperInvariant()) && statusCode != 3 && statusCode != 180620013) { if (serviceRequest.Attributes.Contains("smp_priorityid")) { ServiceRequestHelper.SetIntegrationStatus(serviceRequest, true); } else { SetIntegrationStatusWhenPriorityNotChanged(collection, serviceRequest, service, trace, preImage); } } else { ServiceRequestHelper.SetIntegrationStatus(serviceRequest, false); } }
/// <summary> /// Sets the integration status when priority not changed. /// </summary> /// <param name="context">The context.</param> /// <param name="serviceRequest">The service request.</param> /// <param name="service">The service.</param> private static void SetIntegrationStatusWhenPriorityNotChanged(EntityCollection collection, Entity serviceRequest, IOrganizationService service, ITracingService trace, Entity preImage) { // Get all priorities for 8/8 Mailbox string priorities = collection.Entities.Where(x => x["smp_title"].ToString().Equals(CRMAttributesResource.RoutingPriorities8By8)).First()["smp_value"].ToString(); string preImagePriority = preImage.Attributes.Contains("smp_priorityid") ? ServiceRequestHelper.GetLookupName(service, ((EntityReference)preImage["smp_priorityid"]).Id, "smp_name", "smp_priority") : string.Empty; if (string.IsNullOrWhiteSpace(preImagePriority)) { ServiceRequestHelper.SetIntegrationStatus(serviceRequest, false); } else if (!priorities.Contains(preImagePriority.Trim().ToUpperInvariant())) { ServiceRequestHelper.SetIntegrationStatus(serviceRequest, true); } else if (priorities.Contains(preImagePriority.Trim().ToUpperInvariant()) && ((OptionSetValue)preImage["statuscode"]).Value != 1) { ServiceRequestHelper.SetIntegrationStatus(serviceRequest, true); } else { ServiceRequestHelper.SetIntegrationStatus(serviceRequest, false); } }
public void Execute(IServiceProvider serviceProvider) { //// Obtain the execution context service from the service provider. IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); //// Obtain the tracing service from the service provider. ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the Organization Service factory service from the service provider IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); //// Use the factory to generate the Organization Service. IOrganizationService service = factory.CreateOrganizationService(context.UserId); ////throw new NotImplementedException(); Guid incidentId = Guid.Empty; if (context == null || context.Depth != 4) { return; } if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { trace.Trace("Inside Target method"); Entity entity = (Entity)context.InputParameters["Target"]; Entity postImage = (Entity)context.PostEntityImages["PostImage"]; EntityCollection configurationCollection = ServiceRequestHelper.GetConfigurationValueCollection(service); string providerQuestionOne = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("ProviderQuestionOne")).First()["smp_value"].ToString(); string providerQuestionTwo = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("ProviderQuestionTwo")).First()["smp_value"].ToString(); string callCenterQuestionOne = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("CallCenterQuestionOne")).First()["smp_value"].ToString(); string callCenterQuestionTwo = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("CallCenterQuestionTwo")).First()["smp_value"].ToString(); string singleResponseQuestion = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("SingleResponseQuestion")).First()["smp_value"].ToString(); ////My issue was resolved to my satisfaction if (entity.Attributes.Contains(providerQuestionOne)) { QuestionVariable.Question1 = Convert.ToString(((Microsoft.Xrm.Sdk.OptionSetValue)entity[providerQuestionOne]).Value, CultureInfo.InvariantCulture); } else { QuestionVariable.Question1 = string.Empty; } ////The service provider left the working area in a clean and orderly fashion if (entity.Attributes.Contains(providerQuestionTwo)) { QuestionVariable.Question2 = Convert.ToString(((Microsoft.Xrm.Sdk.OptionSetValue)entity[providerQuestionTwo]).Value, CultureInfo.InvariantCulture); } else { QuestionVariable.Question2 = string.Empty; } ////Was it easy for you to request service? if (entity.Attributes.Contains(callCenterQuestionOne)) { QuestionVariable.Question3 = Convert.ToString(((Microsoft.Xrm.Sdk.OptionSetValue)entity[callCenterQuestionOne]).Value, CultureInfo.InvariantCulture); } else { QuestionVariable.Question3 = string.Empty; } ////How satisfied were you with the overall quality of if (entity.Attributes.Contains(callCenterQuestionTwo)) { QuestionVariable.Question4 = Convert.ToString(((Microsoft.Xrm.Sdk.OptionSetValue)entity[callCenterQuestionTwo]).Value, CultureInfo.InvariantCulture); } else { QuestionVariable.Question4 = string.Empty; } ////Please select any item which you feel could use improvement if (entity.Attributes.Contains(singleResponseQuestion)) { QuestionVariable.Question5 = Convert.ToString(((Microsoft.Xrm.Sdk.OptionSetValue)entity[singleResponseQuestion]).Value, CultureInfo.InvariantCulture); } else { QuestionVariable.Question5 = string.Empty; } if (postImage.Attributes.Contains("smp_incidentid")) { incidentId = ((Microsoft.Xrm.Sdk.EntityReference)postImage.Attributes["smp_incidentid"]).Id; } trace.Trace("Inside Before Create"); CreateServiceRequest(service, incidentId, QuestionVariable.Question1, QuestionVariable.Question2, QuestionVariable.Question3, QuestionVariable.Question4, QuestionVariable.Question5, trace, configurationCollection); } }
/// <summary> /// Creates the service request. /// </summary> /// <param name="service">The service.</param> /// <param name="serviceRequestId">The service request id.</param> /// <param name="question1">The question1.</param> /// <param name="question2">The question2.</param> /// <param name="question3">The question3.</param> /// <param name="question4">The question4.</param> /// <param name="question5">The question5.</param> /// <param name="question5Chinese">The question5 chinese.</param> /// <param name="question5Portuguese">The question5 portuguese.</param> /// <param name="question5French">The question5 french.</param> /// <param name="question5Spanish">The question5 spanish.</param> /// <param name="question5Korean">The question5 korean.</param> /// <param name="question5Japanese">The question5 japanese.</param> private static void CreateServiceRequest(IOrganizationService service, Guid serviceRequestId, string question1, string question2, string question3, string question4, string question5, ITracingService trace, EntityCollection collection) { trace.Trace("Inside CreateServiceRequest"); Guid incidentId = Guid.Empty; string defaultProvider = string.Empty; Guid contactId = Guid.Empty; Entity serviceRequest = service.Retrieve("incident", serviceRequestId, new ColumnSet(true)); if (serviceRequest.Attributes.Contains("smp_contact")) { contactId = ((Microsoft.Xrm.Sdk.EntityReference)serviceRequest.Attributes["smp_contact"]).Id; } Entity contactInfo = ServiceRequestHelper.GetContactDetails(service, contactId); QuestionVariable.ContactLanguageCode = contactInfo.Attributes.Contains("smp_preferredlanguage") ? contactInfo["smp_preferredlanguage"].ToString() : "en-us"; Entity incident = new Entity(); incident.LogicalName = "incident"; incident.Attributes.Add("smp_problemoccureddatetime", DateTime.Now.ToUniversalTime()); defaultProvider = collection.Entities.Where(x => x["smp_title"].ToString().Equals("DefaultProviderName")).First()["smp_value"].ToString(); incident.Attributes.Add("customerid", new EntityReference("account", GetDefaultProviderId(service, defaultProvider))); incident.Attributes.Add("smp_referencesr", new EntityReference("incident", serviceRequestId)); incident.Attributes.Add("smp_issurveyservicerequest", true); QuestionVariable.SurveyQuestions = collection.Entities.Where(x => x["smp_title"].ToString().Equals("SurveyQuestions")).First()["smp_value"].ToString().Split(';'); QuestionVariable.Question1Text = QuestionVariable.SurveyQuestions[0].ToString(); QuestionVariable.Question2Text = QuestionVariable.SurveyQuestions[1].ToString(); QuestionVariable.Question3Text = QuestionVariable.SurveyQuestions[2].ToString(); QuestionVariable.Question4Text = QuestionVariable.SurveyQuestions[3].ToString(); QuestionVariable.Question5Text = QuestionVariable.SurveyQuestions[4].ToString(); incident.Attributes.Add("smp_problemtypedescription", BuildSurveyDetailsToProblemDescription(service, QuestionVariable.Question1Text, QuestionVariable.Question2Text, QuestionVariable.Question3Text, QuestionVariable.Question4Text, QuestionVariable.Question5Text, question1, question2, question3, question4, question5, serviceRequest.Attributes["ticketnumber"].ToString(), QuestionVariable.ContactLanguageCode)); ////requester details BindRequstorDetails(incident, serviceRequest, trace); //// Contact Details BindContactDetails(incident, serviceRequest, trace); //// Building Details BindBuildingDetails(incident, serviceRequest, trace); //// Provider Related response time, technitian if (question1 == "1" || question1 == "2" || question2 == "1" || question2 == "2" || question5 == "3" || question5 == "4") { QuestionVariable.ProblemClass = collection.Entities.Where(x => x["smp_title"].ToString().Equals("SurveyProviderRelatedProblemClass")).First()["smp_value"].ToString(); QuestionVariable.ProblemType = collection.Entities.Where(x => x["smp_title"].ToString().Equals("SurveyProviderRelatedProblemType")).First()["smp_value"].ToString(); incident.Attributes.Add("smp_problemclassid", new EntityReference("smp_problemclass", GetProblemClassId(service, QuestionVariable.ProblemClass))); incident.Attributes.Add("smp_problemtypeid", new EntityReference("smp_problemtype", GetProblemTypeId(service, QuestionVariable.ProblemType))); incident["statuscode"] = new OptionSetValue(2); incidentId = service.Create(incident); UpdateIncident(service, incidentId); trace.Trace("After UpdateIncidnet funciton"); } //// Call Center Management Related ease of use, technology if (question3 == "1" || question3 == "2" || question4 == "1" || question4 == "2" || question5 == "1" || question5 == "2") { QuestionVariable.ProblemClass = collection.Entities.Where(x => x["smp_title"].ToString().Equals("SurveyCallCenterManagementRelatedProblemClass")).First()["smp_value"].ToString(); QuestionVariable.ProblemType = collection.Entities.Where(x => x["smp_title"].ToString().Equals("SurveyCallCenterManagementRelatedProblemType")).First()["smp_value"].ToString(); incident.Attributes.Remove("smp_problemclassid"); incident.Attributes.Remove("smp_problemtypeid"); incident.Attributes.Add("smp_problemclassid", new EntityReference("smp_problemclass", GetProblemClassId(service, QuestionVariable.ProblemClass))); incident.Attributes.Add("smp_problemtypeid", new EntityReference("smp_problemtype", GetProblemTypeId(service, QuestionVariable.ProblemType))); incident["statuscode"] = new OptionSetValue(2); incidentId = service.Create(incident); trace.Trace("Incident Created- " + incidentId); ////SetState(service, incidentId); ////Entity updateIncident = new Entity(); ////updateIncident.LogicalName = "incident"; ////updateIncident.Id = serviceRequestId; ////updateIncident.Attributes["statecode"] = (OptionSet) trace.Trace("After SetState funciton"); UpdateIncident(service, incidentId); trace.Trace("After UpdateIncidnet funciton"); } }
/// <summary> /// Sends email as per status change /// </summary> /// <param name="service">crm service</param> /// <param name="serviceRequest">target object</param> public void Execute(IServiceProvider serviceProvider) { //// Obtain the execution context service from the service provider. IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); //// Obtain the tracing service from the service provider. ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); //// Obtain the Organization Service factory service from the service provider IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); //// Use the factory to generate the Organization Service. IOrganizationService service = factory.CreateOrganizationService(context.UserId); bool isProblemClassAllowForEmailNotification = false; bool isProblemTypeAllowForEmailNotification = false; bool problemBuildingAllowEmailNotification = false; try { if (context == null || context.Depth > 2) { return; } if (context != null) { trace.Trace("In Status Change"); if (context.InputParameters != null && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity serviceRequest = context.InputParameters["Target"] as Entity; var preImageIncident = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; var postImageIncident = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; if (serviceRequest.Attributes.Contains(CRMAttributesResource.StatusCodeAttribute)) { Entity problemClass = postImageIncident.Attributes.Contains("smp_problemclassid") ? ServiceRequestHelper.GetProblemClassDetails(service, ((EntityReference)postImageIncident["smp_problemclassid"]).Id) : null; Entity problemType = postImageIncident.Attributes.Contains("smp_problemtypeid") ? ServiceRequestHelper.GetProblemTypeDetails(service, ((EntityReference)postImageIncident["smp_problemtypeid"]).Id) : null; if (((OptionSetValue)preImageIncident.Attributes[CRMAttributesResource.StatusCodeAttribute]).Value != ((OptionSetValue)postImageIncident.Attributes[CRMAttributesResource.StatusCodeAttribute]).Value) { isProblemClassAllowForEmailNotification = problemClass != null?Convert.ToBoolean(problemClass["smp_allowemailnotification"]) : false; trace.Trace("isProblemClassAllowForEmailNotification " + isProblemClassAllowForEmailNotification); isProblemTypeAllowForEmailNotification = problemType != null?Convert.ToBoolean(problemType["smp_allowemailnotification"]) : false; trace.Trace("isProblemTypeAllowForEmailNotification " + isProblemTypeAllowForEmailNotification); if (postImageIncident.Attributes.Contains("smp_problembuilding")) { problemBuildingAllowEmailNotification = GetBuildingEmailNotificationStatus(service, ((EntityReference)postImageIncident["smp_problembuilding"]).Id); } trace.Trace("problemBuilding_AllowEmailNotification " + problemBuildingAllowEmailNotification); if (problemBuildingAllowEmailNotification && isProblemClassAllowForEmailNotification && isProblemTypeAllowForEmailNotification) { PostServiceRequestStatusChange.ProcessStatusChange(service, postImageIncident, trace, problemType, problemClass, preImageIncident); } } } } } } catch (Exception ex) { trace.Trace("Exception :" + ex.Message); } }
private static void ProcessStatusChange(IOrganizationService service, Entity entity, ITracingService trace, Entity problemType, Entity problemClass, Entity preEntity) { try { EntityCollection configurationCollection = ServiceRequestHelper.GetConfigurationValueCollection(service); List <Entity> toEmail = new List <Entity>(); List <Entity> ccEmail = new List <Entity>(); string fromUserDomainName = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals(CRMAttributesResource.EmailSenderDomainName)).First()["smp_value"].ToString(); Guid senderId = ServiceRequestHelper.GetCrmUserId(service, fromUserDomainName); EntityReference contact = entity.Attributes.Contains(CRMAttributesResource.ServiceRequestContact) ? (EntityReference)entity[CRMAttributesResource.ServiceRequestContact] : null; EntityReference requester = entity.Attributes.Contains(CRMAttributesResource.ServiceRequestRequester) ? (EntityReference)entity[CRMAttributesResource.ServiceRequestRequester] : null; EntityReference cC = entity.Attributes.Contains(CRMAttributesResource.ServiceRequestCC) ? (EntityReference)entity[CRMAttributesResource.ServiceRequestCC] : null; EntityReference approver = entity.Attributes.Contains(CRMAttributesResource.ServiceRequestApprovalManager) ? (EntityReference)entity[CRMAttributesResource.ServiceRequestApprovalManager] : null; OptionSetValue currentStatus = entity.Attributes.Contains(CRMAttributesResource.StatusCodeAttribute) ? (OptionSetValue)entity[CRMAttributesResource.StatusCodeAttribute] : null; EntityReference provider = entity.Attributes.Contains(CRMAttributesResource.ServiceRequestProvider) ? (EntityReference)entity[CRMAttributesResource.ServiceRequestProvider] : null; Entity contactDetails = null; Entity requesterDetails = (requester == null) ? null : ServiceRequestHelper.GetContactDetails(service, requester.Id); Entity ccDetails = (cC == null) ? null : ServiceRequestHelper.GetContactDetails(service, cC.Id); bool allowEmailNotification = false; bool cancelledForReclassification = false; bool contact_AllowEmailNotification = false; string contactLanguageCode = string.Empty; if (contact != null) { contactDetails = ServiceRequestHelper.GetContactDetails(service, contact.Id); contact_AllowEmailNotification = contactDetails.Attributes.Contains("smp_allowemailnotification") ? (bool)contactDetails["smp_allowemailnotification"] : false; contactLanguageCode = contactDetails.Attributes.Contains("smp_preferredlanguage") ? contactDetails["smp_preferredlanguage"].ToString() : "en-us"; } allowEmailNotification = entity.Attributes.Contains("smp_allowemailnotification") ? (bool)entity["smp_allowemailnotification"] : false; cancelledForReclassification = entity.Attributes.Contains("smp_cancelledforreclassification") ? (bool)entity["smp_cancelledforreclassification"] : false; var fromParty = new Entity("activityparty"); fromParty["partyid"] = new EntityReference(CRMAttributesResource.SystemUserEntity, senderId); if (currentStatus.Value == Convert.ToInt32(CRMAttributesResource.DeclinedStatus, CultureInfo.InvariantCulture) && allowEmailNotification == true) { trace.Trace("In Declined Status"); if (requester != null) { var toRequestor = new Entity("activityparty"); toRequestor["partyid"] = new EntityReference("contact", requester.Id); toEmail.Add(toRequestor); } if (contact != null) { if (requester.Id != contact.Id) { var ccContact = new Entity("activityparty"); ccContact["partyid"] = new EntityReference("contact", contact.Id); toEmail.Add(ccContact); } } if (approver != null) { var toApprover = new Entity("activityparty"); toApprover["partyid"] = new EntityReference("contact", approver.Id); ccEmail.Add(toApprover); } EmailHelper.SendTranslatedEmail(service, entity, fromParty, toEmail, ccEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestApprovalRejectionTemplate, configurationCollection); } else if (currentStatus.Value == Convert.ToInt32(CRMAttributesResource.CancelledStatus, CultureInfo.InvariantCulture)) { trace.Trace("In cancelled Status"); if (cancelledForReclassification == false) { if (requester != null) { var toRequester = new Entity("activityparty"); toRequester["partyid"] = new EntityReference("contact", requester.Id); toEmail.Add(toRequester); } if (contact != null) { if (contact.Id != requester.Id) { var ccContact = new Entity("activityparty"); ccContact["partyid"] = new EntityReference("contact", contact.Id); ccEmail.Add(ccContact); } } if (cC != null) { if (contact.Id != cC.Id && cC.Id != requester.Id) { var toCC = new Entity("activityparty"); toCC["partyid"] = new EntityReference("contact", cC.Id); ccEmail.Add(toCC); } } ////End of Code Changes made by Mihika G on 03-12-2017 ////Send email EmailHelper.SendTranslatedEmail(service, entity, fromParty, toEmail, ccEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestCancelledTemplate, configurationCollection); } else if (cancelledForReclassification == true) { ////Code Commented By Mihika G if (provider != null) { var toProvider = new Entity("activityparty"); toProvider["partyid"] = new EntityReference("account", provider.Id); toEmail.Add(toProvider); } trace.Trace("in cancelled"); ////End OF Code Changes if (requester != null) { if (contact.Id != requester.Id) { var toRequester = new Entity("activityparty"); toRequester["partyid"] = new EntityReference("contact", requester.Id); ccEmail.Add(toRequester); } } if (contact != null) { var toContact = new Entity("activityparty"); toContact["partyid"] = new EntityReference("contact", contact.Id); toEmail.Add(toContact); } //// Code Changes made by Mihika G on 03-12-2017 if (cC != null) { if (contact.Id != cC.Id && cC.Id != requester.Id) { var toCC = new Entity("activityparty"); toCC["partyid"] = new EntityReference("contact", cC.Id); ccEmail.Add(toCC); } } trace.Trace("before email"); trace.Trace("Template : " + CRMAttributesResource.ServiceRequestReclassifiedTemplate); EmailHelper.SendTranslatedEmail(service, entity, fromParty, toEmail, ccEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestReclassifiedTemplate, configurationCollection); ////end of code change for reclassification email } } else if (currentStatus.Value == Convert.ToInt32(CRMAttributesResource.CompletedStatus, CultureInfo.InvariantCulture)) { trace.Trace("In Completed Status"); bool noSurvey = (bool)problemClass["smp_donotallowsurvey"] || (bool)problemType["smp_donotallowsurvey"]; bool ccSurvey = false; //Whether the CC contact receives a survey if (requester != null && canReceiveEmail(requesterDetails)) { ((canReceiveSurvey(requesterDetails) && !noSurvey) ? toEmail : ccEmail).Add(getEmailParty(requester)); } if (contact != null && contact.Id != requester.Id && canReceiveEmail(contactDetails)) { ((canReceiveSurvey(contactDetails) && !noSurvey) ? toEmail : ccEmail).Add(getEmailParty(contact)); } if ((cC != null && canReceiveEmail(ccDetails))) { ccSurvey = canReceiveSurvey(ccDetails) && toEmail.Count > 0; //Doesn't make sense to send it just for the CC if (ccSurvey) { toEmail.Add(getEmailParty(cC)); } else { ccEmail.Add(getEmailParty(cC)); } } //Promote the first contact to primary, since we can only have one for the survey generator List <Entity> primary = new List <Entity>(); if (toEmail.Count != 0) { primary.Add(toEmail[0]); toEmail.RemoveAt(0); EmailHelper.SendTranslatedEmail(service, entity, fromParty, primary, toEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestCompletedTemplate, configurationCollection); } primary.Clear(); if (ccEmail.Count != 0) { primary.Add(ccEmail[0]); ccEmail.RemoveAt(0); EmailHelper.SendTranslatedEmail(service, entity, fromParty, primary, ccEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestCompletedTemplateWithoutSurvey, configurationCollection); } } else if (currentStatus.Value == Convert.ToInt32(CRMAttributesResource.WaitingForApprovalStatus, CultureInfo.InvariantCulture)) { trace.Trace("In Waiting for Approval status"); if (contact_AllowEmailNotification == false) { } else { if (allowEmailNotification == true) { if (approver != null) { var toApprover = new Entity("activityparty"); toApprover["partyid"] = new EntityReference("contact", approver.Id); toEmail.Add(toApprover); } if (requester != null) { if (requester.Id != contact.Id) { var toRequester = new Entity("activityparty"); toRequester["partyid"] = new EntityReference("contact", requester.Id); ccEmail.Add(toRequester); } } if (contact != null) { var toContact = new Entity("activityparty"); toContact["partyid"] = new EntityReference("contact", contact.Id); ccEmail.Add(toContact); } ////Send email EmailHelper.SendTranslatedEmail(service, entity, fromParty, toEmail, ccEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestWaitingForApprovalTemplate, configurationCollection); } } } else { trace.Trace("In Final Else "); if (((OptionSetValue)preEntity["statuscode"]).Value != 1 && (currentStatus.Value == 180620017 || currentStatus.Value == 180620007 || currentStatus.Value == 180620008 || currentStatus.Value == 180620009)) { if (((OptionSetValue)preEntity["statuscode"]).Value != currentStatus.Value) { if (contact_AllowEmailNotification == true) { } else { if (allowEmailNotification == true) { if (requester != null) { var toRequestor = new Entity("activityparty"); toRequestor["partyid"] = new EntityReference("contact", requester.Id); toEmail.Add(toRequestor); } if (contact != null) { if (contact.Id != requester.Id) { var ccContact = new Entity("activityparty"); ccContact["partyid"] = new EntityReference("contact", contact.Id); ccEmail.Add(ccContact); } } if (cC != null) { if (cC.Id != contact.Id && cC.Id != requester.Id) { var toCC = new Entity("activityparty"); toCC["partyid"] = new EntityReference("contact", cC.Id); ccEmail.Add(toCC); } } EmailHelper.SendTranslatedEmail(service, entity, fromParty, toEmail, ccEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestStatusChangeTemplate, configurationCollection); } } } } else { trace.Trace("In Final Else--Else"); if (((OptionSetValue)preEntity["statuscode"]).Value == 1 && currentStatus.Value == 2) { if (contact_AllowEmailNotification) { } else { if (requester != null) { var toRequester = new Entity("activityparty"); toRequester["partyid"] = new EntityReference("contact", requester.Id); toEmail.Add(toRequester); } if (contact != null) { if (contact.Id != requester.Id) { var ccContact = new Entity("activityparty"); ccContact["partyid"] = new EntityReference("contact", contact.Id); ccEmail.Add(ccContact); } } if (cC != null) { if (contact.Id != cC.Id && cC.Id != requester.Id) { var toCC = new Entity("activityparty"); toCC["partyid"] = new EntityReference("contact", cC.Id); ccEmail.Add(toCC); } } EmailHelper.SendTranslatedEmail(service, entity, fromParty, toEmail, ccEmail, contactLanguageCode, CRMAttributesResource.ServiceRequestAcknowledgementTemplate, configurationCollection); } } } } } catch (Exception ex) { throw ex; } }
public ActionResult Create() { var viewModel = ServiceRequestHelper.GenerateCreateServiceRequestViewModel(); return(View(viewModel)); }
/// <summary> /// Sends status change email /// </summary> /// <param name="service">The service.</param> /// <param name="objectIncident">The object incident.</param> /// <param name="emailTemplate">Email template name</param> private static void SendStatusChangeEmail(IOrganizationService service, Entity objectIncident, int statusCode, EntityCollection configurationCollection, Entity contactInfo) { try { List <Entity> toEmail = new List <Entity>(); List <Entity> carbonCopyEmail = new List <Entity>(); string emailTemplate = string.Empty; if (statusCode != 3) { emailTemplate = CRMAttributesResource.ServiceRequestAcknowledgementTemplate; } else { emailTemplate = CRMAttributesResource.ServiceRequestApprovalRequiredTemplate; } //// Get the configured user id for sending email. string fromUserDomainName = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals(CRMAttributesResource.EmailSenderDomainName)).First()["smp_value"].ToString(); Guid senderId = ServiceRequestHelper.GetCrmUserId(service, fromUserDomainName); EntityReference contact = objectIncident.Attributes.Contains(CRMAttributesResource.ServiceRequestContact) ? (EntityReference)objectIncident[CRMAttributesResource.ServiceRequestContact] : null; EntityReference requester = objectIncident.Attributes.Contains(CRMAttributesResource.ServiceRequestRequester) ? (EntityReference)objectIncident[CRMAttributesResource.ServiceRequestRequester] : null; EntityReference cC = objectIncident.Attributes.Contains(CRMAttributesResource.ServiceRequestCC) ? (EntityReference)objectIncident[CRMAttributesResource.ServiceRequestCC] : null; EntityReference approver = objectIncident.Attributes.Contains(CRMAttributesResource.ServiceRequestApprovalManager) ? (EntityReference)objectIncident[CRMAttributesResource.ServiceRequestApprovalManager] : null; if (objectIncident.Attributes.Contains(CRMAttributesResource.ServiceRequestIsApprovalRequired) && (bool)objectIncident[CRMAttributesResource.ServiceRequestIsApprovalRequired] == true && statusCode == 3) { if (approver != null) { var toApprover = new Entity("activityparty"); toApprover["partyid"] = new EntityReference("contact", approver.Id); toEmail.Add(toApprover); } if (requester != null) { if (requester.Id != contact.Id) { var toRequester = new Entity("activityparty"); toRequester["partyid"] = new EntityReference("contact", requester.Id); carbonCopyEmail.Add(toRequester); } } if (contact != null) { var toContact = new Entity("activityparty"); toContact["partyid"] = new EntityReference("contact", contact.Id); carbonCopyEmail.Add(toContact); } } //// Get language code for contact string contactLanguageCode = contactInfo.Attributes.Contains("smp_preferredlanguage") ? contactInfo["smp_preferredlanguage"].ToString() : "en-us"; var fromParty = new Entity("activityparty"); fromParty["partyid"] = new EntityReference(CRMAttributesResource.SystemUserEntity, senderId); if (statusCode != 3) { if (requester != null) { var toRequester = new Entity("activityparty"); toRequester["partyid"] = new EntityReference("contact", requester.Id); toEmail.Add(toRequester); } if (contact != null) { if (contact.Id != requester.Id) { var ccContact = new Entity("activityparty"); ccContact["partyid"] = new EntityReference("contact", contact.Id); carbonCopyEmail.Add(ccContact); } } if (cC != null) { if (cC.Id != contact.Id && cC.Id != requester.Id) { var toCC = new Entity("activityparty"); toCC["partyid"] = new EntityReference("contact", cC.Id); carbonCopyEmail.Add(toCC); } } } //// Send email EmailHelper.SendTranslatedEmail(service, objectIncident, fromParty, toEmail, carbonCopyEmail, contactLanguageCode, emailTemplate, configurationCollection); } catch (Exception) { throw; } }
public void Execute(IServiceProvider serviceProvider) { CCRM.REF.TelemetryLog.LocalPluginContext localPluginContext = new CCRM.REF.TelemetryLog.LocalPluginContext(serviceProvider); IConfigurationRetrieval configurationRetrieval = new ConfigurationRetrieval(); this.requestLogging = new RequestLogging(configurationRetrieval, localPluginContext); IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (context != null && context.InputParameters["Target"] != null) { var serRequest = (Entity)context.InputParameters["Target"]; if (service != null && serRequest != null) { bool statusCode = serRequest.Attributes.Contains(CRMAttributesResource.StatusCodeAttribute) ? true : false; int caseorigincode = ((OptionSetValue)serRequest["caseorigincode"]).Value; try { if (statusCode) { bool smp_portalsubmit = (bool)serRequest["smp_portalsubmit"]; if ((caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.Web || caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.IOT || caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.Phone) && ((OptionSetValue)serRequest.Attributes[CRMAttributesResource.StatusCodeAttribute]).Value == (int)ServiceRequestEnum.StatusCode.Draft) { object smp_contact = this.GetFieldFromTargetOrImage(serRequest, "smp_contact"); if (smp_contact != null) { object smp_requestorid = this.GetFieldFromTargetOrImage(serRequest, "smp_requestorid"); if (smp_requestorid != null) { Entity requestor = this.GetRequestorDetails(service, ((EntityReference)smp_requestorid).Id, trace); if (requestor != null) { if (!serRequest.Attributes.Contains("smp_requestorphone")) { if (requestor.Attributes.Contains("telephone1")) { serRequest["smp_requestorphone"] = requestor["telephone1"].ToString(); } else if (caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.Web) { serRequest["smp_requestorphone"] = "<None>"; } } serRequest["smp_requestoralias"] = this.GetFieldFromTargetOrImage(requestor, "smp_alias"); serRequest["smp_requestoremail"] = this.GetFieldFromTargetOrImage(requestor, "emailaddress1"); serRequest["smp_buildingid"] = this.GetFieldFromTargetOrImage(requestor, "smp_buildingid"); serRequest["new_requestorroomnumber"] = this.GetFieldFromTargetOrImage(requestor, "new_requestorroomnumber"); } } EntityReference otherRef = this.GetRoomWithOther(service, trace); EntityReference problemRef = serRequest.Attributes.ContainsKey("new_problemroomnumber") ? (EntityReference)serRequest["new_problemroomnumber"] : null; if (problemRef != null) { problemRef.Name = this.GetRoomName(service, problemRef.Id); } if (problemRef == null) { serRequest["new_problemroomnumber"] = otherRef; } else if (problemRef.Id != otherRef.Id) { serRequest["smp_problemroom"] = problemRef.Name; } else { trace.Trace("Problem room lookup is Other, doing nothing"); } if (serRequest.Attributes.Contains("smp_problembuilding")) { Entity building = this.GetBuildingDetails(service, ((EntityReference)serRequest["smp_problembuilding"]).Id, trace); if (building != null) { serRequest["smp_problembuildingaddressline1"] = this.GetFieldFromTargetOrImage(building, "smp_addressline1"); serRequest["smp_problembuildingaddressline2"] = this.GetFieldFromTargetOrImage(building, "smp_addressline2"); serRequest["smp_problembuildingstate"] = this.GetFieldFromTargetOrImage(building, "smp_state"); serRequest["smp_problembuildingcountry"] = this.GetFieldFromTargetOrImage(building, "smp_country"); serRequest["smp_problembuildingcity"] = this.GetFieldFromTargetOrImage(building, "smp_city"); serRequest["smp_problembuildingzipcode"] = this.GetFieldFromTargetOrImage(building, "smp_zipcode"); serRequest["smp_problembuildingtimezone"] = this.GetFieldFromTargetOrImage(building, "smp_timezoneid"); } } if (smp_portalsubmit == true) { serRequest["statuscode"] = new OptionSetValue(2); this.AssignProviderToServiceRequest(service, serRequest, trace); } else { //// Code to set the Default Provider When SR is Saved as Draft from Portal. this.AssignProviderToServiceRequest(service, serRequest, trace); } ServiceRequestHelper.SetIntegrationStatusandProblemOccuredDateTime(serRequest, false); } } else { trace.Trace("in CRM"); string roomName = string.Empty; EntityReference problemRef = serRequest.Attributes.ContainsKey("new_problemroomnumber") ? (EntityReference)serRequest["new_problemroomnumber"] : null; if (problemRef != null) { roomName = this.GetRoomName(service, problemRef.Id); } else { serRequest["new_problemroomnumber"] = this.GetRoomWithOther(service, trace); serRequest["smp_problemroom"] = serRequest.Attributes.Contains("smp_problemroom") ? serRequest["smp_problemroom"].ToString() : string.Empty; } if (roomName != "Other" && !string.IsNullOrEmpty(roomName)) { serRequest["smp_problemroom"] = roomName; } this.AssignProviderToServiceRequest(service, serRequest, trace); serRequest["smp_integrationstatus"] = false; } } ////this.requestLogging.LogPluginTrace(serRequest, MappingConstants.ServiceRequestCreatedSequenceId, MappingConstants.ServiceRequestCreatedSuccessEventId, MappingConstants.ServiceRequestCreatedEventName, MappingConstants.ServiceRequestCreatedSuccessEventMessage); } catch (CustomServiceManagementPortalException ex) { ////this.requestLogging.LogPluginException(serRequest, ex, MappingConstants.ServiceRequestCreatedSequenceId, MappingConstants.ServiceRequestCreatedFailedEventId, MappingConstants.ServiceRequestCreatedEventName, MappingConstants.ServiceRequestCreatedFailedEventMessage); ////Kill the exception so it does not effect other plugin execution } } } }
public ActionResult Maintain() { var viewModel = ServiceRequestHelper.GenerateMaintainServiceRequestViewModel(); return(View(viewModel)); }
/// <summary> /// Creates a new Email from the Email Template and translates dynamic data as per given language /// </summary> /// <param name="service">The service.</param> /// <param name="serviceRequestId">The service request Id.</param> /// <param name="fromParty">From email party</param> /// <param name="toParty">List of recipients</param> /// <param name="carbonCopyParty">List of recipients who will receive carbon copy of email</param> /// <param name="languageCode">language for translation</param> /// <param name="templateName">Name of the template.</param> /// <returns><c>true</c> if email is sent, <c>false</c> otherwise</returns> public static bool SendTranslatedEmail(IOrganizationService service, Entity entity, Entity fromParty, List <Entity> toParty, List <Entity> carbonCopyParty, string languageCode, string templateName, EntityCollection collection) { bool isEmailSent = false; string surveyLink = string.Empty; try { if (service != null) { int fromEmail = 1; ServiceRequest serviceRequest = ServiceRequestHelper.SetServiceRequestObject(service, entity, fromEmail); //// get the email template from the orion Email Entity emailTemplate = GetTemplateByName(service, languageCode + "|" + templateName); Entity email = new Entity(); //// set the properties of the Email from the email template StringBuilder subject = new StringBuilder(GetDataFromXml(emailTemplate.Attributes["subject"].ToString(), "match")); StringBuilder description = new StringBuilder(GetDataFromXml(emailTemplate.Attributes["body"].ToString(), "match")); //// replace the subject placeholder(s) subject = subject.Replace("[TicketNumber]", serviceRequest.ServiceRequestNumber == null ? string.Empty : serviceRequest.ServiceRequestNumber); //// check to see if the subject of the email is more than maximum allowed length of the subject if (subject.Length > 195) { email["subject"] = subject.ToString().Substring(0, 195) + "...."; } else { email["subject"] = subject.ToString(); } description.Replace("[ProviderName]", serviceRequest.ProviderName); description.Replace("[PriorityName]", serviceRequest.Priority); description.Replace("[TicketNumber]", serviceRequest.ServiceRequestNumber); //// Get translated problem class description.Replace("[ProblemClass]", ServiceRequestHelper.GetTranslatedProblemClass(service, serviceRequest.ProblemClassName, languageCode)); //// Get translated problem type description.Replace("[ProblemType]", ServiceRequestHelper.GetTranslatedProblemTypes(service, serviceRequest.ProblemTypeName, languageCode)); ////Get translated status int statusCode = ((OptionSetValue)entity["statuscode"]).Value; string translatedStatus = ServiceRequestHelper.GetTranslatedStatus(service, statusCode, languageCode); description.Replace("[ServiceRequestStatus]", string.IsNullOrEmpty(translatedStatus) == false ? translatedStatus : serviceRequest.StatusCode); description.Replace("[BuildingName]", serviceRequest.ProblemBuildingName); description.Replace("[RoomNo]", serviceRequest.ProblemRoomNumber); if (!string.IsNullOrEmpty(serviceRequest.ProblemTypeDescription)) { description.Replace("[ProblemDescription]", serviceRequest.ProblemTypeDescription); } else { description.Replace("[ProblemDescription]", string.Empty); } description.Replace("[Sender]", "(GFSC Portal Address)"); description.Replace("[ServiceRequestCompletedOn]", DateTime.Now.ToShortDateString()); if (string.IsNullOrEmpty(serviceRequest.ProblemFloorName)) { description.Replace("[Floor]", "N/A"); } else { description.Replace("[Floor]", serviceRequest.ProblemFloorName); } //// get translated room type description.Replace("[RoomType]", ServiceRequestHelper.GetTranslatedRoomTypes(service, serviceRequest.ProblemRoomTypeName, languageCode)); description.Replace("[RequestorName]", serviceRequest.RequestorFirstName + " " + serviceRequest.RequestorLastName); description.Replace("[RequestorAlias]", serviceRequest.RequestorAlias); description.Replace("[RequestorPhoneNo]", serviceRequest.RequestorPhoneNumber); description.Replace("[ContactName]", serviceRequest.ContactFirstName + " " + serviceRequest.ContactLastName); description.Replace("[ContactAlias]", serviceRequest.ContactAlias); description.Replace("[ContactPhoneNo]", serviceRequest.ContactPhoneNumber); if (entity.Attributes.Contains("smp_requestcancelledreason")) { description.Replace("[CancellationReason]", (string)entity.Attributes["smp_requestcancelledreason"]); } else { description.Replace("[CancellationReason]", string.Empty); } if (entity.Attributes.Contains("smp_completeddate")) { description.Replace("[ServiceRequestCompletedOn]", Convert.ToDateTime(entity.Attributes["smp_completeddate"].ToString(), CultureInfo.InvariantCulture).ToShortDateString()); } else { description.Replace("[ServiceRequestCompletedOn]", string.Empty); } if (entity.Attributes.Contains("smp_completionnotes")) { description.Replace("[SRCompletionNotes]", (string)entity.Attributes["smp_completionnotes"]); } else { description.Replace("[SRCompletionNotes]", string.Empty); } ////Test record if (entity.Attributes.Contains("smp_duedate")) { string priorityName = serviceRequest.Priority; string configurationEntityProrityValue = collection.Entities.Where(x => x["smp_title"].ToString().Equals("PrioritiesToDisplayTheDueDate")).First()["smp_value"].ToString(); if (configurationEntityProrityValue.Contains(priorityName)) { description.Replace("[DueDate]", entity.Attributes["smp_duedatebybuildingtimezone"].ToString()); } else { ////description.Replace("[DueDate]", string.Empty); ////description.Replace("[DueDate]", ServiceRequestHelper.GetValueFromWebsiteLanguage(service, languageCode, "ServiceRequestConfirmation/ToBeScheduled")); if (languageCode == "en-us") { description.Replace("[DueDate]", collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestConfirmation/ToBeScheduled")).First()["smp_value"].ToString()); } else { description.Replace("[DueDate]", collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestConfirmation/ToBeScheduled (" + languageCode + ")")).First()["smp_value"].ToString()); } } } else { ////description.Replace("[DueDate]", ServiceRequestHelper.GetValueFromWebsiteLanguage(service, languageCode, "ServiceRequestConfirmation/ToBeScheduled")); if (languageCode == "en-us") { description.Replace("[DueDate]", collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestConfirmation/ToBeScheduled")).First()["smp_value"].ToString()); } else { description.Replace("[DueDate]", collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestConfirmation/ToBeScheduled (" + languageCode + ")")).First()["smp_value"].ToString()); } } StringBuilder html = new StringBuilder(); if (description.ToString().ToLowerInvariant().Contains("[dynamicproblemtypenotes]")) { if (serviceRequest.DynamicProblemTypeNotesCollection.Count() > 0) { html.Append("<table style=\"margin-left:35px\">"); html.Append("<tr><td style=\"font-family:Calibri;font-size:18px;\" colspan='2'><b><u>Dynamic Problem Type Notes</u></b></td></tr>"); foreach (DynamicProblemTypeNotes dptNotes in serviceRequest.DynamicProblemTypeNotesCollection) { html.Append("<table style=\"margin-left:35px\">"); html.Append("<tr><td style=\"font-family:Calibri;font-size:16px;\"><b>"); html.Append(dptNotes.DynamicsProblemTypeName); html.Append(" : </b></tr></td>"); html.Append("<tr><td style=\"font-family:Calibri;font-size:16px;\">"); html.Append(dptNotes.Answer); html.Append("</tr></td>"); html.Append("</table>"); } html.Append("</table>"); } } description.Replace("[DynamicProblemTypeNotes]", html.ToString()); if (entity.Attributes.Contains("statuscode")) { OptionSetValue entityStatusCode = (OptionSetValue)entity.Attributes["statuscode"]; if (entityStatusCode.Value == 180620017 || entityStatusCode.Value == 180620007 || entityStatusCode.Value == 180620008 || entityStatusCode.Value == 180620009) { EntityCollection notesCollection = GetQueryResponse(service, "annotation", new string[] { "annotationid", "subject", "notetext", "createdon" }, "objectid", entity.Id); if (notesCollection.Entities.Count > 0) { ////StringBuilder htm = new StringBuilder(); ////htm.Append("<table>"); ////htm.Append("<tr><td><b>"); ////htm.Append(ServiceRequestHelper.GetValueFromWebsiteLanguage(service, languageCode, "ServiceRequest/EmailTemplates/Notes")); ////htm.Append("</b></td>"); ////htm.Append("<td style=\"color:red\">"); ////htm.Append(notesCollection.Entities[0].Attributes["notetext"].ToString()); ////htm.Append("</td></tr></table>"); ////description.Replace("[NotesName]", ServiceRequestHelper.GetValueFromWebsiteLanguage(service, languageCode, "ServiceRequest/EmailTemplates/Notes")); ////description.Replace("[DueDate]", ServiceRequestHelper.GetValueFromWebsiteLanguage(service, languageCode, "ServiceRequestConfirmation/ToBeScheduled")); if (languageCode == "en-us") { description.Replace("[NotesName]", collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequest/EmailTemplates/Notes")).First()["smp_value"].ToString()); } else { description.Replace("[NotesName]", collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequest/EmailTemplates/Notes (" + languageCode + ")")).First()["smp_value"].ToString()); } description.Replace("[NoteProvidedWhenPlacedOnHold]", notesCollection.Entities[0].Attributes["notetext"].ToString()); ////description.Replace("[Notes]", string.Format("<b>{0}</b> {1}", ServiceRequestHelper.GetValueFromWebsiteLanguage(service, languageCode, "ServiceRequest/EmailTemplates/Notes"), notesCollection.Entities[0].Attributes["notetext"].ToString())); ////string.Format("<div><b>{0}</b> <p style=\"color:red;\">{1}</p></div>", ServiceRequestHelper.GetValueFromWebsiteLanguage(service, languageCode, "ServiceRequest/EmailTemplates/Notes"), notesCollection.Entities[0].Attributes["notetext"].ToString()) } else { description.Replace("[NotesName]", string.Empty); description.Replace("[NoteProvidedWhenPlacedOnHold]", string.Empty); } } else { description.Replace("[NotesName]", string.Empty); description.Replace("[NoteProvidedWhenPlacedOnHold]", string.Empty); } } description.Replace("[gfscLink]", "<a href=\"" + collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestPortalLink")).First()["smp_value"].ToString() + "\"style=\"color: #0563C1; font-family: Segoe UI;\">www.msfacilities.com</a>"); ////code change for survey snippet by mihika ////if (languageCode == "en-us" || string.IsNullOrEmpty(languageCode)) ////{ //// surveyLink = string.Format(CultureInfo.InvariantCulture, ServiceRequestHelper.GetConfigurationValue(service, "ServiceRequestSurveyLink"), string.Empty); ////} ////else ////{ //// surveyLink = string.Format(CultureInfo.InvariantCulture, ServiceRequestHelper.GetConfigurationValue(service, "ServiceRequestSurveyLink"), "/" + languageCode); ////} ////description.Replace("[Link]", "<a href=" + surveyLink + serviceRequestId + ">Survey Link</a>"); surveyLink = string.Format(CultureInfo.InvariantCulture, collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestSurveyLink")).First()["smp_value"].ToString(), string.Empty); description.Replace("[Link]", surveyLink); string srDetails = string.Empty; if (languageCode == "en-us") { srDetails = collection.Entities.Where(x => x["smp_title"].ToString().Equals("Seemoreinformationaboutyourservicerequest")).First()["smp_value"].ToString(); } else { srDetails = collection.Entities.Where(x => x["smp_title"].ToString().Equals("Seemoreinformationaboutyourservicerequest (" + languageCode + ")")).First()["smp_value"].ToString(); } Guid requestId = Guid.Empty; if (entity.Attributes.Contains("smp_reclassifiedsr")) { requestId = ((EntityReference)entity.Attributes["smp_reclassifiedsr"]).Id; } else { requestId = entity.Id; } if (entity.Attributes.Contains("smp_reasonforreclassifyingtherecordmemo")) { description.Replace("[ReclassificationReason]", (string)entity.Attributes["smp_reasonforreclassifyingtherecordmemo"]); } if (entity.Attributes.Contains("smp_reclassifiedsr")) { Entity reclassifiedSR = service.Retrieve("incident", ((EntityReference)entity.Attributes["smp_reclassifiedsr"]).Id, new ColumnSet("ticketnumber")); description.Replace("[NewTicketNumber]", (string)reclassifiedSR["ticketnumber"]); } description.Replace("[Seemoreinformationaboutyourservicerequest]", "<a href=\"" + collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestPortalLink")).First()["smp_value"].ToString() + languageCode + "/request/?id=" + requestId + "\"style=\"color: #0563C1; font-family: Segoe UI;\">" + srDetails + "</a>"); email["description"] = string.Format(CultureInfo.InstalledUICulture, "<div style=\"font-family:Tahoma;font-size:12px;\"> {0} </div>", description.ToString()); email.LogicalName = "email"; if (toParty != null) { email["to"] = toParty.ToArray(); } email["from"] = new[] { fromParty }; email["regardingobjectid"] = new EntityReference("incident", entity.Id); if (carbonCopyParty != null && carbonCopyParty.Count > 0) { email["cc"] = carbonCopyParty.ToArray(); } Guid emailId = service.Create(email); //// Use the SendEmail message to send an e-mail message. var sendEmailreq = new SendEmailRequest { EmailId = emailId, TrackingToken = string.Empty, IssueSend = true }; service.Execute(sendEmailreq); isEmailSent = true; } } catch (Exception ex) { throw ex; } return(isEmailSent); }
/// <summary> /// Gets due date. /// </summary> /// <param name="service">The service.</param> /// <param name="buildingId">The building Id.</param> /// <param name="dueDate">The due date.</param> /// <returns>Returns due date.</returns> public static DateTime GetDueDateByBuildingTimeZoneConsideringHolidays(IOrganizationService service, Guid buildingId, DateTime dueDate, int priorityMinutes) { bool isHoliday = false; string startHours = string.Empty; string endHours = string.Empty; int count = 0; int diffMinutes = 0; int calculatedMinutes = 0; DateTime finalDate = dueDate; DateTime submitteddate = dueDate.AddMinutes(-1 * priorityMinutes); EntityCollection buildingWorkHoursCollection = GetQueryResponse(service, "smp_buildingworkhours", new string[] { "smp_starthours", "smp_endhours" }, "smp_buildingid", buildingId); if (buildingWorkHoursCollection != null && buildingWorkHoursCollection.Entities.Count > 0) { Entity buildingWorkHours = buildingWorkHoursCollection.Entities[0]; if (buildingWorkHours != null) { if (buildingWorkHours.Attributes.Contains("smp_starthours")) { startHours = buildingWorkHours.FormattedValues["smp_starthours"].ToString(); } if (buildingWorkHours.Attributes.Contains("smp_endhours")) { endHours = buildingWorkHours.FormattedValues["smp_endhours"].ToString(); } DateTime startdatetime = Convert.ToDateTime(submitteddate.ToShortDateString() + " " + startHours, CultureInfo.CurrentCulture); DateTime enddatetime = Convert.ToDateTime(submitteddate.ToShortDateString() + " " + endHours, CultureInfo.CurrentCulture); EntityCollection buildingCollection = ServiceRequestHelper.GetBuildingDetails(service, buildingId, new string[] { "smp_issaturdayholiday", "smp_issundayholiday" }); for (int iterationCount = 1; iterationCount <= priorityMinutes; iterationCount++) { diffMinutes = iterationCount - count; if (startdatetime <= submitteddate.AddMinutes(diffMinutes) && submitteddate.AddMinutes(diffMinutes) <= enddatetime) { if (buildingCollection.Entities.ToList().Where(e => e.Attributes["smp_name"].ToString().ToLower() == submitteddate.DayOfWeek.ToString().ToLower()).FirstOrDefault() != null) { isHoliday = true; } if (IsPublicHoliday(service, buildingId, submitteddate) == true) { isHoliday = true; } if (isHoliday == true) { enddatetime = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + endHours); startdatetime = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + startHours); submitteddate = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + startHours); } else { int balanceMinutes = Convert.ToInt16(Math.Ceiling((enddatetime - submitteddate).TotalMinutes)); if ((priorityMinutes - calculatedMinutes) > balanceMinutes) { startdatetime = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + startHours); enddatetime = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + endHours); submitteddate = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + startHours); } else { submitteddate = submitteddate.AddMinutes(priorityMinutes - calculatedMinutes); } iterationCount = iterationCount + balanceMinutes; calculatedMinutes = calculatedMinutes + balanceMinutes; } count = iterationCount; isHoliday = false; finalDate = submitteddate; } else if (submitteddate.AddMinutes(diffMinutes) > enddatetime) { count = iterationCount; enddatetime = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + endHours); startdatetime = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + startHours); submitteddate = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + startHours); finalDate = submitteddate; } else if (submitteddate.AddMinutes(diffMinutes) < startdatetime) { count = iterationCount; startdatetime = Convert.ToDateTime(submitteddate.ToShortDateString() + " " + startHours); enddatetime = Convert.ToDateTime(submitteddate.ToShortDateString() + " " + endHours); submitteddate = Convert.ToDateTime(submitteddate.ToShortDateString() + " " + startHours); finalDate = submitteddate; } } } } else { endHours = "00:00"; EntityCollection buildingCollection = ServiceRequestHelper.GetBuildingDetails(service, buildingId, new string[] { "smp_issaturdayholiday", "smp_issundayholiday" }); for (int i = 0; i <= 365; i++) { if (buildingCollection.Entities.ToList().Where(e => e.Attributes["smp_name"].ToString().ToLower() == submitteddate.DayOfWeek.ToString().ToLower()).FirstOrDefault() != null) { isHoliday = true; } if (IsPublicHoliday(service, buildingId, submitteddate) == true) { isHoliday = true; } if (isHoliday == true) { submitteddate = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + endHours); } else { DateTime enddatetime = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + endHours); int balanceMinutes = Convert.ToInt16(Math.Ceiling((enddatetime - submitteddate).TotalMinutes)); if ((priorityMinutes - calculatedMinutes) > balanceMinutes) { submitteddate = Convert.ToDateTime(submitteddate.AddDays(1).ToShortDateString() + " " + endHours); } else { submitteddate = submitteddate.AddMinutes(priorityMinutes - calculatedMinutes); break; } calculatedMinutes = calculatedMinutes + balanceMinutes; } isHoliday = false; } finalDate = submitteddate; } return(finalDate); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostServiceRequestCreateEmailNotification(LocalPluginContext localContext) { Guid incidentId = Guid.Empty; bool isProblemClassAllowForEmailNotification = false; bool isProblemTypeAllowForEmailNotification = false; if (localContext == null) { return; } // TODO: Implement your custom Plug-in business logic. IPluginExecutionContext context = localContext.PluginExecutionContext; ITracingService trace = localContext.TracingService; if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity entity = (Entity)context.InputParameters["Target"]; bool allowEmailNotification = false; bool contact_AllowEmailNotification = false; bool problemBuilding_AllowEmailNotification = false; int serviceRequestOriginValue = 0; var service = localContext.OrganizationService; trace.Trace("Depth :" + context.Depth.ToString()); if (entity.LogicalName == "incident") { incidentId = entity.Id; Entity serviceRequest = context.PostEntityImages.Contains("PostImage") ? (Entity)context.PostEntityImages["PostImage"] : null; Entity contactInfo = ServiceRequestHelper.GetContactDetails(service, ((EntityReference)serviceRequest.Attributes["smp_contact"]).Id); contact_AllowEmailNotification = (contactInfo != null && contactInfo.Attributes.Contains("smp_allowemailnotification")) ? (bool)contactInfo["smp_allowemailnotification"] : false; trace.Trace("contact_AllowEmailNotification :" + contact_AllowEmailNotification.ToString()); if (serviceRequest.Attributes.Contains("smp_problembuilding")) { problemBuilding_AllowEmailNotification = ServiceRequestHelper.GetBuildingEmailNotificationStatus(service, ((Microsoft.Xrm.Sdk.EntityReference)serviceRequest.Attributes["smp_problembuilding"]).Id); } trace.Trace("problemBuilding_AllowEmailNotification :" + problemBuilding_AllowEmailNotification.ToString()); allowEmailNotification = serviceRequest.Attributes.Contains("smp_allowemailnotification") ? (bool)serviceRequest["smp_allowemailnotification"] : false; if (serviceRequest.Attributes.Contains("caseorigincode")) { serviceRequestOriginValue = ((Microsoft.Xrm.Sdk.OptionSetValue)serviceRequest["caseorigincode"]).Value; } trace.Trace("serviceRequestOriginValue :" + serviceRequestOriginValue.ToString()); Entity problemClass = serviceRequest.Attributes.Contains("smp_problemclassid") ? ServiceRequestHelper.GetProblemClassDetails(service, ((EntityReference)serviceRequest.Attributes["smp_problemclassid"]).Id) : null; isProblemClassAllowForEmailNotification = problemClass != null ? (bool)problemClass["smp_allowemailnotification"] : false; trace.Trace("isProblemClassAllowForEmailNotification :" + isProblemClassAllowForEmailNotification.ToString()); Entity problemType = serviceRequest.Attributes.Contains("smp_problemtypeid") ? ServiceRequestHelper.GetProblemTypeDetails(service, ((EntityReference)serviceRequest["smp_problemtypeid"]).Id) : null; isProblemTypeAllowForEmailNotification = problemType != null ? (bool)problemType["smp_allowemailnotification"] : false; trace.Trace("isProblemTypeAllowForEmailNotification :" + isProblemTypeAllowForEmailNotification.ToString()); try { OptionSetValue entityStatusCode = (OptionSetValue)entity.Attributes["statuscode"]; trace.Trace("entityStatusCode" + entityStatusCode.Value.ToString()); if (entityStatusCode.Value == 2 || entityStatusCode.Value == 3) { if (contact_AllowEmailNotification == true) { } else { if (allowEmailNotification == true && problemBuilding_AllowEmailNotification == true && isProblemTypeAllowForEmailNotification && isProblemClassAllowForEmailNotification) { EntityCollection configurationCollection = ServiceRequestHelper.GetConfigurationValueCollection(service); if (serviceRequestOriginValue != 180620003) { SendStatusChangeEmail(service, serviceRequest, entityStatusCode.Value, configurationCollection, contactInfo); } } } } } catch (Exception) { throw; } } } }
/// <summary> /// DoIntegration /// </summary> /// <param name="service"></param> /// <param name="serviceRequest"></param> /// <param name="provider"></param> /// <param name="trace"></param> /// <param name="caseOrigin"></param> /// <param name="collection"></param> private static void DoIntegration(IOrganizationService service, Entity serviceRequest, Provider provider, ITracingService trace, int caseOrigin, EntityCollection collection) { bool isEmailSent = false; bool isDataUpdated = false; bool isDebug = false; //// Get the configured user id for sending email. string fromUserDomainName = collection.Entities.Where(x => x["smp_title"].ToString().Equals(CRMAttributesResource.EmailSenderDomainName)).First()["smp_value"].ToString(); Guid senderId = ServiceRequestHelper.GetCrmUserId(service, fromUserDomainName); //// get WCF timeout values string timeOut = collection.Entities.Where(x => x["smp_title"].ToString().Equals(CRMAttributesResource.OutBoundIntegrationtimeOutInSeconds)).First()["smp_value"].ToString(); //// get debugging information string enableDebug = collection.Entities.Where(x => x["smp_title"].ToString().Equals(CRMAttributesResource.DebugOutBoundIntegration)).First()["smp_value"].ToString(); isDebug = (string.IsNullOrEmpty(enableDebug) == false && enableDebug.Equals("1")) ? true : false; int fromIntegration = 0; ServiceRequest providerServiceRequest = ServiceRequestHelper.SetServiceRequestObject(service, serviceRequest, fromIntegration); //// if provider integration is enabled, send details via service else send an email if (provider.IsIntegrationEnabled) { //// Create a task record with XML content Entity task = new Entity("task"); task["subject"] = "CMMS Integration Task " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString(); task["description"] = SerializeObjectToXML(providerServiceRequest); task["regardingobjectid"] = new EntityReference(serviceRequest.LogicalName, serviceRequest.Id); Guid newTaskId = service.Create(task); task["statecode"] = new OptionSetValue(1); task["activityid"] = newTaskId; service.Update(task); //// if provider details are not given, send an email if (!string.IsNullOrWhiteSpace(provider.ProviderServiceAddress)) { //// Calling integration service, trying 3 times isDataUpdated = ServiceRequestHelper.CallIntegrationService(provider, providerServiceRequest, string.IsNullOrEmpty(timeOut) ? 0 : Convert.ToUInt16(timeOut), service, serviceRequest.Id, isDebug, trace); //// if integration fail, log in exception log entity and send an email if (!isDataUpdated && providerServiceRequest != null) { Logger.Write("Service Request data update failed", ExceptionType.SendServiceRequestToProviderFailed, service, "incident", "smp_servicerequestid", serviceRequest.Id, string.Empty); isEmailSent = EmailHelper.SendEmail(service, providerServiceRequest, serviceRequest.Id, "systemuser", senderId, "account", provider.ProviderId, collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestIntegrationFailEmailTemplateName")).First()["smp_value"].ToString()); } } else { Logger.Write("Provider details not updated, please update provider's service url, username and password.", ExceptionType.SendServiceRequestToProviderFailed, service, "incident", "smp_servicerequestid", serviceRequest.Id, string.Empty); isEmailSent = EmailHelper.SendEmail(service, providerServiceRequest, serviceRequest.Id, "systemuser", senderId, "account", provider.ProviderId, collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestIntegrationFailEmailTemplateName")).First()["smp_value"].ToString()); } } else { if (providerServiceRequest != null) { string environment = collection.Entities.Where(x => x["smp_title"].ToString().Equals("Environment")).First()["smp_value"].ToString(); if (environment == "Non-Prod") { isEmailSent = true; } else { isEmailSent = EmailHelper.SendEmail(service, providerServiceRequest, serviceRequest.Id, "systemuser", senderId, "account", provider.ProviderId, collection.Entities.Where(x => x["smp_title"].ToString().Equals("ServiceRequestIntegrationEmailTemplateName")).First()["smp_value"].ToString()); } } } }
public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(context.UserId); try { if ((context.InputParameters == null) || (!context.InputParameters.Contains("Target"))) { return; } Entity serviceRequest = (context.PostEntityImages != null && context.PostEntityImages.Contains("PostImage")) ? (Entity)context.PostEntityImages["PostImage"] : null; if (context.MessageName == "Update" && context.Depth > 1 && serviceRequest.GetAttributeValue <EntityReference>("msdyn_iotalert") == null) { return; } else if (context.MessageName == "Update" && context.Depth > 2) { return; } ////Updated the code to return if the SR status is Cancelled to stop Integration mails and 8x8 Mails. Related Work Items: #4850727 else if (((OptionSetValue)((Entity)context.InputParameters["Target"])["statuscode"]).Value == Constants.SRStatus_Cancelled) { return; } if (serviceRequest != null) { EntityCollection configurationCollection = ServiceRequestHelper.GetConfigurationValueCollection(service); Provider provider = ServiceRequestHelper.GetProviderDetails(service, ((EntityReference)serviceRequest["customerid"]).Id, configurationCollection, trace); //// Check if provider is not updated, ////if not updated no action is desired. if (!provider.IsProviderUpdated) { trace.Trace("Provider Not There"); ServiceRequestHelper.SetProviderCriteriaMissingFields(service, serviceRequest); return; } //// Fetching current status code string currentStatusCode = ServiceRequestHelper.GetStatusCodeFromValue(service, ((OptionSetValue)((Entity)context.InputParameters["Target"])["statuscode"]).Value); trace.Trace("Current Status :" + currentStatusCode.ToString()); int caseOrigin = ((OptionSetValue)serviceRequest["caseorigincode"]).Value; //// if priority is (P1 or P2) and integration status is false - no integration will happen if (!ServiceRequestHelper.IsPrioritySetForIntegration(currentStatusCode, service, serviceRequest, trace, configurationCollection, caseOrigin, provider.ProviderTeamId)) { trace.Trace("The Service Request is of High Priority(P1/P2/PS1/Ps2)"); } else { string invalidIntegrationCodes = configurationCollection.Entities.Where(x => x["smp_title"].ToString().Equals("NoCmmsIntegrationActionCodes")).First()["smp_value"].ToString(); trace.Trace("Invalid Integration Codes :" + invalidIntegrationCodes); if (!string.IsNullOrWhiteSpace(currentStatusCode) && !string.IsNullOrWhiteSpace(invalidIntegrationCodes) && (!invalidIntegrationCodes.ToUpperInvariant().Contains(currentStatusCode.ToUpperInvariant()))) { trace.Trace("The Service Request is of Low Priority or Status is DRAFT"); ServiceRequestHelper.SetServiceRequestStatus(service, serviceRequest, currentStatusCode, "RequestDispatchStatusCode", caseOrigin, configurationCollection, provider.ProviderTeamId); } } } } catch (Exception ex) { trace.Trace("Exception from PostCreateorUpdateSetPriorityBasedStatus :" + ex.Message); throw new InvalidPluginExecutionException("Contact CRM Technical Administrator " + ex.Message); } }