public void ExecuteRecipeStep(RecipeContext recipeContext)
        {
            if (!String.Equals(recipeContext.RecipeStep.Name, SitemapCustomExportStep.ExportStep, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var stepElement = recipeContext.RecipeStep.Step;

            var indexingElement = stepElement.Element("Indexing");
            if (indexingElement != null)
            {
                var indexSettingsModels = indexingElement.Elements("Index").Select(element => new IndexSettingsModel
                {
                    Name = element.Attribute("Name").Value,
                    DisplayName = element.Attribute("DisplayName").Value,
                    IndexForDisplay = Convert.ToBoolean(element.Attribute("IndexForDisplay").Value),
                    IndexForXml = Convert.ToBoolean(element.Attribute("IndexForXml").Value),
                    Priority = Convert.ToInt32(element.Attribute("Priority").Value),
                    UpdateFrequency = element.Attribute("UpdateFrequency").Value
                });

                _sitemapService.SetIndexSettings(indexSettingsModels);
            }

            var customRoutesElement = stepElement.Element("CustomRoutes");
            if (customRoutesElement != null)
            {
                var customRouteModels = customRoutesElement.Elements("CustomRoute").Select(element => new CustomRouteModel
                {
                    Name = element.Attribute("Name").Value,
                    IndexForDisplay = Convert.ToBoolean(element.Attribute("IndexForDisplay").Value),
                    IndexForXml = Convert.ToBoolean(element.Attribute("IndexForXml").Value),
                    Priority = Convert.ToInt32(element.Attribute("Priority").Value),
                    UpdateFrequency = element.Attribute("UpdateFrequency").Value,
                    Url = element.Attribute("Url").Value
                });

                _sitemapService.SetCustomRoutes(customRouteModels);
            }

            var displayRoutesElement = stepElement.Element("DisplayRoutes");
            if (displayRoutesElement != null)
            {
                var routeSettingsModels = displayRoutesElement.Elements("DisplayRoute").Select(element => new RouteSettingsModel
                {
                    Name = element.Attribute("Name").Value,
                    Id = Convert.ToInt32(element.Attribute("Id").Value),
                    Active = Convert.ToBoolean(element.Attribute("Active").Value),
                    DisplayColumn = Convert.ToInt32(element.Attribute("DisplayColumn").Value),
                    DisplayLevels = Convert.ToInt32(element.Attribute("DisplayLevels").Value),
                    Slug = element.Attribute("Slug").Value,
                    Weight = Convert.ToInt32(element.Attribute("Weight").Value),
                });

                _sitemapService.SetRoutes(routeSettingsModels);
            }

            recipeContext.Executed = true;
        }
        /*
          <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>
         */
        //Enable any features that are in the list, disable features that aren't in the list
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Aliases", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var aliasElements = recipeContext.RecipeStep.Step.Descendants("Alias");

            foreach (var aliasElement in aliasElements) {
                var path = aliasElement.Attribute("Path").Value;
                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(path, rvd, "Custom");
            }

            //remove all local pathys that are not present in the remote export
            var allRemotePaths = recipeContext.RecipeStep.Step.XPathSelectElements("Paths/Add").Select(e => e.Attribute("Path").Value);
            var allLocalPaths = _aliasService.List().Select(t=> t.Item1).ToList();

            foreach (var path in allLocalPaths.Where(p=>!allRemotePaths.Contains(p)))
            {
                _aliasService.Delete(path);
            }


            recipeContext.Executed = true;
        }
Example #3
0
        public bool ExecuteNextStep(string executionId) {
            var nextRecipeStep= _recipeStepQueue.Dequeue(executionId);
            if (nextRecipeStep == null) {
                _recipeJournal.ExecutionComplete(executionId);
                return false;
            }
            _recipeJournal.WriteJournalEntry(executionId, string.Format("Executing step {0}.", nextRecipeStep.Name));
            var recipeContext = new RecipeContext { RecipeStep = nextRecipeStep, Executed = false };
            try {
                foreach (var recipeHandler in _recipeHandlers) {
                    recipeHandler.ExecuteRecipeStep(recipeContext);
                }
            }
            catch(Exception exception) {
                Logger.Error(exception, "Recipe execution {0} was cancelled because a step failed to execute", executionId);
                while (_recipeStepQueue.Dequeue(executionId) != null) ;
                _recipeJournal.ExecutionFailed(executionId);
                throw new OrchardCoreException(T("Recipe execution with id {0} was cancelled because the \"{1}\" step failed to execute. The following exception was thrown: {2}. Refer to the recipe journal for more information.", 
                    executionId, nextRecipeStep.Name, exception.Message));
            }

            if (!recipeContext.Executed) {
                Logger.Error("Could not execute recipe step '{0}' because the recipe handler was not found.", recipeContext.RecipeStep.Name);
                while (_recipeStepQueue.Dequeue(executionId) != null) ;
                _recipeJournal.ExecutionFailed(executionId);
                throw new OrchardCoreException(T("Recipe execution with id {0} was cancelled because the recipe handler for step \"{1}\" was not found. Refer to the recipe journal for more information.",
                    executionId, nextRecipeStep.Name));
            }

            return true;
        }
Example #4
0
        // <Data />
        // Import Data
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Data", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            // First pass to resolve content items from content identities for all content items, new and old.
            var importContentSession = new ImportContentSession(_orchardServices.ContentManager);
            foreach (var element in recipeContext.RecipeStep.Step.Elements()) {
                var elementId = element.Attribute("Id");
                if (elementId == null)
                    continue;

                var identity = elementId.Value;
                var status = element.Attribute("Status");
                
                importContentSession.Set(identity, element.Name.LocalName);
                
                var item = importContentSession.Get(identity);
            }

            // Second pass to import the content items.
            foreach (var element in recipeContext.RecipeStep.Step.Elements()) {
                _orchardServices.ContentManager.Import(element, importContentSession);
            }

            recipeContext.Executed = true;
        }
        /*
          <EnabledFeatures>
            <Feature Id="Orchard.ImportExport" />
         */
        //Enable any features that are in the list, disable features that aren't in the list
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "FeatureSync", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var features = recipeContext.RecipeStep.Step.Descendants();
            var featureIds = features.Where(f => f.Name == "Feature").Select(f => f.Attribute("Id").Value).ToList();

            //we now have the list of features that are enabled on the remote site
            //next thing to do is add and remove features to and from this list based on our feature redactions
            var featureRedactions = _featureRedactionService.GetRedactions().ToList();

            featureIds.AddRange(featureRedactions.Where(r => r.Enabled).Select(r => r.FeatureId)); //adding features that need to be enabled
            featureIds.RemoveAll(f => featureRedactions.Where(r => !r.Enabled).Select(r => r.FeatureId).Contains(f)); //removing features that need to be disabled

            //adding redactions may have caused duplicity
            featureIds = featureIds.Distinct().ToList();

            var availableFeatures = _featureManager.GetAvailableFeatures();
            var enabledFeatures = _featureManager.GetEnabledFeatures().ToList();

            var featuresToDisable = enabledFeatures.Where(f => !featureIds.Contains(f.Id)).Select(f => f.Id).ToList();
            var featuresToEnable = availableFeatures
                .Where(f => featureIds.Contains(f.Id)) //available features that are in the list of features that need to be enabled
                .Where(f => !enabledFeatures.Select(ef => ef.Id).Contains(f.Id)) //remove features that are already enabled
                .Select(f => f.Id)
                .ToList();

            _featureManager.DisableFeatures(featuresToDisable, true);
            _featureManager.EnableFeatures(featuresToEnable, true);

            recipeContext.Executed = true;
        }
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Roles", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            var installedPermissions = _roleService.GetInstalledPermissions().SelectMany(p => p.Value).ToList();

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

                if (string.IsNullOrEmpty(recipeContext.ExecutionId)) {
                    _recipeJournal.WriteJournalEntry(recipeContext.ExecutionId, T("Roles: Executing item {0}.", roleName).Text);
                }

                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)));
            }
            recipeContext.Executed = true;
        }
        /*  
         <Settings>
          <SiteSettingsPart PageSize="30" />
          <CommentSettingsPart ModerateComments="true" />
         </Settings>
        */
        // Set site and part settings.
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Settings", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            var siteContentItem = _siteService.GetSiteSettings().ContentItem;

            var importContentSession = new ImportContentSession(_contentManager);

            var context = new ImportContentContext(siteContentItem, recipeContext.RecipeStep.Step, importContentSession);
            foreach (var contentHandler in Handlers) {
                contentHandler.Importing(context);
            }

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

                if (!string.IsNullOrEmpty(recipeContext.ExecutionId)) {
                    _recipeJournal.WriteJournalEntry(recipeContext.ExecutionId, T("Setting: {0}.", contentPart.PartDefinition.Name).Text);
                }

                ImportSettingPart(contentPart, partElement);
            }

            foreach (var contentHandler in Handlers) {
                contentHandler.Imported(context);
            }

            recipeContext.Executed = true;
        }
        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;
            }
        }
        /* 
           <Metadata>
            <Types>
             <Blog creatable="true">
              <Body format="abodyformat"/>
             </Blog>
            </Types>
            <Parts>
            </Parts>
           </Metadata>
         */
        // Set type settings and attach parts to types.
        // Create dynamic parts.
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Metadata", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            foreach (var metadataElement in recipeContext.RecipeStep.Step.Elements()) {
                switch (metadataElement.Name.LocalName) {
                    case "Types":
                        foreach (var element in metadataElement.Elements()) {
                            var typeElement = element;
                            var typeName = XmlConvert.DecodeName(element.Name.LocalName);
                            _contentDefinitionManager.AlterTypeDefinition(typeName, alteration => _contentDefinitionReader.Merge(typeElement, alteration));
                        }
                        break;
                    case "Parts":
                        // create dynamic part.
                        foreach (var element in metadataElement.Elements()) {
                            var partElement = element;
                            var partName = XmlConvert.DecodeName(element.Name.LocalName);
                            _contentDefinitionManager.AlterPartDefinition(partName, alteration => _contentDefinitionReader.Merge(partElement, alteration));
                        }
                        break;
                    default:
                        Logger.Error("Unrecognized element {0} encountered in step Metadata. Skipping.", metadataElement.Name.LocalName);
                        break;
                }
            }

            recipeContext.Executed = true;
        }
Example #10
0
        // <Data />
        // Import Data
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Rules", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            foreach (var rule in recipeContext.RecipeStep.Step.Elements()) {

                var ruleRecord = _rulesServices.CreateRule(rule.Attribute("Name").Value);
                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();

            }

            recipeContext.Executed = true;
        }
Example #11
0
        private Task UpdateStepResultRecordAsync(
            RecipeContext recipeContext,
            bool IsSuccessful,
            Exception exception = null)
        {
            // TODO: bad pattern, use an index

            //var stepResults = await _session
            //    .QueryAsync<RecipeResult>()
            //    .List();

            //var recipeResult = stepResults
            //    .First(record => record.ExecutionId == recipeContext.ExecutionId);

            //var recipeStepResult = recipeResult
            //    .Steps
            //    .First(step => step.StepId == recipeContext.RecipeStep.Id);

            //recipeStepResult.IsCompleted = true;
            //recipeStepResult.IsSuccessful = IsSuccessful;
            //recipeStepResult.ErrorMessage = exception?.ToString();

            //_session.Save(recipeResult);

            return Task.CompletedTask;
        }
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "AuditTrail", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            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);
                recipeContext.Executed = false;
                return;
            }

            foreach (var eventElement in recipeContext.RecipeStep.Step.Elements()) {
                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);
            }

            recipeContext.Executed = true;
        }
Example #13
0
        // <Migration features="f1, f2" /> 
        // <Migration features="*" />
        // Run migration for features.
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Migration", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            bool runAll = false;
            var features = new List<string>();
            foreach (var attribute in recipeContext.RecipeStep.Step.Attributes()) {
                if (String.Equals(attribute.Name.LocalName, "features", StringComparison.OrdinalIgnoreCase)) {
                    features = ParseFeatures(attribute.Value);
                    if (features.Contains("*"))
                        runAll = true;
                }
                else {
                    Logger.Error("Unrecognized attribute {0} encountered in step Migration. Skipping.", attribute.Name.LocalName);
                }
            }

            if (runAll) {
                foreach (var feature in _dataMigrationManager.GetFeaturesThatNeedUpdate()) {
                    _dataMigrationManager.Update(feature);
                }
            }
            else {
                _dataMigrationManager.Update(features);
            }

            // run migrations
            recipeContext.Executed = true;
        }
        // <Data />
        // Import Data
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Data", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            var importContentSession = new ImportContentSession(_orchardServices.ContentManager);

            // Populate local dictionary with elements and their ids
            var elementDictionary = CreateElementDictionary(recipeContext.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 startIndex = 0;
            int batchSize = GetBatchSizeForDataStep(recipeContext.RecipeStep.Step);

            //Run the import
            try {
                while (startIndex < elementDictionary.Count) {
                    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) {
                        if (!string.IsNullOrEmpty(recipeContext.ExecutionId) && elementDictionary[nextIdentity.ToString()].HasAttributes) {
                            var itemId = elementDictionary[nextIdentity.ToString()].FirstAttribute.Value;
                            _recipeJournal.WriteJournalEntry(recipeContext.ExecutionId, T("Data: Importing {0}.", itemId).Text);
                        }
                        _orchardServices.ContentManager.Import(
                            elementDictionary[nextIdentity.ToString()],
                            importContentSession);
                        nextIdentity = importContentSession.GetNextInBatch();
                    }

                    startIndex += batchSize;

                    //Create a new transaction for each batch
                    if (startIndex < elementDictionary.Count) {
                        _transactionManager.RequireNew();
                    }
                }
            }
            catch (Exception) {
                //Ensure a failed batch is rolled back
                _transactionManager.Cancel();
                throw;
            }

            recipeContext.Executed = true;
        }
        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;
            }
        }
        /*
          <RunContentMigrations />
         */
        //Run any pending content migrations
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "RunContentMigrations", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            _realtimeFeedbackService.Info(T("Starting 'Run Content Migrations' step"));

            _contentMigrationManager.ExecutePendingMigrations();

            _realtimeFeedbackService.Info(T("Step 'Run Content Migrations' has finished"));
            recipeContext.Executed = true;
        }
        public void ExecuteRecipeExecutionStepHandlerTest() {
            var handlerUnderTest = _container.Resolve<RecipeExecutionStepHandler>();
            var fakeRecipeStep = _container.Resolve<StubRecipeExecutionStep>();

            var context = new RecipeContext {
                RecipeStep = new RecipeStep (id: "1", recipeName: "FakeRecipe",  name: "FakeRecipeStep", step: new XElement("FakeRecipeStep")),
                ExecutionId = "12345"
            };

            handlerUnderTest.ExecuteRecipeStep(context);

            Assert.That(fakeRecipeStep.IsExecuted, Is.True);
            Assert.That(context.Executed, Is.True);
        }
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Workflows", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            foreach (var workflowDefinitionElement in recipeContext.RecipeStep.Step.Elements()) {
                var workflowDefinition = new WorkflowDefinitionRecord {
                    Name = ProbeWorkflowDefinitionName(workflowDefinitionElement.Attribute("Name").Value),
                    Enabled = Boolean.Parse(workflowDefinitionElement.Attribute("Enabled").Value)
                };
                
                _workflowDefinitionRepository.Create(workflowDefinition);

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

                foreach (var activityElement in activitiesElement.Elements()) {
                    var localId = Int32.Parse(activityElement.Attribute("Id").Value);
                    var activity = new ActivityRecord {
                        Name = activityElement.Attribute("Name").Value,
                        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;

                    workflowDefinition.TransitionRecords.Add(new TransitionRecord {
                        SourceActivityRecord = activitiesDictionary[sourceActivityId],
                        SourceEndpoint = sourceEndpoint,
                        DestinationActivityRecord = activitiesDictionary[destinationActivityId],
                        DestinationEndpoint = destinationEndpoint
                    });
                }
            }

            recipeContext.Executed = true;
        }
        /*
            <CurrentTheme name="MySuperTheme" />
         */
        //Enable any features that are in the list, disable features that aren't in the list
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "CurrentTheme", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            _realtimeFeedbackService.Info(T("Entering the 'Current Theme' step"));

            var themeToEnable = recipeContext.RecipeStep.Step.Attribute("id").Value;
            _realtimeFeedbackService.Info(T("Setting the current theme to {0}", themeToEnable));

            _siteThemeService.SetSiteTheme(themeToEnable);

            _realtimeFeedbackService.Info(T("The current theme has been set to {0}", themeToEnable));
            recipeContext.Executed = true;
        }
        /* <ContentTrim>
         *   <ContentTypes>
         *      <add type="page"/>
         *      <add type="widget"/>
         *   </ContentTypes>
         *   <ContentToKeep>
         *      <add identifier="123456789"/>
         *      <add identifier="321654897"/>
         *   </ContentType>
         *  </ContentTrim>
         */
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "ContentTrim", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            _realtimeFeedbackService.Info(T("Entering the 'Content Trim' step"));

            var contentTypesElement = recipeContext.RecipeStep.Step.Descendants("ContentTypes").FirstOrDefault();
            var contentToKeepElement = recipeContext.RecipeStep.Step.Descendants("ContentToKeep").FirstOrDefault();

            if (contentTypesElement == null) 
            {
                _realtimeFeedbackService.Error(T("Could not execute the Content Trim step as there was no 'ContentTypes' element in the step"));

                return;
            }
            if (contentToKeepElement == null)
            {
                _realtimeFeedbackService.Error(T("Could not execute the Content Trim step as there was no 'ContentToKeep' element in the step"));

                return;
            }

            var contentTypes = contentTypesElement.Descendants("add").Select(e => e.Attribute("type").Value).ToList();
            _realtimeFeedbackService.Info(T("The following content types will be synced:"));

            foreach (var contentType in contentTypes)
            {
                _realtimeFeedbackService.Info(T(contentType));
            }

            var contentToKeep = contentToKeepElement.Descendants("add").Select(e => e.Attribute("identifier").Value).ToList();
            _realtimeFeedbackService.Info(T("Identified {0} pieces of content from the remote site", contentTypes.Count()));

            var contentItems = _contentManager.Query<IdentityPart, IdentityPartRecord>(contentTypes.ToArray()).Where(c => !contentToKeep.Contains(c.Identifier)).List().ToList();
            _realtimeFeedbackService.Info(T("Identified {0} pieces of content that exist in the local site, but not in the remote site. This content will be removed.", contentItems.Count()));

            foreach (var contentItem in contentItems)
            {
                _realtimeFeedbackService.Info(T("Removing {0} '{2}' (ID: {1})", contentItem.ContentItem.ContentType, contentItem.ContentItem.Id, contentItem.ContentItem.GetContentName()));
                _contentManager.Remove(contentItem.ContentItem);
            }

            _realtimeFeedbackService.Info(T("The 'Content Trim' step has successfully executed"));
            recipeContext.Executed = true;
        }
        /*  
         <FeatureRedactions>
          <add FeatureId="Orchard.Azure" Enabled="true" />
         </FeatureRedactions>
        */
        // Add a set of redactions
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "FeatureRedactions", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var redactions = recipeContext.RecipeStep.Step.Descendants().Where(f => f.Name == "add");
            foreach (var redaction in redactions)
            {
                var featureId = redaction.Attribute("FeatureId").Value;
                var enabled = String.Equals(redaction.Attribute("Enabled").Value, "true", StringComparison.OrdinalIgnoreCase);

                _featureRedactionService.AddRedaction(new FeatureRedactionRecord { FeatureId = featureId, Enabled = enabled});
            }

            recipeContext.Executed = true;
        }
        /*  
         <SettingRedactions>
          <add Setting="SiteSettingsPart.SiteOwner" Value="admin" />
         </SettingRedactions>
        */
        // Add a set of redactions
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "SettingRedactions", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var redactions = recipeContext.RecipeStep.Step.Descendants().Where(f => f.Name == "add");
            foreach (var redaction in redactions)
            {
                var setting = redaction.Attribute("Setting").Value;
                var value = redaction.Attribute("Value").Value;

                _settingRedactionService.AddRedaction(new SettingRedactionRecord { SettingName = setting, Value = value});
            }

            recipeContext.Executed = true;
        }
        /*  
         <RemoteSiteConfigs>
          <add Url="http://www.example.com" Username="******" Password="******" />
         </RemoteSiteConfigs>
        */
        // Add a set of redactions
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "RemoteSiteConfigs", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var redactions = recipeContext.RecipeStep.Step.Descendants().Where(f => f.Name == "add");
            foreach (var redaction in redactions)
            {
                var url = redaction.Attribute("Url").Value;
                var username = redaction.Attribute("Username").Value;
                var password = redaction.Attribute("Password").Value;

                _repository.Create(new RemoteSiteConfigRecord{Url = url, Username = username, Password = password});
            }

            recipeContext.Executed = true;
        }
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "LayoutElements", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            foreach (var elementElement in recipeContext.RecipeStep.Step.Elements()) {
                var typeName = elementElement.Attribute("ElementTypeName").Value;
                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;
            }

            recipeContext.Executed = true;
        }
Example #25
0
        public async Task ExecuteAsync(string executionId, RecipeStepDescriptor recipeStep)
        {
            _logger.LogInformation("Executing recipe step '{0}'.", recipeStep.Name);

            var recipeContext = new RecipeContext
            {
                RecipeStep = recipeStep,
                Executed = false,
                ExecutionId = executionId
            };

            await _eventBus.NotifyAsync<IRecipeEventHandler>(e => e.RecipeStepExecutingAsync(executionId, recipeStep));

            await _recipeHandlers.InvokeAsync(rh => rh.ExecuteRecipeStepAsync(recipeContext), _logger);

            await UpdateStepResultRecordAsync(recipeContext, true);

            await _eventBus.NotifyAsync<IRecipeEventHandler>(e => e.RecipeStepExecutedAsync(executionId, recipeStep));
        }
        /*  
         <Settings>
          <SiteSettingsPart PageSize="30" />
          <CommentSettingsPart ModerateComments="true" />
         </Settings>
        */
        // Set site and part settings.
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Settings", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            var site = _siteService.GetSiteSettings();
            foreach (var element in recipeContext.RecipeStep.Step.Elements()) {
                var partName = XmlConvert.DecodeName(element.Name.LocalName);
                foreach (var contentPart in site.ContentItem.Parts) {
                    if (!String.Equals(contentPart.PartDefinition.Name, partName, StringComparison.OrdinalIgnoreCase)) {
                        continue;
                    }
                    foreach (var attribute in element.Attributes()) {
                        SetSetting(attribute, contentPart);
                    }
                }
            }

            recipeContext.Executed = true;
        }
Example #27
0
        // <Feature enable="f1,f2,f3" disable="f4" />
        // Enable/Disable features.
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Feature", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            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.Error("Unrecognized attribute {0} encountered in step Feature. 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.Count != 0) {
                _featureManager.DisableFeatures(featuresToDisable, true);
            }
            if (featuresToEnable.Count != 0) {
                _featureManager.EnableFeatures(featuresToEnable, true);
            }

            recipeContext.Executed = true;
        }
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Forms", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            var formsElement = recipeContext.RecipeStep.Step.Elements();
            foreach (var formElement in formsElement) {
                var formName = formElement.Attr<string>("Name");
                var submissionElements = formElement.Element("Submissions").Elements();

                foreach (var submissionElement in submissionElements) {
                    _formService.CreateSubmission(new Submission {
                        FormName = formName,
                        CreatedUtc = submissionElement.Attr<DateTime>("CreatedUtc"),
                        FormData = submissionElement.Value
                    });
                }
            }

            recipeContext.Executed = true;
        }
        /* 
         <Command>
            command1
            command2
            command3
         </Command>
        */
        // run Orchard commands.
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "Command", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            var commands = 
                recipeContext.RecipeStep.Step.Value
                .Split(new[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries)
                .Select(commandEntry => commandEntry.Trim());

            foreach (var command in commands) {
                if (!String.IsNullOrEmpty(command)) {
                    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 });
                }
            }

            recipeContext.Executed = true;
        }
        /*
          <ExecutedDataMigrations>
            <Migration Name="~/Modules/CJP.ContentSync/ContentMigrations/CJP.ContentSync/TestMigration1" />
         */
        //Save any migrations that are in the list, delete migrations that aren't in the list
        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "ExecutedDataMigrations", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            _realtimeFeedbackService.Info(T("Entering the 'Executed Data Migrations' step. This step will reset the local record of content migrations to the state of the remote server"));

            var migrations = recipeContext.RecipeStep.Step.Descendants();
            var migrationNames = migrations.Where(f => f.Name == "Migration").Select(f => f.Attribute("Name").Value).ToList();

            _realtimeFeedbackService.Info(T("Found {0} migrations that have ran remotely:", migrationNames.Count()));
            foreach (var migrationName in migrationNames)
            {
                _realtimeFeedbackService.Info(T(migrationName));
            }

            var locallyRanMigrations = _contentMigrationStateService.GetExecutedMigrations().ToList();

            _realtimeFeedbackService.Info(T("Found {0} migrations that have ran locally:", locallyRanMigrations.Count()));
            foreach (var migrationName in locallyRanMigrations)
            {
                _realtimeFeedbackService.Info(T(migrationName));
            }

            foreach (var migration in locallyRanMigrations.Where(m => !migrationNames.Contains(m)))
            {//migrations that have been executed locally, but not in the recipe that is being executed
                _realtimeFeedbackService.Info(T("Marking migration '{0}' as pending", migration));
                _contentMigrationStateService.MarkMigrationAsPending(migration);
            }

            foreach (var migrationToAdd in migrationNames.Where(m => !locallyRanMigrations.Contains(m)))
            {
                _realtimeFeedbackService.Info(T("Marking migration '{0}' as executed", migrationToAdd));
                _contentMigrationStateService.MarkMigrationAsExecuted(migrationToAdd);
            }

            _realtimeFeedbackService.Info(T("The 'Executed Data Migrations' step is finished"));
            recipeContext.Executed = true;
        }