A context for passing state along a task execution queue
 /// <summary>
 /// Executes this task instance.
 /// </summary>
 /// <remarks></remarks>
 public override void Execute(TaskExecutionContext context)
 {
     if (NeedsInstallOrUpgrade)
     {
         InstallOrUpgrade();
     }            
 }
示例#2
0
 /// <summary>
 /// Executes this task instance.
 /// </summary>
 /// <remarks></remarks>
 public override void Execute(TaskExecutionContext context)
 {
     var eventArgs = context.EventArgs.CallerEventArgs as HiveEntityPostActionEventArgs;
     if (eventArgs != null)
     {
         OperateOnPostAction(eventArgs);
     }
 }
        /// <summary>
        /// Runs package actions for either PostPackageInstall and PostPackageUninstall & the packagefoldername specific task
        /// </summary>
        /// <param name="state"></param>
        /// <param name="taskExecContext"></param>
        /// <param name="packageFolderName"></param>
        internal void RunPostPackageInstallActions(PackageInstallationState state, TaskExecutionContext taskExecContext, string packageFolderName)
        {
            //Run the post pacakge install/uninstall tasks
            var triggerType = state == PackageInstallationState.Installing
                                  ? TaskTriggers.PostPackageInstall
                                  : TaskTriggers.PostPackageUninstall;

            _backOfficeRequestContext.Application.FrameworkContext.TaskManager.ExecuteInContext(triggerType, taskExecContext);

            //Execute all  tasks registered with the package folder name... though that will only fire for packages that have just been installed obviously.
            // ...This will redirect to the appopriate controller/action if a UI task is found for this package
            _backOfficeRequestContext.Application.FrameworkContext.TaskManager.ExecuteInContext(packageFolderName + "-" + triggerType, taskExecContext);
        }
        /// <summary>
        /// This gets all tasks found in configuration blocks and dynamically creates real task definitions from them 
        /// and registers them with the task manager with the trigger name of the package they were found in 
        /// </summary>
        /// <param name="context"></param>
        public override void Execute(TaskExecutionContext context)
        {
            using (DisposableTimer.TraceDuration<ConfigurationTaskBuilder>("Building configuration tasks", "End building configuration tasks"))
            {
                //get all tasks in configuration
                foreach (var t in ApplicationContext.Settings.Tasks)
                {
                    //create a new config task context with the configuration task's parameters
                    var configTaskContext = new ConfigurationTaskContext(ApplicationContext, t.Parameters, t);

                    //create a new instance of the configuration task
                    var task = (ConfigurationTask)Activator.CreateInstance(t.TaskType, new[] { configTaskContext });
                    var meta = new TaskMetadata(null)
                    {
                        ComponentType = task.GetType(),
                        ContinueOnError = true,
                        Id = Guid.NewGuid(),
                    };
                    //now we need to check the trigger name, if it is either post-package-install or pre-package-uninstall 
                    //then we need to check if this task has been registered with a package. If so, then we change the trigger
                    //to be PackageFolderName-post-package-install so that the task only executes for the current packages installation
                    //changes. If its neither of these names, then we just use the normal trigger
                    if ((t.Trigger.InvariantEquals(TaskTriggers.PostPackageInstall) || t.Trigger.InvariantEquals(TaskTriggers.PrePackageUninstall))
                        && !t.PackageFolder.IsNullOrWhiteSpace())
                    {
                        var parts = t.PackageFolder.Split(Path.DirectorySeparatorChar);
                        var packageName = parts[parts.Length - 1];
                        var newTriggername = packageName + "-" + t.Trigger;
                        var t1 = t;
                        LogHelper.TraceIfEnabled<ConfigurationTaskBuilder>("Found {0} config task of type {1} for package, registering it as {2}", () => t1.Trigger, () => t1.TaskType.Name, () => newTriggername);
                        //ok, we've got a task declared on a package for post package install or pre package uninstall, so need to update the trigger accordingly
                        meta.TriggerName = newTriggername;
                    }
                    else
                    {
                        //nope, this is a task declared in config that is not a package... unexpected but i guess it could happen
                        //so we just use the normal trigger that it was declared with.
                        var t1 = t;
                        LogHelper.TraceIfEnabled<ConfigurationTaskBuilder>("Found {0} config task of type {1} outside of a package", () => t1.Trigger, () => t1.TaskType.Name);
                        meta.TriggerName = t.Trigger;
                    }

                    //create a new task definition
                    var taskDefinition = new Lazy<AbstractTask, TaskMetadata>(() => task, meta);
                    //add the definition to the manager
                    ApplicationContext.FrameworkContext.TaskManager.AddTask(taskDefinition);
                }
            }
            
        }
        public override void Execute(TaskExecutionContext context)
        {
            var args = context.EventArgs.CallerEventArgs as HiveSchemaPostActionEventArgs;
            if (args != null)
            {
                var attType = args.SchemaPart as AttributeType;
                if (attType != null)
                {
                    //first refresh the code for the filter
                    RefreshCodeBlocks(attType.Id, CSharpCodeBlockType.NodeFilter);
                    //second refresh the code for the start node query
                    RefreshCodeBlocks(attType.Id, CSharpCodeBlockType.StartNodeQuery);

                }
            }
        }
示例#6
0
        public override void Execute(TaskExecutionContext context)
        {
            var controller = context.EventSource as Controller;
            if (controller != null)
            {
                Mandate.That(ConfigurationTaskContext.Parameters.ContainsKey("controllerType"), x => new ArgumentNullException("The 'controllerType' configuration parameter is required for DisplayUITask"));
                Mandate.That(ConfigurationTaskContext.Parameters.ContainsKey("action"), x => new ArgumentNullException("The 'action' configuration parameter is required for DisplayUITask"));

                var urlHelper = new UrlHelper(controller.ControllerContext.RequestContext);
                var controllerType = Type.GetType(ConfigurationTaskContext.Parameters["controllerType"]);
                if (controllerType != null)
                {
                    var url = urlHelper.GetEditorUrl(ConfigurationTaskContext.Parameters["action"], controllerType, null);
                    controller.HttpContext.Response.Redirect(url);
                }
            }
        }
        public override void Execute(TaskExecutionContext context)
        {
            if (context.TriggerName == TaskTriggers.Hive.Revisions.PostAddOrUpdateOnUnitComplete)
            {
                var uow = context.EventSource as IGroupUnit<IProviderTypeFilter>;
                var args = context.EventArgs.CallerEventArgs as HiveRevisionPostActionEventArgs;

                if (uow != null && args != null && args.Entity != null)
                {
                    var shouldInvalidate = new[] {FixedStatusTypes.Published.Alias, FixedStatusTypes.Unpublished.Alias};
                    if (shouldInvalidate.Contains(args.Entity.MetaData.StatusType.Alias))
                    {
                        Clear();
                    }
                }
            }
            if (context.TriggerName == TaskTriggers.Hive.Relations.PostRelationAdded || context.TriggerName == TaskTriggers.Hive.Relations.PostRelationRemoved)
            {
                Clear();
            }
        }
示例#8
0
        public override void Execute(TaskExecutionContext context)
        {
            //ensure the correct parameters exist
            Mandate.That(ConfigurationTaskContext.Parameters.ContainsKey("source"), x => new ArgumentNullException("The 'source' configuration parameter is required for CopyFileTask"));
            Mandate.That(ConfigurationTaskContext.Parameters.ContainsKey("destination"), x => new ArgumentNullException("The 'destination' configuration parameter is required for CopyFileTask"));
            
            //check that paths to see if they're relative
            var sourceString = ConfigurationTaskContext.Parameters["source"];
            var destString = ConfigurationTaskContext.Parameters["destination"];

            var httpContext = _httpContextResolver();

            //delegate to get the absolute path from the source or destination and checks if a relative path has been entered
            //which bases it's path on the configuration elements path.
            Func<string, string, string> getAbsolutePath = (s, packageFolder)
                        => !s.StartsWith("~/")
                            ? Path.Combine(packageFolder, s.Replace("/", "\\"))
                            : httpContext.Server.MapPath(s);

            var sourcePath = getAbsolutePath(sourceString, ConfigurationTaskContext.Task.PackageFolder);
            var destPath = getAbsolutePath(destString, ConfigurationTaskContext.Task.PackageFolder);

            //ensure the source exists
            var source = new FileInfo(sourcePath);
            Mandate.That(source.Exists, x => new FileNotFoundException("The source file " + sourceString + " could not be found"));

            //get the dest, if it exists, remove it
            var dest = new FileInfo(destPath);
            if (dest.Exists)
                dest.Delete();

            var destDir = Path.GetDirectoryName(destPath);
            if (!string.IsNullOrWhiteSpace(destDir) && !Directory.Exists(destDir))
                Directory.CreateDirectory(destDir);

            source.CopyTo(dest.FullName);            
        }
示例#9
0
 /// <summary>
 /// Executes this task instance.
 /// </summary>
 /// <remarks></remarks>
 public abstract void Execute(TaskExecutionContext context);
示例#10
0
        public JsonResult PerformInstall(bool onlyCheck)
        {

            if (!onlyCheck)
            {
                var statuses = new List<InstallStatus>();
                var context = new TaskExecutionContext(this, new TaskEventArgs(_requestContext.Application.FrameworkContext, null));
                //for each hive provider, get them to serialize their config to our xml file
                foreach (var hive in _requestContext.Application.Hive.GetAllReadWriteProviders())
                {
                    var installStatus = hive.Bootstrapper.GetInstallStatus();

                    //it needs to be configured by now,
                    if (installStatus.StatusType == InstallStatusType.Pending
                        || installStatus.StatusType == InstallStatusType.TriedAndFailed)
                    {
                        var status = hive.Bootstrapper.TryInstall();
                        statuses.Add(status);
                        //now check if was successful and see if there are some tasks to run
                        if (status.StatusType == InstallStatusType.Completed)
                        {
                            foreach (var t in status.TasksToRun)
                            {
                                t.Execute(context);
                            }
                        }
                    }
                }

                //TODO: Handle this
                ////if for some reason there's nothing been installed
                //if (statuses.Count == 0)
                //{
                //    if (!_requestContext.Application.AnyProvidersHaveStatus(InstallStatusType.Pending))
                //    {
                //        //go back to step one
                //        return RedirectToAction("Index");
                //    }
                //}


                //now, if there were no errors, then we can run the post hive install tasks
                if (!statuses.Any(x => x.StatusType == InstallStatusType.TriedAndFailed))
                {
                    context = _requestContext.Application.FrameworkContext.TaskManager.ExecuteInContext(
                        TaskTriggers.Hive.PostInstall,
                        this,
                        new TaskEventArgs(_requestContext.Application.FrameworkContext, new EventArgs()));

                }

                if (!context.Exceptions.Any())
                {
                    return Json(new
                    {
                        status = "complete",
                        message = "Installation completed!",
                        percentage = 100
                    });
                }
                else
                {
                    context.Exceptions.AddRange(statuses.Where(x => x.StatusType == InstallStatusType.TriedAndFailed).SelectMany(x => x.Errors).ToArray());

                    var errorMsg = ControllerContext.RenderPartialViewToString("Error", context.Exceptions);
                    return Json(new
                    {
                        status = "failure",
                        message = errorMsg,
                        percentage = 100,
                        fail = true
                    });

                }

            }

            return Json(new
            {
                percentage = 40
            });
        }
 /// <summary>
 /// Runs the actions for PrePackageUninstall and for the packagefoldername specific task
 /// </summary>
 /// <param name="taskExecContext"></param>
 /// <param name="packageFolderName"></param>
 internal void RunPrePackageUninstallActions(TaskExecutionContext taskExecContext, string packageFolderName)
 {
     _backOfficeRequestContext.Application.FrameworkContext.TaskManager.ExecuteInContext(TaskTriggers.PrePackageUninstall, taskExecContext);
     _backOfficeRequestContext.Application.FrameworkContext.TaskManager.ExecuteInContext(packageFolderName + "-" + TaskTriggers.PrePackageUninstall, taskExecContext);
 }
示例#12
0
 /// <summary>
 /// Executes this task instance.
 /// </summary>
 /// <remarks></remarks>
 public override void Execute(TaskExecutionContext context)
 {
     // Set the context here if it's null as sometimes we don't accept it in our constructor
     Context = Context ?? context.EventArgs.FrameworkContext;
     _callback.Invoke(context);
 }
        public override void Execute(TaskExecutionContext context)
        {
            var uow = context.EventSource as IGroupUnit<IProviderTypeFilter>;
            var args = context.EventArgs.CallerEventArgs as HiveRevisionPreActionEventArgs;
            if (uow != null && args != null)
            {
                var item = args.Entity.Item as TypedEntity;
                if (item != null && item.Attributes.Any(x => x.AttributeDefinition.Alias == NodeNameAttributeDefinition.AliasValue))
                {
                    //var siblings = uow.Repositories.GetBranchRelations(item.Id, FixedRelationTypes.DefaultRelationType)
                    //    .Select(x => x.DestinationId).ToArray();

                    //if(siblings.Length == 0)
                    //{
                    //    // Could be that it isn't saved yet
                    //    var parentsManual = item.RelationProxies.GetManualParentProxies().ToArray();
                    //    var firstManualParent = parentsManual.FirstOrDefault();
                    //    if (firstManualParent != null && !firstManualParent.Item.SourceId.IsNullValueOrEmpty())
                    //    {
                    //        var manualSiblings = uow.Repositories.GetChildRelations(firstManualParent.Item.SourceId).ToArray();
                    //        siblings = manualSiblings.Select(x => x.DestinationId).ToArray();
                    //    }
                    //}

                    //if (siblings.Length == 0)
                    //    return;

                    // Get the parent(s)
                    var parentIds = uow.Repositories.GetParentRelations(item.Id).Select(x => x.SourceId).ToArray();
                    if (!parentIds.Any())
                    {
                        parentIds = item.RelationProxies.GetManualParentProxies().Select(x => x.Item.SourceId).ToArray();
                    }

                    if (!parentIds.Any())
                        return;

                    // Establish if this is Media or Content by checking the ancestors of the parents
                    // If not, don't do anything (e.g. it might be a member / user)
                    var allowedAncestors = new[] {FixedHiveIds.ContentVirtualRoot, FixedHiveIds.MediaVirtualRoot};
                    var isContentOrMedia = false;
                    foreach (var parentId in parentIds)
                    {
                        var ancestors = uow.Repositories.GetAncestorIds(parentId, FixedRelationTypes.DefaultRelationType).ToArray();
                        if (ancestors.Any(ancestor => allowedAncestors.Any(x => x.EqualsIgnoringProviderId(ancestor))))
                        {
                            isContentOrMedia = true;
                        }
                    }

                    if (!isContentOrMedia)
                    {
                        LogHelper.TraceIfEnabled<EnsureUniqueNameTask>("Not checking for unique name as item is not a descendent of Content or Media roots");
                        return;
                    }

                    var nodeNameAttr = item.Attributes[NodeNameAttributeDefinition.AliasValue];
                    var changed = false;
                    int duplicateNumber = 0;
                    var parentQuery = uow.Repositories.WithParentIds(parentIds); //.OfRevisionType(FixedStatusTypes.Published);
                    // Replace name
                    string name = string.Empty;
                    if (nodeNameAttr.Values.ContainsKey("Name"))
                    {
                        name = nodeNameAttr.Values["Name"].ToString();

                        // Check if there are any items matching the name
                        ChangeValue(nodeNameAttr, parentQuery, item, name, "Name", " (", " (1)", " ({0})");

                        changed = true;
                    }

                    // Replace url name
                    string urlName = string.Empty;
                    if (nodeNameAttr.Values.ContainsKey("UrlName"))
                    {
                        urlName = nodeNameAttr.Values["UrlName"].ToString();

                        // Check if there are any items matching the name
                        ChangeValue(nodeNameAttr, parentQuery, item, urlName, "UrlName", "-", "-1", "-{0}");

                        //var urlName = nodeNameAttr.Values["UrlName"].ToString();
                        //while (uow.Repositories.Query().InIds(siblings)
                        //    .OfRevisionType(FixedStatusTypes.Published)
                        //    .Any(x => x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, "UrlName") == urlName &&
                        //        x.Id != item.Id))
                        //{
                        //    var urlNameMatch = _urlNamePattern.Match(urlName);
                        //    if (urlNameMatch.Success)
                        //        urlName = urlName.TrimEnd(urlNameMatch.Groups[1].Value) + (Convert.ToInt32(urlNameMatch.Groups[1].Value) + 1);
                        //    else
                        //        urlName = urlName + "-1";
                        //}

                        //nodeNameAttr.Values["UrlName"] = urlName;
                        changed = true;
                    }

                    if (changed)
                    {
                        LogHelper.TraceIfEnabled<EnsureUniqueNameTask>("Changing name of item '{0}' (url: '{1}') as it wasn't unique", () => name, () => urlName);
                        uow.Repositories.Revisions.AddOrUpdate((Revision<TypedEntity>)args.Entity);
                        // Don't commit here; we're dealing with a unit of work that is owned by someone else
                    }
                }
            }
        }