Ejemplo n.º 1
0
        public override void Execute(RecipeExecutionContext context)
        {
            if (!_authorizer.Authorize(Permissions.ImportAuditTrail)) {
                Logger.Warning("Blocked {0} from importing an audit trail because this user does not have the ImportauditTrail permission.", _wca.GetContext().CurrentUser.UserName);
                return;
            }

            var elements = context.RecipeStep.Step.Elements().ToArray();
            for (var i = 0; i < elements.Length; i ++) {
                var eventElement = elements[i];
                Logger.Information("Importing audit trail event {0}/{1}.", i + 1, elements.Length);

                try {
                    var record = new AuditTrailEventRecord {
                        EventName = eventElement.Attr<string>("Name"),
                        FullEventName = eventElement.Attr<string>("FullName"),
                        Category = eventElement.Attr<string>("Category"),
                        UserName = eventElement.Attr<string>("User"),
                        CreatedUtc = eventElement.Attr<DateTime>("CreatedUtc"),
                        EventFilterKey = eventElement.Attr<string>("EventFilterKey"),
                        EventFilterData = eventElement.Attr<string>("EventFilterData"),
                        Comment = eventElement.El("Comment"),
                        EventData = eventElement.Element("EventData").ToString(),
                    };

                    _auditTrailEventRepository.Create(record);
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while importing audit trail event {0}/{1}.", i + 1, elements.Length);
                    throw;
                }
            }
        }
Ejemplo n.º 2
0
        /*  
         <Recipes>
          <Recipe ExtensionId="Orchard.Setup" Name="Core" />
         </Recipes>
        */
        public override void Execute(RecipeExecutionContext context) {
            var recipeElements = context.RecipeStep.Step.Elements();
            var recipesDictionary = new Dictionary<string, IDictionary<string, Recipe>>();

            foreach (var recipeElement in recipeElements) {
                var extensionId = recipeElement.Attr("ExtensionId");
                var recipeName = recipeElement.Attr("Name");

                Logger.Information("Executing recipe '{0}' in extension '{1}'.", recipeName, extensionId);

                try {
                    var recipes = recipesDictionary.ContainsKey(extensionId) ? recipesDictionary[extensionId] : default(IDictionary<string, Recipe>);
                    if (recipes == null)
                        recipes = recipesDictionary[extensionId] = HarvestRecipes(extensionId);

                    if (!recipes.ContainsKey(recipeName))
                        throw new Exception(String.Format("No recipe named '{0}' was found in extension '{1}'.", recipeName, extensionId));

                    EnqueueRecipe(context.ExecutionId, recipes[recipeName]);
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while executing recipe '{0}' in extension '{1}'.", recipeName, extensionId);
                    throw;
                }
            }
        }
Ejemplo n.º 3
0
        /*
        <Aliases>
        <Alias Path="Profile/Edit" Area="Custom.Profile">
        <RouteValues>
        <Add Key="area" Value="Custom.Profile" />
        <Add Key="controller" Value="Profile" />
        <Add Key="action" Value="Edit" />
        </RouteValues>
        </Alias>
        */
        public override void Execute(RecipeExecutionContext context) {

            foreach (var aliasElement in context.RecipeStep.Step.Elements()) {
                var aliasPath = aliasElement.Attribute("Path").Value;

                Logger.Information("Importing alias '{0}'.", aliasPath);

                try {
                    var rvd = new RouteValueDictionary();

                    var routeValuesElement = aliasElement.Descendants("RouteValues").FirstOrDefault();

                    if (routeValuesElement != null) {
                        foreach (var routeValue in routeValuesElement.Descendants("Add")) {
                            rvd.Add(routeValue.Attribute("Key").Value, routeValue.Attribute("Value").Value);
                        }
                    }

                    _aliasService.Set(aliasPath, rvd, "Custom", false);
                }

                catch (Exception ex) {
                    Logger.Error(ex, "Error while processing alias '{0}'.", aliasPath);
                    throw;
                }
            }
        }
Ejemplo n.º 4
0
        /*
         {
            "name": "recipes",
            "recipes": [
                { "executionid": "Orchard.Setup", name="Core" }
            ]
         }
        */
        public override async Task ExecuteAsync(RecipeExecutionContext context)
        {
            var step = context.RecipeStep.Step.ToObject<InternalStep>();
            var recipesDictionary = new Dictionary<string, IDictionary<string, RecipeDescriptor>>();

            foreach (var recipe in step.Values)
            {
                Logger.LogInformation("Executing recipe '{0}' in extension '{1}'.", recipe.Name, recipe.ExecutionId);

                try
                {
                    var recipes = recipesDictionary.ContainsKey(recipe.ExecutionId) ? recipesDictionary[recipe.ExecutionId] : default(IDictionary<string, RecipeDescriptor>);
                    if (recipes == null)
                    {
                        recipes = recipesDictionary[recipe.ExecutionId] = HarvestRecipes(recipe.ExecutionId);
                    }

                    if (!recipes.ContainsKey(recipe.Name))
                    {
                        throw new Exception(string.Format("No recipe named '{0}' was found in extension '{1}'.", recipe.Name, recipe.ExecutionId));
                    }

                    await _recipeManager.ExecuteAsync(context.ExecutionId, recipes[recipe.Name]);
                }
                catch
                {
                    Logger.LogError("Error while executing recipe '{0}' in extension '{1}'.", recipe.Name, recipe.ExecutionId);
                    throw;
                }
            }
        }
Ejemplo n.º 5
0
        public async Task ExecuteRecipeStepAsync(RecipeContext recipeContext)
        {
            var recipeExecutionSteps = _serviceProvider.GetServices<IRecipeExecutionStep>();

            var executionStep = recipeExecutionSteps
                .FirstOrDefault(x => x.Names.Contains(recipeContext.RecipeStep.Name, StringComparer.OrdinalIgnoreCase));

            if (executionStep != null)
            {
                var recipeExecutionContext = new RecipeExecutionContext
                {
                    ExecutionId = recipeContext.ExecutionId,
                    RecipeStep = recipeContext.RecipeStep
                };

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Executing recipe step '{0}'.", recipeContext.RecipeStep.Name);
                }

                await executionStep.ExecuteAsync(recipeExecutionContext);

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Finished executing recipe step '{0}'.", recipeContext.RecipeStep.Name);
                }

                recipeContext.Executed = true;
            }
        }
Ejemplo n.º 6
0
        public override void Execute(RecipeExecutionContext context) {
            var installedPermissions = _roleService.GetInstalledPermissions().SelectMany(p => p.Value).ToList();

            foreach (var roleElement in context.RecipeStep.Step.Elements()) {
                var roleName = roleElement.Attribute("Name").Value;

                Logger.Information("Importing role '{0}'.", roleName);

                try {
                    var role = _roleService.GetRoleByName(roleName);
                    if (role == null) {
                        _roleService.CreateRole(roleName);
                        role = _roleService.GetRoleByName(roleName);
                    }

                    var permissions = roleElement.Attribute("Permissions").Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    // Only import permissions for currenlty installed modules.
                    var permissionsValid = permissions.Where(permission => installedPermissions.Any(x => x.Name == permission)).ToList();

                    // Union to keep existing permissions.
                    _roleService.UpdateRole(role.Id, role.Name, permissionsValid.Union(role.RolesPermissions.Select(p => p.Permission.Name)));
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while importing role '{0}'.", roleName);
                    throw;
                }
            }
        }
Ejemplo n.º 7
0
        /*  
         <Settings>
          <SiteSettingsPart PageSize="30" />
          <CommentSettingsPart ModerateComments="true" />
         </Settings>
        */
        // Set site and part settings.
        public override void Execute(RecipeExecutionContext context) {
            var siteContentItem = _siteService.GetSiteSettings().ContentItem;
            var importContentSession = new ImportContentSession(_contentManager);
            var importContentContext = new ImportContentContext(siteContentItem, context.RecipeStep.Step, importContentSession);

            foreach (var contentHandler in Handlers) {
                contentHandler.Importing(importContentContext);
            }

            foreach (var contentPart in siteContentItem.Parts) {
                var partElement = importContentContext.Data.Element(contentPart.PartDefinition.Name);
                if (partElement == null) {
                    continue;
                }

                Logger.Information("Importing settings part '{0}'.", contentPart.PartDefinition.Name);
                try {
                    ImportSettingPart(contentPart, partElement);
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while importing settings part '{0}'.", contentPart.PartDefinition.Name);
                    throw;
                }
            }

            foreach (var contentHandler in Handlers) {
                contentHandler.Imported(importContentContext);
            }
        }
Ejemplo n.º 8
0
        public override void Execute(RecipeExecutionContext context) {
            foreach (var rule in context.RecipeStep.Step.Elements()) {
                var ruleName = rule.Attribute("Name").Value;
                Logger.Information("Importing rule '{0}'.", ruleName);

                try {
                    var ruleRecord = _rulesServices.CreateRule(ruleName);
                    ruleRecord.Enabled = bool.Parse(rule.Attribute("Enabled").Value);

                    ruleRecord.Actions = rule.Element("Actions").Elements().Select(action =>
                        new ActionRecord {
                            Type = action.Attribute("Type").Value,
                            Category = action.Attribute("Category").Value,
                            Position = int.Parse(action.Attribute("Position").Value),
                            Parameters = action.Attribute("Parameters").Value,
                            RuleRecord = ruleRecord
                        }).ToList();

                    ruleRecord.Events = rule.Element("Events").Elements().Select(action =>
                        new EventRecord {
                            Type = action.Attribute("Type").Value,
                            Category = action.Attribute("Category").Value,
                            Parameters = action.Attribute("Parameters").Value,
                            RuleRecord = ruleRecord
                        }).ToList();
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while importing rule '{0}'.", ruleName);
                    throw;
                }
            }
        }
Ejemplo n.º 9
0
        // <Module packageId="module1" [repository="somerepo"] version="1.1" />
        // Install modules from feed.
        public override void Execute(RecipeExecutionContext context) {
            string packageId = null, version = null, repository = null;
            foreach (var attribute in context.RecipeStep.Step.Attributes()) {
                if (String.Equals(attribute.Name.LocalName, "packageId", StringComparison.OrdinalIgnoreCase)) {
                    packageId = attribute.Value;
                }
                else if (String.Equals(attribute.Name.LocalName, "version", StringComparison.OrdinalIgnoreCase)) {
                    version = attribute.Value;
                }
                else if (String.Equals(attribute.Name.LocalName, "repository", StringComparison.OrdinalIgnoreCase)) {
                    repository = attribute.Value;
                }
                else {
                    throw new InvalidOperationException(String.Format("Unrecognized attribute {0} encountered in step Module.", attribute.Name.LocalName));
                }
            }

            if (packageId == null) {
                throw new InvalidOperationException("PackageId is required in a module declaration in a recipe file.");
            }

            // download and install module from the orchard feed or a custom feed if repository is specified.
            var enforceVersion = version != null;
            var installed = false;
            PackagingEntry packagingEntry = null;

            var packagingSource = _packagingSourceManager.GetSources().FirstOrDefault();
            if (repository != null) {
                packagingSource = new PackagingSource {FeedTitle = repository, FeedUrl = repository};
            }

            if (enforceVersion) {
                packagingEntry = _packagingSourceManager.GetExtensionList(false, packagingSource, 
                    packages => packages.Where(package => 
                        package.PackageType.Equals(DefaultExtensionTypes.Module) && 
                        package.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) && 
                        package.Version.Equals(version, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
            }
            else {
                packagingEntry = _packagingSourceManager.GetExtensionList(false, packagingSource, 
                    packages => packages.Where(package => 
                        package.PackageType.Equals(DefaultExtensionTypes.Module) && 
                        package.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) && 
                        package.IsLatestVersion)).FirstOrDefault();
            }

            if (packagingEntry != null) {
                if (!ModuleAlreadyInstalled(packagingEntry.PackageId)) {
                    Logger.Information("Installing module {0}.", packagingEntry.Title);
                    _packageManager.Install(packagingEntry.PackageId, packagingEntry.Version, packagingSource.FeedUrl, HostingEnvironment.MapPath("~/")); 
                }
                installed = true;
            }

            if (!installed) {
                throw new InvalidOperationException(String.Format("Module {0} was not found in the specified location.", packageId));
            }
        }
Ejemplo n.º 10
0
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            var executionStep = _recipeExecutionSteps.FirstOrDefault(x => x.Names.Contains(recipeContext.RecipeStep.Name));
            var recipeExecutionContext = new RecipeExecutionContext {ExecutionId = recipeContext.ExecutionId, RecipeStep = recipeContext.RecipeStep};

            if (executionStep != null) {
                Logger.Information("Executing recipe step '{0}'.", recipeContext.RecipeStep.Name);
                executionStep.Execute(recipeExecutionContext);
                Logger.Information("Finished executing recipe step '{0}'.", recipeContext.RecipeStep.Name);
                recipeContext.Executed = true;
            }
        }
Ejemplo n.º 11
0
 // <Data />
 // Import Data.
 public override void Execute(RecipeExecutionContext context) {
     // Run the import.
     BatchedInvoke(context, "Import", (itemId, nextIdentityValue, element, importContentSession, elementDictionary) => {
         _orchardServices.ContentManager.Import(element, importContentSession);
     });
     
     // Invoke ImportCompleted.
     BatchedInvoke(context, "ImportCompleted", (itemId, nextIdentityValue, element, importContentSession, elementDictionary) => {
         _orchardServices.ContentManager.CompleteImport(element, importContentSession);
     });
 }
Ejemplo n.º 12
0
        public override void Execute(RecipeExecutionContext context) {
            var themeId = context.RecipeStep.Step.Attribute("id").Value;
            Logger.Information("Setting site theme to '{0}'.", themeId);

            try {
                _siteThemeService.SetSiteTheme(themeId);
            }
            catch (Exception ex) {
                Logger.Error(ex, "Error while setting site theme to '{0}'.", themeId);
                throw;
            }
        }
Ejemplo n.º 13
0
        public override void Execute(RecipeExecutionContext context) {
            var root = context.RecipeStep.Step;
            var homePageIdentifier = root.Attr("Id");
            var homePageIdentity = !String.IsNullOrWhiteSpace(homePageIdentifier) ? new ContentIdentity(homePageIdentifier) : default(ContentIdentity);
            var homePage = homePageIdentity != null ? _contentManager.ResolveIdentity(homePageIdentity) : default(ContentItem);

            if (homePage != null)
                _homeAliasService.PublishHomeAlias(homePage);
            else {
                var routeValueDictionary = root.Elements().ToDictionary(x => x.Name.LocalName.ToLower(), x => (object) x.Value);
                _homeAliasService.PublishHomeAlias(new RouteValueDictionary(routeValueDictionary));
            }
        }
Ejemplo n.º 14
0
        public override async Task ExecuteAsync(RecipeExecutionContext recipeContext)
        {
            var model = recipeContext.RecipeStep.Step.ToObject<ThemeStepModel>();

            if (!String.IsNullOrEmpty(model.Site))
            {
                await _siteThemeService.SetSiteThemeAsync(model.Site);
            }

            if (!String.IsNullOrEmpty(model.Admin))
            {
                await _adminThemeService.SetAdminThemeAsync(model.Admin);
            }
        }
Ejemplo n.º 15
0
        public override void Execute(RecipeExecutionContext context) {
            foreach (var workflowDefinitionElement in context.RecipeStep.Step.Elements()) {
                var workflowName = workflowDefinitionElement.Attribute("Name").Value;
                Logger.Information("Importing workflow '{0}'.", workflowName);

                try {
                    var workflowDefinition = GetOrCreateWorkflowDefinition(workflowName);
                    var activitiesElement = workflowDefinitionElement.Element("Activities");
                    var transitionsElement = workflowDefinitionElement.Element("Transitions");
                    var activitiesDictionary = new Dictionary<int, ActivityRecord>();

                    workflowDefinition.Enabled = Boolean.Parse(workflowDefinitionElement.Attribute("Enabled").Value);

                    foreach (var activityElement in activitiesElement.Elements()) {
                        var localId = Int32.Parse(activityElement.Attribute("Id").Value);
                        var activityName = activityElement.Attribute("Name").Value;
                        Logger.Information("Importing activity '{0}' with ID '{1}'.", activityName, localId);
                        var activity = new ActivityRecord {
                            Name = activityName,
                            Start = Boolean.Parse(activityElement.Attribute("Start").Value),
                            X = Int32.Parse(activityElement.Attribute("X").Value),
                            Y = Int32.Parse(activityElement.Attribute("Y").Value),
                            State = activityElement.Element("State").Value
                        };

                        activitiesDictionary.Add(localId, activity);
                        workflowDefinition.ActivityRecords.Add(activity);
                    }

                    foreach (var transitionElement in transitionsElement.Elements()) {
                        var sourceActivityId = Int32.Parse(transitionElement.Attribute("SourceActivityId").Value);
                        var sourceEndpoint = transitionElement.Attribute("SourceEndpoint").Value;
                        var destinationActivityId = Int32.Parse(transitionElement.Attribute("DestinationActivityId").Value);
                        var destinationEndpoint = transitionElement.Attribute("DestinationEndpoint").Value;
                        Logger.Information("Importing transition between activities '{0}' and '{1}'.", sourceActivityId, destinationActivityId);

                        workflowDefinition.TransitionRecords.Add(new TransitionRecord {
                            SourceActivityRecord = activitiesDictionary[sourceActivityId],
                            SourceEndpoint = sourceEndpoint,
                            DestinationActivityRecord = activitiesDictionary[destinationActivityId],
                            DestinationEndpoint = destinationEndpoint
                        });
                    }
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while importing workflow '{0}'.", workflowName);
                    throw;
                }
            }
        }
Ejemplo n.º 16
0
        /* 
           <ContentDefinition>
            <Types>
             <Blog creatable="true">
              <Body format="abodyformat"/>
             </Blog>
            </Types>
            <Parts>
            </Parts>
           </ContentDefinition>
         */
        // Set type settings and attach parts to types.
        // Create dynamic parts.
        public override void Execute(RecipeExecutionContext context) {
            foreach (var metadataElement in context.RecipeStep.Step.Elements()) {
                Logger.Debug("Processing element '{0}'.", metadataElement.Name.LocalName);
                switch (metadataElement.Name.LocalName) {
                    case "Types":
                        foreach (var element in metadataElement.Elements()) {
                            var typeElement = element;
                            var typeName = XmlConvert.DecodeName(element.Name.LocalName);

                            Logger.Information("Importing content type '{0}'.", typeName);
                            try {
                                _contentDefinitonEventHandlers.ContentTypeImporting(new ContentTypeImportingContext { ContentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(typeName), ContentTypeName = typeName });
                                _contentDefinitionManager.AlterTypeDefinition(typeName, alteration => _contentDefinitionReader.Merge(typeElement, alteration));
                                _contentDefinitonEventHandlers.ContentTypeImported(new ContentTypeImportedContext { ContentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(typeName) });
                            }
                            catch (Exception ex) {
                                Logger.Error(ex, "Error while importing content type '{0}'.", typeName);
                                throw;
                            }
                        }
                        break;

                    case "Parts":
                        foreach (var element in metadataElement.Elements()) {
                            var partElement = element;
                            var partName = XmlConvert.DecodeName(element.Name.LocalName);

                            Logger.Information("Importing content part '{0}'.", partName);
                            try {
                                _contentDefinitonEventHandlers.ContentPartImporting(new ContentPartImportingContext { ContentPartDefinition = _contentDefinitionManager.GetPartDefinition(partName), ContentPartName = partName });
                            _contentDefinitionManager.AlterPartDefinition(partName, alteration => _contentDefinitionReader.Merge(partElement, alteration));
                            _contentDefinitonEventHandlers.ContentPartImported(new ContentPartImportedContext { ContentPartDefinition = _contentDefinitionManager.GetPartDefinition(partName)});
                            }
                            catch (Exception ex) {
                                Logger.Error(ex, "Error while importing content part '{0}'.", partName);
                                throw;
                            }
                        }
                        break;

                    default:
                        Logger.Warning("Unrecognized element '{0}' encountered; skipping", metadataElement.Name.LocalName);
                        break;
                }
            }
        }
Ejemplo n.º 17
0
        // <RemoveContent>
        //   <Page Id="{identifier}" />
        //   <BlogPost Id="{identifier}" />
        //   ...
        // </RemoveContent>
        public override void Execute(RecipeExecutionContext context) {
            var identitiesQuery =
                from element in context.RecipeStep.Step.Elements()
                let id = element.Attr("Id")
                where !String.IsNullOrWhiteSpace(id)
                select new ContentIdentity(id);

            foreach (var identity in identitiesQuery) {
                Logger.Information("Removing content item with identity '{0}'...", identity);
                var contentItem = _contentManager.ResolveIdentity(identity);

                if (contentItem == null) {
                    Logger.Warning("No content item with identity '{0}' could be found.", identity);
                    continue;
                }

                _contentManager.Remove(contentItem);
                Logger.Information("Content item with identity '{0}' was found with id '{1}' and has been successfully removed.", identity, contentItem.Id);
            }
        }
Ejemplo n.º 18
0
        public override void Execute(RecipeExecutionContext context)
        {
            foreach (var elementElement in context.RecipeStep.Step.Elements()) {
                var typeName = elementElement.Attribute("ElementTypeName").Value;
                Logger.Information("Importing custom element '{0}'.", typeName);

                try {
                    var element = GetOrCreateElement(typeName);
                    element.BaseElementTypeName = elementElement.Attribute("BaseElementTypeName").Value;
                    element.ElementDisplayName = elementElement.Attribute("ElementDisplayName").Value;
                    element.ElementDescription = elementElement.Attribute("ElementDescription").Value;
                    element.ElementCategory = elementElement.Attribute("ElementCategory").Value;
                    element.BaseElementState = elementElement.Element("BaseElementState").Value;
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while importing custom element '{0}'.", typeName);
                    throw;
                }
            }
        }
Ejemplo n.º 19
0
        public override async Task ExecuteAsync(RecipeExecutionContext recipeContext)
        {
            var step = recipeContext.RecipeStep.Step.ToObject<InternalStep>();

            var availableFeatures = _featureManager.GetAvailableFeaturesAsync().Result.Select(x => x.Id).ToArray();
            foreach (var featureName in step.Disable)
            {
                if (!availableFeatures.Contains(featureName))
                {
                    throw new InvalidOperationException(string.Format("Could not disable feature {0} because it was not found.", featureName));
                }
            }

            foreach (var featureName in step.Enable)
            {
                if (!availableFeatures.Contains(featureName))
                {
                    throw new InvalidOperationException(string.Format("Could not enable feature {0} because it was not found.", featureName));
                }
            }

            if (step.Disable.Any())
            {
                if (Logger.IsEnabled(LogLevel.Information))
                {
                    Logger.LogInformation("Disabling features: {0}", string.Join(";", step.Disable));
                }

                await _featureManager.DisableFeaturesAsync(step.Disable, true);
            }

            if (step.Enable.Any())
            {
                if (Logger.IsEnabled(LogLevel.Information))
                {
                    Logger.LogInformation("Enabling features: {0}", string.Join(";", step.Enable));
                }

                await _featureManager.EnableFeaturesAsync(step.Enable, true);
            }
        }
Ejemplo n.º 20
0
        /*
         <Command>
            command1
            command2
            command3
         </Command>
        */
        // Run Orchard commands.
        public override void Execute(RecipeExecutionContext context)
        {
            var commands =
                context.RecipeStep.Step.Value
                .Split(new[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries)
                .Select(commandEntry => commandEntry.Trim());

            foreach (var command in commands) {
                if (!String.IsNullOrEmpty(command)) {
                    Logger.Information("Executing command: {0}", command);
                    try {
                        var commandParameters = _commandParser.ParseCommandParameters(command);
                        var input = new StringReader("");
                        var output = new StringWriter();
                        _commandManager.Execute(new CommandParameters { Arguments = commandParameters.Arguments, Input = input, Output = output, Switches = commandParameters.Switches });
                    }
                    catch (Exception ex) {
                        Logger.Error(ex, "Error while executing command: {0}", command);
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 21
0
        // <Migration features="f1, f2" /> 
        // <Migration features="*" />
        // Run migration for features.
        public override void Execute(RecipeExecutionContext context) {
            var runAll = false;
            var features = new List<string>();
            foreach (var attribute in context.RecipeStep.Step.Attributes()) {
                if (String.Equals(attribute.Name.LocalName, "features", StringComparison.OrdinalIgnoreCase)) {
                    features = ParseFeatures(attribute.Value);
                    if (features.Contains("*"))
                        runAll = true;
                }
                else {
                    Logger.Warning("Unrecognized attribute '{0}' encountered; skipping.", attribute.Name.LocalName);
                }
            }

            if (runAll) {
                foreach (var feature in _dataMigrationManager.GetFeaturesThatNeedUpdate()) {
                    Logger.Information("Updating feature '{0}'.", feature);
                    try {
                        _dataMigrationManager.Update(feature);
                    }
                    catch (Exception ex) {
                        Logger.Error(ex, "Error while updating feature '{0}'", feature);
                        throw;
                    }
                }
            }
            else {
                Logger.Information("Updating features: {0}", String.Join(";", features));
                try {
                    _dataMigrationManager.Update(features);
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while updating features: {0}", String.Join(";", features));
                    throw;
                }
            }
        }
Ejemplo n.º 22
0
        // <Feature enable="f1,f2,f3" disable="f4" />
        // Enable/Disable features.
        public override void Execute(RecipeExecutionContext recipeContext) {
            var featuresToEnable = new List<string>();
            var featuresToDisable = new List<string>();
            foreach (var attribute in recipeContext.RecipeStep.Step.Attributes()) {
                if (String.Equals(attribute.Name.LocalName, "disable", StringComparison.OrdinalIgnoreCase)) {
                    featuresToDisable = ParseFeatures(attribute.Value);
                }
                else if (String.Equals(attribute.Name.LocalName, "enable", StringComparison.OrdinalIgnoreCase)) {
                    featuresToEnable = ParseFeatures(attribute.Value);
                }
                else {
                    Logger.Warning("Unrecognized attribute '{0}' encountered; skipping", attribute.Name.LocalName);
                }
            }

            var availableFeatures = _featureManager.GetAvailableFeatures().Select(x => x.Id).ToArray();
            foreach (var featureName in featuresToDisable) {
                if (!availableFeatures.Contains(featureName)) {
                    throw new InvalidOperationException(string.Format("Could not disable feature {0} because it was not found.", featureName));
                }
            }

            foreach (var featureName in featuresToEnable) {
                if (!availableFeatures.Contains(featureName)) {
                    throw new InvalidOperationException(string.Format("Could not enable feature {0} because it was not found.", featureName));
                }
            }

            if (featuresToDisable.Any()) {
                Logger.Information("Disabling features: {0}", String.Join(";", featuresToDisable));
                _featureManager.DisableFeatures(featuresToDisable, true);
            }
            if (featuresToEnable.Any()) {
                Logger.Information("Enabling features: {0}", String.Join(";", featuresToEnable));
                _featureManager.EnableFeatures(featuresToEnable, true);
            }
        }
Ejemplo n.º 23
0
        public override void Execute(RecipeExecutionContext context) {
            var formElements = context.RecipeStep.Step.Elements();
            foreach (var formElement in formElements) {
                var formName = formElement.Attr<string>("Name");
                Logger.Information("Importing form '{0}'.", formName);

                try {
                    var submissionElements = formElement.Element("Submissions").Elements().ToArray();
                    for (var i = 0; i < submissionElements.Length; i++) {
                        Logger.Information("Importing form submission {0}/{1}.", i + 1, submissionElements.Length);
                        var submissionElement = submissionElements[i];
                        _formService.CreateSubmission(new Submission {
                            FormName = formName,
                            CreatedUtc = submissionElement.Attr<DateTime>("CreatedUtc"),
                            FormData = submissionElement.Value
                        });
                    }
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while importing form '{0}'.", formName);
                    throw;
                }
            }
        }
Ejemplo n.º 24
0
        private void BatchedInvoke(RecipeExecutionContext context, string batchLabel, Action<string, string, XElement, ImportContentSession, IDictionary<string, XElement>> contentItemAction) {
            var importContentSession = new ImportContentSession(_orchardServices.ContentManager);

            // Populate local dictionary with elements and their ids.
            var elementDictionary = CreateElementDictionary(context.RecipeStep.Step);

            // Populate import session with all identities to be imported.
            foreach (var identity in elementDictionary.Keys) {
                importContentSession.Set(identity, elementDictionary[identity].Name.LocalName);
            }

            // Determine if the import is to be batched in multiple transactions.
            var batchSize = GetBatchSizeForDataStep(context.RecipeStep.Step);
            var startIndex = 0;
            var itemIndex = 0;

            Logger.Debug("Using batch size {0} for '{1}'.", batchSize, batchLabel);

            try {
                while (startIndex < elementDictionary.Count) {
                    Logger.Debug("Batch '{0}' execution starting at index {1}.", batchLabel, startIndex);
                    importContentSession.InitializeBatch(startIndex, batchSize);

                    // The session determines which items are included in the current batch
                    // so that dependencies can be managed within the same transaction.
                    var nextIdentity = importContentSession.GetNextInBatch();
                    while (nextIdentity != null) {
                        var itemId = "";
                        var nextIdentityValue = nextIdentity.ToString();
                        if (elementDictionary[nextIdentityValue].HasAttributes) {
                            itemId = elementDictionary[nextIdentityValue].FirstAttribute.Value;
                        }
                        Logger.Information("Handling content item '{0}' (item {1}/{2} of '{3}').", itemId, itemIndex + 1, elementDictionary.Count, batchLabel);
                        try {
                            contentItemAction(itemId, nextIdentityValue, elementDictionary[nextIdentityValue], importContentSession, elementDictionary);
                        }
                        catch (Exception ex) {
                            Logger.Error(ex, "Error while handling content item '{0}' (item {1}/{2} of '{3}').", itemId, itemIndex + 1, elementDictionary.Count, batchLabel);
                            throw;
                        }
                        itemIndex++;
                        nextIdentity = importContentSession.GetNextInBatch();
                    }

                    startIndex += batchSize;

                    // Create a new transaction for each batch.
                    if (startIndex < elementDictionary.Count) {
                        _transactionManager.RequireNew();
                    }

                    Logger.Debug("Finished batch '{0}' starting at index {1}.", batchLabel, startIndex);
                }
            }
            catch (Exception) {
                // Ensure a failed batch is rolled back.
                _transactionManager.Cancel();
                throw;
            }
        }
Ejemplo n.º 25
0
        public void ExecuteRecipeStepTest() {
            _folders.Manifests.Add("SuperWiki", @"
Name: SuperWiki
Version: 1.0.3
OrchardVersion: 1
Features:
    SuperWiki: 
        Description: My super wiki theme for Orchard.
");
            _packagesInRepository.AddPublishedPackage(new PublishedPackage {
                Id = "Orchard.Theme.SuperWiki",
                PackageType = DefaultExtensionTypes.Theme,
                Title = "SuperWiki",
                Version = "1.0.3",
                IsLatestVersion = true,
            });

            IShellDescriptorManager shellDescriptorManager = _container.Resolve<IShellDescriptorManager>();
            // No features enabled.
            shellDescriptorManager.UpdateShellDescriptor(0,
                                                         Enumerable.Empty<ShellFeature>(),
                                                         Enumerable.Empty<ShellParameter>());

            var themeStep = _container.Resolve<ThemeStep>();
            var recipeExecutionContext = new RecipeExecutionContext {RecipeStep = new RecipeStep (id: "1", recipeName: "Test", name: "Theme", step: new XElement("SuperWiki")) };

            recipeExecutionContext.RecipeStep.Step.Add(new XAttribute("packageId", "Orchard.Theme.SuperWiki"));
            recipeExecutionContext.RecipeStep.Step.Add(new XAttribute("repository", "test"));

            var featureManager = _container.Resolve<IFeatureManager>();
            var enabledFeatures = featureManager.GetEnabledFeatures();
            Assert.That(enabledFeatures.Count(), Is.EqualTo(0));
            themeStep.Execute(recipeExecutionContext);

            // Without setting enable no feature should be activated...
            featureManager.GetEnabledFeatures();
            Assert.That(enabledFeatures.Count(), Is.EqualTo(0));

            // Adding enable the feature should get active.
            recipeExecutionContext.RecipeStep.Step.Add(new XAttribute("enable", true));
            themeStep.Execute(recipeExecutionContext);

            enabledFeatures = featureManager.GetEnabledFeatures();
            Assert.That(enabledFeatures.FirstOrDefault(feature => feature.Id.Equals("SuperWiki")), Is.Not.Null);
            Assert.That(enabledFeatures.Count(), Is.EqualTo(1));
        }
Ejemplo n.º 26
0
        public void ExecuteRecipeStepWithRepositoryAndVersionNotLatestTest() {
            _packagesInRepository.AddPublishedPackage(new PublishedPackage {
                Id = "Orchard.Theme.SuperWiki",
                PackageType = DefaultExtensionTypes.Theme,
                Title = "SuperWiki",
                Version = "1.0.3",
                IsLatestVersion = true,
            });
            _packagesInRepository.AddPublishedPackage(new PublishedPackage {
                Id = "Orchard.Theme.SuperWiki",
                PackageType = DefaultExtensionTypes.Theme,
                Title = "SuperWiki",
                Version = "1.0.2",
                IsLatestVersion = false,
            });

            var themeStep = _container.Resolve<ThemeStep>();
            var recipeExecutionContext = new RecipeExecutionContext { RecipeStep = new RecipeStep(id: "1", recipeName: "Test", name: "Theme", step: new XElement("SuperWiki")) };

            recipeExecutionContext.RecipeStep.Step.Add(new XAttribute("packageId", "Orchard.Theme.SuperWiki"));
            recipeExecutionContext.RecipeStep.Step.Add(new XAttribute("repository", "test"));
            recipeExecutionContext.RecipeStep.Step.Add(new XAttribute("version", "1.0.2"));

            themeStep.Execute(recipeExecutionContext);

            var installedPackage = _packageManager.GetInstalledPackages().FirstOrDefault(info => info.ExtensionName == "Orchard.Theme.SuperWiki");
            Assert.That(installedPackage, Is.Not.Null);
            Assert.That(installedPackage.ExtensionVersion, Is.EqualTo("1.0.2"));
        }
Ejemplo n.º 27
0
        public void ExecuteRecipeStepNeedsNameTest() {
            _folders.Manifests.Add("SuperWiki", @"
Name: SuperWiki
Version: 1.0.3
OrchardVersion: 1
Features:
    SuperWiki: 
        Description: My super wiki module for Orchard.
");

            var themeStep = _container.Resolve<ThemeStep>();
            var recipeExecutionContext = new RecipeExecutionContext { RecipeStep = new RecipeStep(id: "1", recipeName: "Test", name: "Theme", step: new XElement("SuperWiki")) };

            recipeExecutionContext.RecipeStep.Step.Add(new XAttribute("repository", "test"));
            Assert.Throws(typeof (InvalidOperationException), () => themeStep.Execute(recipeExecutionContext));
        }
Ejemplo n.º 28
0
 public override void Execute(RecipeExecutionContext context)
 {
     _sweepGenerator.Activate();
 }
Ejemplo n.º 29
0
 public abstract void Execute(RecipeExecutionContext context);
Ejemplo n.º 30
0
        public override async Task ExecuteAsync(RecipeExecutionContext recipeContext)
        {
            var model = recipeContext.RecipeStep.Step;
            var site = await _siteService.GetSiteSettingsAsync();

            if (model["BaseUrl"] != null)
            {
                site.BaseUrl = model["BaseUrl"].ToString();
            }

            if (model["Calendar"] != null)
            {
                site.Calendar = model["Calendar"].ToString();
            }

            if (model["Culture"] != null)
            {
                site.Culture = model["Culture"].ToString();
            }

            if (model["MaxPagedCount"] != null)
            {
                site.MaxPagedCount = model.Value<int>("MaxPagedCount");
            }

            if (model["MaxPageSize"] != null)
            {
                site.MaxPageSize = model.Value<int>("MaxPageSize");
            }

            if (model["PageSize"] != null)
            {
                site.PageSize = model.Value<int>("PageSize");
            }

            if (model["PageTitleSeparator"] != null)
            {
                site.PageTitleSeparator = model["PageTitleSeparator"].ToString();
            }

            if (model["ResourceDebugMode"] != null)
            {
                site.ResourceDebugMode = model.Value<ResourceDebugMode>("ResourceDebugMode");
            }

            if (model["SiteName"] != null)
            {
                site.SiteName = model["SiteName"].ToString();
            }

            if (model["SiteSalt"] != null)
            {
                site.SiteSalt = model["SiteSalt"].ToString();
            }

            if (model["SuperUser"] != null)
            {
                site.SuperUser = model["SuperUser"].ToString();
            }

            if (model["TimeZone"] != null)
            {
                site.TimeZone = model["TimeZone"].ToString();
            }

            if (model["UseCdn"] != null)
            {
                site.UseCdn = model.Value<bool>("UseCdn");
            }

            if (model["HomeRoute"] != null)
            {
                site.HomeRoute = model["HomeRoute"].ToObject<RouteValueDictionary>();
            }

            await _siteService.UpdateSiteSettingsAsync(site);
        }