/// <summary>
 /// Initializes a new instance of class PluginServices
 /// </summary>
 /// <param name="serviceProvider">Service provider</param>
 public PluginServices(IServiceProvider serviceProvider)
 {
     // Instanciation des services
     _executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
     _serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
     _tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
 }
Ejemplo n.º 2
0
        private void InitializeServices(IServiceProvider serviceProvider, out IPluginExecutionContext context)
        {
            context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            ((IProxyTypesAssemblyProvider)context).ProxyTypesAssembly = typeof(Contact).Assembly;

            t = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            service = serviceFactory.CreateOrganizationService(context.UserId);

            xrmContext = new crmContext(service);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                _tracingService = executionContext.GetExtension<ITracingService>();
                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                _service = serviceFactory.CreateOrganizationService(context.UserId);

                //Do stuff
            }
            catch (Exception ex)
            {
                _tracingService.Trace("Exception: {0}", ex.ToString());
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            _tracing = (ITracingService) serviceProvider.GetService(typeof (ITracingService));
            var context = (IPluginExecutionContext) serviceProvider.GetService(typeof (IPluginExecutionContext));
            var factory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof (IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);

            if (!IsValidContext(context))
            {
                return;
            }

            var target = ((Entity) context.InputParameters["Target"]);

            //using (var crmContext = new CrmContext(service))
            //{
            //    // Your code here
            //}
        }
Ejemplo n.º 5
0
            internal LocalPluginContext(IServiceProvider serviceProvider)
            {
                if (serviceProvider == null)
                {
                    throw new ArgumentNullException("serviceProvider");
                }

                // Obtain the execution context service from the service provider.
                this.PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                // Obtain the tracing service from the service provider.
                this.TracingService = (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.
                this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);
            }
Ejemplo n.º 6
0
        private static void HandleException(Exception e, ITracingService tracingService)
        {
            tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e));
            tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "StackTrace: {0}", e.StackTrace));

            var organizationServiceFault = new OrganizationServiceFault { Message = e.Message };
            organizationServiceFault.ErrorDetails.Add("Original Exception", e);

            throw new FaultException<OrganizationServiceFault>(organizationServiceFault, e.Message);
        }
 public LogToCrmTracingService(ITracingService tracingService)
 {
     if (tracingService == null) throw new ArgumentNullException("tracingService");
     _tracingService = tracingService;
 }
Ejemplo n.º 8
0
 public msdyncrmWorkflowTools_Class(IOrganizationService _service)
 {
     service = _service;
     tracing = null;
 }
Ejemplo n.º 9
0
 public override IDataService GetDataService(IOrganizationService service, ITracingService tracing, Entity dataSource)
 {
     return(new DataService(service, tracing, dataSource));
 }
        private void UpdatePrimaryMembership(Entity target, IOrganizationService service, ITracingService tracer)
        {
            EntityReference msnfp_customer = target.GetAttributeValue <EntityReference>("msnfp_customer");

            if (msnfp_customer == null || target.GetAttributeValue <bool?>("msnfp_primary") != true)
            {
                return;
            }
            using OrganizationServiceContext organizationServiceContext = new OrganizationServiceContext(service);
            Entity entity = new Entity
            {
                LogicalName = msnfp_customer.LogicalName,
                Id          = msnfp_customer.Id
            };

            entity["msnfp_primarymembershipid"] = target.ToEntityReference();
            service.Update(entity);
            IQueryable <Guid> queryable = from m in organizationServiceContext.CreateQuery("msnfp_membership")
                                          where (byte)m["msnfp_primary"] != 0 == true && (Guid)m["msnfp_membershipid"] != target.Id && (EntityReference)m["msnfp_customer"] != null && (EntityReference)m["msnfp_customer"] == msnfp_customer
                                          select m.Id;

            foreach (Guid item in queryable)
            {
                Entity entity2 = new Entity("msnfp_membership", item);
                entity2["msnfp_primary"] = false;
                service.Update(entity2);
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "gcbase_riskfactorvalue")
                {
                    return;
                }

                FaultException ex1 = new FaultException();
                //  throw new InvalidPluginExecutionException("test", ex1);

                try
                {
                    //// Obtain the organization service reference.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    if (entity.Attributes.Contains("gcbase_risklevel"))
                    {
                        var riskfactorValue = service.Retrieve("gcbase_riskfactorvalue", entity.Id, new ColumnSet("gcbase_fundingcaseriskassessment", "statuscode"));

                        // int indexOfStatus = optHelper.getIndexOfLabel("gcbase_riskfactorvalue", "statuscode", "Completed", service);
                        //  throw new InvalidPluginExecutionException(optHelper.getLabelFromField(entity, "statuscode", service), ex1);

                        if (!new RiskTemplate(null, service).generateTotalWeightedRiskScoreForRiskAssessment(riskfactorValue))
                        {
                            throw new InvalidPluginExecutionException("something went wrong contact sys admin re. postriskfactorvalue plugin", ex1);
                        }

                        // var riskTemplateRef = postEntity.GetAttributeValue<EntityReference>("gcbase_risktemplate");
                        //first check if there are any completed risk asssessments using this template, if yes the user will not have the ability
                        //change the weights etc, they will need to create a new template - only thing they should be allowed to edit is the rick factor titles maybe
                        //if (!new Common_Modules.RiskTemplateHelper(riskTemplateRef, service).templateHasExistingCompletedAssessments())
                        //{
                        //    // throw new InvalidPluginExecutionException("asfsdafasd", ex1);
                        //    if (!new Common_Modules.RiskTemplateHelper(riskTemplateRef, service).generateTotalWeightedRiskScore())
                        //    {
                        //        throw new InvalidPluginExecutionException("something went wrong contact system admin-postrisktemplateriskfactorupdate plugin", ex1);
                        //    };
                        //}
                        //else
                        //{
                        //    throw new InvalidPluginExecutionException("You cannot modify the weight of a risk element that already has been used in a completed assessment", ex1);
                        //}
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the FollowupPlugin plug-in.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
Ejemplo n.º 12
0
 public InsuredRisk(IOrganizationService svc, ITracingService tracingSvc, Entity entity)
     : base(svc, tracingSvc, entity)
 {
 }
Ejemplo n.º 13
0
 public RecountPaidAmountCommand(IOrganizationService service, ITracingService traceService)
 {
     this.service      = service ?? throw new ArgumentNullException(nameof(service));
     this.traceService = traceService;
 }
Ejemplo n.º 14
0
 public VehicleInTransitTransferHandler(IOrganizationService service, ITracingService trace, VehicleInTransitTransferReceivingHandler receivingHandler)
 {
     _organizationService = service;
     _tracingService      = trace;
     _receivingHandler    = receivingHandler;
 }
Ejemplo n.º 15
0
 public VehicleInTransitTransferHandler(IOrganizationService service, ITracingService trace)
 {
     _organizationService = service;
     _tracingService      = trace;
 }
Ejemplo n.º 16
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            tracingService.Trace("{0}{1}", "Start Custom Workflow Activity: SetOperatingCapacity", DateTime.Now.ToLongTimeString());

            //Update to run on school district
            var recordId = context.PrimaryEntityId;

            try
            {
                //Get Global Capacity values
                var capacity = new Services.CapacityFactors(service);

                Services.OperatingCapacity capacityService = new Services.OperatingCapacity(service, tracingService, capacity);

                tracingService.Trace("Section: {0}", "Update Facilities");
                #region Update Facilities
                //get Facilities
                var fetchXML = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\" >" +
                               "<entity name=\"caps_facility\">" +
                               "<attribute name=\"caps_facilityid\" /> " +
                               "<attribute name=\"caps_name\" /> " +
                               "<attribute name=\"caps_lowestgrade\" /> " +
                               "<attribute name=\"caps_highestgrade\" /> " +
                               "<attribute name=\"caps_adjusteddesigncapacitysecondary\" /> " +
                               "<attribute name=\"caps_adjusteddesigncapacitykindergarten\" /> " +
                               "<attribute name=\"caps_adjusteddesigncapacityelementary\" /> " +
                               "<order attribute=\"caps_name\" descending=\"false\" /> " +
                               "<filter type=\"and\" > " +
                               "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /> " +
                               "<condition attribute=\"caps_lowestgrade\" operator=\"not-null\" />" +
                               "<condition attribute=\"caps_highestgrade\" operator=\"not-null\" />" +
                               "<condition attribute=\"caps_schooldistrict\" operator=\"eq\" value=\"{" + recordId + "}\" />" +
                               "</filter> " +
                               "<link-entity name=\"caps_facilitytype\" from=\"caps_facilitytypeid\" to=\"caps_currentfacilitytype\" link-type=\"inner\" alias=\"ac\" > " +
                               "<filter type=\"and\" > " +
                               "<condition attribute=\"caps_schooltype\" operator=\"not-null\" /> " +
                               "</filter> " +
                               "</link-entity> " +
                               "</entity> " +
                               "</fetch>";


                EntityCollection results = service.RetrieveMultiple(new FetchExpression(fetchXML));

                foreach (caps_Facility facilityRecord in results.Entities)
                {
                    tracingService.Trace("Facility:{0}", facilityRecord.caps_Name);

                    var kDesign      = facilityRecord.caps_AdjustedDesignCapacityKindergarten.GetValueOrDefault(0);
                    var eDesign      = facilityRecord.caps_AdjustedDesignCapacityElementary.GetValueOrDefault(0);
                    var sDesign      = facilityRecord.caps_AdjustedDesignCapacitySecondary.GetValueOrDefault(0);
                    var lowestGrade  = facilityRecord.caps_LowestGrade.Value;
                    var highestGrade = facilityRecord.caps_HighestGrade.Value;

                    var result = capacityService.Calculate(kDesign, eDesign, sDesign, lowestGrade, highestGrade);

                    //Update Facility
                    var recordToUpdate = new caps_Facility();
                    recordToUpdate.Id = facilityRecord.Id;
                    recordToUpdate.caps_OperatingCapacityKindergarten = result.KindergartenCapacity;
                    recordToUpdate.caps_OperatingCapacityElementary   = result.ElementaryCapacity;
                    recordToUpdate.caps_OperatingCapacitySecondary    = result.SecondaryCapacity;
                    service.Update(recordToUpdate);
                }
                #endregion

                tracingService.Trace("Section: {0}", "Update Capacity Reporting");
                #region Update Capacity Reporting
                //Update Capacity Reporting
                var capacityFetchXML = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\" >" +
                                       "<entity name=\"caps_capacityreporting\" > " +
                                       "<attribute name=\"caps_capacityreportingid\" /> " +
                                       "<attribute name=\"caps_secondary_designcapacity\" /> " +
                                       "<attribute name=\"caps_kindergarten_designcapacity\" /> " +
                                       "<attribute name=\"caps_elementary_designcapacity\" /> " +
                                       "<order attribute=\"caps_secondary_designutilization\" descending=\"false\" /> " +
                                       "<link-entity name=\"caps_facility\" from=\"caps_facilityid\" to=\"caps_facility\" visible=\"false\" link-type=\"inner\" alias=\"facility\" > " +
                                       "<attribute name=\"caps_lowestgrade\" /> " +
                                       "<attribute name=\"caps_highestgrade\" /> " +
                                       "<filter type=\"and\" > " +
                                       "<condition attribute=\"caps_schooldistrict\" operator=\"eq\" value=\"{" + recordId + "}\" />" +
                                       "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /> " +
                                       "<condition attribute=\"caps_lowestgrade\" operator=\"not-null\" />" +
                                       "<condition attribute=\"caps_highestgrade\" operator=\"not-null\" />" +
                                       "</filter> " +
                                       "</link-entity> " +
                                       "<link-entity name=\"edu_year\" from=\"edu_yearid\" to=\"caps_schoolyear\" link-type=\"inner\" alias=\"ab\" >" +
                                       "<filter type=\"and\"> " +
                                       "<condition attribute=\"statuscode\" operator=\"in\">" +
                                       "<value>1</value> " +
                                       "<value>757500000</value> " +
                                       "</condition>" +
                                       "</filter>" +
                                       "</link-entity>" +
                                       "</entity> " +
                                       "</fetch> ";

                tracingService.Trace("Capacity Reporting Fetch: {0}", capacityFetchXML);

                EntityCollection capacityResults = service.RetrieveMultiple(new FetchExpression(capacityFetchXML));

                foreach (caps_CapacityReporting capacityRecord in capacityResults.Entities)
                {
                    var kDesign = capacityRecord.caps_Kindergarten_designcapacity.GetValueOrDefault(0);
                    var eDesign = capacityRecord.caps_Elementary_designcapacity.GetValueOrDefault(0);
                    var sDesign = capacityRecord.caps_Secondary_designcapacity.GetValueOrDefault(0);

                    tracingService.Trace("Capacity Reporting: {0}", capacityRecord.Id);
                    tracingService.Trace("Lowest: {0}", ((AliasedValue)capacityRecord["facility.caps_lowestgrade"]).Value);
                    tracingService.Trace("Highest: {0}", ((AliasedValue)capacityRecord["facility.caps_highestgrade"]).Value);

                    var lowestGrade  = ((OptionSetValue)((AliasedValue)capacityRecord["facility.caps_lowestgrade"]).Value).Value;
                    var highestGrade = ((OptionSetValue)((AliasedValue)capacityRecord["facility.caps_highestgrade"]).Value).Value;

                    tracingService.Trace("Start Calculate: {0}", capacityRecord.Id);
                    var result = capacityService.Calculate(kDesign, eDesign, sDesign, lowestGrade, highestGrade);
                    tracingService.Trace("End Calculate: {0}", capacityRecord.Id);

                    //Update Capacity Reporting
                    var recordToUpdate = new caps_CapacityReporting();
                    recordToUpdate.Id = capacityRecord.Id;
                    recordToUpdate.caps_Kindergarten_operatingcapacity = result.KindergartenCapacity;
                    recordToUpdate.caps_Elementary_operatingcapacity   = result.ElementaryCapacity;
                    recordToUpdate.caps_Secondary_operatingcapacity    = result.SecondaryCapacity;
                    service.Update(recordToUpdate);
                }
                #endregion

                tracingService.Trace("Section: {0}", "Update Draft Project Requests");
                #region Update Draft Project Requests
                //Update Draft Project Requests
                var projectRequestFetchXML = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\">" +
                                             "<entity name=\"caps_project\" > " +
                                             "<attribute name=\"caps_facility\" /> " +
                                             "<attribute name=\"caps_changeindesigncapacitykindergarten\" /> " +
                                             "<attribute name=\"caps_changeindesigncapacityelementary\" /> " +
                                             "<attribute name=\"caps_changeindesigncapacitysecondary\" /> " +
                                             "<attribute name=\"caps_futurelowestgrade\" /> " +
                                             "<attribute name=\"caps_futurehighestgrade\" /> " +
                                             "<order attribute=\"caps_projectcode\" descending=\"false\" /> " +
                                             "<filter type=\"and\" > " +
                                             "<condition attribute=\"statuscode\" operator=\"eq\" value=\"1\" /> " +
                                             "<condition attribute=\"caps_schooldistrict\" operator=\"eq\" value=\"{" + recordId + "}\" />" +
                                             "<filter type=\"or\" > " +
                                             "<condition attribute=\"caps_changeinoperatingcapacitykindergarten\" operator=\"not-null\" /> " +
                                             "<condition attribute=\"caps_changeinoperatingcapacityelementary\" operator=\"not-null\" /> " +
                                             "<condition attribute=\"caps_changeinoperatingcapacitysecondary\" operator=\"not-null\" /> " +
                                             "</filter> " +
                                             "</filter> " +
                                             "</entity> " +
                                             "</fetch> ";

                EntityCollection projectResults = service.RetrieveMultiple(new FetchExpression(projectRequestFetchXML));

                foreach (caps_Project projectRecord in projectResults.Entities)
                {
                    if (projectRecord.caps_FutureLowestGrade != null && projectRecord.caps_FutureHighestGrade != null)
                    {
                        var startingDesign_K = 0;
                        var startingDesign_E = 0;
                        var startingDesign_S = 0;

                        //if facility exists, then retrieve it
                        if (projectRecord.caps_Facility != null && projectRecord.caps_Facility.Id != Guid.Empty)
                        {
                            var facility = service.Retrieve(caps_Facility.EntityLogicalName, projectRecord.caps_Facility.Id, new ColumnSet("caps_adjusteddesigncapacitykindergarten", "caps_adjusteddesigncapacityelementary", "caps_adjusteddesigncapacitysecondary")) as caps_Facility;

                            if (facility != null)
                            {
                                startingDesign_K = facility.caps_AdjustedDesignCapacityKindergarten.GetValueOrDefault(0);
                                startingDesign_E = facility.caps_AdjustedDesignCapacityElementary.GetValueOrDefault(0);
                                startingDesign_S = facility.caps_AdjustedDesignCapacitySecondary.GetValueOrDefault(0);
                            }
                        }

                        var changeInDesign_K = startingDesign_K + projectRecord.caps_ChangeinDesignCapacityKindergarten.GetValueOrDefault(0);
                        var changeInDesign_E = startingDesign_E + projectRecord.caps_ChangeinDesignCapacityElementary.GetValueOrDefault(0);
                        var changeInDesign_S = startingDesign_S + projectRecord.caps_ChangeinDesignCapacitySecondary.GetValueOrDefault(0);

                        var result = capacityService.Calculate(changeInDesign_K, changeInDesign_E, changeInDesign_S, projectRecord.caps_FutureLowestGrade.Value, projectRecord.caps_FutureHighestGrade.Value);

                        var recordToUpdate = new caps_Project();
                        recordToUpdate.Id = projectRecord.Id;
                        recordToUpdate.caps_ChangeinOperatingCapacityKindergarten = Convert.ToInt32(result.KindergartenCapacity);
                        recordToUpdate.caps_ChangeinOperatingCapacityElementary   = Convert.ToInt32(result.ElementaryCapacity);
                        recordToUpdate.caps_ChangeinOperatingCapacitySecondary    = Convert.ToInt32(result.SecondaryCapacity);
                        service.Update(recordToUpdate);
                    }
                    else
                    {
                        //blank out operating capacity
                        var recordToUpdate = new caps_Project();
                        recordToUpdate.Id = projectRecord.Id;
                        recordToUpdate.caps_ChangeinOperatingCapacityKindergarten = null;
                        recordToUpdate.caps_ChangeinOperatingCapacityElementary   = null;
                        recordToUpdate.caps_ChangeinOperatingCapacitySecondary    = null;
                        service.Update(recordToUpdate);
                    }
                }
                #endregion


                this.error.Set(executionContext, false);
            }
            catch (Exception ex)
            {
                tracingService.Trace("Error Details: {0}", ex.Message);
                //might want to also include error message
                this.error.Set(executionContext, true);
                this.errorMessage.Set(executionContext, ex.Message);
            }

            tracingService.Trace("{0}{1}", "End Custom Workflow Activity: SetOperatingCapacity", DateTime.Now.ToLongTimeString());
        }
Ejemplo n.º 17
0
 public ReinsuranceSection(IOrganizationService svc, ITracingService tracingSvc, Entity entity)
     : base(svc, tracingSvc, entity)
 {
 }
Ejemplo n.º 18
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //  throw new InvalidPluginExecutionException("proceedInReservation " + proceedInReservation);
            //throw new InvalidPluginExecutionException("ghada ^_^");

            #region definitionAttributes
            string          entityName  = "new_contracting";
            EntityReference destination = null;
            #endregion

            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (context.Depth > 1)
                {
                    return;
                }


                // The InputParameters collection contains all the data passed in the message request.
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters.
                    Entity entity = (Entity)context.InputParameters["Target"];

                    // Verify that the target entity represents an sale.
                    // If not, this plug-in was not registered correctly.
                    if (entity.LogicalName != entityName)
                    {
                        return;
                    }

                    var proceedInReservation = new OptionSetValue();
                    if (entity.Attributes.Contains("ohd_proceedinreservationos"))
                    {
                        proceedInReservation = entity.GetAttributeValue <OptionSetValue>("ohd_proceedinreservationos");
                    }

                    //Update
                    if (context.MessageName.ToLower() == "update")
                    {
                        #region Retrieve All Blob Storage
                        // Instantiate QueryExpression QEohd_blobstorage
                        var QEohd_blobstorage = new QueryExpression("ohd_blobstorage");

                        // Add columns to QEohd_blobstorage.ColumnSet
                        QEohd_blobstorage.ColumnSet.AddColumns("createdon", "ohd_uri", "ohd_url", "ohd_blobstorageid");
                        QEohd_blobstorage.AddOrder("ohd_uri", OrderType.Ascending);

                        // Define filter QEohd_blobstorage.Criteria
                        QEohd_blobstorage.Criteria.AddCondition("ohd_blobazurestorageid", ConditionOperator.Equal, context.PrimaryEntityId);

                        // Add link-entity QEohd_blobstorage_new_contracting
                        var QEohd_blobstorage_new_contracting = QEohd_blobstorage.AddLink("new_contracting", "ohd_blobazurestorageid", "new_contractingid");
                        QEohd_blobstorage_new_contracting.EntityAlias = "al";

                        // Add link-entity QEohd_blobstorage_new_contracting_ohd_destination
                        var QEohd_blobstorage_new_contracting_ohd_destination = QEohd_blobstorage_new_contracting.AddLink("ohd_destination", "ohd_destination", "ohd_destinationid");
                        QEohd_blobstorage_new_contracting_ohd_destination.EntityAlias = "am";

                        // Define filter QEohd_blobstorage_new_contracting_ohd_destination.LinkCriteria
                        QEohd_blobstorage_new_contracting_ohd_destination.LinkCriteria.AddCondition("ohd_name", ConditionOperator.Equal, "Owest");

                        var blobStorageResult = service.RetrieveMultiple(QEohd_blobstorage);
                        #endregion

                        #region Retrieve Sale Recod to Get Destination

                        //retrieve contact record
                        ColumnSet fields = new ColumnSet()
                        {
                            AllColumns = false
                        };
                        fields.AddColumns("ohd_destination");
                        Entity saleEntity = service.Retrieve(entityName, context.PrimaryEntityId, fields);
                        #endregion

                        if (saleEntity != null)
                        {
                            destination = saleEntity.Contains("ohd_destination") ? (EntityReference)saleEntity.Attributes["ohd_destination"] : new EntityReference();

                            if ((blobStorageResult == null || blobStorageResult.Entities.Count < 1) &&
                                (int)(proceedInReservation.Value) == 1 &&
                                (destination != null && destination.Name.ToLower() == "Owest".ToLower()))
                            {
                                //throw new InvalidPluginExecutionException("Sorry!! You must choose at least one attachment related to the sale");
                                throw new InvalidPluginExecutionException("Please attach required file(s) to proceed in reservation");
                            }
                            else
                            {
                                return;
                            }
                        }
                    }

                    //Create
                    else if (context.MessageName.ToLower() == "create")
                    {
                        // throw new InvalidPluginExecutionException("ghada 1");

                        destination = entity.Attributes.Contains("ohd_destination") ? (Microsoft.Xrm.Sdk.EntityReference)entity.Attributes["ohd_destination"] : new EntityReference();

                        #region Retrieve Sale Recod to Get Destination

                        //retrieve contact record
                        ColumnSet fields = new ColumnSet()
                        {
                            AllColumns = false
                        };
                        fields.AddColumns("ohd_name");
                        Entity saleEntity = service.Retrieve("ohd_destination", destination.Id, fields);
                        #endregion

                        if (saleEntity != null)
                        {
                            if ((int)(proceedInReservation.Value) == 1 && (destination != null && saleEntity["ohd_name"].ToString().ToLower() == "Owest".ToLower()))
                            {
                                entity.Attributes["ohd_proceedinreservationos"] = new OptionSetValue(0);
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            tracingService.Trace("{0}{1}", "Start Custom Workflow Activity: SetOperatingCapacity", DateTime.Now.ToLongTimeString());

            var recordId = context.PrimaryEntityId;

            try
            {
                //Get Global Capacity values
                var capacity = new Services.CapacityFactors(service);

                Services.OperatingCapacity capacityService = new Services.OperatingCapacity(service, tracingService, capacity);

                #region Update Capacity Reporting
                //Update Capacity Reporting
                var capacityFetchXML = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\" >" +
                                       "<entity name=\"caps_capacityreporting\" > " +
                                       "<attribute name=\"caps_capacityreportingid\" /> " +
                                       "<attribute name=\"caps_secondary_designcapacity\" /> " +
                                       "<attribute name=\"caps_kindergarten_designcapacity\" /> " +
                                       "<attribute name=\"caps_elementary_designcapacity\" /> " +
                                       "<order attribute=\"caps_secondary_designutilization\" descending=\"false\" /> " +
                                       "<link-entity name=\"caps_facility\" from=\"caps_facilityid\" to=\"caps_facility\" visible=\"false\" link-type=\"inner\" alias=\"facility\" > " +
                                       "<attribute name=\"caps_lowestgrade\" /> " +
                                       "<attribute name=\"caps_highestgrade\" /> " +
                                       "</link-entity> " +
                                       "<link-entity name=\"edu_year\" from=\"edu_yearid\" to=\"caps_schoolyear\" link-type=\"inner\" alias=\"ab\" >" +
                                       "<filter type=\"and\"> " +
                                       "<condition attribute=\"statuscode\" operator=\"in\">" +
                                       "<value>1</value> " +
                                       "<value>757500000</value> " +
                                       "</condition>" +
                                       "</filter>" +
                                       "</link-entity>" +
                                       "</entity> " +
                                       "</fetch> ";

                EntityCollection capacityResults = service.RetrieveMultiple(new FetchExpression(capacityFetchXML));

                foreach (caps_CapacityReporting capacityRecord in capacityResults.Entities)
                {
                    var kDesign      = capacityRecord.caps_Kindergarten_designcapacity.GetValueOrDefault(0);
                    var eDesign      = capacityRecord.caps_Elementary_designcapacity.GetValueOrDefault(0);
                    var sDesign      = capacityRecord.caps_Secondary_designcapacity.GetValueOrDefault(0);
                    var lowestGrade  = ((OptionSetValue)((AliasedValue)capacityRecord["facility.caps_lowestgrade"]).Value).Value;
                    var highestGrade = ((OptionSetValue)((AliasedValue)capacityRecord["facility.caps_highestgrade"]).Value).Value;

                    var result = capacityService.Calculate(kDesign, eDesign, sDesign, lowestGrade, highestGrade);

                    //Update Capacity Reporting
                    var recordToUpdate = new caps_CapacityReporting();
                    recordToUpdate.Id = capacityRecord.Id;
                    recordToUpdate.caps_Kindergarten_operatingcapacity = result.KindergartenCapacity;
                    recordToUpdate.caps_Elementary_operatingcapacity   = result.ElementaryCapacity;
                    recordToUpdate.caps_Secondary_operatingcapacity    = result.SecondaryCapacity;
                    service.Update(recordToUpdate);
                }
                #endregion

                this.error.Set(executionContext, false);
            }
            catch (Exception ex)
            {
                tracingService.Trace("Error Details: {0}", ex.Message);
                //might want to also include error message
                this.error.Set(executionContext, true);
                this.errorMessage.Set(executionContext, ex.Message);
            }

            tracingService.Trace("{0}{1}", "End Custom Workflow Activity: SetOperatingCapacity", DateTime.Now.ToLongTimeString());
        }
Ejemplo n.º 20
0
        public ConverterService(ITracingService tracingService)
        {
            _tracingService = tracingService;

            _token = new List <string>
            {
                "Avenue",
                "St.",
                "Square",
                "Highway",
                "avenue",
                "st.",
                "square",
                "highway",
            };
            _ending = new Dictionary <string, string>
            {
                { @"ий", @"iy" },
                { @"ый", @"y" },
                { @"aя", @"aya" },

                { @"яя", @"yaya" },
                { @"ое", @"oye" },
                { @"ее", @"eye" },

                { @"чий", @"chiy" },
                { @"ский", @"skiy" },

                { @"ша", @"sha" },
                { @"цкий", @"tskiy" },
                { @"ный", @"ny" },
                { @"ща", @"scha" },
                { @"мый", @"my" },
                { @"щий", @"schiy" },
            };

            _charmapping = new Dictionary <char, string>
            {
                { 'а', @"a" },
                { 'А', @"A" },
                { 'б', @"b" },
                { 'Б', @"B" },
                { 'в', @"v" },
                { 'В', @"V" },
                { 'г', @"g" },
                { 'Г', @"G" },
                { 'д', @"d" },
                { 'Д', @"D" },
                { 'е', @"e" },
                { 'Е', @"E" },
                { 'ё', @"yo" },
                { 'Ё', @"Yo" },
                { 'ж', @"zh" },
                { 'Ж', @"Zh" },
                { 'з', @"z" },
                { 'З', @"Z" },
                { 'и', @"i" },
                { 'И', @"I" },
                { 'й', @"y" },
                { 'Й', @"Y" },
                //{'i', @"i"},
                { 'I', @"I" },
                { 'к', @"k" },
                { 'К', @"K" },
                { 'л', @"l" },
                { 'Л', @"L" },
                { 'м', @"m" },
                { 'М', @"M" },
                { 'н', @"n" },
                { 'Н', @"N" },
                { 'о', @"o" },
                { 'О', @"O" },
                { 'п', @"p" },
                { 'П', @"P" },
                { 'р', @"r" },
                { 'Р', @"R" },
                { 'с', @"s" },
                { 'С', @"S" },
                { 'т', @"t" },
                { 'Т', @"T" },
                { 'у', @"u" },
                { 'У', @"U" },
                { 'ф', @"f" },
                { 'Ф', @"F" },
                { 'х', @"kh" },
                { 'Х', @"Kh" },
                { 'ц', @"ts" },
                { 'Ц', @"Ts" },
                { 'ч', @"ch" },
                { 'Ч', @"Ch" },
                { 'ш', @"sh" },
                { 'Ш', @"Sh" },
                { 'щ', @"shh" },
                { 'Щ', @"Shh" },
                { 'ъ', string.Empty },
                { 'Ъ', string.Empty },
                { 'ы', @"y" },
                { 'Ы', @"Y" },
                { 'ь', string.Empty },
                { 'Ь', string.Empty },
                { 'э', @"e" },
                { 'Э', @"E" },
                { 'ю', @"yu" },
                { 'Ю', @"Yu" },
                { 'я', @"ya" },
                { 'Я', @"Ya" }
            };

            _patternmapping = new Dictionary <string, string>
            {
                { "Федеральный округ", "Federal District" },
                { "Субъект федерации", "Federal Subject" },
                { "Республика", "Republic" },
                { "Край", "Territory" },
                { "Область", "Region" },
                { "Город федерального значения", "Federal City" },
                { "Автономная область", "Autonomous Region" },
                { "Автономный округ", "Autonomous District" },
                { "Район", "District" },
                { "Административный округ", "Administrative District" },

                { "Автономная", "Autonomous" },
                { "Автономный", "Autonomous" },
                { "область", "Region" },
                { "округ", "District" },
                { "Административный", "Administrative" },


                { "Улица", "Street" },
                { "Переулок", "Lane" },
                { "Проспект", "Avenue" },
                { "Шоссе", "Highway" },
                { "Бульвар", "Boulevard" },
                { "Проезд", "Passage" },
                { "Площадь", "Square" },
                { "Набережная", "Embankment" },
                { "Тупик", "Blind Alley" },
                { "Аллея", "Alley" },
                { "Просек", "Path" },
                { "Квартал", "Block" },
                { "Линия", "Line" },
                { "Дорога", "Road" },
                { "Магистраль", "Main Road" },
                { "Проулок", "Lane" },
                { "Тракт", "High Road" },
                { "Въезд", "Drive" },
                { "Заезд", "Drive" },
                { "Спуск", "Slope" },
                { "Съезд", "Descent" },
                { "Разъезд", "Furcation" },
                { "Луч", "Ray" },
                { "Кольцо", "Ring" },
                { "Взвоз", "Drive" },

                { "улица", "Street" },
                { "переулок", "Lane" },
                { "проспект", "Avenue" },
                { "шоссе", "Highway" },
                { "бульвар", "Boulevard" },
                { "проезд", "Passage" },
                { "площадь", "Square" },
                { "набережная", "Embankment" },
                { "тупик", "Blind Alley" },
                { "аллея", "Alley" },
                { "просек", "Path" },
                { "квартал", "Block" },
                { "линия", "Line" },
                { "дорога", "Road" },
                { "магистраль", "Main Road" },
                { "проулок", "Lane" },
                { "тракт", "High Road" },
                { "въезд", "Drive" },
                { "заезд", "Drive" },
                { "спуск", "Slope" },
                { "съезд", "Descent" },
                { "разъезд", "Furcation" },
                { "луч", "Ray" },
                { "кольцо", "Ring" },
                { "взвоз", "Drive" },

                { "ул.", "St." },
                { "пер.", "Ln." },
                { "просп.", "Ave." },
                { "ш.", "Hwy." },
                { "бул.", "Blvd." },
                { "пр.", "Psge." },
                { "пл.", "Sq." },
                { "наб.", "Emb." },
                { "туп.", "Bl. Aly." },
                { "ал.", "Aly." },
                { "дор.", "Rd." },


                { "фаза", "Phase" },
                { "Фаза.", "Phase" },

                { "станция метро", "metro station" },
                { "вокзал", "Railway Station" },
                { "«…»", "‘...’" },


                { "Бульварное кольцо", "The Boulevard Ring" },
                { "Садовое кольцо", "The Garden Ring" },

                { "Третье транспортное кольцо", "The Third Transport Ring" },
                { "Московская кольцевая автомобильная дорога", "Automobile Ring Road" },
                { "МКАД", "MKAD" },
                { "ТТК", "The TTR" },

                { "Первый", "First" },
                { "Второй", "Second" },
                { "Третий", "Third" },
                { "Четвёртый", "Fourth" },
                { "Пятый", "Fifth" },
                { "Шестой", "Sixth" },
                { "Седьмой", "Seventh" },
                { "Восьмой", "Eighth" },
                { "Девятый", "Ninth" },
                { "Десятый", "Tenth" },
                { "Одиннадцатый", "Eleventh" },
                { "Двенадцатый", "Twelfth" },
                { "Тринадцатый", "Thirteenth" },
                { "Четырнадцатый", "Fourteenth" },
                { "Пятнадцатый", "Fifteenth" },
                { "Шестнадцатый", "Sixteenth" },
                { "Семнадцатый", "Seventeenth" },
                { "Восемнадцатый", "Eighteenth" },
                { "Девятнадцатый", "Nineteenth" },
                { "Двадцатый", "Twentieth" },

                { "Первая", "First" },
                { "Вторая", "Second" },
                { "Третья", "Third" },
                { "Четвёртая", "Fourth" },
                { "Пятая", "Fifth" },
                { "Шестая", "Sixth" },
                { "Седьмая", "Seventh" },
                { "Восьмая", "Eighth" },
                { "Девятая", "Ninth" },
                { "Десятая", "Tenth" },
                { "Одиннадцатая", "Eleventh" },
                { "Двенадцатая", "Twelfth" },
                { "Тринадцатая", "Thirteenth" },
                { "Четырнадцатая", "Fourteenth" },
                { "Пятнадцатая", "Fifteenth" },
                { "Шестнадцатая", "Sixteenth" },
                { "Семнадцатая", "Seventeenth" },
                { "Восемнадцатая", "Eighteenth" },
                { "Девятнадцатая", "Nineteenth" },
                { "Двадцатая", "Twentieth" },


                { "1-й", "1st" },
                { "2-й", "2nd" },
                { "3-й", "3rd" },
                { "4-й", "4th" },
                { "5-й", "5th" },
                { "6-й", "6th" },
                { "7-й", "7th" },
                { "8-й", "8th" },
                { "9-й", "9th" },
                { "10-й", "10th" },
                { "11-й", "11th" },
                { "12-й", "12th" },
                { "13-й", "13th" },
                { "14-й", "14th" },
                { "15-й", "15th" },
                { "16-й", "16th" },
                { "17-й", "17th" },
                { "18-й", "18th" },
                { "19-й", "19th" },
                { "20-й", "20h" },


                { "1-я", "1st" },
                { "2-я", "2nd" },
                { "3-я", "3rd" },
                { "4-я", "4th" },
                { "5-я", "5th" },
                { "6-я", "6th" },
                { "7-я", "7th" },
                { "8-я", "8th" },
                { "9-я", "9th" },
                { "10-я", "10th" },
                { "11-я", "11th" },
                { "12-я", "12th" },
                { "13-я", "13th" },
                { "14-я", "14th" },
                { "15-я", "15th" },
                { "16-я", "16th" },
                { "17-я", "17th" },
                { "18-я", "18th" },
                { "19-я", "19th" },
                { "20-я", "20h" },

                { "стр.", "bldg." },
                { "Строение", "Building" },
                { "Литера", "Letter" },
                { "Владение", "Estate" },
                { "Корпус", "Building" },
                { "корпус", "Building" },
                { "корп.", "bldg." },
                { "лит.", "letter" },
                { "вл.", "estate" },
                { "класс", "class" },
                { "Класс", "Class" },
                { "участок", "land plot" },
                { "Участок", "Land plot" },
                //{ "от", "from" },
                //{ "От", "From" },
            };

            _numericmapping = new Dictionary <string, string>
            {
                { "1 кв.", "Q1" },
                { "2 кв.", "Q2" },
                { "3 кв.", "Q3" },
                { "4 кв.", "Q4" },
                { "1 пол.", "H1" },
                { "2 пол.", "H2" },
                { "м²", "m²" },
                { "кв. м", "m²" },
                { "млн", "million" },
                { "млрд", "billion" },
                { "долл.", "US" },
                { "руб.", "RUB" },
                { "евро", "EURO" },
            };
        }
        public void Setup()
        {
            tracingService = A.Fake <ITracingService>();

            A.CallTo(() => tracingService.Trace(A <string> ._)).DoesNothing();
        }
Ejemplo n.º 22
0
 public AccountHandler(IOrganizationService service, ITracingService trace)
 {
     _organizationService = service;
     _tracingService      = trace;
 }
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);
            ITracingService             tracer  = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                var query = (QueryExpression)context.InputParameters["Query"];

                var pageNumber     = query.PageInfo.PageNumber;
                var recordsPerPage = query.PageInfo.Count;

                var sort = query.Orders.FirstOrDefault();

                var contactId = Guid.Parse(query.Criteria.Conditions[0].Values.FirstOrDefault()?.ToString());
                var contact   = service.Retrieve("contact", contactId, new ColumnSet(new string[] { "emailaddress1" }));
                var email     = contact.GetAttributeValue <string>("emailaddress1");

                // Get redis settings
                var qe = new QueryExpression("fic_redissettings");
                qe.ColumnSet = new ColumnSet("fic_isenabled", "fic_posturl");
                var redisSettings = service.RetrieveMultiple(qe).Entities.FirstOrDefault();

                if (redisSettings == null)
                {
                    throw new InvalidPluginExecutionException("There is no Redis Settings record found.");
                }

                var redisEnabled = (bool)redisSettings["fic_isenabled"];
                var postUrl      = (string)redisSettings["fic_posturl"];

                // Get pwned account by email
                List <PwnedAccountData> pdata = CallPwnedApi(email);

                WebClient wc = new WebClient();
                wc.Headers.Add("Content-Type", "application/json");

                DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(QueryExpression));
                MemoryStream ms = new MemoryStream();
                dc.WriteObject(ms, query);
                ms.Flush();
                ms.Position = 0;
                StreamReader sr = new StreamReader(ms);
                tracer.Trace($"Query:{sr.ReadToEnd()}");

                List <Entity> list = new List <Entity>();
                if (pdata != null)
                {
                    foreach (var p in pdata)
                    {
                        var record = new Entity("fic_pwnedaccount", Guid.NewGuid());
                        record["fic_name"]           = $"{p.Title}";
                        record["fic_pwnedaccountid"] = p.Id;
                        record["fic_description"]    = p.Description;
                        record["fic_isverified"]     = p.IsVerified;
                        record["fic_breachdate"]     = DateTime.Parse(p.BreachDate);
                        record["fic_domain"]         = p.Domain;
                        record["fic_pwncount"]       = p.PwnCount;

                        list.Add(record);
                    }

                    //Serialze object into JSON
                    DataContractJsonSerializer dc1 = new DataContractJsonSerializer(typeof(List <PwnedAccountData>));
                    MemoryStream ms1 = new MemoryStream();
                    dc1.WriteObject(ms1, pdata);
                    ms1.Flush();
                    ms1.Position = 0;
                    StreamReader sr1  = new StreamReader(ms1);
                    var          json = sr1.ReadToEnd();

                    tracer.Trace($"JSON: {json}");
                    if (redisEnabled)
                    {
                        // Send data to Redis Cache
                        wc.UploadString(postUrl, json);
                    }
                }

                if (sort != null)
                {
                    list = sort.OrderType == 0 ? list.OrderBy(x => x[sort.AttributeName]).ToList() : list.OrderByDescending(x => x[sort.AttributeName]).ToList();
                }

                var hasMoreRecords = list.Count > (pageNumber * recordsPerPage);
                var totalCount     = list.Count;

                list = list.Skip((pageNumber - 1) * recordsPerPage).Take(recordsPerPage).ToList();

                EntityCollection ec = new EntityCollection();
                ec.EntityName  = "fic_pwnedaccount";
                ec.MoreRecords = hasMoreRecords;
                ec.Entities.AddRange(list);
                ec.TotalRecordCount = totalCount;

                context.OutputParameters["BusinessEntityCollection"] = ec;
            }
            catch (Exception ex)
            {
                tracer.Trace($"Error: " + ex.Message + ex.StackTrace);
            }
        }
Ejemplo n.º 24
0
 public InvoiceService(IOrganizationService service, ITracingService tracingService)
 {
     _service        = service ?? throw new ArgumentNullException(nameof(service));
     _tracingService = tracingService ?? throw new ArgumentNullException(nameof(tracingService));
 }
 protected abstract void Execute(
     IOrganizationService organizationService,
     IPluginExecutionContext pluginExecutionContext,
     ITracingService tracingService,
     Guid invoiceId);
Ejemplo n.º 26
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //--> This class will not be executed as per the new DSO lead assignment....
            //Extract the tracing service for use in debugging sandboxed plug-ins....
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            //Obtain execution contest from the service provider....
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            //Call Input parameter collection to get all the data passes....
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity leadEntity = (Entity)context.InputParameters["Target"];

                if (leadEntity.LogicalName != "lead")
                {
                    return;
                }

                //Entity object to update Lead....
                Entity leadUpdate = new Entity()
                {
                    LogicalName = "lead",
                    Id          = leadEntity.Id
                };

                try
                {
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    //Get current user information....
                    WhoAmIResponse response = (WhoAmIResponse)service.Execute(new WhoAmIRequest());

                    //Fetch data from lead entity....
                    bool isGroupPractice = leadEntity.GetAttributeValue <bool>("fdx_grppracactice");
                    int  step            = 0;


                    if (isGroupPractice)
                    {
                        Guid   state     = new Guid();
                        Entity leadState = service.Retrieve("lead", leadEntity.Id, new ColumnSet("fdx_stateprovince"));
                        if (leadState.Attributes.Contains("fdx_stateprovince"))
                        {
                            state = ((EntityReference)leadState.Attributes["fdx_stateprovince"]).Id;
                        }
                        step = 1;
                        #region 1st check --> Get DSO rep based on territory assigned to State....
                        Entity stateEntity = service.Retrieve("fdx_state", state, new ColumnSet("fdx_territory"));

                        if (stateEntity.Attributes.Contains("fdx_territory"))
                        {
                            step = 21;
                            Entity territory = service.Retrieve("territory", ((EntityReference)stateEntity.Attributes["fdx_territory"]).Id, new ColumnSet("managerid"));
                            if (territory.Attributes.Contains("managerid"))
                            {
                                leadUpdate["ownerid"] = new EntityReference("systemuser", ((EntityReference)territory["managerid"]).Id);
                            }

                            service.Update(leadUpdate);
                        }
                        #endregion
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the AssignLead_Update plug-in.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("AssignLead_Update: {0}", ex.ToString());
                    throw;
                }
            }
        }
Ejemplo n.º 27
0
 public SalesOrderMonthlyAmortizationHandler(IOrganizationService service, ITracingService trace)
 {
     _organizationService = service;
     _tracingService      = trace;
 }
Ejemplo n.º 28
0
        public static void CalculateTurnSchStartandEndDate(ITracingService tracer, IOrganizationService service, Entity projectEntity, Entity jobEntity, Mapping mapping, int timeZoneCode)
        {
            if (jobEntity.Attributes.Contains(Constants.Jobs.JobAmount))
            {
                //EntityCollection jobVendorsEntityCollection = RetrieveJobVenodrsByJob(tracer, service, jobEntity.ToEntityReference());
                //if (jobVendorsEntityCollection.Entities.Count > 0)
                //{
                //Entity startDateEntity = jobVendorsEntityCollection.Entities.Where(e => e.Attributes.Contains(Constants.JobVendors.StartDate)).OrderBy(e => e.Attributes[Constants.JobVendors.StartDate]).FirstOrDefault();
                DateTime schJobStartDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, DateTime.Now).ChangeTime(6, 0, 0, 0);
                tracer.Trace($"Project Template is : {mapping.Name}");

                if (mapping.Name.Equals(TURNPROCESS_PROJECT_TEMPLATE))
                {
                    tracer.Trace("Processing Turn Project...");
                    if (projectEntity.Attributes.Contains(Constants.Projects.Unit))
                    {
                        Entity unitEntity = service.Retrieve(Constants.Units.LogicalName, projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.Unit).Id, new ColumnSet(Constants.Units.MoveOutDate));
                        if (unitEntity is Entity && unitEntity.Attributes.Contains(Constants.Units.MoveOutDate))
                        {
                            DateTime moveOutDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, unitEntity.GetAttributeValue <DateTime>(Constants.Units.MoveOutDate));
                            tracer.Trace($"Property Move Out Date  : {moveOutDate}");
                            schJobStartDate = moveOutDate;
                            tracer.Trace($"Sched. Start Date from Property Move Out Date : {schJobStartDate.AddDays(1)}.");
                            DateTime schJobCompletionDate = moveOutDate.AddDays((double)Math.Ceiling(jobEntity.GetAttributeValue <Money>(Constants.Jobs.JobAmount).Value / 700) + 1);
                            tracer.Trace($"Final Sched. Job Completion Date  : {schJobCompletionDate}.");

                            PerformScheduledDateMoveOut(tracer, service, projectEntity, schJobCompletionDate, timeZoneCode, true);
                            //CreateVendorProjectTask(tracer, service, projectEntity, jobVendorsEntityCollection, mapping, schJobCompletionDate, timeZoneCode);

                            Entity tmpPrj = new Entity(projectEntity.LogicalName);
                            tmpPrj.Id = projectEntity.Id;
                            tmpPrj[Constants.Projects.ScheduledJobStartDate]      = schJobStartDate.AddDays(1);
                            tmpPrj[Constants.Projects.ScheduledJobCompletionDate] = schJobCompletionDate;
                            service.Update(tmpPrj);
                        }
                        else
                        {
                            tracer.Trace("Unit Entity does not contain Move Out Date.");
                        }
                    }
                    else
                    {
                        tracer.Trace("Project Entity does not contain Unit");
                    }
                }
                else
                {
                    tracer.Trace("Processing Reno Project...");
                    //DateTime schJobStartDate = DateTime.Now.ChangeTime(6, 0, 0, 0);
                    bool schJobCompFound = false;
                    //First use ESCRO
                    EntityCollection prop_acquired_EntityCollection = CommonMethods.RetrieveAllProjectTaskByProjectAndTaskIdentifier(tracer, service, projectEntity.ToEntityReference(), projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.ProjectTemplate), (int)Events.CLOSE_ESCROW);
                    if (prop_acquired_EntityCollection.Entities.Count > 0)
                    {
                        Entity propAcquiredProjectTaskEntity = prop_acquired_EntityCollection.Entities[0];
                        if (propAcquiredProjectTaskEntity is Entity && propAcquiredProjectTaskEntity.Attributes.Contains(Constants.ProjectTasks.ActualEnd))
                        {
                            schJobStartDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, propAcquiredProjectTaskEntity.GetAttributeValue <DateTime>(Constants.ProjectTasks.ActualEnd)).AddDays(1);
                            tracer.Trace($"Sched. Start Date from Property Acquired Task End Date : {schJobStartDate}.");

                            schJobCompFound = true;
                        }
                    }
                    if (!schJobCompFound)
                    {
                        if (projectEntity.Attributes.Contains(Constants.Projects.Unit))
                        {
                            Entity unitEntity = service.Retrieve(Constants.Units.LogicalName, projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.Unit).Id, new ColumnSet(Constants.Units.ScheduledAcquisitionDate));
                            if (unitEntity is Entity && unitEntity.Attributes.Contains(Constants.Units.ScheduledAcquisitionDate))
                            {
                                schJobStartDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, unitEntity.GetAttributeValue <DateTime>(Constants.Units.ScheduledAcquisitionDate)).AddDays(1);
                                tracer.Trace($"Sched. Start Date from Unit Acquisition Date : {schJobStartDate}.");
                                schJobCompFound = true;
                            }
                        }
                    }
                    if (!schJobCompFound)
                    {
                        EntityCollection jobVendorsEntityCollection = RetrieveJobVenodrsByJob(tracer, service, jobEntity.ToEntityReference());
                        if (jobVendorsEntityCollection.Entities.Count > 0)
                        {
                            Entity endDateEntity = jobVendorsEntityCollection.Entities.Where(e => e.Attributes.Contains(Constants.JobVendors.EndDate)).OrderByDescending(e => e.Attributes[Constants.JobVendors.EndDate]).FirstOrDefault();
                            schJobStartDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, endDateEntity.GetAttributeValue <DateTime>(Constants.JobVendors.EndDate)).AddDays(1);
                            tracer.Trace($"Sched. Start Date from Last Job End Date : {schJobStartDate}.");
                            schJobCompFound = true;
                        }
                    }


                    tracer.Trace($"Sched. Start Date before Job Amount Cal Date : {schJobStartDate}. Job Amount : {jobEntity.GetAttributeValue<Money>(Constants.Jobs.JobAmount).Value}");
                    DateTime schJobCompletionDate = schJobStartDate.AddDays((double)Math.Ceiling(jobEntity.GetAttributeValue <Money>(Constants.Jobs.JobAmount).Value / 700));
                    tracer.Trace($"Final Sched. Job Completion Date  : {schJobCompletionDate}.");


                    Entity tmpPrj = new Entity(projectEntity.LogicalName);
                    tmpPrj.Id = projectEntity.Id;
                    tmpPrj[Constants.Projects.ScheduledJobStartDate]      = schJobStartDate;
                    tmpPrj[Constants.Projects.ScheduledJobCompletionDate] = schJobCompletionDate;
                    service.Update(tmpPrj);

                    PerformScheduledDateMoveOut(tracer, service, projectEntity, schJobCompletionDate, timeZoneCode, false);
                    //CreateVendorProjectTask(tracer, service, projectEntity, jobVendorsEntityCollection, mapping, schJobCompletionDate, timeZoneCode);
                }
                // }
            }
            else
            {
                tracer.Trace("Job Entity does not contain either Job Amount or Unit");
            }
        }
 public CrmTracing(ITracingService tracingSerivce)
 {
     _tracingSerivce = tracingSerivce;
 }
Ejemplo n.º 30
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracer  = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);
            ProjectTemplateSettings     projectTemplateSettings = null;

            if (!string.IsNullOrEmpty(_unsecureConfig))
            {
                StringReader  stringReader = new StringReader(_unsecureConfig);
                XmlSerializer serializer   = new XmlSerializer(typeof(ProjectTemplateSettings));

                projectTemplateSettings = (ProjectTemplateSettings)serializer.Deserialize(stringReader);
            }

            if (projectTemplateSettings == null)
            {
                tracer.Trace($"Project Template Setting not available in Plugin UnSecure Configuration.");
                return;
            }

            Entity jobEntity = null;

            if (!context.InputParameters.Contains(Constants.TARGET))
            {
                return;
            }
            if (((Entity)context.InputParameters[Constants.TARGET]).LogicalName != Constants.Jobs.LogicalName)
            {
                return;
            }


            try
            {
                switch (context.MessageName)
                {
                //case Constants.Messages.Create:
                //    if (context.InputParameters.Contains(Constants.TARGET) && context.InputParameters[Constants.TARGET] is Entity)
                //        jobEntity = context.InputParameters[Constants.TARGET] as Entity;
                //    else
                //        return;
                //    break;
                case Constants.Messages.Update:
                    if (context.InputParameters.Contains(Constants.TARGET) && context.InputParameters[Constants.TARGET] is Entity && context.PostEntityImages.Contains(Constants.POST_IMAGE))
                    {
                        jobEntity = context.PostEntityImages[Constants.POST_IMAGE] as Entity;
                    }
                    else
                    {
                        return;
                    }
                    break;
                }
                //TODO: Do stuff

                if (jobEntity == null || context.Depth > 2)
                {
                    tracer.Trace($"Job entity is Null OR Context Depth is higher than 2. Actual Depth is : {context.Depth}");
                    return;
                }

                if (!jobEntity.Attributes.Contains(Constants.Jobs.JobStatus) || (!jobEntity.Attributes.Contains(Constants.Jobs.Unit) && !jobEntity.Attributes.Contains(Constants.Jobs.RenowalkID)))
                {
                    tracer.Trace($"Job Enity missing either Job Status or Unit or Renowalk ID field. Exiting PlugIn Pipeline");
                    return;
                }

                tracer.Trace($"Job Enity Job Status : {jobEntity.GetAttributeValue<OptionSetValue>(Constants.Jobs.JobStatus).Value}");
                if (jobEntity.GetAttributeValue <OptionSetValue>(Constants.Jobs.JobStatus).Value != 963850004)
                {
                    tracer.Trace($"Job Enity Job Status is NOT Contract Created (963850004). Existing PlugIn Pipeline.");
                    return;
                }

                if (jobEntity is Entity && projectTemplateSettings is ProjectTemplateSettings)
                {
                    tracer.Trace($"Finding Active Project using Unit or Renowalk ID.");
                    EntityCollection projectEntityCollection = new EntityCollection();
                    if (jobEntity.Attributes.Contains(Constants.Jobs.RenowalkID))
                    {
                        projectEntityCollection = CommonMethods.RetrieveActivtProjectByRenowalkId(tracer, service, jobEntity.GetAttributeValue <string>(Constants.Jobs.RenowalkID));
                    }
                    if (projectEntityCollection.Entities.Count == 0 && jobEntity.Attributes.Contains(Constants.Jobs.Unit))
                    {
                        projectEntityCollection = CommonMethods.RetrieveActivtProjectByUnitId(tracer, service, jobEntity.GetAttributeValue <EntityReference>(Constants.Jobs.Unit));
                    }
                    foreach (Entity projectEntity in projectEntityCollection.Entities)
                    {
                        if (projectEntity.Attributes.Contains(Constants.Projects.ProjectTemplate))
                        {
                            Mapping mapping = (
                                from m in projectTemplateSettings.Mappings
                                where m.Key.Equals(projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.ProjectTemplate).Id.ToString(), StringComparison.OrdinalIgnoreCase)
                                select m).FirstOrDefault <Mapping>();


                            if (mapping is Mapping)
                            {
                                tracer.Trace($"Project Template is : {mapping.Name}");
                                int      timeZoneCode    = CommonMethods.RetrieveCurrentUsersSettings(service);
                                DateTime currentDateTime = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, DateTime.Now);
                                tracer.Trace($"Current Date Time : {currentDateTime}");
                                CalculateTurnSchStartandEndDate(tracer, service, projectEntity, jobEntity, mapping, timeZoneCode);
                                //EntityCollection job_and_contracts_sub_to_yardi_EntityCollection = CommonMethods.RetrieveOpenProjectTaskByProjectAndTaskIdentifier(tracer, service, projectEntity.ToEntityReference(), projectEntity.GetAttributeValue<EntityReference>(Constants.Projects.ProjectTemplate),
                                //    mapping.Name.Equals(TURNPROCESS_PROJECT_TEMPLATE) ? 10 : 209, mapping.Name.Equals(TURNPROCESS_PROJECT_TEMPLATE) ? "10" : "9");
                                //foreach (Entity e in job_and_contracts_sub_to_yardi_EntityCollection.Entities)
                                //{
                                //    Entity num = new Entity(e.LogicalName)
                                //    {
                                //        Id = e.Id
                                //    };
                                //    num[Constants.ProjectTasks.ActualStart] = currentDateTime;
                                //    num[Constants.ProjectTasks.ActualEnd] = currentDateTime;
                                //    num[Constants.ProjectTasks.ActualDurationInMinutes] = (!e.Attributes.Contains(Constants.ProjectTasks.ActualStart)) ? 0 : (((currentDateTime - e.GetAttributeValue<DateTime>(Constants.ProjectTasks.ActualStart)).TotalMinutes > 0) ? (int)Math.Floor((currentDateTime - e.GetAttributeValue<DateTime>(Constants.ProjectTasks.ActualStart)).TotalMinutes) : 0);
                                //    //(!e.Attributes.Contains(Constants.ProjectTasks.ActualStart)) ? (int) 0 : (currentDateTime - e.GetAttributeValue<DateTime>(Constants.ProjectTasks.ActualStart)).TotalMinutes;
                                //    num[Constants.ProjectTasks.Progress] = new decimal(100);
                                //    num[Constants.Status.StatusCode] = new OptionSetValue(963850001);
                                //    service.Update(num);
                                //    tracer.Trace("Task for Event : JOB_AND_CONTRACTS_SUBMITTED_TO_YARDI Successfully Updated.");
                                //}

                                EntityCollection job_assign_to_vendor_in_cc_EntityCollection = CommonMethods.RetrieveOpenProjectTaskByProjectAndTaskIdentifier(tracer, service, projectEntity.ToEntityReference(), projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.ProjectTemplate),
                                                                                                                                                               mapping.Name.Equals(TURNPROCESS_PROJECT_TEMPLATE) ? 9 : 207, mapping.Name.Equals(TURNPROCESS_PROJECT_TEMPLATE) ? "9" : "7");
                                foreach (Entity e in job_assign_to_vendor_in_cc_EntityCollection.Entities)
                                {
                                    Entity num = new Entity(e.LogicalName)
                                    {
                                        Id = e.Id
                                    };
                                    if (!e.Attributes.Contains(Constants.ProjectTasks.ActualStart))
                                    {
                                        num[Constants.ProjectTasks.ActualStart] = currentDateTime;
                                    }
                                    num[Constants.ProjectTasks.ActualEnd] = currentDateTime;
                                    num[Constants.ProjectTasks.ActualDurationInMinutes] = (!e.Attributes.Contains(Constants.ProjectTasks.ActualStart)) ? 0 : (((currentDateTime - e.GetAttributeValue <DateTime>(Constants.ProjectTasks.ActualStart)).TotalMinutes > 0) ? (int)Math.Floor((currentDateTime - e.GetAttributeValue <DateTime>(Constants.ProjectTasks.ActualStart)).TotalMinutes) : 0);
                                    num[Constants.ProjectTasks.Progress] = new decimal(100);
                                    num[Constants.Status.StatusCode]     = new OptionSetValue(963850001);
                                    service.Update(num);
                                    tracer.Trace("Task for Event : JOB_ASSIGNMENT_TO_VENDORS_IN_CONTRACT_CREATOR Successfully Updated.");
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                tracer.Trace(e.Message + e.StackTrace);
            }
        }
Ejemplo n.º 31
0
 private void ExecutePlugin(IPluginExecutionContext context, IOrganizationServiceFactory serviceFactory, IOrganizationService service, ITracingService tracing)
 {
     //var target = (???)context.InputParameters["Target"];
     //var preEntity = (Entity)context.PreEntityImages["PreImage"];
     //var postEntity = (Entity)context.PostEntityImages["PostImage"];
     //YOUR PLUGIN-CODE GO HERE
 }
Ejemplo n.º 32
0
 public CrmServices(IOrganizationService service, CrmServiceContext xrmContext, ITracingService t)
 {
     this.Service = service;
     this.T = t;
     this.Context = xrmContext;
 }
Ejemplo n.º 33
0
 public msdyncrmWorkflowTools_Class(IOrganizationService _service, ITracingService _tracing)
 {
     service = _service;
     tracing = _tracing;
 }
Ejemplo n.º 34
0
        public void _createlineitem(IPluginExecutionContext context, IOrganizationService service, Entity lineitem, Guid id, ITracingService tracingService)
        {
            // Create a task activity to follow up with the account customer in 7 days.
            Entity quoteline = new Entity("quotedetail");

            quoteline["productdescription"] = lineitem.GetAttributeValue <string>("us_name");
            tracingService.Trace("Setting cpm");
            quoteline["us_cpm"] = lineitem.GetAttributeValue <Money>("us_cpm");
            tracingService.Trace("Setting cpv");
            quoteline["us_cpv"] = lineitem.GetAttributeValue <Money>("us_cpv");
            tracingService.Trace("Setting priceperunit");
            quoteline["priceperunit"] = new Money(lineitem.GetAttributeValue <Money>("us_cpm").Value / 1000);
            tracingService.Trace("Setting quantity");
            quoteline["quantity"] = lineitem.GetAttributeValue <decimal>("us_amountofimpressions");
            tracingService.Trace("Setting amountofviews");
            quoteline["us_amountofviews"] = lineitem.GetAttributeValue <decimal>("us_amountofviews");
            tracingService.Trace("Setting campaigntype");
            quoteline["us_campaigntype"] = lineitem.GetAttributeValue <OptionSetValue>("us_campaigntype");
            tracingService.Trace("Setting extendedamount");
            quoteline["extendedamount"] = lineitem.GetAttributeValue <Money>("us_budget");
            tracingService.Trace("Setting baseamount");
            quoteline["baseamount"] = lineitem.GetAttributeValue <Money>("us_budget");
            tracingService.Trace("Setting budget");
            quoteline["us_budget"] = lineitem.GetAttributeValue <Money>("us_budget");
            tracingService.Trace("Setting overridden");
            quoteline["ispriceoverridden"] = true;
            tracingService.Trace("Setting quote");
            quoteline["quoteid"] = new EntityReference("quote", id);


            // Create the quoteline in Microsoft Dynamics CRM.
            tracingService.Trace("CreateQuotelinePlugin: Creating the quoteline activity.");
            service.Create(quoteline);
            tracingService.Trace("Quoteline created");
        }
Ejemplo n.º 35
0
        private static void PerformScheduledDateMoveOut(ITracingService tracer, IOrganizationService service, Entity projectEntity, DateTime schJobCompletionDate, int timeZoneCode, bool isTurn)
        {
            List <Entity> TaskIndentifierEntityList = CommonMethods.RetrieveActivtTaskIdentifier(tracer, service);

            EntityCollection projectTaskEntityCollection = CommonMethods.RetrieveAllOpenProjectTaskByProject(tracer, service, projectEntity.ToEntityReference());

            foreach (Entity projectTaskEntity in projectTaskEntityCollection.Entities)
            {
                if (projectTaskEntity.Attributes.Contains(Constants.ProjectTasks.TaskIdentifier))
                {
                    Entity taskIdentifierEntity = TaskIndentifierEntityList.Where(e => e.Id.Equals(projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.TaskIdentifier).Id)).FirstOrDefault();
                    if (taskIdentifierEntity is Entity && taskIdentifierEntity.Attributes.Contains(Constants.TaskIdentifiers.WBSID))
                    {
                        tracer.Trace($"Task Identifier Found ID : {projectTaskEntity.GetAttributeValue<EntityReference>(Constants.ProjectTasks.TaskIdentifier).Id} Name : {projectTaskEntity.GetAttributeValue<EntityReference>(Constants.ProjectTasks.TaskIdentifier).Name}");
                        tracer.Trace($"Task Identifier WBS ID : {taskIdentifierEntity.GetAttributeValue<string>(Constants.TaskIdentifiers.WBSID)}");

                        Entity tmpPrjTskEntity = new Entity(projectTaskEntity.LogicalName);
                        tmpPrjTskEntity.Id = projectTaskEntity.Id;
                        bool     requiredUpdate = false, orgSchStartDateFound = false;
                        DateTime orgSchStartDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, DateTime.Now);
                        if (projectTaskEntity.Attributes.Contains(Constants.ProjectTasks.ScheduledStart))
                        {
                            orgSchStartDateFound = true;
                            orgSchStartDate      = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, projectTaskEntity.GetAttributeValue <DateTime>(Constants.ProjectTasks.ScheduledStart));
                        }

                        if (isTurn)
                        {
                            #region TURN SWITCH
                            switch (taskIdentifierEntity.GetAttributeValue <string>(Constants.TaskIdentifiers.WBSID))
                            {
                            //case "11":          //VENDOR(S) SAYS JOB STARTED
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = startDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = startDate;
                            //    requiredUpdate = true;
                            //    break;
                            //case "12":          //WORK IN PROGRESS
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = startDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = endDate;
                            //    requiredUpdate = true;
                            //    break;
                            //case "13":          //VENDOR SAYS JOB?S COMPLETE
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = endDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = endDate;
                            //    requiredUpdate = true;
                            //    break;
                            //case "14":          //QUALITY CONTROL INSPECTION
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = endDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = (schJobCompletionDate > endDate) ? schJobCompletionDate : endDate.AddDays(1);
                            //    requiredUpdate = true;
                            //    break;
                            case "15":              //JOB COMPLETED
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate;
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd]   = schJobCompletionDate;
                                requiredUpdate = true;
                                break;

                            case "16":              //HERO SHOT PICTURE
                                if (orgSchStartDateFound)
                                {
                                    tracer.Trace($"Original Scheduled Start Date : {orgSchStartDate}");
                                    tracer.Trace($"New Sch Job Completion Date : {schJobCompletionDate}");
                                    if (orgSchStartDate > schJobCompletionDate)
                                    {
                                        tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate.AddDays(-1).ChangeTime(6, 0, 0, 0);
                                    }
                                }
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = schJobCompletionDate;
                                requiredUpdate = true;
                                break;

                            case "17":              //MARKETING INSPECTION
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate;
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd]   = schJobCompletionDate.AddDays(2);
                                requiredUpdate = true;
                                break;

                            case "18":              //BI-WEEKLY INSPECTION
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate.AddDays(13);
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd]   = schJobCompletionDate.AddDays(14);
                                requiredUpdate = true;
                                break;
                            }

                            #endregion
                        }
                        else
                        {
                            #region RENO SWITCH
                            switch (taskIdentifierEntity.GetAttributeValue <string>(Constants.TaskIdentifiers.WBSID))
                            {
                            //case "10":           //IR : VENDORS_SAYS_JOB_STARTED
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = startDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = startDate;
                            //    requiredUpdate = true;
                            //    break;
                            //case "11":           //IR : WORK_IN_PROGRESS
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = startDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = endDate;
                            //    requiredUpdate = true;
                            //    break;
                            //case "12":           //IR : VENDOR_SAYS_JOBS_COMPLETE
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = endDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = endDate;
                            //    requiredUpdate = true;
                            //    break;
                            //case "13":           //IR : QUALITY_CONTROL_INSPECTION
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = endDate;
                            //    tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = (schJobCompletionDate > endDate) ? schJobCompletionDate : endDate.AddDays(1);
                            //    requiredUpdate = true;
                            //    break;
                            case "14":               //IR : JOB_COMPLETED
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate;
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd]   = schJobCompletionDate;
                                requiredUpdate = true;
                                break;

                            case "15":               //IR : HERO_SHOT_PICTURE
                                if (orgSchStartDateFound)
                                {
                                    tracer.Trace($"Original Scheduled Start Date : {orgSchStartDate}");
                                    tracer.Trace($"New Sch Job Completion Date : {schJobCompletionDate}");
                                    if (orgSchStartDate > schJobCompletionDate)
                                    {
                                        tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate.AddDays(-1).ChangeTime(6, 0, 0, 0);
                                    }
                                }
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd] = schJobCompletionDate;
                                requiredUpdate = true;
                                break;

                            case "16":               //IR : MARKETING_INSPECTION
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate;
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd]   = schJobCompletionDate.AddDays(2);
                                requiredUpdate = true;
                                break;

                            case "17":               //IR : BI_WEEKLY_INSPECTION
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledStart] = schJobCompletionDate.AddDays(13);
                                tmpPrjTskEntity[Constants.ProjectTasks.ScheduledEnd]   = schJobCompletionDate.AddDays(14);
                                requiredUpdate = true;
                                break;
                            }
                            #endregion
                        }
                        try
                        {
                            if (requiredUpdate)
                            {
                                tracer.Trace($"Updating Project Task: {projectTaskEntity.GetAttributeValue<EntityReference>(Constants.ProjectTasks.TaskIdentifier).Name}");
                                service.Update(tmpPrjTskEntity);
                                tracer.Trace($"Project Task: {projectTaskEntity.GetAttributeValue<EntityReference>(Constants.ProjectTasks.TaskIdentifier).Name} successfully updated.");
                            }
                        }
                        catch (Exception ex)
                        {
                            tracer.Trace(ex.Message + ex.StackTrace);
                        }
                    }
                }
            }
            //
        }
Ejemplo n.º 36
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the tracing service
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    // Plug-in business logic goes here.
                    // Create a task activity to follow up with the account customer in 7 days.
                    Entity followup = new Entity("task");

                    followup["subject"]     = "Send e-mail to the new customer.";
                    followup["description"] =
                        "Follow up with the customer. Check if there are any new issues that need resolution.";
                    followup["scheduledstart"] = DateTime.Now.AddDays(7);
                    followup["scheduledend"]   = DateTime.Now.AddDays(7);
                    followup["category"]       = context.PrimaryEntityName;

                    // Refer to the account in the task activity.
                    if (context.OutputParameters.Contains("id"))
                    {
                        Guid   regardingobjectid     = new Guid(context.OutputParameters["id"].ToString());
                        string regardingobjectidType = "account";

                        followup["regardingobjectid"] =
                            new EntityReference(regardingobjectidType, regardingobjectid);
                    }

                    // Create the task in Microsoft Dynamics CRM.
                    tracingService.Trace("FollowupPlugin: Creating the task activity.");
                    service.Create(followup);
                }

                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
 public XrmTraceUserInterface(ITracingService tracingService)
 {
     _trace = tracingService;
     UiActive = true;
 }
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            tracingService.Trace("{0}{1}", "Start Custom Workflow Activity: CalculateFacilityReplacementCost", DateTime.Now.ToLongTimeString());

            var recordId = context.PrimaryEntityId;

            try
            {
                //Get all facilities for the school district
                FilterExpression filterName = new FilterExpression();
                filterName.Conditions.Add(new ConditionExpression("caps_schooldistrict", ConditionOperator.Equal, recordId));
                filterName.Conditions.Add(new ConditionExpression("caps_isschool", ConditionOperator.Equal, true));
                filterName.Conditions.Add(new ConditionExpression("statecode", ConditionOperator.Equal, 0));
                filterName.Conditions.Add(new ConditionExpression("caps_geographicalschooldistrict", ConditionOperator.NotNull));
                filterName.Conditions.Add(new ConditionExpression("caps_communitylocation", ConditionOperator.NotNull));

                QueryExpression query = new QueryExpression("caps_facility");
                query.ColumnSet.AddColumns("caps_communitylocation"
                                           , "caps_designcapacitykindergarten"
                                           , "caps_strongstartcapacitykindergarten"
                                           , "caps_designcapacityelementary"
                                           , "caps_strongstartcapacityelementary"
                                           , "caps_designcapacitysecondary"
                                           , "caps_strongstartcapacitysecondary"
                                           , "caps_currentfacilitytype"
                                           , "caps_geographicalschooldistrict"
                                           , "caps_neighbourhoodlearningcentre");

                query.Criteria.AddFilter(filterName);

                EntityCollection results = service.RetrieveMultiple(query);

                tracingService.Trace("Line: {0}", "58");

                foreach (caps_Facility facility in results.Entities)
                {
                    var communityLocationRecord = service.Retrieve(facility.caps_CommunityLocation.LogicalName, facility.caps_CommunityLocation.Id, new ColumnSet("caps_projectlocationfactor")) as caps_BudgetCalc_CommunityLocation;
                    tracingService.Trace("Line: {0}", "63");
                    var hostSchoolDistrictRecord = service.Retrieve(facility.caps_GeographicalSchoolDistrict.LogicalName, facility.caps_GeographicalSchoolDistrict.Id, new ColumnSet("caps_freightrateallowance")) as edu_schooldistrict;
                    tracingService.Trace("Line: {0}", "65");
                    var facilityTypeRecord = service.Retrieve(facility.caps_CurrentFacilityType.LogicalName, facility.caps_CurrentFacilityType.Id, new ColumnSet("caps_schooltype")) as caps_FacilityType;
                    tracingService.Trace("Line: {0}", "67");
                    var adjustedDesignK = (int)facility.caps_DesignCapacityKindergarten.GetValueOrDefault(0) + facility.caps_StrongStartCapacityKindergarten.GetValueOrDefault(0);
                    var adjustedDesignE = (int)facility.caps_DesignCapacityElementary.GetValueOrDefault(0) + facility.caps_StrongStartCapacityElementary.GetValueOrDefault(0);
                    var adjustedDesignS = (int)facility.caps_DesignCapacitySecondary.GetValueOrDefault(0) + facility.caps_StrongStartCapacitySecondary.GetValueOrDefault(0);

                    tracingService.Trace("Line: {0}", "72");
                    var scheduleB = new ScheduleB(service, tracingService);
                    //set parameters
                    scheduleB.SchoolType            = facilityTypeRecord.caps_SchoolType.Id;
                    scheduleB.BudgetCalculationType = (int)caps_BudgetCalculationType.Replacement;
                    scheduleB.IncludeNLC            = facility.caps_NeighbourhoodLearningCentre.GetValueOrDefault(false);
                    scheduleB.ProjectLocationFactor = communityLocationRecord.caps_ProjectLocationFactor.GetValueOrDefault(1);

                    scheduleB.ExistingAndDecreaseDesignCapacity = new Services.DesignCapacity(0, 0, 0);
                    scheduleB.ExtraSpaceAllocation   = 0;
                    scheduleB.ApprovedDesignCapacity = new Services.DesignCapacity(adjustedDesignK, adjustedDesignE, adjustedDesignS);

                    scheduleB.MunicipalFees = 0;
                    //scheduleB.ConstructionNonStructuralSeismicUpgrade = 0;
                    scheduleB.ConstructionSeismicUpgrade = 0;
                    //scheduleB.ConstructionSPIRAdjustment = 0;

                    tracingService.Trace("Line: {0}", "89");
                    //scheduleB.SPIRFees = 0;

                    scheduleB.FreightRateAllowance = hostSchoolDistrictRecord.caps_FreightRateAllowance.GetValueOrDefault(0);

                    //Supplemental Items
                    scheduleB.Demolition         = 0;
                    scheduleB.AbnormalTopography = 0;
                    scheduleB.TempAccommodation  = 0;
                    scheduleB.OtherSupplemental  = 0;

                    //call Calculate
                    tracingService.Trace("CalculateScheduleB: {0}", "Call Calculate Function");
                    CalculationResult result = scheduleB.Calculate();

                    tracingService.Trace("Line: {0}", "104");
                    //Update the facility
                    var recordToUpdate = new caps_Facility();
                    recordToUpdate.Id = facility.Id;
                    recordToUpdate.caps_PreliminaryReplacementValue        = result.Total;
                    recordToUpdate.caps_PreliminaryReplacementCalculatedOn = DateTime.Now;
                    service.Update(recordToUpdate);
                }

                //Update Project Request
                this.error.Set(executionContext, false);
            }
            catch (Exception ex)
            {
                tracingService.Trace("Error Details: {0}", ex.Message);
                //might want to also include error message
                this.error.Set(executionContext, true);
                this.errorMessage.Set(executionContext, ex.Message);
            }
        }
 internal static void WriteToTrace(ITracingService traceService, string message)
 {
     if (traceService != null)
         traceService.Trace(message);
 }
Ejemplo n.º 40
0
 public VehiclePostDeliveryMonitoringHandler(IOrganizationService service, ITracingService trace)
 {
     _organizationService = service;
     _tracingService      = trace;
 }