Exemple #1
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            LocalWorkflowContext    localWorkflowContext   = new LocalWorkflowContext(executionContext);
            IConfigurationRetrieval configurationRetrieval = new ConfigurationRetrieval();

            requestLogging = new RequestLogging(configurationRetrieval, localWorkflowContext);
            ITracingService             tracer         = executionContext.GetExtension <ITracingService>();
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                tracer.Trace("Gettting Current User Id from execution context " + DateTime.Now.ToString());
                var currentUserId = CurrentUserId.Get <EntityReference>(executionContext);
                ////requestLogging.LogWorkflowTrace(MappingConstants.RetrieveContactEmailAddressSequenceId, MappingConstants.RetrieveCurrentUserIdSuccessEventId, MappingConstants.RetrieveContactEmailAddressEventName, MappingConstants.RetrieveCurrentUserIdSuccessEventMessage);

                tracer.Trace("Retrieving Internal Email Address of a User " + DateTime.Now.ToString());
                var emailAddress = WorkflowHelper.GetPrimaryEmailAddressOfUser(service, currentUserId.Id);
                tracer.Trace("Retrived Internal Email Address of a User " + DateTime.Now.ToString());
                ////requestLogging.LogWorkflowTrace(MappingConstants.RetrieveContactEmailAddressSequenceId, MappingConstants.RetrieveInternalEmailSuccessEventId, MappingConstants.RetrieveContactEmailAddressEventName, MappingConstants.RetrieveInternalEmailSuccessEventMessage);

                tracer.Trace("Retrieving Contact By Primary Email Address of a Contact " + DateTime.Now.ToString());
                var contact = WorkflowHelper.GetContactByEmailAddress(service, emailAddress);
                tracer.Trace("Retrived Contact By Primary Email Address of a Contact " + DateTime.Now.ToString());
                ////requestLogging.LogWorkflowTrace(MappingConstants.RetrieveContactEmailAddressSequenceId, MappingConstants.RetrieveContactByEmailSuccessEventId, MappingConstants.RetrieveContactEmailAddressEventName, MappingConstants.RetrieveContactByEmailSuccessEventMessage);

                if (contact != null)
                {
                    ContactRelatedToUser.Set(executionContext, contact?.ToEntityReference());
                }
                else
                {
                    tracer.Trace("Retrieving Default Contact from Configuration " + DateTime.Now.ToString());
                    string ESBDefaultEmailAddress = WorkflowHelper.GetConfigurationValue(service, "ESBDefaultContact");
                    tracer.Trace("Retrived Default Contact from Configuration " + DateTime.Now.ToString());

                    tracer.Trace("Retrieving Default Contact By Primary Email Address of a Contact " + DateTime.Now.ToString());
                    var defaultContact = WorkflowHelper.GetContactByEmailAddress(service, ESBDefaultEmailAddress);
                    tracer.Trace("Retrived Default Contact By Primary Email Address of a Contact " + DateTime.Now.ToString());
                    ////requestLogging.LogWorkflowTrace(MappingConstants.RetrieveContactEmailAddressSequenceId, MappingConstants.RetrieveDefaultContactByEmailSuccessEventId, MappingConstants.RetrieveContactEmailAddressEventName, MappingConstants.RetrieveDefaultContactByEmailSuccessEventMessage);
                    ContactRelatedToUser.Set(executionContext, defaultContact?.ToEntityReference());
                }
                ////requestLogging.LogWorkflowTrace(MappingConstants.RetrieveContactEmailAddressSequenceId, MappingConstants.RetrieveContactEmailAddressSuccessEventId, MappingConstants.RetrieveContactEmailAddressEventName, MappingConstants.RetrieveContactEmailAddressSuccessEventMessage);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                ////requestLogging.LogWorkflowException(e, MappingConstants.RetrieveContactEmailAddressSequenceId, MappingConstants.RetrieveContactEmailAddressFailedEventId, MappingConstants.RetrieveContactEmailAddressEventName, MappingConstants.RetrieveContactEmailAddressFailedEventMessage);
                tracer.Trace("GetContactByUser Code Activity : {0}", e.ToString());
                throw new InvalidPluginExecutionException("An error occurred in GetContactByUser Code Activity." + e.Message);
            }
            catch (Exception ex)
            {
                ////requestLogging.LogWorkflowException(ex, MappingConstants.RetrieveContactEmailAddressSequenceId, MappingConstants.RetrieveContactEmailAddressFailedEventId, MappingConstants.RetrieveContactEmailAddressEventName, MappingConstants.RetrieveContactEmailAddressFailedEventMessage);
                tracer.Trace("GetContactByUser Code Activity : {0}", ex.ToString());
                throw;
            }
        }
Exemple #2
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            LocalWorkflowContext    localWorkflowContext   = new LocalWorkflowContext(executionContext);
            IConfigurationRetrieval configurationRetrieval = new ConfigurationRetrieval();

            requestLogging = new RequestLogging(configurationRetrieval, localWorkflowContext);
            ITracingService             tracer         = executionContext.GetExtension <ITracingService>();
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                tracer.Trace("Gettting Service Request Id from execution context " + DateTime.Now.ToString());
                var serviceRequestId = ServiceRequestId.Get <EntityReference>(executionContext);
                tracer.Trace("Retrieve Active Work Order ID using Service Request Id " + DateTime.Now.ToString());
                var workOrder = GetWorkOrderByServiceActivity(service, serviceRequestId);
                tracer.Trace("Retrieved Active Work Order ID  " + DateTime.Now.ToString());
                if (workOrder != null)
                {
                    WorkOrderId.Set(executionContext, workOrder.ToEntityReference());
                    IsExists.Set(executionContext, true);
                }
                else
                {
                    WorkOrderId.Set(executionContext, null);
                    IsExists.Set(executionContext, false);
                }
                ////requestLogging.LogWorkflowTrace(MappingConstants.GetWORelatedToSRSequenceId, MappingConstants.GetWORelatedToSRSuccessEventId, MappingConstants.GetWORelatedToSREventName, MappingConstants.GetWORelatedToSRSuccessEventMessage);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                ////requestLogging.LogWorkflowException(e, MappingConstants.GetWORelatedToSRSequenceId, MappingConstants.GetWORelatedToSRFailedEventId, MappingConstants.GetWORelatedToSREventName, MappingConstants.GetWORelatedToSRFailedEventMessage);
                tracer.Trace("GetWorkOrderRelatedServiceRequest Code Activity : {0}", e.ToString());
                throw new InvalidPluginExecutionException("An error occurred in GetWorkOrderRelatedServiceRequest Code Activity." + e.Message);
            }
            catch (Exception ex)
            {
                ////requestLogging.LogWorkflowException(ex, MappingConstants.GetWORelatedToSRSequenceId, MappingConstants.GetWORelatedToSRFailedEventId, MappingConstants.GetWORelatedToSREventName, MappingConstants.GetWORelatedToSRFailedEventMessage);
                tracer.Trace("GetWorkOrderRelatedServiceRequest Code Activity : {0}", ex.ToString());
                throw;
            }
        }
Exemple #3
0
        ////Thid Plugin will fire on Work order pre Create. it will map all the Required Fields from the Service Request.
        protected void PreCreateWorkOrder(LocalPluginContext localContext)
        {
            try
            {
                CCRM.REF.TelemetryLog.LocalPluginContext localPluginContext = new CCRM.REF.TelemetryLog.LocalPluginContext(localContext.ServiceProvider);
                IConfigurationRetrieval configurationRetrieval = new ConfigurationRetrieval();
                requestLogging = new RequestLogging(configurationRetrieval, localPluginContext);
                IPluginExecutionContext context        = localContext.PluginExecutionContext;
                ITracingService         tracingService = localContext.TracingService;
                IOrganizationService    service        = localContext.OrganizationService;
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    workOrder = context.InputParameters["Target"] as Entity;
                    if (workOrder.Attributes.Contains("msdyn_servicerequest"))
                    {
                        EntityReference serviceRequest = workOrder.GetAttributeValue <EntityReference>("msdyn_servicerequest");
                        Entity          caserecord     = service.Retrieve("incident", serviceRequest.Id, new ColumnSet("smp_requestedduedate", "smp_costcentercode",
                                                                                                                       "smp_iocode", "smp_problembuilding", "new_problemroomnumber", "smp_problemroom",
                                                                                                                       "smp_problemroomtype", "smp_problemtypedescription", "caseorigincode",
                                                                                                                       "smp_problemclassid", "smp_problemtypeid", "smp_cc", "smp_contact",
                                                                                                                       "smp_requestorid", "smp_priorityid", "smp_duedate",
                                                                                                                       "smp_duedatebybuildingtimezone", "smp_occureddatetimebybuildingtimezone",
                                                                                                                       "smp_submitteddatetimebybuildingtimezone", "smp_createddatetimebybuildingtimezone",
                                                                                                                       "smp_contactphone", "smp_contactemail", "smp_requestorphone", "smp_requestoremail"
                                                                                                                       , "msdyn_iotalert"));
                        Entity building = service.Retrieve(caserecord.GetAttributeValue <EntityReference>("smp_problembuilding").LogicalName,
                                                           caserecord.GetAttributeValue <EntityReference>("smp_problembuilding").Id,
                                                           new ColumnSet("smp_feedstoreid"));
                        EntityReference iotAlert       = caserecord.GetAttributeValue <EntityReference>("msdyn_iotalert");
                        Entity          iotAlertRecord = null;
                        if (iotAlert != null)
                        {
                            iotAlertRecord = service.Retrieve(caserecord.GetAttributeValue <EntityReference>("msdyn_iotalert").LogicalName, caserecord.GetAttributeValue <EntityReference>("msdyn_iotalert").Id, new ColumnSet("smp_correlationid", "msdyn_customerasset"));
                        }
                        if (building != null)
                        {
                            tracingService.Trace("mapping servicing account with Buliding Name");

                            QueryExpression query = new QueryExpression("account");
                            query.ColumnSet = new ColumnSet("smp_tieroneprovider");
                            query.Criteria.AddFilter(LogicalOperator.And);
                            query.Criteria.AddCondition(new ConditionExpression("smp_accounttype", ConditionOperator.Equal, 180620000));
                            query.Criteria.AddCondition(new ConditionExpression("accountnumber", ConditionOperator.Equal, building.GetAttributeValue <string>("smp_feedstoreid")));
                            EntityCollection entityCollection = service.RetrieveMultiple(query);

                            if (entityCollection.Entities.Count > 0)
                            {
                                workOrder.Attributes["msdyn_serviceaccount"] = new EntityReference("account", entityCollection.Entities[0].Id);
                                workOrder.Attributes["smp_tier1provider"]    = entityCollection.Entities[0].GetAttributeValue <string>("smp_tieroneprovider");
                            }
                            else
                            {
                                tracingService.Trace("No Service Account existed with Same Building");
                                throw new InvalidPluginExecutionException("Building record does not exist in account entity, Service Request cannot dispatch. Map building record in account entity as account type is building.");
                            }
                        }

                        workOrder.Attributes["smp_contactphonenumber"]   = caserecord.GetAttributeValue <string>("smp_contactphone");
                        workOrder.Attributes["smp_contactemail"]         = caserecord.GetAttributeValue <string>("smp_contactemail");
                        workOrder.Attributes["smp_requestorphonenumber"] = caserecord.GetAttributeValue <string>("smp_requestorphone");
                        workOrder.Attributes["smp_requestoremail"]       = caserecord.GetAttributeValue <string>("smp_requestoremail");
                        workOrder.Attributes["smp_costcentercode"]       = caserecord.GetAttributeValue <string>("smp_costcentercode");
                        workOrder.Attributes["smp_iocode"]   = caserecord.GetAttributeValue <string>("smp_iocode");
                        workOrder.Attributes["smp_building"] = new EntityReference(building.LogicalName, building.Id);
                        workOrder.Attributes["smp_room"]     = caserecord.GetAttributeValue <EntityReference>("new_problemroomnumber");

                        if (caserecord.GetAttributeValue <EntityReference>("new_problemroomnumber") != null && caserecord.GetAttributeValue <EntityReference>("new_problemroomnumber").Name != string.Empty)
                        {
                            workOrder.Attributes["smp_problemroom"] = caserecord.GetAttributeValue <string>("smp_problemroom");
                        }

                        if (caserecord.GetAttributeValue <EntityReference>("smp_problemroomtype") != null)
                        {
                            workOrder.Attributes["smp_roomtype"] = caserecord.GetAttributeValue <EntityReference>("smp_problemroomtype");
                        }

                        if (caserecord.GetAttributeValue <string>("smp_problemtypedescription") != string.Empty)
                        {
                            workOrder.Attributes["msdyn_workordersummary"] = caserecord.GetAttributeValue <string>("smp_problemtypedescription");
                        }

                        workOrder.Attributes["smp_source"] = caserecord.GetAttributeValue <OptionSetValue>("caseorigincode");

                        if (caserecord.Attributes.Contains("smp_requestedduedate"))
                        {
                            AttributeHelper.MapDataTimeValue("smp_requestedduedate", caserecord, "msdyn_datewindowend", ref workOrder);
                        }

                        if (caserecord.Attributes.Contains("smp_duedate") && Convert.ToDateTime(caserecord["smp_duedate"]) != DateTime.MinValue)
                        {
                            workOrder.Attributes["msdyn_timetopromised"] = caserecord.GetAttributeValue <DateTime>("smp_duedate");
                        }

                        AttributeHelper.MapDataTimeValue("smp_duedate", caserecord, "smp_duedate", ref workOrder);
                        AttributeHelper.MapStringValue("smp_duedatebybuildingtimezone", caserecord, "smp_duedatebybuildingtimezone", ref workOrder);
                        AttributeHelper.MapStringValue("smp_occureddatetimebybuildingtimezone", caserecord, "smp_problemoccureddatetimebybuildingtimezone", ref workOrder);
                        AttributeHelper.MapStringValue("smp_submitteddatetimebybuildingtimezone", caserecord, "smp_submitteddatetimebybuildingtimezone", ref workOrder);
                        AttributeHelper.MapStringValue("smp_createddatetimebybuildingtimezone", caserecord, "smp_createddatetimebybuildingtimezone", ref workOrder);
                        EntityReference priority = caserecord.GetAttributeValue <EntityReference>("smp_priorityid");

                        if (priority != null)
                        {
                            QueryExpression priorityquery = new QueryExpression("msdyn_priority");
                            priorityquery.ColumnSet = new ColumnSet("msdyn_priorityid");
                            priorityquery.Criteria.AddCondition("msdyn_priority", "msdyn_name", ConditionOperator.Equal, priority.Name);
                            var prrecordcollection = service.RetrieveMultiple(priorityquery);
                            if (prrecordcollection.Entities != null && prrecordcollection.Entities.Count > 0)
                            {
                                Entity prrecord = prrecordcollection.Entities[0];
                                workOrder["msdyn_priority"] = new EntityReference(prrecord.LogicalName, prrecord.Id);
                            }

                            tracingService.Trace("Priority is mapped");
                        }

                        EntityReference problemClass = caserecord.GetAttributeValue <EntityReference>("smp_problemclassid");
                        EntityReference problemType  = caserecord.GetAttributeValue <EntityReference>("smp_problemtypeid");
                        if (problemClass.Name != string.Empty)
                        {
                            QueryExpression problemquery = new QueryExpression("msdyn_workordertype");
                            problemquery.ColumnSet = new ColumnSet("msdyn_workordertypeid");
                            problemquery.Criteria.AddFilter(LogicalOperator.Or);
                            problemquery.Criteria.AddCondition("msdyn_workordertype", "msdyn_name", ConditionOperator.Equal, problemClass.Name.ToUpper());
                            problemquery.Criteria.AddCondition("msdyn_workordertype", "msdyn_name", ConditionOperator.Equal, problemClass.Name.ToLower());
                            problemquery.Criteria.AddCondition("msdyn_workordertype", "statecode", ConditionOperator.Equal, 0);
                            var problemclasscollection = service.RetrieveMultiple(problemquery);

                            if (problemclasscollection.Entities != null && problemclasscollection.Entities.Count > 0)
                            {
                                Entity problemclassrecord = problemclasscollection.Entities[0];
                                workOrder["msdyn_workordertype"] = new EntityReference(problemclassrecord.LogicalName, problemclassrecord.Id);
                            }

                            tracingService.Trace("WO Type is mapped");
                        }

                        if (problemType.Name != string.Empty)
                        {
                            QueryExpression problemtypequery = new QueryExpression("msdyn_incidenttype");
                            problemtypequery.ColumnSet = new ColumnSet("msdyn_incidenttypeid");
                            problemtypequery.Criteria.AddFilter(LogicalOperator.Or);
                            problemtypequery.Criteria.AddCondition("msdyn_incidenttype", "msdyn_name", ConditionOperator.Equal, problemType.Name.ToUpper());
                            problemtypequery.Criteria.AddCondition("msdyn_incidenttype", "msdyn_name", ConditionOperator.Equal, problemType.Name.ToLower());
                            problemtypequery.Criteria.AddCondition("msdyn_incidenttype", "statecode", ConditionOperator.Equal, 0);
                            var problemtypecollection = service.RetrieveMultiple(problemtypequery);

                            if (problemtypecollection.Entities != null && problemtypecollection.Entities.Count > 0)
                            {
                                Entity problemtyperecord = problemtypecollection.Entities[0];
                                workOrder["msdyn_primaryincidenttype"] = new EntityReference(problemtyperecord.LogicalName, problemtyperecord.Id);
                            }

                            tracingService.Trace("Incident Type is mapped");
                        }

                        EntityReference ccperson = caserecord.GetAttributeValue <EntityReference>("smp_cc");
                        if (ccperson != null)
                        {
                            workOrder["smp_ccperson"] = ccperson;
                            tracingService.Trace("CC is mapped");
                        }

                        EntityReference contactname = caserecord.GetAttributeValue <EntityReference>("smp_contact");
                        if (contactname != null)
                        {
                            workOrder["msdyn_reportedbycontact"] = contactname;
                            tracingService.Trace("contactname is mapped");
                        }

                        EntityReference requestorname = caserecord.GetAttributeValue <EntityReference>("smp_requestorid");
                        if (requestorname != null)
                        {
                            workOrder["smp_requestorname"] = requestorname;
                            tracingService.Trace("requestorname is mapped");
                        }

                        if (iotAlert != null)
                        {
                            workOrder["msdyn_iotalert"] = iotAlert;
                            tracingService.Trace("IOT Alert is mapped");
                            ////requestLogging.LogPluginTrace(workOrder, MappingConstants.WorkOrderCreatedSequenceId, MappingConstants.IOTAlertMappedSuccessEventId, MappingConstants.WorkOrderCreatedEventName, MappingConstants.IOTAlertMappedSuccessEventMessage);
                        }

                        if (iotAlertRecord != null)
                        {
                            if (iotAlertRecord.Attributes.Contains("smp_correlationid") && iotAlertRecord["smp_correlationid"] != null)
                            {
                                workOrder["smp_correlationid"] = iotAlertRecord.GetAttributeValue <string>("smp_correlationid");
                                ////requestLogging.LogPluginTrace(workOrder, MappingConstants.WorkOrderCreatedSequenceId, MappingConstants.CorrelationIDMappedSuccessEventId, MappingConstants.WorkOrderCreatedEventName, MappingConstants.CorrelationIDMappedSuccessEventMessage);
                            }

                            if (iotAlertRecord.Attributes.Contains("msdyn_customerasset") && iotAlertRecord["msdyn_customerasset"] != null)
                            {
                                EntityReference customerAsset = iotAlertRecord.GetAttributeValue <EntityReference>("msdyn_customerasset");
                                if (customerAsset != null)
                                {
                                    workOrder["msdyn_customerasset"] = customerAsset;
                                    ////requestLogging.LogPluginTrace(workOrder, MappingConstants.WorkOrderCreatedSequenceId, MappingConstants.CustomerAssetMappedSuccessEventId, MappingConstants.WorkOrderCreatedEventName, MappingConstants.CustomerAssetMappedSuccessEventMessage);
                                }
                            }
                        }

                        EntityReference agreement = workOrder.GetAttributeValue <EntityReference>("msdyn_agreement");
                        if (agreement == null)
                        {
                            Entity providermatrix = this.GetProviedmatrix(caserecord, service, tracingService);
                            if (providermatrix != null)
                            {
                                tracingService.Trace(providermatrix.GetAttributeValue <bool>("smp_billable").ToString());
                                workOrder["smp_billable"] = providermatrix.GetAttributeValue <bool>("smp_billable");
                            }
                        }

                        workOrder["smp_dynamicproblemtypenotes"] = this.GetDynamicQuestionandAnsewrs(caserecord, service, tracingService);
                    }

                    else if (workOrder.Attributes.Contains("msdyn_agreement"))
                    {
                        if (workOrder.Attributes.Contains("msdyn_serviceaccount"))
                        {
                            EntityReference account        = workOrder.GetAttributeValue <EntityReference>("msdyn_serviceaccount");
                            Entity          serviceaccount = service.Retrieve(account.LogicalName, account.Id, new ColumnSet("name"));
                            QueryExpression query          = new QueryExpression("smp_building");
                            query.ColumnSet = new ColumnSet("smp_buildingid");
                            query.Criteria.AddFilter(LogicalOperator.Or);
                            query.Criteria.AddCondition(new ConditionExpression("smp_buildingname", ConditionOperator.Equal, serviceaccount.GetAttributeValue <string>("name").ToUpper()));
                            query.Criteria.AddCondition(new ConditionExpression("smp_buildingname", ConditionOperator.Equal, serviceaccount.GetAttributeValue <string>("name").ToLower()));
                            EntityCollection entityCollection = service.RetrieveMultiple(query);

                            if (entityCollection.Entities.Count > 0)
                            {
                                workOrder.Attributes["smp_building"] = new EntityReference("smp_building", entityCollection.Entities[0].Id);
                            }
                        }
                    }

                    ////requestLogging.LogPluginTrace(workOrder, MappingConstants.WorkOrderCreatedSequenceId, MappingConstants.WorkOrderCreatedSuccessEventId, MappingConstants.WorkOrderCreatedEventName, MappingConstants.WorkOrderCreatedSuccessEventMessage);
                }
            }
            catch (Exception ex)
            {
                ////requestLogging.LogPluginException(workOrder, ex, MappingConstants.WorkOrderCreatedSequenceId, MappingConstants.WorkOrderCreatedFailedEventId, MappingConstants.WorkOrderCreatedEventName, MappingConstants.WorkOrderCreatedFailedEventMessage);
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
        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);
            Entity entity = new Entity();

            try
            {
                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);
                Guid     buildingId         = Guid.Empty;
                Guid     problemClassId     = Guid.Empty;
                Guid     problemTypeId      = Guid.Empty;
                Guid     problemRoomType    = Guid.Empty;
                DateTime problemoccureddate = Convert.ToDateTime(null, CultureInfo.CurrentCulture);
                DateTime duedate            = Convert.ToDateTime(null, CultureInfo.CurrentCulture);
                DateTime createdOn          = Convert.ToDateTime(null, CultureInfo.CurrentCulture);
                DateTime submitteddate      = Convert.ToDateTime(null, CultureInfo.CurrentCulture);
                DateTime emptysubmitteddate = Convert.ToDateTime(null, CultureInfo.CurrentCulture);
                Guid     priorityId         = Guid.Empty;
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    entity = (Entity)context.InputParameters["Target"];
                    trace.Trace("Depth From PreServiceRequestCreateSetPriority :" + context.Depth.ToString());
                    if (entity.LogicalName == "incident")
                    {
                        createdOn = Convert.ToDateTime(entity.Attributes["createdon"].ToString(), CultureInfo.CurrentCulture);
                        if (entity.Attributes.Contains("smp_problembuilding"))
                        {
                            buildingId = ((Microsoft.Xrm.Sdk.EntityReference)entity.Attributes["smp_problembuilding"]).Id;
                        }

                        if (entity.Attributes.Contains("smp_duedate"))
                        {
                            duedate = Convert.ToDateTime(entity.Attributes["smp_duedate"], CultureInfo.CurrentCulture);
                        }

                        if (entity.Attributes.Contains("smp_problemoccureddatetime"))
                        {
                            problemoccureddate = Convert.ToDateTime(entity.Attributes["smp_problemoccureddatetime"], CultureInfo.CurrentCulture);
                        }

                        if (entity.Attributes.Contains("smp_problemclassid"))
                        {
                            problemClassId = ((Microsoft.Xrm.Sdk.EntityReference)entity.Attributes["smp_problemclassid"]).Id;
                        }

                        if (entity.Attributes.Contains("smp_problemtypeid"))
                        {
                            problemTypeId = ((Microsoft.Xrm.Sdk.EntityReference)entity.Attributes["smp_problemtypeid"]).Id;
                        }

                        if (entity.Attributes.Contains("smp_problemroomtype"))
                        {
                            problemRoomType = ((Microsoft.Xrm.Sdk.EntityReference)entity.Attributes["smp_problemroomtype"]).Id;
                        }

                        if (entity.Attributes.Contains("smp_submitteddatetime"))
                        {
                            submitteddate = Convert.ToDateTime(entity.Attributes["smp_submitteddatetime"], CultureInfo.CurrentCulture);
                        }

                        if (entity.Attributes.Contains("smp_priorityid"))
                        {
                            priorityId = ((Microsoft.Xrm.Sdk.EntityReference)entity.Attributes["smp_priorityid"]).Id;
                        }

                        OptionSetValue entityStatusCode = (OptionSetValue)entity.Attributes["statuscode"];
                        OptionSetValue caseOrigin       = (OptionSetValue)entity["caseorigincode"];

                        ////code change on 09-01-2018 for priority set only on portal submit true and not just on case origin 3
                        bool portalSubmit = (bool)entity["smp_portalsubmit"];
                        int  statusCode   = Convert.ToInt32(entityStatusCode.Value, CultureInfo.InvariantCulture);
                        trace.Trace("entityStatusCode :" + statusCode);
                        if (statusCode == (int)ServiceRequestEnum.StatusCode.Closed)
                        {
                            ////Logger.Write("Priority not set", ExceptionType.SetPriorityFailed, service, "incident", "smp_servicerequestid", entity.Id, "Service Request Status is Draft");
                        }
                        else if (statusCode == (int)ServiceRequestEnum.StatusCode.Draft || statusCode == (int)ServiceRequestEnum.StatusCode.Open)
                        {
                            if (submitteddate == Convert.ToDateTime(null, CultureInfo.CurrentCulture))
                            {
                                emptysubmitteddate = Convert.ToDateTime(DateTime.UtcNow, CultureInfo.CurrentCulture);
                            }

                            int zone = 0;
                            if (problemRoomType != Guid.Empty)
                            {
                                zone = GetZoneByProblemRoomType(service, problemRoomType, context, entity.Id);
                            }

                            if (buildingId != Guid.Empty && problemoccureddate != null && problemClassId != Guid.Empty && problemTypeId != Guid.Empty && problemRoomType != Guid.Empty)
                            {
                                trace.Trace("Before the UpdateUserTimeZonesToServiceRequest");
                                UpdateUserTimeZonesToServiceRequest(
                                    service,
                                    entity.Id,
                                    buildingId,
                                    createdOn,
                                    duedate,
                                    problemoccureddate,
                                    context,
                                    problemClassId,
                                    problemTypeId,
                                    zone,
                                    submitteddate,
                                    emptysubmitteddate,
                                    priorityId,
                                    statusCode,
                                    trace);
                            }
                            else
                            {
                                trace.Trace("In Final Elese");
                                LogNotAllAttributesPopulated(service, entity);
                            }
                        }
                    }
                }

                ////this.requestLogging.LogPluginTrace(entity, MappingConstants.ServiceRequestCreatedSequenceId, MappingConstants.ServiceRequestCreatedSuccessEventId, MappingConstants.ServiceRequestCreatedEventName, MappingConstants.ServiceRequestCreatedSuccessEventMessage);
            }
            catch (Exception ex)
            {
                ////this.requestLogging.LogPluginException(entity, ex, MappingConstants.ServiceRequestCreatedSequenceId, MappingConstants.ServiceRequestCreatedFailedEventId, MappingConstants.ServiceRequestCreatedEventName, MappingConstants.ServiceRequestCreatedFailedEventMessage);
                throw new InvalidPluginExecutionException("Error in Pre create Set priority " + ex.Message);
            }
        }
        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
                    }
                }
            }
        }