Esempio n. 1
0
 public void FeatureHasDefaultValue()
 {
     using (ContextSwitcher.For(_featureContext))
     {
         Assert.True(Feature.IsEnabled(_testFeature));
     }
 }
Esempio n. 2
0
    public override CommandResult Run()
    {
      var showAll = !ShowBadLinks && !ShowIncomingLinks && !ShowOutgoingLinks;

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var linkDb = Sitecore.Configuration.Factory.GetLinkDatabase();
        if (linkDb == null)
          return new CommandResult(CommandStatus.Failure, "Failed to find the link database");

        var output = new StringBuilder();

        if (!OutputIds)
        {
          Formatter.PrintTable(new[] { "Direction", "Valid", "Field", "Link" }, DISPLAY_COLUMN_WIDTHS, output);
          Formatter.PrintTable(new[] { "---------", "-----", "-----", "----" }, DISPLAY_COLUMN_WIDTHS, output);
          Formatter.PrintLine(string.Empty, output);
        }

        if (ShowIncomingLinks || showAll)
          ProcessIncomingLinks(linkDb.GetReferrers(Context.CurrentItem), output);

        if (ShowOutgoingLinks || showAll)
          ProcessOutgoingLinks(linkDb.GetReferences(Context.CurrentItem), output);

        if (ShowIncomingLinks || showAll)
          ProcessBadLinks(linkDb.GetBrokenLinks(Context.CurrentDatabase), output);

        return new CommandResult(CommandStatus.Success, output.ToString());
      }
    }
Esempio n. 3
0
    public override CommandResult Run()
    {
      var output = new StringBuilder();

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var inspector = new ItemInspector(Context.CurrentItem);

        if (Attribute.Length > 0)
        {
          var value = inspector.GetItemAttribute(Attribute);
          if (value == null)
            return new CommandResult(CommandStatus.Failure, "Failed to find attribute " + Attribute);

          output.Append(value);
        }
        else
        {
          Formatter.PrintDefinition("id", inspector.GetItemAttribute("id") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("name", inspector.GetItemAttribute("name") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("key", inspector.GetItemAttribute("key") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("template", inspector.GetItemAttribute("template") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("templateid", inspector.GetItemAttribute("templateid") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("branch", inspector.GetItemAttribute("branch") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("branchid", inspector.GetItemAttribute("branchid") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("language", inspector.GetItemAttribute("language") ?? Constants.NotDefinedLiteral, output);
          Formatter.PrintDefinition("version", inspector.GetItemAttribute("version") ?? Constants.NotDefinedLiteral, output);
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Esempio n. 4
0
 public static int Count(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.ProCampaignStatuses.Count());
     }
 }
Esempio n. 5
0
    public override CommandResult Run()
    {
      var count = 0;
      string msg;

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var inspector = new ItemInspector(Context.CurrentItem);
        count = inspector.CountDescendants();

        var parent = Context.CurrentItem.Parent;

        if (NoRecycle)
        {
          Context.CurrentItem.Delete();
          msg = "Deleted";
        }
        else
        {
          Context.CurrentItem.Recycle();
          msg = "Recycled";
        }

        if (Path.Length == 0)
          Context.CurrentItem = parent;
      }

      return new CommandResult(CommandStatus.Success, string.Format(msg + " {0} {1}", count, count == 1 ? "item" : "items"));
    }
        public void WhenKnownUserLoggedIn_ThenContextShouldSwitchToMenu()
        {
            var contextSwitcher = new ContextSwitcher(this.dataBaseService.Object);

            contextSwitcher.UserLoggedIn("name", false);
            Approvals.Verify("Content = " + contextSwitcher.ViewModel.Context);
        }
        public void WhenOpenMainMenu_ThenMainMenuShouldOpen()
        {
            var contextSwitcher = new ContextSwitcher(this.dataBaseService.Object);

            contextSwitcher.OpenMainMenu();
            Approvals.Verify("Content = " + contextSwitcher.ViewModel.Context);
        }
        public void WhenStartNewGame_ThenMatchConfigShouldOpen()
        {
            var contextSwitcher = new ContextSwitcher(this.dataBaseService.Object);

            contextSwitcher.OpenNewGame();
            Approvals.Verify("Content = " + contextSwitcher.ViewModel.Context);
        }
Esempio n. 9
0
 public static Entities.Ingredient GetIngredientFromName(string name, ContextType contextType = ContextType.Default)
 {
     using (var ctx = ContextSwitcher.CreateContext(contextType))
     {
         return((from ingredientToSearch in ctx.Ingredients where ingredientToSearch.Name.ToLower() == name.ToLower() select ingredientToSearch).FirstOrDefault());
     }
 }
Esempio n. 10
0
        public static void InsertFromExistingParticipant(Participant participant, ParticipantDataCache participantDataCache, Entry entry, ContextType contextType = ContextType.Default)
        {
            try
            {
                using (var context = ContextSwitcher.CreateContext(contextType))
                {
                    participantDataCache.ParticipantId = participant.Id;
                    context.ParticipantDataCaches.Add(participantDataCache);

                    if (entry.Ingredient1 != null)
                    {
                        context.Ingredients.Attach(entry.Ingredient1);
                    }
                    if (entry.Ingredient2 != null)
                    {
                        context.Ingredients.Attach(entry.Ingredient2);
                    }
                    if (entry.Ingredient3 != null)
                    {
                        context.Ingredients.Attach(entry.Ingredient3);
                    }
                    entry.ParticipantId          = participant.Id;
                    entry.ParticipantDataCacheId = participantDataCache.Id;
                    context.Entries.Add(entry);

                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 11
0
        public ResultDTO Process()
        {
            var dateTimeFromNow = DateTime.UtcNow.AddDays(-DaysPeriodFromNow);

            using (var context = ContextSwitcher.CreateContext())
            {
                IList <ParticipantDataCache> participantDataCaches = context.ParticipantDataCaches
                                                                     .Where(
                    e => e.Email.Contains("@") &&
                    e.CreatedOn < dateTimeFromNow
                    ).ToList();
                foreach (ParticipantDataCache participantDataCache in participantDataCaches)
                {
                    participantDataCache.Email                = StringUtils.HashSHA256(participantDataCache.Email.ToLower());
                    participantDataCache.FirstName            = StringUtils.HashSHA256(participantDataCache.FirstName.ToLower());
                    participantDataCache.LastName             = StringUtils.HashSHA256(participantDataCache.LastName.ToLower());
                    participantDataCache.MobileNumber         = StringUtils.HashSHA256(participantDataCache.MobileNumber.ToLower());
                    participantDataCache.City                 = StringUtils.HashSHA256(participantDataCache.City.ToLower());
                    participantDataCache.UpdatedOn            = DateTime.UtcNow;
                    context.Entry(participantDataCache).State = EntityState.Modified;
                    context.SaveChanges();
                }
            }

            Result.HttpStatusCode = HttpStatusCode.OK;

            return(Result);
        }
Esempio n. 12
0
 public static int Count(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.Entries.Count());
     }
 }
Esempio n. 13
0
 public static int Count(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.ExistingBarCombinations.Count());
     }
 }
 private void FunctionDumpWithFailureAssertion(Object state, ContextSwitcher switcher)
 {
     if (((String)state) == "C")
     {
         Assert.Fail();
     }
     trace.Append((String)state);
 }
 private void FunctionDumpThatThrowsException(Object state, ContextSwitcher switcher)
 {
     if (((String)state) == "C")
     {
         throw new System.SystemException();
     }
     trace.Append((String)state);
 }
Esempio n. 16
0
        public void WhenNewUserLoggedIn_ThenContextShouldSwitchToMenu()
        {
            var contextSwitcher = new ContextSwitcher(this.dataBaseService.Object);

            contextSwitcher.UserLoggedIn("name", true);
            this.dataBaseService.Verify(x => x.InsertNewUser("name"), Times.Once, "User was not inserted in Databae");
            Approvals.Verify("Content = " + contextSwitcher.ViewModel.Context);
        }
Esempio n. 17
0
 public static int CountByStatus(string status, ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.ProCampaignTransactions
                .Count(e => e.Status == status));
     }
 }
Esempio n. 18
0
 public static void Update(ProCampaignStatus entity, ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         context.Entry(entity).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
Esempio n. 19
0
 public static void Insert(ProCampaignStatus entity, ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         context.ProCampaignStatuses.Add(entity);
         context.SaveChanges();
     }
 }
Esempio n. 20
0
 public static void Insert(Entities.Ingredient entity, ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         context.Ingredients.Add(entity);
         context.SaveChanges();
     }
 }
Esempio n. 21
0
    public override CommandResult Run()
    {
      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var languages = new List<Language>();
        languages.Add(Context.CurrentItem.Language);

        if (AllLanguages)
        {
          languages.Clear();
          languages.AddRange(Context.CurrentItem.Languages);
        }

        var versions = new List<int>();
        versions.Add(Context.CurrentItem.Version.Number);

        if (OtherVersions)
        {
          versions.Clear();
          versions.AddRange(Context.CurrentItem.Versions.GetVersionNumbers().Select(x => x.Number));
          versions.Remove(Context.CurrentItem.Version.Number);

          if (AllLanguages)
          {
            // Other languages may have different version numbers. Need to add those extras
            foreach (var language in Context.CurrentItem.Languages)
            {
              var langItem = Context.CurrentItem.Database.GetItem(Context.CurrentItem.ID, language);
              foreach (var version in langItem.Versions.GetVersionNumbers())
              {
                if (!versions.Contains(version.Number) && version.Number != Context.CurrentItem.Version.Number)
                  versions.Add(version.Number);
              }
            }
          }
        }

        var count = 0;

        foreach (var language in languages)
        {
          foreach (var version in versions)
          {
            var versionItem = Context.CurrentItem.Database.GetItem(Context.CurrentItem.ID, language, new Version(version));
            if (versionItem != null)
            {
              versionItem.Versions.RemoveVersion();
              count++;
            }
          }
        }

        return new CommandResult(CommandStatus.Success, "Deleted {0} version{1}".FormatWith(count, count == 1 ? string.Empty : "s"));
      }
    }
Esempio n. 22
0
        public MainWindow()
        {
            InitializeComponent();
            var dataBaseService = new DataBaseService();
            var contextSwitcher = new ContextSwitcher(dataBaseService);

            contextSwitcher.CloseEvent += OnClose;
            this.DataContext            = contextSwitcher.GetMainScreen();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="state"></param>
        /// <param name="switcher"></param>
        private void FunctionForThread(Object state, ContextSwitcher switcher)
        {
            Int32 value = retStatus;

            ++retStatus;             // add 1
            switcher.Switch();       // I ask for switch, the next function should be executed so another 1 is added
            Assert.That(retStatus, Is.EqualTo(value + 2));
            ++retStatus;
        }
Esempio n. 24
0
        public void WhenGetMainScreen_ThenContextShouldBeLoginViewModel()
        {
            this.dataBaseService.Setup(x => x.GetUsers()).Returns(new List <string>());
            var contextSwitcher = new ContextSwitcher(this.dataBaseService.Object);

            contextSwitcher.GetMainScreen();
            this.dataBaseService.Verify(x => x.GetUsers(), Times.Once, "Users was not fetched from Database");
            Approvals.Verify("Content = " + contextSwitcher.ViewModel.Context);
        }
Esempio n. 25
0
 public static IList <ProCampaignStatus> Get(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.ProCampaignStatuses
                .OrderByDescending(e => e.CreatedOn)
                .ToList());
     }
 }
Esempio n. 26
0
        private void AssignContext()
        {
            if (Session["CurrentContext"] == null)
            {
                Session["CurrentContext"] = ContextType.Default;
            }
            string contextFromSession = Session["CurrentContext"].ToString();

            CurrentContextType = ContextSwitcher.GetUserContext(contextFromSession);
        }
Esempio n. 27
0
 public override CommandResult Run()
 {
   using (var cs = new ContextSwitcher(Context, Path))
   {
     if (cs.Result.Status == CommandStatus.Success)
       return new CommandResult(CommandStatus.Success, base.Context.CurrentItem.Paths.FullPath);
     else
       return new CommandResult(CommandStatus.Failure, "Failed to find item '" + Path + "'");
   }
 }
Esempio n. 28
0
 public static List <Entities.Ingredient> Get(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return((
                    from ingredient
                    in context.Ingredients
                    orderby ingredient.CreatedOn descending
                    select ingredient
                    ).ToList());
     }
 }
Esempio n. 29
0
 public static IList <ExistingBarCombination> Get(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.ExistingBarCombinations
                .Include(nameof(ExistingBarCombination.Ingredient1))
                .Include(nameof(ExistingBarCombination.Ingredient2))
                .Include(nameof(ExistingBarCombination.Ingredient3))
                .OrderByDescending(e => e.CreatedOn)
                .ToList());
     }
 }
Esempio n. 30
0
 public static Entities.Ingredient GetIngredient(Guid id, ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return((
                    from ingredientToSearch
                    in context.Ingredients
                    where ingredientToSearch.Id == id
                    select ingredientToSearch
                    ).FirstOrDefault());
     }
 }
Esempio n. 31
0
 public static IList <ProCampaignTransaction> Get(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.ProCampaignTransactions
                .Include(nameof(ProCampaignTransaction.ProCampaignStatus))
                .Include(e => e.ProCampaignStatus.Entry)
                .Include(e => e.ProCampaignStatus.Entry.Participant)
                .OrderByDescending(e => e.CreatedOn)
                .ToList());
     }
 }
Esempio n. 32
0
    public override CommandResult Run()
    {
      var xml = string.Empty;

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        xml = Context.CurrentItem.GetOuterXml(Recursive);
      }

      return new CommandResult(CommandStatus.Success, xml);
    }
Esempio n. 33
0
 public static IList <Participant> Get(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.Participants
                .Include(nameof(InventorContext.ParticipantDataCaches))
                .Include(nameof(InventorContext.Entries))
                .Include(p => p.Entries.Select(e => e.Ingredient1))
                .Include(p => p.Entries.Select(e => e.Ingredient2))
                .Include(p => p.Entries.Select(e => e.Ingredient3))
                .OrderByDescending(e => e.CreatedOn)
                .ToList());
     }
 }
Esempio n. 34
0
 public static IList <Entry> Get(ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.Entries
                .Include(nameof(Entry.Ingredient1))
                .Include(nameof(Entry.Ingredient2))
                .Include(nameof(Entry.Ingredient3))
                .Include(nameof(Entry.Participant))
                .Include(nameof(Entry.ParticipantDataCache))
                .OrderByDescending(e => e.CreatedOn)
                .ToList());
     }
 }
Esempio n. 35
0
    public override CommandResult Run()
    {
      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var res = Context.CurrentItem.Locking.Unlock();

        if(res)
          return new CommandResult(CommandStatus.Success, "'" + Context.CurrentItem.Name + "' checked in");
        else
          return new CommandResult(CommandStatus.Failure, "'" + Context.CurrentItem.Name + "' check in failed");
      }
    }
Esempio n. 36
0
 public static Participant GetByEmailHash(string emailHash, ContextType contextType = ContextType.Default)
 {
     using (var context = ContextSwitcher.CreateContext(contextType))
     {
         return(context.Participants
                .Include(nameof(InventorContext.ParticipantDataCaches))
                .Include(nameof(InventorContext.Entries))
                .Include(p => p.Entries.Select(e => e.Ingredient1))
                .Include(p => p.Entries.Select(e => e.Ingredient2))
                .Include(p => p.Entries.Select(e => e.Ingredient3))
                .Where(p => p.EmailHash == emailHash)
                .OrderByDescending(e => e.CreatedOn)
                .FirstOrDefault());
     }
 }
Esempio n. 37
0
        public MvcHtmlString DisplayFor <TValue>(Expression <Func <TModel, TValue> > expression, bool scopeBindingToProperty, object additionalViewData = null)
        {
            if (!scopeBindingToProperty)
            {
                return(DisplayFor(expression, additionalViewData));
            }

            var model     = ContextSwitcher.SwitchContext(expression, HtmlHelper.ViewData.Model);
            var container = new BindingScopeUIContainerBuilder().BuildUIContainer(expression, "div", additionalViewData);
            var newHelper = HtmlHelperFactory.BuildHtmlHelper(HtmlHelper.ViewContext, model);
            var builder   = new KnockoutUIBuilder <TValue>(newHelper, ContainerBuilder);

            container.InnerHtml = builder.DisplayForModel(false, additionalViewData).ToHtmlString();
            return(new MvcHtmlString(container.ToString()));
        }
Esempio n. 38
0
    public override CommandResult Run()
    {
      var output = new StringBuilder();

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var item = Context.CurrentItem;

        if (!string.IsNullOrEmpty(FieldName))
        {
          var field = item.Fields[FieldName];

          if (field == null)
            return new CommandResult(CommandStatus.Failure, "Failed to find field '{0}'".FormatWith(FieldName));

          output.Append(field.GetValue(!NoStandardValues));
        }
        else
        {
          var fields = item.Fields.OrderBy(x => x.Name);

          foreach (Field field in fields)
          {
            string name = field.Name;

            if (string.IsNullOrEmpty(name))
            {
              var fieldItem = field.Database.GetItem(field.ID);
              if (fieldItem != null)
                name = fieldItem.Name;
            }

            Formatter.PrintDefinition(name, field.GetValue(!NoStandardValues), output);
          }
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Esempio n. 39
0
		public override CommandResult Run()
		{
      // Check both item level rules and global rules. Looks like page editor may run global rules separatley.

      var all = !(ModeGutter || ModeButton || ModeBar || ModeWorkflow);

      var output = new StringBuilder();
      var count = 0;

      var result = true;

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        if (all || ModeButton)
          result &= RunValidation(ValidatorsMode.ValidateButton, output, ref count);

        if (all || ModeGutter)
          result &= RunValidation(ValidatorsMode.Gutter, output, ref count);

        if (all || ModeBar)
          result &= RunValidation(ValidatorsMode.ValidatorBar, output, ref count);

        if (all || ModeWorkflow)
          result &= RunValidation(ValidatorsMode.Workflow, output, ref count);
      }

      output.AppendLine();

      if(Verbose)
        output.AppendLine(string.Format("Ran {0} validator{1}", count, count == 1 ? string.Empty : "s"));

      if (result)
        output.AppendLine("Validation passed");
      else
        output.AppendLine(string.Format("FAILED: Validation failed for '{0}'", Context.CurrentItem.Name)); ;

      var status = result ? CommandStatus.Success : CommandStatus.Failure;
      return new CommandResult(status, output.ToString());
		}
Esempio n. 40
0
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Template))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("template"));

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var templateItem = Context.CurrentDatabase.Templates[Template];
        if (templateItem == null)
          return new CommandResult(CommandStatus.Failure, "Failed to find the template");

        var itemFieldNames = from field in Context.CurrentItem.Fields
                             select field.Name;

        var templateFieldNames = from field in templateItem.Fields
                                 select field.Name;

        // Check if the new template contains all the currently used fields.
        var missingFields = itemFieldNames.Except(templateFieldNames);

        if (missingFields.Any() && !Force)
        {
          var output = new StringBuilder();
          Formatter.PrintLine("Incompatible template. Use -f to force the change. The following fields are missing on the target template: ", output);

          foreach (var fieldName in missingFields.OrderBy(x => x))
          {
            Formatter.PrintLine(fieldName, output);
          } 

          return new CommandResult(CommandStatus.Failure, output.ToString());
        }
        else
        {
          Context.CurrentItem.ChangeTemplate(templateItem);
          return new CommandResult(CommandStatus.Success, "Item's template has been changed");
        }
      }
    }
Esempio n. 41
0
    public override CommandResult Run() {
      
      using (ContextSwitcher cs = new ContextSwitcher(Context, Path)) {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        StringBuilder sb = new StringBuilder(500);
        Item item = Context.CurrentItem;
        // TODO: Review using item.Fields here. Check source item is of type document ('a' wasn't during testing)
        for (int i = 0; i < item.Template.Fields.Length; i++) {
          // Get regex from template field def
          string regexStr = item.Template.Fields[i].Validation;
          Sitecore.Data.ID id = item.Template.Fields[i].ID;
          if (regexStr != null && regexStr != string.Empty) {
            if (!Regex.Match(item.Fields[id].Value, item.Fields[id].Validation).Success) {
              if (sb.Length > 0)
                Formatter.PrintLine(string.Empty, sb);
                
              sb.Append("\"");
              sb.Append(item.Fields[id].ValidationText);
              sb.Append("\" in field ");
              sb.Append(item.Fields[id].Name);
            }
          }
        }

        if (sb.Length > 0)
        {
          var output = new StringBuilder();
          Formatter.PrintLine("FAILED: Validation failed for " + item.Paths.FullPath, output);
          output.Append(sb);

          return new CommandResult(CommandStatus.Success, output.ToString());
        } else
          return new CommandResult(CommandStatus.Success, "PASSED: Validation passed for " + item.Paths.FullPath);
      }
    }
Esempio n. 42
0
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(TargetPath))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("targetPath"));

      // Evaulate the target path
      var evalTargetPath = PathParser.EvaluatePath(Context, TargetPath);
      Item parent = null;

      using (var targetSwitcher = new ContextSwitcher(Context, evalTargetPath))
      {
        if (targetSwitcher.Result.Status != CommandStatus.Success)
          return targetSwitcher.Result;

        parent = Context.CurrentItem;
        if (parent == null)
          return new CommandResult(CommandStatus.Failure, "Failed to find the target path '" + TargetPath + "'");
      }

      int count = 0;
      Item movedItem = null;

      using (var sourceSwitcher = new ContextSwitcher(Context, Path))
      {
        if (sourceSwitcher.Result.Status != CommandStatus.Success)
          return sourceSwitcher.Result;

        // Now perform the move
        string sourceName = Context.CurrentItem.Name;
        if (parent.Database == Context.CurrentItem.Database)
          Context.CurrentItem.MoveTo(parent);
        else
        {
          string xml = Context.CurrentItem.GetOuterXml(true);
          parent.Paste(xml, false, PasteMode.Overwrite);

          // Now the item has been copied, delete the original

          var deleteCommand = new DeleteItem();
          deleteCommand.Initialise(Context, Formatter);
          deleteCommand.Path = Context.CurrentItem.Paths.FullPath;
          deleteCommand.Run();
        }

        movedItem = parent.Children[Context.CurrentItem.ID];

        if(movedItem == null)
          movedItem = parent.Children[sourceName];

        if (movedItem != null)
        {
          var inspector = new ItemInspector(movedItem);
          count = inspector.CountDescendants();
        }
      }

      if (movedItem == null)
        return new CommandResult(CommandStatus.Failure, string.Format("Failed to move item"));

      if (Context.CurrentItem == null)
        Context.CurrentItem = movedItem;

      return new CommandResult(CommandStatus.Success, string.Format("Moved {0} {1}", count, count == 1 ? "item" : "items"));
    }
Esempio n. 43
0
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Query))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("query"));

      if (string.IsNullOrEmpty(Command) && !StatisticsOnly)
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("command") + " or -so flag");

      if (!string.IsNullOrEmpty(Command) && StatisticsOnly)
        return new CommandResult(CommandStatus.Failure, "Cannot specify a command when returning statistics only");

      var isFastQuery = Query.ToLower().StartsWith(Constants.FastQueryQualifier);

      if (isFastQuery && !string.IsNullOrEmpty(Path))
        return new CommandResult(CommandStatus.Failure, "Cannot specify a path for fast query");

      var output = new StringBuilder();

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        Item[] items = null;

        if (isFastQuery)
          items = Context.CurrentDatabase.SelectItems(Query);
        else
          items = Context.CurrentItem.Axes.SelectItems(Query);

        if (StatisticsOnly)
          output.Append(items != null ? items.Length : 0);
        else
        {
          if (items != null)
          {
            for(var i = 0; i  < items.Length; i++)
            {
              var item = items[i];
              using (new ContextSwitcher(Context, item.ID.ToString()))
              {
                output.Append(Context.ExecuteCommand(Command, Formatter));
              }

              if (i < items.Length - 1)
                Formatter.PrintLine(string.Empty, output);
            }

            if (!NoStatistics)
            {
              Formatter.PrintLine(string.Empty, output);
              Formatter.PrintLine(string.Empty, output);
              output.Append(string.Format("Found {0} {1}", items.Length, (items.Length == 1 ? "item" : "items")));

              if (items.Length == Sitecore.Configuration.Settings.Query.MaxItems)
              {
                Formatter.PrintLine(string.Empty, output);
                output.Append("WARNING: Number of results equals the maximum query items length. You may not have all the results. Try increasing the value of the Query.MaxItems setting in web.config");
              }
            }
          }
          else if (!NoStatistics)
            output.Append("Found 0 items");
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Esempio n. 44
0
    public override CommandResult Run()
    {
      var output = new StringBuilder();

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var item = Context.CurrentItem;

        if (item.HasChildren)
        {
          var children = item.GetChildren(ChildListOptions.None);
          var includeItems = new List<Item>(children.Count);
          var options = RegexOptions.Compiled;
          if (!CaseSensitiveRegex)
            options |= RegexOptions.IgnoreCase;

          var regex = new Regex(Regex, options);

          for (int i = 0; i < children.Count; i++)
          {
            if (Regex != string.Empty)
              if (!regex.IsMatch(children[i].Name))
                continue;

            includeItems.Add(children[i]);
          }

          var items = includeItems.ToArray();

          if (Alphabetical)
            Array.Sort(items, delegate(Item x, Item y)
            {
              return string.Compare(x.Name, y.Name);
            });

          if (ReverseOrder)
            Array.Reverse(items);

          for (int i = 0; i < items.Length; i++)
          {
            if (items[i].HasChildren)
              output.Append("+ ");
            else
              output.Append("  ");

            output.Append(items[i].Name);

            if (i < (items.Length - 1))
              Formatter.PrintLine(string.Empty, output);
          }
        }
        else
        {
          output.Append("zero items found");
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Esempio n. 45
0
    public override CommandResult Run()
    {
      if(string.IsNullOrEmpty(TargetPath))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("targetPath"));

      if (!string.IsNullOrEmpty(PathParser.ParseVersionFromPath(TargetPath)))
        return new CommandResult(CommandStatus.Failure, "Version in target path is not supported");

      if (!string.IsNullOrEmpty(PathParser.ParseVersionFromPath(SourcePath)))
        return new CommandResult(CommandStatus.Failure, "Version in source path is not supported");

      if (!string.IsNullOrEmpty(PathParser.ParseLanguageFromPath(TargetPath)))
        return new CommandResult(CommandStatus.Failure, "Language in target path is not supported");

      if (!string.IsNullOrEmpty(PathParser.ParseLanguageFromPath(SourcePath)))
        return new CommandResult(CommandStatus.Failure, "Language in source path is not supported");

      // Evaulate the target path
      var fullTargetPath = PathParser.EvaluatePath(Context, TargetPath);

      var count = 0;

      using (var cs = new ContextSwitcher(Context, SourcePath))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        // Parse out path and name from targetPath argument
        var tpPath = string.Empty;
        var tpName = string.Empty;

        Item parent = null;
        try
        {
          tpName = Context.CurrentItem.Name;
          var targetSwitchResult = Context.SetContext(fullTargetPath);
          if (targetSwitchResult.Status == CommandStatus.Success)
          {
            tpPath = fullTargetPath;
            Context.Revert();
          }
          else
            ParseTargetPath(fullTargetPath, out tpPath, out tpName);

          CommandResult contextres = Context.SetContext(tpPath);
          if (contextres.Status != CommandStatus.Success)
            return contextres;

          parent = Context.CurrentItem;
          if (parent == null)
            return new CommandResult(CommandStatus.Failure, "Failed to find the target path '" + tpPath + "'");
        }
        finally
        {
          Context.Revert();
        }

        // Now perform the copy
        Item copy = null;

        var sourceName = Context.CurrentItem.Name;
        if (parent.Database == Context.CurrentItem.Database)
          copy = Context.CurrentItem.CopyTo(parent, tpName, Sitecore.Data.ID.NewID, Recursive);
        else
        {
          // Check if target database contains an item with that ID
          var alreadyExists = parent.Database.GetItem(Context.CurrentItem.ID) != null;
          var useNewId = true;

          if (!NewId || alreadyExists)
            useNewId = false;

          var xml = Context.CurrentItem.GetOuterXml(Recursive);
          var regex = new Regex("name=\"[^\"]*\"");
          xml = regex.Replace(xml, "name=\"" + tpName + "\"");
          parent.Paste(xml, useNewId, PasteMode.Overwrite);
          copy = parent.Children[tpName];
        }

        count = CountChildren(copy);

        // If item is a media item copy the blob
        CopyMediaBlobs(Context.CurrentItem, copy, Recursive);
      }

      return new CommandResult(CommandStatus.Success, string.Format("Copied {0} item{1}", count, count == 1 ? string.Empty : "s"));
    }
Esempio n. 46
0
    public override CommandResult Run()
    {
      var output = new StringBuilder();

      // Get the field name
      if (string.IsNullOrEmpty(Field))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("field"));

      // Get the field value
      if (Value == null && !Reset)
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("value"));

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        Item item = base.Context.CurrentItem;

        if (item.Fields[Field] != null)
        {
          // Check if we're using a replacement
          if (Value != null && Value.Contains("$prev"))
          {
            string previousValue = item.Fields[Field].Value;
            Value = Value.Replace("$prev", previousValue);
          }

          // Add a new version and move item to it
          if (!NoVersion)
          {
            item = item.Versions.AddVersion();
            base.Context.CurrentItem = item;
          }

          item.Editing.BeginEdit();
          if (Reset)
            item.Fields[Field].Reset();
          else
            item.Fields[Field].Value = Value;
          item.Editing.EndEdit(!NoStats, Silent);

          // Show new version
          Formatter.PrintLine("Version " + item.Version, output);

          // Show new field value
          var gf = new GetFields();
          gf.Initialise(base.Context, Formatter);
          gf.FieldName = Field;
          gf.Path = item.ID.ToString();
          
          var result = gf.Run();

          Formatter.PrintDefinition(Field, result.ToString(), output);
        }
        else
        {
          return new CommandResult(CommandStatus.Failure, "Failed to find field '" + Field + "'");
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Esempio n. 47
0
    public override CommandResult Run()
    {
      if(string.IsNullOrEmpty(LanguageName))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("language"));

      Language targetLanguage = null;

      if (!Language.TryParse(LanguageName, out targetLanguage))
        return new CommandResult(CommandStatus.Failure, "Failed to parse language '" + LanguageName + "'");

      // Ensure the selected language has been configured for this server
      if(!(from l in Context.CurrentDatabase.Languages where l == targetLanguage select l).Any())
        return new CommandResult(CommandStatus.Failure, "Language not found in database '" + Context.CurrentDatabase.Name + "'");

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        // Get the target item
        var target = Context.CurrentDatabase.GetItem(Context.CurrentItem.ID, targetLanguage);
        if (target != null)
        {
          if (!string.IsNullOrEmpty(FieldName))
          {
            var itemField = Context.CurrentItem.Fields[FieldName];
            if (itemField != null)
            {
              if (target[itemField.Name] == string.Empty || Overwrite)
              {
                using (new EditContext(target))
                {
                  target[itemField.Name] = itemField.Value;
                }
              }
              else
                return new CommandResult(CommandStatus.Failure, "Target field not empty. Use -o to overwrite the target field value.");
            }
            else
            {
              return new CommandResult(CommandStatus.Failure, "Failed to find field '" + FieldName + "' on source item.");
            }
          }
          else
          {
            for (int i = 0; i < Context.CurrentItem.Fields.Count; i++)
            {
              var itemFieldname = Context.CurrentItem.Fields[i].Name;

              if (string.IsNullOrEmpty(itemFieldname))
              {
                var fieldItem = Context.CurrentDatabase.GetItem(Context.CurrentItem.Fields[i].ID);
                if (fieldItem != null)
                  itemFieldname = fieldItem.Name;
              }

              if (!string.IsNullOrEmpty(itemFieldname) && (target[itemFieldname] == string.Empty || Overwrite))
              {
                using (new EditContext(target))
                {
                  target[itemFieldname] = Context.CurrentItem[itemFieldname];
                }
              }
            }
          }
        }
        else
          return new CommandResult(CommandStatus.Failure, "Failed to find the item");
      }

      return new CommandResult(CommandStatus.Success, string.Format("Copied {0} field{2} to {1} field{2}", Context.CurrentLanguage.GetDisplayName() ?? Context.CurrentLanguage.Name, targetLanguage.GetDisplayName() ?? targetLanguage.Name, FieldName == string.Empty ? "s" : string.Empty));
    }
Esempio n. 48
0
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Attribute))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("attribute"));

      if (string.IsNullOrEmpty(Value))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("value"));

      // resolve template
      TemplateItem template = null;

      if (Attribute == "template")
      {
        template = Context.CurrentDatabase.GetItem(Value);
        if (template == null)
        {
          if (ID.IsID(Attribute))
            return new CommandResult(CommandStatus.Failure, "Failed to find template with ID '" + Attribute + "'");
          else
            return new CommandResult(CommandStatus.Failure, "Failed to find template '" + Attribute + "'");
        }
      }

      string toRet = string.Empty;

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        string query = Attribute;

        Item item = Context.CurrentItem;
        item.Editing.BeginEdit();

        switch (Attribute)
        {
          case "name":
            Value = Value.Replace("$prev", item.Name);
            item.Name = Value;
            break;

          case "template":
            item.TemplateID = template.ID;
            if (Value.StartsWith("{"))
              query += "id";
            break;

          default:
            return new CommandResult(CommandStatus.Failure, "Unknown attribute " + Attribute);
        }

        item.Editing.EndEdit();

        GetAttributes ga = new GetAttributes();
        ga.Initialise(Context, Formatter);
        ga.Attribute = query;
        CommandResult result = ga.Run();
        StringBuilder sb = new StringBuilder(200);
        Formatter.PrintDefinition(query, result.ToString(), sb);
        toRet = sb.ToString();
      }

      return new CommandResult(CommandStatus.Success, toRet);
    }
Esempio n. 49
0
    public override CommandResult Run()
    {
      // Resolve device names into device objects
      DeviceItem sourceDevice = null;
      DeviceItem targetDevice = null;

      if (!string.IsNullOrEmpty(SourceDeviceName) || !string.IsNullOrEmpty(TargetDeviceName))
      {
        if (string.IsNullOrEmpty(SourceDeviceName) && string.IsNullOrEmpty(TargetDeviceName))
          return new CommandResult(CommandStatus.Failure, "If either source or target device is specified the other must be as well.");
        else
        {
          var devices = Context.CurrentDatabase.Resources.Devices.GetAll();

          foreach (var device in devices)
          {
            if(ID.IsID(SourceDeviceName) && device.ID == ID.Parse(SourceDeviceName))
              sourceDevice = device;
            else if (string.Compare(device.Name, SourceDeviceName, true) == 0)
              sourceDevice = device;

            if (ID.IsID(TargetDeviceName) && device.ID == ID.Parse(TargetDeviceName))
              targetDevice = device;
            else if (string.Compare(device.Name, TargetDeviceName, true) == 0)
              targetDevice = device;
          }

          if (sourceDevice == null)
            return new CommandResult(CommandStatus.Failure, "Failed to find source device '" + SourceDeviceName + "'");

          if (targetDevice == null)
            return new CommandResult(CommandStatus.Failure, "Failed to find target device '" + TargetDeviceName + "'");
        }
      }

      var source = Context.CurrentItem;

      using (var sourcecs = new ContextSwitcher(Context, SourcePath))
      {
        if (sourcecs.Result.Status != CommandStatus.Success)
          return sourcecs.Result;

        source = Context.CurrentItem;
      } 

      using (var targetcs = new ContextSwitcher(Context, TargetPath))
      {
        if (targetcs.Result.Status != CommandStatus.Success)
          return targetcs.Result;

        var target = Context.CurrentItem;
        target = target.Versions.AddVersion();

        if (sourceDevice != null && targetDevice != null)
        {
          // get the layout from the current item for the source device
#if SC62
          // todo: verify this works with layout deltas
          var sldf = source.Fields[Sitecore.FieldIDs.LayoutField].GetValue(true);
#else
          var sldf = LayoutField.GetFieldValue(source.Fields[Sitecore.FieldIDs.LayoutField]);
#endif
          var sld = string.IsNullOrEmpty(sldf) ? new LayoutDefinition() : Sitecore.Layouts.LayoutDefinition.Parse(sldf);
          var sdd = sld.GetDevice(sourceDevice.ID.ToString());

          // todo: verify this works with layout deltas
#if SC62
          var tldf = target.Fields[Sitecore.FieldIDs.LayoutField].GetValue(true);
#else
          var tldf = LayoutField.GetFieldValue(target.Fields[Sitecore.FieldIDs.LayoutField]);
#endif
          var tld = string.IsNullOrEmpty(tldf) ? new LayoutDefinition() : Sitecore.Layouts.LayoutDefinition.Parse(tldf);
          var tdd = tld.GetDevice(targetDevice.ID.ToString());

          // Copy the layout
          tdd.Layout = sdd.Layout;

          // Copy the renderings
          if (tdd.Renderings != null)
            tdd.Renderings.Clear();

          foreach (var rendering in sdd.Renderings ?? new ArrayList())
          {
            tdd.AddRendering((Sitecore.Layouts.RenderingDefinition)rendering);
          }

          target.Editing.BeginEdit();
          target[Sitecore.FieldIDs.LayoutField] = tld.ToXml();
          target.Editing.EndEdit();
        }
        else
        {
          // Copy entire layout from source item to target item
          target.Editing.BeginEdit();
          target[Sitecore.FieldIDs.LayoutField] = source[Sitecore.FieldIDs.LayoutField];
          target.Editing.EndEdit();
        }
      }

      return new CommandResult(CommandStatus.Success, "Presentation copied");
    }
Esempio n. 50
0
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Command) && !StatisticsOnly)
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("command") + " or -so flag.");

      if (!string.IsNullOrEmpty(Command) && StatisticsOnly)
        return new CommandResult(CommandStatus.Failure, "Cannot specify a command when returning statistics only.");

      // Make sure we have the right parameters filled in
      if (string.IsNullOrEmpty(FindByField.Key) ^ string.IsNullOrEmpty(FindByField.Value))
        return new CommandResult(CommandStatus.Failure, "Field name or value is missing.");

      // Reset regexs so they get rebuilt if required, based on current parameters
      _fieldRegex = null;
      _attributeRegex = null;

      // Convert template and branch arguments to IDs
      var templateId = ID.Null;
      if(!string.IsNullOrEmpty(Template))
      {
        var templateItem = Context.CurrentDatabase.Templates[Template];
        if (templateItem == null)
          return new CommandResult(CommandStatus.Failure, "Faild to find template '{0}'".FormatWith(Template));

        templateId = templateItem.ID;
      }

      var branchId = ID.Null;
      if (!string.IsNullOrEmpty(Branch))
      {
        var branchItem = Context.CurrentDatabase.Branches[Branch];
        if (branchItem == null)
          return new CommandResult(CommandStatus.Failure, "Faild to find branch '{0}'".FormatWith(Branch));

        branchId = branchItem.ID;
      }

      var output = new StringBuilder();

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var items = new ItemCollection();
        if (!string.IsNullOrEmpty(Ids))
        {
          foreach (var id in ID.ParseArray(Ids))
          {
            var item = Context.CurrentDatabase.GetItem(id);
            if (item != null)
            {
              if (IncludeItem(item, templateId, branchId))
                items.Add(item);
            }
            else
              return new CommandResult(CommandStatus.Failure, "Failed to find item with id '{0}'".FormatWith(id));
          }
        }
        else
          ProcessItem(items, Context.CurrentItem, templateId, branchId, true);

        // Return number of matched items if only returning stats
        if (StatisticsOnly)
          output.Append(items.Count);
        else
        {
          // Execute command against each found item
          var limit = items.Count;
          for (var i = 0; i < limit; i++)
          {
            var item = items[i];
            using (new ContextSwitcher(Context, item.ID.ToString()))
            {
              var result = Context.ExecuteCommand(Command, Formatter);

              // Should we check the status? Maybe abort if stoponerror is set?

              output.Append(result);
            }

            if(i < limit - 1)
              Formatter.PrintLine(string.Empty, output);
          }

          if (!NoStatistics)
          {
            Formatter.PrintLine(string.Empty, output);
            Formatter.PrintLine(string.Empty, output);
            output.Append(string.Format("Found {0} {1}", items.Count, (items.Count == 1 ? "item" : "items")));
          }
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Esempio n. 51
0
    public override CommandResult Run()
    {
      var flagCount = 0;

      if (IncrementalPublish)
        flagCount++;

      if (SmartPublish)
        flagCount++;

      if (FullPublish)
        flagCount++;

      if (flagCount > 1)
        return new CommandResult(CommandStatus.Failure, "Only one of -i, -s or -f may be used");

      if (Recursive && (IncrementalPublish || SmartPublish || FullPublish))
        return new CommandResult(CommandStatus.Failure, "-r cannot be used with -i, -s or -f");

      var targetNames = (Targets ?? string.Empty).Split(new [] {'|'}, StringSplitOptions.RemoveEmptyEntries);
      var languageNames = (Languages ?? string.Empty).Split(new [] {'|'}, StringSplitOptions.RemoveEmptyEntries);

      using (var cs = new ContextSwitcher(Context, Path))
      {
        // Find targets for DB inside context switcher in case path changes the database

        var targets = (from ti in PublishManager.GetPublishingTargets(Context.CurrentDatabase)
                       let t = Sitecore.Configuration.Factory.GetDatabase(ti[Sitecore.FieldIDs.PublishingTargetDatabase])
                       where t != null && (targetNames.Length == 0 || targetNames.Contains(t.Name))
                       select t).ToArray();

        var languages = (from l in Context.CurrentItem.Languages
                         where languageNames.Length == 0 || languageNames.Contains(l.Name)
                         select l).ToArray();

        Handle publishHandle = null;

        if (IncrementalPublish)
          publishHandle = PublishManager.PublishIncremental(Context.CurrentDatabase, targets, languages);
        else if (SmartPublish)
          publishHandle = PublishManager.PublishSmart(Context.CurrentDatabase, targets, languages);
        else if (FullPublish)
          publishHandle = PublishManager.Republish(Context.CurrentDatabase, targets, languages);
        else
        {
          if (!Context.CurrentItem.Publishing.IsPublishable(DateTime.Now, true))
            return new CommandResult(CommandStatus.Failure, "Item or ancestor is not publishable");

          var provider = Context.CurrentDatabase.WorkflowProvider;
          if (provider != null)
          {
            var workflow = Context.CurrentDatabase.WorkflowProvider.GetWorkflow(Context.CurrentItem);
            if (workflow != null)
            {
              if (!workflow.IsApproved(Context.CurrentItem))
                return new CommandResult(CommandStatus.Failure, "Item is not approved in workflow");
            }
          }

          publishHandle = PublishManager.PublishItem(Context.CurrentItem, targets, languages, Recursive, true);
        }

        var message = publishHandle.ToString();

        if (WaitForCompletion)
        {
          PublishManager.WaitFor(publishHandle);

          if (!OutputHandleOnly)
            message = "Publish completed.";
        }
        else if(!OutputHandleOnly)
          message = "Publish started.";

        if(!OutputHandleOnly)
          message = message + " Publish job handle: '" + publishHandle.ToString() + "'";

        return new CommandResult(CommandStatus.Success, message);
      }
    }
Esempio n. 52
0
    public override CommandResult Run()
    {
      if (NewVersion)
        return AddNewVersion();
#if NET35
      if (string.IsNullOrEmpty((Xml ?? string.Empty).Trim()))
#else
      if (string.IsNullOrWhiteSpace(Xml))
#endif
      {
#if NET35
        if (string.IsNullOrEmpty((Template ?? string.Empty).Trim()) && string.IsNullOrEmpty((Branch ?? string.Empty).Trim()))
#else
        if (string.IsNullOrWhiteSpace(Template) && string.IsNullOrWhiteSpace(Branch))
#endif
          return new CommandResult(CommandStatus.Failure, "Missing either 'template' or 'branch 'parameter.");
       
#if NET35
        if (string.IsNullOrEmpty((Name ?? string.Empty).Trim()))
#else
        if (string.IsNullOrWhiteSpace(Name))
#endif
          return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("name"));
      }

      Item created = null;

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        // Resolve the temaplate or master
        Item constructor = null;
#if NET35
        if (!string.IsNullOrEmpty((Template ?? string.Empty).Trim()))
#else
        if (!string.IsNullOrWhiteSpace(Template))
#endif
          constructor = Context.CurrentDatabase.Templates[Template];

#if NET35
        if (!string.IsNullOrEmpty((Branch ?? string.Empty).Trim()))
#else
        if (!string.IsNullOrWhiteSpace(Branch))
#endif
          constructor = Context.CurrentDatabase.Branches[Branch];

        if (!string.IsNullOrEmpty(Xml))
        {
          try
          {
            created = Context.CurrentItem.PasteItem(Xml, ChangeIds, PasteMode.Merge);
            if (created == null)
              return new CommandResult(CommandStatus.Failure, "Failed to create item from XML.");
          }
          catch (Exception ex)
          {
            return new CommandResult(CommandStatus.Failure, "Failed to create item from XML: " + ex.ToString());
          }
        }
        else
        {
          if (constructor == null)
          {
            return new CommandResult(CommandStatus.Failure, "Failed to find the template or branch.");
          }

          // create the item
#if NET35
          if (!string.IsNullOrEmpty((Template ?? string.Empty).Trim()))
#else
          if (!string.IsNullOrWhiteSpace(Template))
#endif
            created = Context.CurrentItem.Add(Name, (TemplateItem)constructor);

#if NET35
          if (!string.IsNullOrEmpty((Branch ?? string.Empty).Trim()))
#else
          if (!string.IsNullOrWhiteSpace(Branch))
#endif
            created = Context.CurrentItem.Add(Name, (BranchItem)constructor);
        }
      }

      /*var message = string.Empty;
      if (Name != string.Empty)
        message = "Created item '" + Name + "'";
      else
        message = "Created Item";*/

      return new CommandResult(CommandStatus.Success, created.ID.ToString());
    }
Esempio n. 53
0
    protected virtual CommandResult AddNewVersion()
    {
      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        Context.CurrentItem = Context.CurrentItem.Versions.AddVersion();
        return new CommandResult(CommandStatus.Success, "Added version " + Context.CurrentItem.Version.Number);
      }
    }