private void StoreTemplate(IUnitOfWork uow)
            {
                var  plan = uow.PlanRepository.GetPlanQueryUncached().FirstOrDefault(x => x.Name == _name);
                bool add  = plan == null;

                if (add)
                {
                    plan    = new PlanDO();
                    plan.Id = Guid.NewGuid();
                }

                plan.Fr8Account  = _fr8AccountDO;
                plan.Name        = _name;
                plan.Description = "Template for testing";
                plan.CreateDate  = DateTime.UtcNow;
                plan.LastUpdated = DateTime.UtcNow;
                plan.PlanState   = PlanState.Inactive; // we don't want this process template can be executed ouside of tests

                if (add)
                {
                    uow.PlanRepository.Add(plan);
                    uow.SaveChanges();
                }

                _ptId = plan.Id;
            }
        // Manual mapping method to resolve DO-1164.
        public static PlanDTO MapPlanToDto(PlanDO curPlanDO)
        {
            var subPlanDTOList = curPlanDO.ChildNodes.OfType <SubplanDO>()
                                 .OrderBy(x => x.Ordering)
                                 .ToList()
                                 .Select((SubplanDO x) =>
            {
                var pntDTO = Mapper.Map <FullSubplanDto>(x);

                pntDTO.Activities = x.ChildNodes.OrderBy(y => y.Ordering).Select(Mapper.Map <ActivityDTO>).ToList();

                return(pntDTO);
            }).ToList();

            var result = new PlanDTO()
            {
                Description = curPlanDO.Description,
                Id          = curPlanDO.Id,
                Name        = curPlanDO.Name,
                PlanState   = PlanState.IntToString(curPlanDO.PlanState),
                Visibility  = new PlanVisibilityDTO()
                {
                    Hidden = curPlanDO.Visibility.BooleanValue()
                },
                StartingSubPlanId = curPlanDO.StartingSubPlanId,
                SubPlans          = subPlanDTOList,
                Fr8UserId         = curPlanDO.Fr8AccountId,
                Tag         = curPlanDO.Tag,
                Category    = curPlanDO.Category,
                LastUpdated = curPlanDO.LastUpdated
            };

            return(result);
        }
        public static PlanDO TestPlanWithStartingSubPlanAndActivityList()
        {
            var curPlanDO = new PlanDO
            {
                Id          = GetTestGuidById(1),
                Description = "DO-1124 Proper  deletion of Plan",
                Name        = "TestPlanWithStartingSubPlan",
                PlanState   = PlanState.Executing,
            };

            var curSubPlanDO = new SubplanDO()
            {
                Id              = GetTestGuidById(2),
                Name            = string.Format("curSubPlanDO-{0}", 1),
                ParentPlanNode  = curPlanDO,
                StartingSubPlan = true
            };

            curPlanDO.ChildNodes.Add(curSubPlanDO);

            var curImmediateActionList = FixtureData.TestActivityList_ImmediateActivities();

            foreach (var node in curImmediateActionList)
            {
                curSubPlanDO.ChildNodes.Add(node);
            }

            return(curPlanDO);
        }
Exemplo n.º 4
0
        public bool IsMonitoringPlan(IUnitOfWork uow, PlanDO plan)
        {
            var solutionId = ActivityCategories.SolutionId;
            var monitorId  = ActivityCategories.MonitorId;

            var initialActivity = plan.StartingSubplan.GetDescendantsOrdered()
                                  .OfType <ActivityDO>()
                                  .FirstOrDefault(x => !uow.ActivityTemplateRepository.GetByKey(x.ActivityTemplateId).Categories.Any(y => y.ActivityCategoryId == solutionId));

            if (initialActivity == null)
            {
                return(false);
            }

            var activityTemplate = uow.ActivityTemplateRepository.GetByKey(initialActivity.ActivityTemplateId);

            if (activityTemplate.Categories.Any(y => y.ActivityCategoryId == monitorId))
            {
                return(true);
            }

            var storage = _crate.GetStorage(initialActivity.CrateStorage);

            // First activity has event subsribtions. This means that this plan can be triggered by external event
            if (storage.CrateContentsOfType <EventSubscriptionCM>().Any(x => x.Subscriptions?.Count > 0))
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 5
0
        /**********************************************************************************/
        // this is just simplification the first implementation.
        // We can only delete plans. If we want to edit plan, we need to get corresponding node and edit it's children
        public void Delete(PlanDO node)
        {
            var plan = GetById <PlanNodeDO>(node.Id);

            if (plan == null)
            {
                return;
            }

            lock (_loadedNodes)
            {
                LoadedPlan loadedPlan;

                // if we have loaded this node before?
                if (_loadedNodes.TryGetValue(node.Id, out loadedPlan))
                {
                    if (loadedPlan.IsNew)
                    {
                        _loadedNodes.Remove(node.Id);
                        _loadedPlans.Remove(loadedPlan);
                    }
                    else
                    {
                        loadedPlan.IsDeleted = true;
                    }
                }
            }
        }
Exemplo n.º 6
0
        public async Task ActivityWithNestedUpdated_StructureUnchanged()
        {
            var tree        = FixtureData.CreateTestActivityTreeWithOnlyActivityDo();
            var updatedTree = FixtureData.CreateTestActivityTreeWithOnlyActivityDo();

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                var plan = new PlanDO
                {
                    PlanState  = PlanState.Executing,
                    Name       = "name",
                    ChildNodes = { tree }
                };
                uow.PlanRepository.Add(plan);
                uow.SaveChanges();

                Visit(updatedTree, x => x.Label = string.Format("We were here {0}", x.Id));
            }

            await _activity.SaveOrUpdateActivity(updatedTree);

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                var result = uow.PlanRepository.GetById <ActivityDO>(tree.Id);
                Compare(updatedTree, result, (r, a) =>
                {
                    if (r.Label != a.Label)
                    {
                        throw new Exception("Update failed");
                    }
                });
            }
        }
Exemplo n.º 7
0
        public static async Task LaunchPlanCallback(Guid planId, params CrateDTO[] curPayload)
        {
            Logger.GetLogger().Info($"Starting executing plan {planId} as a reaction to external event");

            if (planId == default(Guid))
            {
                Logger.GetLogger().Error("Can't lanunch plan with empty id");
            }

            // We "eat" this exception to make Hangfire thinks that everthying is good and job is completed
            // This exception should be already logged somewhere
            var planService = ObjectFactory.GetInstance <Plan>();

            try
            {
                using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
                {
                    var plan = uow.PlanRepository.GetById <PlanDO>(planId);

                    if (plan == null)
                    {
                        Logger.GetLogger().Error($"Unable to find plan: {planId}");
                        return;
                    }

                    await planService.Run(uow, plan, curPayload.Select(x => CrateStorageSerializer.Default.ConvertFromDto(x)).ToArray());
                }
            }
            catch (InvalidTokenRuntimeException ex)
            {
                PlanDO monitoringPlan = null;

                using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
                {
                    var plan = uow.PlanRepository.GetById <PlanDO>(planId);

                    if (plan != null && planService.IsMonitoringPlan(uow, plan))
                    {
                        monitoringPlan = plan;
                    }
                }

                if (monitoringPlan != null)
                {
                    await planService.Deactivate(planId);

                    Logger.GetLogger().Error($"Plan {planId} was deactivated due to authentication problems.");
                    using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
                    {
                        await planService.ReportAuthDeactivation(uow, monitoringPlan, ex);
                    }
                }
            }
            catch
            {
            }

            Logger.GetLogger().Info($"Finished executing plan {planId} as a reaction to external event");
        }
 private async Task RunPlan(PlanDO plan)
 {
     if (plan.PlanState == PlanState.Executing || plan.PlanState == PlanState.Active)
     {
         return;
     }
     await _plan.Run(plan.Id, null, null);
 }
Exemplo n.º 9
0
        public async Task ExecuteOnlyStartingSubplanByDefault()
        {
            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                PlanDO plan;

                uow.PlanRepository.Add(plan = new PlanDO
                {
                    Name       = "TestPlan",
                    Id         = FixtureData.GetTestGuidById(0),
                    ChildNodes =
                    {
                        new SubplanDO(true)
                        {
                            Id         = FixtureData.GetTestGuidById(1),
                            ChildNodes =
                            {
                                new ActivityDO()
                                {
                                    ActivityTemplateId = FixtureData.GetTestGuidById(1),
                                    Id       = FixtureData.GetTestGuidById(2),
                                    Ordering = 1
                                },
                            }
                        },
                        new SubplanDO(false)
                        {
                            Id         = FixtureData.GetTestGuidById(3),
                            ChildNodes =
                            {
                                new ActivityDO()
                                {
                                    ActivityTemplateId = FixtureData.GetTestGuidById(1),
                                    Id       = FixtureData.GetTestGuidById(4),
                                    Ordering = 1
                                },
                            }
                        }
                    }
                });

                plan.PlanState       = PlanState.Executing;
                plan.StartingSubplan = (SubplanDO)plan.ChildNodes[0];

                var userAcct = FixtureData.TestUser1();
                uow.UserRepository.Add(userAcct);
                plan.Fr8Account = userAcct;

                uow.SaveChanges();

                await Plan.Run(plan.Id, null, null);

                AssertExecutionSequence(new[]
                {
                    new ActivityExecutionCall(ActivityExecutionMode.InitialRun, FixtureData.GetTestGuidById(2)),
                }, ActivityService.ExecutedActivities);
            }
        }
Exemplo n.º 10
0
        public static void PlanActivationFailed(PlanDO plan, string reason)
        {
            var handler = PlanActivationFailedEvent;

            if (handler != null)
            {
                handler(plan, reason);
            }
        }
Exemplo n.º 11
0
        public static void ContainerFailed(PlanDO plan, Exception ex, string containerId)
        {
            var handler = EventContainerFailed;

            if (handler != null)
            {
                handler(plan, ex, containerId);
            }
        }
        public static PlanDO TestPlan_CanCreate()
        {
            var curPlanDO = new PlanDO
            {
                Description = "DO-1217 Unit Tests for Process#Create",
                Name        = "DO-1217",
                PlanState   = PlanState.Executing,
            };

            return(curPlanDO);
        }
        public static PlanDO TestPlan_CanCreate(string name)
        {
            var curPlanDO = new PlanDO
            {
                Id          = Guid.NewGuid(),
                Description = name,
                Name        = name,
                PlanState   = PlanState.Executing,
            };

            return(curPlanDO);
        }
        public static PlanDO TestContainerCreateAddsLogs()
        {
            var curPlanDO = new PlanDO
            {
                Id          = GetTestGuidById(1),
                Description = "DO-1419 Container Create Adds Logs Test",
                Name        = "Container Create",
                PlanState   = PlanState.Executing
            };

            return(curPlanDO);
        }
        public static PlanDO TestPlan1()
        {
            var plan = new PlanDO
            {
                Id          = GetTestGuidById(33),
                Description = "descr 1",
                Name        = "template1",
                PlanState   = PlanState.Executing,
            };

            return(plan);
        }
        public static PlanDO TestPlanHealthDemo()
        {
            var healthPlan = new PlanDO
            {
                Id          = GetTestGuidById(23),
                Description = "DO-866 HealthDemo Integration Test",
                Name        = "HealthDemoIntegrationTest",
                PlanState   = PlanState.Executing,
            };

            return(healthPlan);
        }
        public static PlanDO TestPlan5()
        {
            var plan = new PlanDO
            {
                Id          = GetTestGuidById(40),
                Description = "Description 5",
                Name        = "Plan 5",
                PlanState   = PlanState.Executing,
                Fr8Account  = FixtureData.TestDockyardAccount5()
            };

            return(plan);
        }
Exemplo n.º 18
0
        public PlanDO Create(IUnitOfWork uow, string name, string category = "", string ownerId = "", PlanVisibility visibility = PlanVisibility.Standard)
        {
            var plan = new PlanDO
            {
                Id         = Guid.NewGuid(),
                Name       = name,
                Fr8Account = string.IsNullOrEmpty(ownerId) ? _security.GetCurrentAccount(uow) : uow.UserRepository.FindOne(x => x.Id == ownerId),
                PlanState  = PlanState.Inactive,
                Visibility = visibility,
                Category   = category
            };

            uow.PlanRepository.Add(plan);
            return(plan);
        }
        public static PlanDO TestPlan2()
        {
            var plan = new PlanDO
            {
                Id          = GetTestGuidById(50),
                Description = "descr 2",
                Name        = "template2",
                PlanState   = PlanState.Executing,

                //UserId = "testUser1"
                //Fr8Account = FixtureData.TestDockyardAccount1()
            };

            return(plan);
        }
Exemplo n.º 20
0
        private void PlanActivated(Guid planId)
        {
            PlanDO planDO = null;

            using (var uowPlan = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                planDO = uowPlan.PlanRepository.GetById <PlanDO>(planId);
            }

            if (planDO != null)
            {
                var factDO = CreatedPlanFact(planId, "Activated");
                SaveAndLogFact(factDO);
            }
        }
Exemplo n.º 21
0
        private void PlanActivationFailed(PlanDO plan, string reason)
        {
            var incident = new IncidentDO
            {
                Fr8UserId = "unknown",
                Data      = "Plan activation failed, plan.Id = " + plan.Id.ToString()
                            + ", plan.Name = " + plan.Name
                            + ", plan.PlanState = " + plan.PlanState.ToString()
                            + ", reason = " + reason,
                PrimaryCategory   = "Plan",
                SecondaryCategory = "Activation",
                Component         = "Hub",
                Activity          = "Plan Activation"
            };

            SaveAndLogIncident(incident);
        }
Exemplo n.º 22
0
        private void NotifyWithErrorMessage(Exception exception, PlanDO planDO, string userId, string errorMessage = "")
        {
            var messageToNotify = string.Empty;

            if (!string.IsNullOrEmpty(errorMessage))
            {
                messageToNotify = errorMessage;
            }

            _pusherNotifier.NotifyUser(new NotificationMessageDTO
            {
                NotificationType = NotificationType.GenericFailure,
                Subject          = "Plan Failed",
                Message          = String.Format("Plan \"{0}\" failed. {1}", planDO.Name, messageToNotify),
                Collapsed        = false
            }, userId);
        }
Exemplo n.º 23
0
        private async Task ReportAuthDeactivation(IUnitOfWork uow, PlanDO plan, InvalidTokenRuntimeException ex)
        {
            var activityTemplate = ex?.FailedActivityDTO.ActivityTemplate;

            string errorMessage = $"Activity {ex?.FailedActivityDTO.Label} was unable to authenticate with remote web-service.";

            errorMessage += $"Plan \"{plan.Name}\" which contains failed activity was deactivated.";

            _pusherNotifier.NotifyUser(new NotificationMessageDTO
            {
                NotificationType = NotificationType.GenericFailure,
                Subject          = "Plan Failed",
                Message          = errorMessage,
                Collapsed        = false
            }, plan.Fr8AccountId);

            //Sending an Email

            var account = uow.UserRepository.GetQuery().FirstOrDefault(a => a.Id == plan.Fr8AccountId);

            try
            {
                var userEmail = account.UserName;
                var emailDO   = new EmailDO();
                IConfigRepository configRepository = ObjectFactory.GetInstance <IConfigRepository>();
                string            fromAddress      = configRepository.Get("EmailAddress_GeneralInfo");
                var emailAddressDO = uow.EmailAddressRepository.GetOrCreateEmailAddress(fromAddress);
                emailDO.From   = emailAddressDO;
                emailDO.FromID = emailAddressDO.Id;
                emailDO.AddEmailRecipient(EmailParticipantType.To,
                                          uow.EmailAddressRepository.GetOrCreateEmailAddress(userEmail));
                emailDO.Subject = "Your plan was deactivated due to authentication expiration";
                string htmlText = $"Plan “{plan.Name}” was deactivated due to authentication problems. <br>If you would like to keep it active, please reauthenticate <a href='{Server.ServerUrl}dashboard/plans/{plan.Id}/builder?viewMode=plan'>here</a>";
                emailDO.HTMLText = htmlText;

                uow.EnvelopeRepository.ConfigureTemplatedEmail(emailDO, "PlanDeactivated_Template");
                uow.SaveChanges();

                await ObjectFactory.GetInstance <IEmailPackager>().Send(new EnvelopeDO {
                    Email = emailDO
                });
            }

            catch { Logger.GetLogger().Error($"Couldn't send email to user {account.Id} to notify him about plan deactivation"); }
        }
Exemplo n.º 24
0
        /**********************************************************************************/
        // this is just simplification for the first implementation.
        // We can only insert plans. If we want to edit plan, we need to get corresponding node and edit it's children
        public void Add(PlanDO plan)
        {
            lock (_loadedNodes)
            {
                var loadedPlan = new LoadedPlan(plan, true);

                PlanTreeHelper.Visit(plan, x =>
                {
                    if (x.Id == Guid.Empty)
                    {
                        x.Id = Guid.NewGuid();
                    }

                    _loadedNodes.Add(x.Id, loadedPlan);
                });
                _loadedPlans.Add(loadedPlan);
            }
        }
Exemplo n.º 25
0
        public async Task ActivityWithNestedUpdated_RemoveElements()
        {
            var tree        = FixtureData.CreateTestActivityTreeWithOnlyActivityDo();
            var updatedTree = FixtureData.CreateTestActivityTreeWithOnlyActivityDo();


            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                var plan = new PlanDO
                {
                    PlanState  = PlanState.Executing,
                    Name       = "name",
                    ChildNodes = { tree }
                };
                uow.PlanRepository.Add(plan);
                uow.SaveChanges();
                int removeCounter = 0;

                Visit(updatedTree, a =>
                {
                    if (removeCounter % 3 == 0 && a.ParentPlanNode != null)
                    {
                        a.ParentPlanNode.ChildNodes.Remove(a);
                    }

                    removeCounter++;
                });
            }

            await _activity.SaveOrUpdateActivity(updatedTree);

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                var result = uow.PlanRepository.GetById <ActivityDO>(tree.Id);
                Compare(updatedTree, result, (r, a) =>
                {
                    if (r.Id != a.Id)
                    {
                        throw new Exception("Update failed");
                    }
                });
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// New Process object
        /// </summary>
        /// <param name="planId"></param>
        /// <param name="envelopeId"></param>
        /// <returns></returns>
        public ContainerDO Create(IUnitOfWork uow, PlanDO curPlan, params Crate[] curPayload)
        {
            var containerDO = new ContainerDO {
                Id = Guid.NewGuid()
            };

            containerDO.PlanId = curPlan.Id;
            containerDO.Name   = curPlan.Name;
            containerDO.State  = State.Unstarted;

            using (var crateStorage = _crate.UpdateStorage(() => containerDO.CrateStorage))
            {
                if (curPayload?.Length > 0)
                {
                    foreach (var crate in curPayload)
                    {
                        if (crate != null && !crate.IsOfType <OperationalStateCM>())
                        {
                            crateStorage.Add(crate);
                        }
                    }
                }

                var operationalState = new OperationalStateCM();

                operationalState.CallStack.PushFrame(new OperationalStateCM.StackFrame
                {
                    NodeName = "Starting subplan",
                    NodeId   = curPlan.StartingSubPlanId,
                });

                crateStorage.Add(Crate.FromContent("Operational state", operationalState));
            }

            uow.ContainerRepository.Add(containerDO);

            uow.SaveChanges();

            EventManager.ContainerCreated(containerDO);

            return(containerDO);
        }
        public static PlanDO TestPlanWithStartingSubPlans_ID0()
        {
            var curPlanDO = new PlanDO
            {
                Description = "DO-1124 Proper  deletion of Plan",
                Name        = "TestPlanWithStartingSubPlans_ID0",
                PlanState   = PlanState.Executing,
            };

            var curSubPlanDO = new SubplanDO()
            {
                Name            = string.Format("curSubPlanDO-{0}", 1),
                ParentPlanNode  = curPlanDO,
                StartingSubPlan = true
            };

            curPlanDO.ChildNodes.Add(curSubPlanDO);


            return(curPlanDO);
        }
Exemplo n.º 28
0
        private void ContainerFailed(PlanDO plan, Exception ex, string containerId)
        {
            var incident = new IncidentDO
            {
                Fr8UserId = _sercurity.GetCurrentUser(),
                Data      = string.Join(
                    Environment.NewLine,
                    "Container failure.",
                    "PlanName: " + (plan != null ? plan.Name : "unknown"),
                    "PlanId: " + (plan != null ? plan.Id.ToString() : "unknown"),
                    ex.Message,
                    ex.StackTrace ?? ""
                    ),
                ObjectId          = containerId,
                PrimaryCategory   = "Container",
                SecondaryCategory = "Execution",
                Component         = "Hub",
                Activity          = "Container failure"
            };

            SaveAndLogIncident(incident);
        }
        public void ActivityController_Save_WithActionExists_ExistingActionShouldBeUpdated()
        {
            //Arrange
            //Add one test action
            var activity = FixtureData.TestActivity1();

            var plan = new PlanDO
            {
                PlanState  = PlanState.Executing,
                Name       = "name",
                ChildNodes = { activity }
            };

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                uow.PlanRepository.Add(plan);
                uow.SaveChanges();
            }
            //Act
            var actualAction = CreateActivityWithId(FixtureData.GetTestGuidById(1));

            actualAction.ParentPlanNodeId = plan.Id;

            var controller = ObjectFactory.GetInstance <ActivitiesController>();

            controller.Save(actualAction);

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                //Assert
                Assert.IsNotNull(uow.PlanRepository);
                Assert.IsTrue(uow.PlanRepository.GetActivityQueryUncached().Count() == 1);

                //Still there is only one action as the update happened.
                var expectedAction = uow.PlanRepository.GetById <ActivityDO>(actualAction.Id);
                Assert.IsNotNull(expectedAction);
            }
        }
Exemplo n.º 30
0
        public void GetAvailableData_ShouldReturnFields()
        {
            var plan = new PlanDO();

            plan.Name      = "sdfasdfasdf";
            plan.PlanState = PlanState.Executing;
            var testActionTree = FixtureData.TestActivity2Tree();

            plan.ChildNodes.Add(testActionTree);

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                uow.PlanRepository.Add(plan);
                uow.SaveChanges();
            }

            IPlanNode planNodeService = ObjectFactory.GetInstance <IPlanNode>();
            var       fieldsCrate     = planNodeService.GetIncomingData(testActionTree.ChildNodes.Last().Id, CrateDirection.Upstream, AvailabilityType.NotSet);

            Assert.NotNull(fieldsCrate);
            Assert.NotNull(fieldsCrate.AvailableCrates.SelectMany(x => x.Fields).ToList());
            Assert.AreEqual(33, fieldsCrate.AvailableCrates.SelectMany(x => x.Fields).ToList().Count);
        }