public virtual Item GetSitecoreItem(ID itemId, Language language, Version version)
        {
            Assert.ArgumentNotNull(itemId, "itemId");
            Assert.ArgumentNotNull(language, "language");
            Assert.ArgumentNotNull(version, "version");

            if (!this.FakeItems.ContainsKey(itemId))
            {
                return(null);
            }

            // TODO:[High] Avoid the templates resetting. Required to avoid sharing templates between unit tests.
            this.Database.Engines.TemplateEngine.Reset();

            var fakeItem = this.FakeItems[itemId];

            if (version == Version.Latest)
            {
                version = Version.Parse(fakeItem.GetVersionCount(language.Name));
                if (version == Version.Latest)
                {
                    version = Version.First;
                }
            }

            var fields = this.BuildItemFieldList(fakeItem, fakeItem.TemplateID, language, version);

            return(ItemHelper.CreateInstance(this.database, fakeItem.Name, fakeItem.ID, fakeItem.TemplateID, fakeItem.BranchId, fields, language, version));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets an <see cref="Item"/> by path, language and version number.
        /// </summary>
        /// <param name="path">The item path.</param>
        /// <param name="language">The item language.</param>
        /// <param name="version">The item version.</param>
        /// <returns>The item.</returns>
        public Item GetItem(string path, string language, int version)
        {
            Assert.ArgumentNotNullOrEmpty(path, "path");
            Assert.ArgumentNotNull(language, "language");

            return(this.Database.GetItem(path, Language.Parse(language), Version.Parse(version)));
        }
Ejemplo n.º 3
0
        public void ShouldGetItemByUri()
        {
            // arrange
            using (var db = new Db
            {
                new DbItem("home", this.itemId)
                {
                    new DbField("Title")
                    {
                        { "en", 1, "Welcome!" },
                        { "da", 1, "Hello!" },
                        { "da", 2, "Velkommen!" }
                    }
                }
            })
            {
                // act & assert
                var uriEn1 = new ItemUri(this.itemId, Language.Parse("en"), Version.Parse(1), db.Database);
                Database.GetItem(uriEn1)["Title"].Should().Be("Welcome!");

                var uriDa1 = new ItemUri(this.itemId, Language.Parse("da"), Version.Parse(1), db.Database);
                Database.GetItem(uriDa1)["Title"].Should().Be("Hello!");

                var uriDa2 = new ItemUri(this.itemId, Language.Parse("da"), Version.Parse(2), db.Database);
                Database.GetItem(uriDa2)["Title"].Should().Be("Velkommen!");
            }
        }
Ejemplo n.º 4
0
        public void IsDerived_ItemIsOfGivenTemplate_ReturnsTrue()
        {
            // setup
            #region Setup

            var baseTemplateId = ID.NewID;
            var itemId         = ID.NewID;

            var item = Substitute.For <Item>(
                itemId,
                new ItemData(
                    new ItemDefinition(itemId, "Item Of Template", baseTemplateId, ID.NewID),
                    this.Language,
                    Version.Parse(1),
                    new FieldList()
                    ),
                this.Database);

            var template = new Template.Builder("Base Template", baseTemplateId, new TemplateCollection()).Template;

            this.TemplateManager.GetTemplate(baseTemplateId, this.Database).Returns(template);
            this.TemplateManager.GetTemplate(item).Returns(template);

            #endregion

            // act
            var isDerived = this.ItemExtensions.IsDerived(item, baseTemplateId);

            // assert
            isDerived.Should().BeTrue();
        }
Ejemplo n.º 5
0
        public void FakeDataUri_WhenCalledWithParams_SetsLanguage(ID id, int versionNumber)
        {
            var language = Language.Invariant;
            var version  = Version.Parse(versionNumber);

            var uri = FakeUtil.FakeDataUri(id, language, version);

            uri.Language.Should().Be(language);
        }
Ejemplo n.º 6
0
        public void FakeDataUri_WhenCalledWithParams_NeverReturnsNull(ID id, int versionNumber)
        {
            var language = Language.Invariant;
            var version  = Version.Parse(versionNumber);

            var uri = FakeUtil.FakeDataUri(id, language, version);

            uri.Should().NotBeNull();
        }
 public override VersionUriList GetItemVersions(ItemDefinition itemDefinition, CallContext context)
 {
     if (Items.ContainsKey(itemDefinition.ID))
     {
         VersionUriList versionUriList = new VersionUriList();
         versionUriList.Add(LanguageManager.DefaultLanguage, Version.Parse(1));
         return(versionUriList);
     }
     return(null);
 }
Ejemplo n.º 8
0
        public void CreatesItemData()
        {
            IFixture fixture = new Fixture().Customize(new AutoSitecoreCustomization());

            var data = fixture.Create <ItemData>();

            data.Should().NotBeNull();
            data.Language.Should().Be(Language.Invariant);
            data.Version.Should().Be(Version.Parse(0));
        }
Ejemplo n.º 9
0
        private static Item GetCurrentItem()
        {
            string queryString = WebUtil.GetQueryString("db");
            string path        = WebUtil.GetQueryString("id");

            Language language = Language.Parse(WebUtil.GetQueryString("la"));
            Version  version  = Version.Parse(WebUtil.GetQueryString("vs"));
            Database database = Factory.GetDatabase(queryString);

            Assert.IsNotNull(database, queryString);
            return(database.GetItem(path, language, version));
        }
Ejemplo n.º 10
0
        public void FakeItemUri_WhenCalledWithItem_SetsDatabaseName(string itemName, ID itemId, int versionNumber, string databaseName)
        {
            var database = FakeUtil.FakeDatabase(databaseName);
            var item     = FakeUtil.FakeItem(itemId, itemName, database);

            FakeUtil.FakeItemLanguage(item);

            var version = Version.Parse(versionNumber);

            item.Version.Returns(version);

            var uri = FakeUtil.FakeItemUri(item).Uri;

            uri.DatabaseName.Should().Be(databaseName);
        }
Ejemplo n.º 11
0
        public void AddVersionAddsNewVersionAndReturnsNewVersionNumber(
            [Greedy] FakeDataProvider sut,
            ItemDefinition itemDefinition,
            Language language,
            int version,
            DbItem item)
        {
            sut.DataStorage.GetFakeItem(itemDefinition.ID).Returns(item);
            var baseVersion     = new VersionUri(language, Version.Parse(version));
            var expectedVersion = version + 1;

            var result = sut.AddVersion(itemDefinition, baseVersion, null);

            result.Should().Be(expectedVersion);
            item.GetVersionCount(language.Name).Should().Be(expectedVersion);
        }
        public override VersionUriList GetItemVersions(ItemDefinition itemDefinition, CallContext context)
        {
            var versions = new VersionUriList();

            if (itemDefinition == ItemDefinition.Empty)
            {
                return(versions);
            }

            var database = GetDatabase(context);
            var syncItem = database.GetItem(itemDefinition.ID.ToString());

            foreach (var syncVersion in syncItem.Versions)
            {
                versions.Add(Language.Parse(syncVersion.Language), Version.Parse(syncVersion.Version));
            }

            return(versions);
        }
Ejemplo n.º 13
0
        public override VersionUriList GetItemVersions(ItemDefinition itemDefinition, CallContext context)
        {
            Assert.ArgumentNotNull(itemDefinition, "itemDefinition");

            if (itemDefinition == ItemDefinition.Empty)
            {
                return(null);
            }

            var versions = new VersionUriList();

            var syncItem = SerializedDatabase.GetItem(itemDefinition.ID);

            foreach (var syncVersion in syncItem.Versions)
            {
                versions.Add(Language.Parse(syncVersion.Language), Version.Parse(syncVersion.Version));
            }

            return(versions);
        }
Ejemplo n.º 14
0
        public void Setup()
        {
            this.ItemExtensions  = Substitute.For <IItemExtensionsService>();
            this.Database        = Substitute.For <Database>();
            this.Language        = Substitute.For <Language>();
            this.MetadataService = new MetadataService(this.ItemExtensions);

            var pageItemId = ID.NewID;

            this.MetadataItem = Substitute.For <Item>(
                pageItemId,
                new ItemData(
                    new ItemDefinition(pageItemId, "Page Item", Templates.Metadata.TemplateId, ID.NewID),
                    this.Language,
                    Version.Parse(1),
                    new FieldList()
                    ),
                this.Database);

            this.MetadataItem[Templates.Metadata.FieldNames.MetaTitle].Returns("Page Meta Title");
            //var field = Substitute.For<Field>();
            //field.Value.Returns("Page Meta Title");
            //this.MetadataItem.Fields[Templates.Metadata.FieldNames.MetaTitle].Returns(field);
            this.MetadataItem[Templates.Metadata.FieldNames.MetaDescription].Returns("Page Meta Description");
            this.MetadataItem[Templates.Metadata.FieldNames.MetaKeywords].Returns("Page Meta Keywords");

            var rootItemId = ID.NewID;

            this.WebsiteMetadataItem = Substitute.For <Item>(
                rootItemId,
                new ItemData(
                    new ItemDefinition(rootItemId, "Website Metadata", Templates.WebsiteMetadata.TemplateId, ID.NewID),
                    this.Language,
                    Version.Parse(1),
                    new FieldList()
                    ),
                this.Database);

            this.WebsiteMetadataItem[Templates.WebsiteMetadata.FieldNames.MetaTitle].Returns("Site Meta Title");
        }
Ejemplo n.º 15
0
        public override VersionUriList GetItemVersions(ItemDefinition itemDefinition, CallContext context)
        {
            var list     = new List <VersionUri>();
            var versions = new VersionUriList();

            var item = this.DataStorage.GetFakeItem(itemDefinition.ID);

            if (item == null)
            {
                return(versions);
            }

            foreach (var field in item.Fields)
            {
                foreach (var fieldLang in field.Values)
                {
                    var language = fieldLang.Key;

                    foreach (var fieldVer in fieldLang.Value)
                    {
                        var version = fieldVer.Key;

                        if (list.Any(l => l.Language.Name == language && l.Version.Number == version))
                        {
                            continue;
                        }

                        list.Add(new VersionUri(Language.Parse(language), Version.Parse(version)));
                    }
                }
            }

            foreach (var version in list)
            {
                versions.Add(version);
            }

            return(versions);
        }
Ejemplo n.º 16
0
        public void IsDerived_ItemInheritsBaseTemplate_ReturnsTrue()
        {
            // setup
            #region Setup

            var itemTemplateId = ID.NewID;
            var baseTemplateId = ID.NewID;
            var itemId         = ID.NewID;

            var item = Substitute.For <Item>(
                itemId,
                new ItemData(
                    new ItemDefinition(itemId, "Item Of Base Template", itemTemplateId, ID.Null),
                    this.Language,
                    Version.Parse(1),
                    new FieldList()
                    ),
                this.Database);

            var baseTemplate     = new Template.Builder("Base Template", baseTemplateId, this.TemplateEngine).Template;
            var itemTemplateItem = new Template.Builder("Item Template", itemTemplateId, this.TemplateEngine);
            itemTemplateItem.SetBaseIDs(baseTemplateId.ToString());
            var itemTemplate = itemTemplateItem.Template;

            this.TemplateEngine.GetTemplate(itemTemplateId).Returns(itemTemplate);
            this.TemplateEngine.GetTemplate(baseTemplateId).Returns(baseTemplate);

            this.TemplateManager.GetTemplate(itemTemplateId, this.Database).Returns(itemTemplate);
            this.TemplateManager.GetTemplate(baseTemplateId, this.Database).Returns(baseTemplate);
            this.TemplateManager.GetTemplate(item).Returns(itemTemplate);

            #endregion

            // act
            var isDerived = this.ItemExtensions.IsDerived(item, baseTemplateId);

            // assert
            isDerived.Should().BeTrue();
        }
        public void ShouldGetNewItemVersion(AddVersionCommand sut, ID itemId)
        {
            // arrange
            var dbitem = new DbItem("home")
            {
                { "Title", "Hello!" }
            };

            sut.DataStorage.GetFakeItem(itemId).Returns(dbitem);

            var originalItem       = ItemHelper.CreateInstance(itemId);
            var itemWithNewVersion = ItemHelper.CreateInstance(itemId);

            sut.DataStorage.GetSitecoreItem(itemId, Language.Parse("en"), Version.Parse(2)).Returns(itemWithNewVersion);

            sut.Initialize(originalItem);

            // act
            var result = ReflectionUtil.CallMethod(sut, "DoExecute");

            // assert
            result.Should().BeSameAs(itemWithNewVersion);
        }
Ejemplo n.º 18
0
        protected void Run(ClientPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            string   dbName   = args.Parameters["databasename"];
            string   id       = args.Parameters["id"];
            string   lang     = args.Parameters["language"];
            string   ver      = args.Parameters["version"];
            Database database = Factory.GetDatabase(dbName);

            Assert.IsNotNull(database, dbName);

            Item obj = database.Items[id, Language.Parse(lang), Version.Parse(ver)];

            if (obj == null)
            {
                SheerResponse.Alert("Item not found.");
            }
            else
            {
                if (!SheerResponse.CheckModified())
                {
                    return;
                }
                if (args.IsPostBack)
                {
                    return;
                }

                UrlString urlString = new UrlString(UIUtil.GetUri("control:SchedulePublish"));
                urlString.Append("id", obj.ID.ToString());
                urlString.Append("unpublish", args.Parameters["unpublish"]);
                SheerResponse.ShowModalDialog(urlString.ToString(), "600", "600", string.Empty, true);
                args.WaitForPostBack();
            }
        }
 // Methods
 public void Comment(ClientPipelineArgs args)
 {
     if (!args.IsPostBack)
     {
         Context.ClientPage.ClientResponse.Input("Enter a comment:", string.Empty);
         args.WaitForPostBack();
     }
     else if (args.Result.Length > 0x7d0)
     {
         Context.ClientPage.ClientResponse.ShowError(new Exception(string.Format("The comment is too long.\n\nYou have entered {0} characters.\nA comment cannot contain more than 2000 characters.", args.Result.Length)));
         Context.ClientPage.ClientResponse.Input("Enter a comment:", string.Empty);
         args.WaitForPostBack();
     }
     else if (((args.Result != null) && (args.Result != "null")) && (args.Result != "undefined"))
     {
         IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;
         if (workflowProvider != null)
         {
             IWorkflow workflow = workflowProvider.GetWorkflow(Context.ClientPage.ServerProperties["workflowid"] as string);
             if (workflow != null)
             {
                 Item item = Context.ContentDatabase.Items[Context.ClientPage.ServerProperties["id"] as string, Language.Parse(Context.ClientPage.ServerProperties["language"] as string), Version.Parse(Context.ClientPage.ServerProperties["version"] as string)];
                 if (item != null)
                 {
                     try
                     {
                         workflow.Execute(Context.ClientPage.ServerProperties["command"] as string, item, args.Result, true, new object[0]);
                     }
                     catch (WorkflowStateMissingException)
                     {
                         SheerResponse.Alert("One or more items could not be processed because their workflow state does not specify the next step.", new string[0]);
                     }
                     Context.ClientPage.ClientResponse.SetLocation(string.Empty);
                 }
             }
         }
     }
 }
Ejemplo n.º 20
0
        public void FiltersOnPathAndTemplate()
        {
            // Mock the database
            var db = Mock.Of <Database>();

            // Mock the parent item
            var parentId   = ID.NewID;
            var parentDef  = new ItemDefinition(parentId, "parent", Templates.Product.Id, ID.Null);
            var parentData = new ItemData(parentDef, Language.Parse("en"), Version.Parse(1), new FieldList());
            var parent     = new Mock <Item>(parentId, parentData, db);

            // Mock the Sitecore services
            var factoryMock = new Mock <BaseFactory>();

            factoryMock.Setup(x => x.GetDatabase(It.IsAny <string>())).Returns(db);
            var factory     = factoryMock.Object;
            var itemManager = Mock.Of <BaseItemManager>();

            // Mock search context, so we are testing LINQ to Objects instead of LINQ to Sitecore
            var itemUri           = new ItemUri("sitecore://master/{11111111-1111-1111-1111-111111111111}?lang=en&ver=1");
            var mockSearchContext = new Mock <IProviderSearchContext>();

            mockSearchContext.Setup(x => x.GetQueryable <ProductSearchQuery>())
            .Returns(new[]
            {
                // Matches Path and Template
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { Templates.Product.Id },
                    Paths     = new[] { parentId }
                },
                // Matches Path and Template
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { ID.NewID, Templates.Product.Id, ID.NewID },
                    Paths     = new[] { ID.NewID, parentId, ID.NewID }
                },
                // Matches Template Only
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { Templates.Product.Id },
                    Paths     = new[] { ID.NewID }
                },
                // Matches Path Only
                new ProductSearchQuery
                {
                    UniqueId  = itemUri,
                    Templates = new[] { ID.NewID },
                    Paths     = new[] { parentId }
                }
            }.AsQueryable());

            // Use Moq.Protected to ensure our test object uses the mock search context
            var mockRepo = new Mock <ProductRepository>(factory, itemManager);

            mockRepo.Protected()
            .Setup <IProviderSearchContext>("GetSearchContext", ItExpr.IsAny <Item>())
            .Returns(mockSearchContext.Object);

            // Act
            var result = mockRepo.Object.GetProducts(parent.Object).ToList();

            // If the tested class is filtering appropriately, we should get predictible results
            Assert.Equal(2, result.Count);
        }
Ejemplo n.º 21
0
 public SkinnyItem(string id, string language, string version, string databaseName)
     : this(new ItemUri(ID.Parse(id), SCLang.Parse(language), SCVersion.Parse(version), databaseName))
 {
 }
        public void ShouldNotUpdateFieldsIfItemVersionIsZero(SaveItemCommand sut, DbItem item, FieldList fields, Language language)
        {
            // arrange
            sut.DataStorage.GetFakeItem(item.ID).Returns(item);
            var updatedItem = ItemHelper.CreateInstance(sut.Database, "updated item", item.ID, ID.NewID, ID.Null, fields, language, Version.Parse(0));

            sut.Initialize(updatedItem);

            // act
            Action action = () => ReflectionUtil.CallMethod(sut, "DoExecute");

            // assert
            action.ShouldNotThrow();
        }
Ejemplo n.º 23
0
        public void ShouldCreateVersionedItem()
        {
            using (var db = new Db
            {
                new DbItem("home")
                {
                    Fields =
                    {
                        new DbField("Title")
                        {
                            { "en", 1, "title version 1" },
                            { "en", 2, "title version 2" }
                        }
                    }
                }
            })
            {
                var item1 = db.Database.GetItem("/sitecore/content/home", Language.Parse("en"), Version.Parse(1));
                item1["Title"].Should().Be("title version 1");
                item1.Version.Number.Should().Be(1);

                var item2 = db.Database.GetItem("/sitecore/content/home", Language.Parse("en"), Version.Parse(2));
                item2["Title"].Should().Be("title version 2");
                item2.Version.Number.Should().Be(2);
            }
        }
        public void ShouldUpdateBranchId(SaveItemCommand sut, DbItem item, ID branchId, FieldList fields, Language language)
        {
            // arrange
            sut.DataStorage.GetFakeItem(item.ID).Returns(item);
            var updatedItem = ItemHelper.CreateInstance(sut.Database, "updated item", item.ID, ID.NewID, branchId, fields, language, Version.Parse(0));

            sut.Initialize(updatedItem);

            // act
            ReflectionUtil.CallMethod(sut, "DoExecute");

            // assert
            item.BranchId.Should().Be(branchId);
        }
        public void BuildDiff(string server)
        {
            Compare = new Dictionary <string, List <Tuple <string, string> > >();
            IItemData itemData = null;

            itemData = Bootstrap.Container.Resolve <IRemoteContentService>().GetRemoteItemData(Guid.Parse(Id), server);
            using (new SecurityDisabler())
            {
                var localItem = Factory.GetDatabase("master", true).DataManager.DataEngine.GetItem(new ID(Id), LanguageManager.DefaultLanguage, Sitecore.Data.Version.Latest);
                localItem.Fields.ReadAll();
                foreach (var chk in itemData.SharedFields)
                {
                    if (AreFieldsEqual(localItem.Fields[new ID(chk.FieldId)], chk))
                    {
                        continue;
                    }

                    if (!Compare.ContainsKey("shared"))
                    {
                        Compare["shared"] = new List <Tuple <string, string> >();
                    }

                    Compare["shared"].Add(chk.BlobId != null
                                                ? new Tuple <string, string>(chk.NameHint, "Blob value changed")
                                                : new Tuple <string, string>(chk.NameHint, HtmlDiff.HtmlDiff.Execute(HttpUtility.HtmlEncode(localItem[new ID(chk.FieldId)].Replace("\r", "")), HttpUtility.HtmlEncode(chk.Value.Replace("\r", "")))));
                }
                Dictionary <string, int> tracker = new Dictionary <string, int>();
                foreach (var ver in itemData.Versions)
                {
                    if (!tracker.ContainsKey(LanguageManager.GetLanguage(ver.Language.Name).Name))
                    {
                        tracker.Add(LanguageManager.GetLanguage(ver.Language.Name).Name, 1);
                    }
                    else
                    {
                        tracker[LanguageManager.GetLanguage(ver.Language.Name).Name]++;
                    }
                    Item verItem = localItem.Database.DataManager.DataEngine.GetItem(new ID(Id), LanguageManager.GetLanguage(ver.Language.Name), Version.Parse(ver.VersionNumber));
                    verItem.Fields.ReadAll();
                    HashSet <Guid> fieldsProcessed = new HashSet <Guid>(ver.Fields.Select(x => x.FieldId));
                    foreach (var verfield in ver.Fields)
                    {
                        if (AreFieldsEqual(verItem.Fields[new ID(verfield.FieldId)], verfield))
                        {
                            continue;
                        }
                        string key = ver.Language.Name + " v" + ver.VersionNumber;
                        if (!Compare.ContainsKey(key))
                        {
                            Compare[key] = new List <Tuple <string, string> >();
                        }
                        Compare[key].Add(verfield.BlobId != null
                                                        ? new Tuple <string, string>(verfield.NameHint, "Blob value changed")
                                                        : new Tuple <string, string>(verfield.NameHint, HtmlDiff.HtmlDiff.Execute(HttpUtility.HtmlEncode(verItem[new ID(verfield.FieldId)].Replace("\r", "")), HttpUtility.HtmlEncode(verfield.Value.Replace("\r", "")))));
                    }

                    foreach (Field field in verItem.Fields.Where(x => !x.Unversioned && !x.Shared).Where(x => !fieldsProcessed.Contains(x.ID.Guid) && !string.IsNullOrWhiteSpace(x.Value)))
                    {
                        string key = ver.Language.Name + " v" + ver.VersionNumber;
                        if (!Compare.ContainsKey(key))
                        {
                            Compare[key] = new List <Tuple <string, string> >();
                        }
                        Compare[key].Add(field.HasBlobStream
                                                        ? new Tuple <string, string>(field.DisplayName, "Blob value changed")
                                                        : new Tuple <string, string>(field.DisplayName, HtmlDiff.HtmlDiff.Execute(HttpUtility.HtmlEncode(verItem[field.ID].Replace("\r", "")), "")));
                    }
                }
                foreach (var lang in localItem.Languages.Where(x => !tracker.ContainsKey(x.Name)))
                {
                    Item langItem = localItem.Database.DataManager.DataEngine.GetItem(new ID(Id), lang, Version.Latest);
                    langItem.Fields.ReadAll();
                    for (int ver = 1; ver <= langItem.Versions.Count; ver++)
                    {
                        string key = "Extra version";
                        if (!Compare.ContainsKey(key))
                        {
                            Compare[key] = new List <Tuple <string, string> >();
                        }
                        Compare[key].Add(new Tuple <string, string>("Extra local version exists that's not on the remote.", $"{lang.Name} v{ver}"));
                    }
                }
                foreach (var lang in localItem.Languages.Where(x => tracker.ContainsKey(x.Name)))
                {
                    Item langItem = localItem.Database.DataManager.DataEngine.GetItem(new ID(Id), lang, Version.Latest);
                    langItem.Fields.ReadAll();
                    for (int ver = tracker[lang.Name] + 1; ver <= langItem.Versions.Count; ver++)
                    {
                        string key = "Extra version";
                        if (!Compare.ContainsKey(key))
                        {
                            Compare[key] = new List <Tuple <string, string> >();
                        }
                        Compare[key].Add(new Tuple <string, string>("Extra local version exists that's not on the remote.", $"{lang.Name} v{ver}"));
                    }
                }
                foreach (var unver in itemData.UnversionedFields)
                {
                    Item verItem = localItem.Database.DataManager.DataEngine.GetItem(new ID(Id), LanguageManager.GetLanguage(unver.Language.Name), Version.Latest);
                    verItem.Fields.ReadAll();
                    foreach (var unverfield in unver.Fields)
                    {
                        if (AreFieldsEqual(verItem.Fields[new ID(unverfield.FieldId)], unverfield))
                        {
                            continue;
                        }
                        if (!Compare.ContainsKey(unver.Language.Name))
                        {
                            Compare[verItem.Language.Name] = new List <Tuple <string, string> >();
                        }
                        Compare[unver.Language.Name].Add(unverfield.BlobId != null
                                                        ? new Tuple <string, string>(unverfield.NameHint, "Blob value changed")
                                                        : new Tuple <string, string>(unverfield.NameHint, HtmlDiff.HtmlDiff.Execute(HttpUtility.HtmlEncode(verItem[new ID(unverfield.FieldId)].Replace("\r", "")), HttpUtility.HtmlEncode(unverfield.Value.Replace("\r", "")))));
                    }
                }
            }
        }
        public override void HandleMessage(Message message)
        {
            switch (message.Name)
            {
            case "workflow:send":
                this.Send(message);
                return;

            case "workflow:sendselected":
                this.SendSelected(message);
                return;

            case "workflow:sendall":
                this.SendAll(message);
                return;

            case "window:close":
                Windows.Close();
                return;

            case "workflow:showhistory":
                ShowHistory(message, Context.ClientPage.ClientRequest.Control);
                return;

            case "workbox:hide":
                Context.ClientPage.SendMessage(this, "pane:hide(id=" + message["id"] + ")");
                Context.ClientPage.ClientResponse.SetAttribute("Check_Check_" + message["id"], "checked", "false");
                break;

            case "pane:hidden":
                Context.ClientPage.ClientResponse.SetAttribute("Check_Check_" + message["paneid"], "checked", "false");
                break;

            case "workbox:show":
                Context.ClientPage.SendMessage(this, "pane:show(id=" + message["id"] + ")");
                Context.ClientPage.ClientResponse.SetAttribute("Check_Check_" + message["id"], "checked", "true");
                break;

            case "pane:showed":
                Context.ClientPage.ClientResponse.SetAttribute("Check_Check_" + message["paneid"], "checked", "true");
                break;
            }
            base.HandleMessage(message);
            string str = message["id"];

            if ((str != null) && (str.Length > 0))
            {
                string name = StringUtil.GetString(new string[] { message["language"] });
                string str3 = StringUtil.GetString(new string[] { message["version"] });
                Item   item = Context.ContentDatabase.Items[str, Language.Parse(name), Version.Parse(str3)];
                if (item != null)
                {
                    Dispatcher.Dispatch(message, item);
                }
            }
        }
Ejemplo n.º 27
0
        protected virtual Item PasteVersion(Item item, IItemVersion serializedVersion, bool creatingNewItem, List <TemplateMissingFieldException> softErrors)
        {
            Language language      = Language.Parse(serializedVersion.Language.Name);
            var      targetVersion = Version.Parse(serializedVersion.VersionNumber);

            Item languageItem = item.Database.GetItem(item.ID, language);

            if (languageItem == null)
            {
                throw new InvalidOperationException("Item retrieved from the database was null. This may indicate issues with the Sitecore cache. Recycle your app pool and try again and it should work.");
            }

            Item languageVersionItem = languageItem.Versions[targetVersion];

            IDictionary <Guid, IItemFieldValue> serializedVersionFieldsLookup = serializedVersion.Fields.ToDictionary(field => field.FieldId);

            // Add a new version if we need to for the serialized version we're pasting
            // NOTE: normally Sitecore will return an empty version when requested (e.g. you can ask for 'en#25' and get a blank version back)
            // so this null check is only here for legacy support
            if (languageVersionItem == null)
            {
                languageVersionItem = languageItem.Versions.AddVersion();

                if (languageVersionItem == null)
                {
                    throw new InvalidOperationException("Failed to add a new version: AddVersion() returned null.");
                }

                if (!creatingNewItem)
                {
                    _logger.AddedNewVersion(languageVersionItem);
                }
            }

            // Based on the note above, in order to detect the modern form where item.Versions[] returns a blank version no matter what,
            // we need to check again to see if the version we requested is actually currently present on the item or not, so we can correctly log version adds
            // ReSharper disable once SimplifyLinqExpression
            if (!languageVersionItem.Versions.GetVersionNumbers().Any(x => x.Number == languageVersionItem.Version.Number))
            {
                if (!creatingNewItem)
                {
                    _logger.AddedNewVersion(languageVersionItem);
                }
            }

            // begin writing the version data
            bool commitEdit = false;

            try
            {
                languageVersionItem.Editing.BeginEdit();

                languageVersionItem.RuntimeSettings.ReadOnlyStatistics = true;

                if (languageVersionItem.Versions.Count == 0)
                {
                    languageVersionItem.Fields.ReadAll();
                }

                // find versioned fields that need to be reset to standard value, because they are not in serialized
                // (we do all these checks so we can back out of the edit context and avoid a DB write if we don't need one)
                foreach (Field field in languageVersionItem.Fields)
                {
                    // if the field is excluded by the fieldFilter
                    if (!_fieldFilter.Includes(field.ID.Guid))
                    {
                        continue;
                    }

                    // shared/unversioned fields = ignore, those are handled in their own paste methods
                    if (field.Shared || field.Unversioned)
                    {
                        continue;
                    }

                    // if we have a value in the serialized item, we don't need to reset the field
                    if (serializedVersionFieldsLookup.ContainsKey(field.ID.Guid))
                    {
                        continue;
                    }

                    // if the field is one of revision, updated, or updated by we can specially ignore it, because these will get set below if actual field changes occur
                    // so there's no need to reset them as well
                    if (field.ID == FieldIDs.Revision || field.ID == FieldIDs.UpdatedBy || field.ID == FieldIDs.Updated)
                    {
                        continue;
                    }

                    _logger.ResetFieldThatDidNotExistInSerialized(field);

                    field.Reset();

                    commitEdit = true;
                }

                bool wasOwnerFieldParsed = false;
                foreach (IItemFieldValue field in serializedVersion.Fields)
                {
                    if (field.FieldId == FieldIDs.Owner.Guid)
                    {
                        wasOwnerFieldParsed = true;
                    }

                    try
                    {
                        if (PasteField(languageVersionItem, field, creatingNewItem))
                        {
                            commitEdit = true;
                        }
                    }
                    catch (TemplateMissingFieldException tex)
                    {
                        softErrors.Add(tex);
                    }
                }

                if (!wasOwnerFieldParsed)
                {
                    languageVersionItem.Fields[FieldIDs.Owner].Reset();
                    commitEdit = true;
                }

                // if the item came with blank statistics, and we're creating the item or have version updates already, let's set some sane defaults - update revision, set last updated, etc
                if (creatingNewItem || commitEdit)
                {
                    if (!serializedVersionFieldsLookup.ContainsKey(FieldIDs.Revision.Guid))
                    {
                        languageVersionItem.Fields[FieldIDs.Revision].SetValue(Guid.NewGuid().ToString(), true);
                    }

                    if (!serializedVersionFieldsLookup.ContainsKey(FieldIDs.Updated.Guid))
                    {
                        languageVersionItem[FieldIDs.Updated] = DateUtil.ToIsoDate(DateTime.UtcNow);
                    }

                    if (!serializedVersionFieldsLookup.ContainsKey(FieldIDs.UpdatedBy.Guid))
                    {
                        languageVersionItem[FieldIDs.UpdatedBy] = @"sitecore\unicorn";
                    }
                }

                // we commit the edit context - and write to the DB - only if we changed something
                if (commitEdit)
                {
                    languageVersionItem.Editing.EndEdit();
                }
            }
            finally
            {
                if (languageVersionItem.Editing.IsEditing)
                {
                    languageVersionItem.Editing.CancelEdit();
                }
            }

            if (commitEdit)
            {
                ClearCaches(languageVersionItem.Database, languageVersionItem.ID);
                ResetTemplateEngineIfItemIsTemplate(languageVersionItem);
            }

            return(languageVersionItem);
        }
        private void Send(Message message)
        {
            IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;

            if (workflowProvider != null)
            {
                string    workflowID = message["wf"];
                IWorkflow workflow   = workflowProvider.GetWorkflow(workflowID);
                if (workflow != null)
                {
                    Item item = Context.ContentDatabase.Items[message["id"], Language.Parse(message["la"]), Version.Parse(message["vs"])];
                    if (item != null)
                    {
                        if ((message["ui"] != "1") && !(message["suppresscomment"] == "1"))
                        {
                            Context.ClientPage.ServerProperties["id"]         = message["id"];
                            Context.ClientPage.ServerProperties["language"]   = message["la"];
                            Context.ClientPage.ServerProperties["version"]    = message["vs"];
                            Context.ClientPage.ServerProperties["command"]    = message["command"];
                            Context.ClientPage.ServerProperties["workflowid"] = workflowID;
                            Context.ClientPage.Start(this, "Comment");
                        }
                        else
                        {
                            try
                            {
                                workflow.Execute(message["command"], item, string.Empty, true, new object[0]);
                            }
                            catch (WorkflowStateMissingException)
                            {
                                SheerResponse.Alert("One or more items could not be processed because their workflow state does not specify the next step.", new string[0]);
                            }
                            Context.ClientPage.ClientResponse.SetLocation(string.Empty);
                        }
                    }
                }
            }
        }
        private void SendSelected(Message message)
        {
            IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;

            if (workflowProvider != null)
            {
                string    workflowID = message["wf"];
                string    str2       = message["ws"];
                IWorkflow workflow   = workflowProvider.GetWorkflow(workflowID);
                if (workflow != null)
                {
                    int  num  = 0;
                    bool flag = false;
                    foreach (string str3 in Context.ClientPage.ClientRequest.Form.Keys)
                    {
                        if ((str3 != null) && str3.StartsWith("check_"))
                        {
                            string   str4     = "hidden_" + str3.Substring(6);
                            string[] strArray = Context.ClientPage.ClientRequest.Form[str4].Split(new char[] { ',' });
                            Item     item     = Context.ContentDatabase.Items[strArray[0], Language.Parse(strArray[1]), Version.Parse(strArray[2])];
                            if (item != null)
                            {
                                WorkflowState state = workflow.GetState(item);
                                if (state.StateID == str2)
                                {
                                    try
                                    {
                                        workflow.Execute(message["command"], item, state.DisplayName, true, new object[0]);
                                    }
                                    catch (WorkflowStateMissingException)
                                    {
                                        flag = true;
                                    }
                                    num++;
                                }
                            }
                        }
                    }
                    if (flag)
                    {
                        SheerResponse.Alert("One or more items could not be processed because their workflow state does not specify the next step.", new string[0]);
                    }
                    if (num == 0)
                    {
                        Context.ClientPage.ClientResponse.Alert("There are no selected items.");
                    }
                    else
                    {
                        Context.ClientPage.ClientResponse.SetLocation(string.Empty);
                    }
                }
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Gets an <see cref="Item"/> by id, language and version number.
        /// </summary>
        /// <param name="id">The item id.</param>
        /// <param name="language">The item language.</param>
        /// <param name="version">The item version.</param>
        /// <returns>The item.</returns>
        public Item GetItem(ID id, string language, int version)
        {
            Assert.ArgumentNotNullOrEmpty(language, "language");

            return(this.Database.GetItem(id, Language.Parse(language), Version.Parse(version)));
        }