Ejemplo n.º 1
0
        public void TestMethodSimpleImplicitCast()
        {
            Simple s = new Simple();

            ReflectionUtil.CallMethod(s, "SetInt", 3.4f);
            Assert.AreEqual(3, s._a);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 根据服务 id 和参数,调用服务,返回服务运行的结果
        /// </summary>
        /// <param name="serviceId"></param>
        /// <param name="serviceParamValues">服务的参数</param>
        /// <param name="defaultValues">默认参数</param>
        /// <returns></returns>
        public static IList GetData(long serviceId, Dictionary <string, string> serviceParamValues, Dictionary <string, string> defaultValues)
        {
            ArrayList argList = new ArrayList();

            Service service = Get(serviceId);
            IList   parms   = service.GetParams();

            for (int i = 0; i < parms.Count; i++)
            {
                String pkey = "param" + i;
                String val  = serviceParamValues.ContainsKey(pkey) ? serviceParamValues[pkey] : null;

                Object argValue = ((ParamControl)parms[i]).ChangeType(val);
                argList.Add(argValue);
            }

            foreach (KeyValuePair <String, String> pair in defaultValues)
            {
                Object argValue = getValue(service, pair);
                argList.Add(argValue);
            }

            object[] args = argList.ToArray();

            Object objService = ObjectContext.GetByType(service.Type);

            return(ReflectionUtil.CallMethod(objService, service.Method, args) as IList);
        }
Ejemplo n.º 3
0
        // In this method we re-retrieve the item form the repository and populate the
        // Sitecore item fields we care about from this item. By breaking this out from
        // GetItemDefinition, we're able to keeps things flexible in terms of later updates.
        public override FieldList GetItemFields(ItemDefinition itemDefinition, VersionUri versionUri, CallContext context)
        {
            if (this.canProcessItem(itemDefinition.ID))
            {
                Trace.WriteLine(String.Format("GetItemFields({0}, {1}, {2})", itemDefinition, versionUri, context), "ProductDataProvider");

                var fields = new FieldList();

                var template = TemplateManager.GetTemplate(this.productTemplateId, this.ContentDatabase);
                if (template != null)
                {
                    var originalId = this.getExternalId(itemDefinition.ID);
                    if (originalId != Guid.Empty)
                    {
                        if (context.DataManager.DataSource.ItemExists(itemDefinition.ID))
                        {
                            ReflectionUtil.CallMethod(typeof(ItemCache), "RemoveItem", true, true, new Object[] { itemDefinition.ID });
                        }

                        var product = this.productRepository.Find(originalId);
                        if (product != null)
                        {
                            foreach (var dataField in template.GetFields().Where(ItemUtil.IsDataField))
                            {
                                fields.Add(dataField.ID, this.getFieldValue(dataField, product));
                            }
                        }
                    }
                }

                return(fields);
            }
            return(base.GetItemFields(itemDefinition, versionUri, context));
        }
        public void ShouldThrowExceptionIfNoFieldFoundInOriginalItem(SaveItemCommand sut, ID itemId, ID templateId, ID fieldId)
        {
            // arrange
            var originalItem = new DbItem("original item", itemId)
            {
                new DbField("Title")
            };

            sut.DataStorage.GetFakeItem(itemId).Returns(originalItem);
            sut.DataStorage.GetFakeTemplate(null).ReturnsForAnyArgs(new DbTemplate("Sample", templateId));

            var fields = new FieldList {
                { fieldId, "updated title" }
            };
            var updatedItem = ItemHelper.CreateInstance(sut.Database, "updated item", itemId, ID.NewID, ID.Null, fields);

            sut.Initialize(updatedItem);

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

            // assert
            action
            .ShouldThrow <TargetInvocationException>()
            .WithInnerException <InvalidOperationException>()
            .WithInnerMessage("Item field not found. Item: 'updated item', '{0}'; field: '{1}'.".FormatWith(itemId, fieldId));
        }
Ejemplo n.º 5
0
        public void ShouldMoveItemToNewDestination(MoveItemCommand sut, Item item, Item destination, ID parentId, DataStorageSwitcher switcher)
        {
            // arrange
            var fakeItem = new DbItem("item", item.ID)
            {
                ParentID = parentId
            };
            var fakeParent = new DbItem("parent", parentId)
            {
                Children = { fakeItem }
            };
            var fakeDestination = new DbItem("destination", destination.ID)
            {
                FullPath = "/new destination path"
            };

            sut.DataStorage.GetFakeItem(item.ID).Returns(fakeItem);
            sut.DataStorage.GetFakeItem(parentId).Returns(fakeParent);
            sut.DataStorage.GetFakeItem(destination.ID).Returns(fakeDestination);

            sut.Initialize(item, destination);

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

            // assert
            result.Should().BeTrue();
            fakeItem.ParentID.Should().Be(destination.ID);
            fakeItem.FullPath.Should().Be("/new destination path/item");
            fakeParent.Children.Should().NotContain(fakeItem);
            fakeDestination.Children.Should().Contain(fakeItem);
        }
        public void ShouldAddMissingFieldToItemIfFieldExistsInTemplate(SaveItemCommand sut, ID itemId, ID templateId, ID fieldId)
        {
            // arrange
            var template = new DbTemplate("Sample", templateId)
            {
                fieldId
            };
            var originalItem = new DbItem("original item", itemId, templateId);

            sut.DataStorage.GetFakeItem(itemId).Returns(originalItem);
            sut.DataStorage.GetFakeTemplate(templateId).Returns(template);

            var fields = new FieldList {
                { fieldId, "updated title" }
            };
            var updatedItem = ItemHelper.CreateInstance(sut.Database, "updated item", itemId, ID.NewID, ID.Null, fields);

            sut.Initialize(updatedItem);

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

            // assert
            originalItem.Name.Should().Be("updated item");
            originalItem.Fields[fieldId].Value.Should().Be("updated title");
        }
        public void ShouldUpdateExistingItemInDataStorage(SaveItemCommand sut, ID itemId, ID templateId, ID fieldId)
        {
            // arrange
            var originalItem = new DbItem("original item", itemId)
            {
                new DbField("Title", fieldId)
                {
                    Value = "original title"
                }
            };

            sut.DataStorage.GetFakeItem(itemId).Returns(originalItem);
            sut.DataStorage.GetFakeTemplate(null).ReturnsForAnyArgs(new DbTemplate("Sample", templateId));

            var fields = new FieldList {
                { fieldId, "updated title" }
            };
            var updatedItem = ItemHelper.CreateInstance(sut.Database, "updated item", itemId, ID.NewID, ID.Null, fields);

            sut.Initialize(updatedItem);

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

            // assert
            originalItem.Name.Should().Be("updated item");
            originalItem.Fields[fieldId].Value.Should().Be("updated title");
        }
        public void ShouldResolvePath(string path, ResolvePathCommand sut, DbItem item)
        {
            item.FullPath = "/sitecore/content/home";
            sut.DataStorage.GetFakeItems().Returns(new[] { item });
            sut.Initialize(path);

            ReflectionUtil.CallMethod(sut, "DoExecute").Should().Be(item.ID);
        }
        public void ShouldReturnNullIfNoBlobStreamExistsInDataStorage(GetBlobStreamCommand sut, Guid blobId)
        {
            // arrange
            sut.Initialize(blobId);

            // act & assert
            ReflectionUtil.CallMethod(sut, "DoExecute").Should().BeNull();
        }
Ejemplo n.º 10
0
        public void DoExecuteThrowsNotSupportedException(Type command, DataStorage dataStorage)
        {
            var sut = ReflectionUtil.CreateObject(command, new object[] { dataStorage });

            Action action = () => ReflectionUtil.CallMethod(sut, "CreateInstance");

            action.ShouldThrow <TargetInvocationException>().WithInnerException <NotSupportedException>();
        }
        public void DoExecuteThrowsNotSupportedException(Type prototype)
        {
            var sut = Activator.CreateInstance(prototype, Database.GetDatabase("master"));

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

            action.ShouldThrow <TargetInvocationException>().WithInnerException <NotSupportedException>();
        }
Ejemplo n.º 12
0
        protected virtual void RemoveItemFromCaches(IItemMetadata metadata, string databaseName)
        {
            try
            {
                if (databaseName != Database.Name)
                {
                    return;
                }

                // this is a bit heavy handed, sure.
                // but the caches get interdependent stuff - like caching child IDs
                // that make it difficult to cleanly remove a single item ID from all cases in the cache
                // either way, this should be a relatively rare occurrence (from runtime changes on disk)
                // and we're preserving prefetch, etc. Seems pretty zippy overall.
                CacheManager.ClearAllCaches();

                if (metadata == null)
                {
                    return;
                }

                if (metadata.TemplateId == TemplateIDs.Template.Guid ||
                    metadata.TemplateId == TemplateIDs.TemplateField.Guid ||
                    (metadata.Path != null && metadata.Path.EndsWith("__Standard Values", StringComparison.OrdinalIgnoreCase)))
                {
                    Database.Engines.TemplateEngine.Reset();
                }

                if (_syncConfiguration != null && (_syncConfiguration.UpdateLinkDatabase || _syncConfiguration.UpdateSearchIndex))
                {
                    var item = GetSourceItemFromId(new ID(metadata.Id), true);

                    if (item == null)
                    {
                        return;
                    }

                    if (_syncConfiguration.UpdateLinkDatabase)
                    {
                        Globals.LinkDatabase.UpdateReferences(item);
                    }

                    if (_syncConfiguration.UpdateSearchIndex)
                    {
                        foreach (var index in ContentSearchManager.Indexes)
                        {
                            ReflectionUtil.CallMethod(typeof(IndexCustodian), "UpdateItem", true, true, true, new object[] { index, new SitecoreItemUniqueId(item.Uri) });
                            //IndexCustodian.UpdateItem(index, new SitecoreItemUniqueId(item.Uri));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // we catch this because this method runs on a background thread. If an unhandled exception occurs there, the app pool terminates and that's Naughty(tm).
                Log.Error($"[Unicorn] Exception occurred while processing a background item cache removal on {metadata?.Path ?? "unknown item"}", ex, this);
            }
        }
Ejemplo n.º 13
0
 public void ShouldCreateInstance(
     CopyItemCommandPrototype sut,
     DataStorage dataStorage)
 {
     using (new DataStorageSwitcher(dataStorage))
     {
         ReflectionUtil.CallMethod(sut, "CreateInstance").Should().BeOfType <CopyItemCommand>();
     }
 }
        public void ShouldGetBlobStreamFromDataStorage(GetBlobStreamCommand sut, Guid blobId, [Modest] MemoryStream stream)
        {
            // arrange
            sut.DataStorage.GetBlobStream(blobId).Returns(stream);
            sut.Initialize(blobId);

            // act & assert
            ReflectionUtil.CallMethod(sut, "DoExecute").Should().BeSameAs(stream);
        }
Ejemplo n.º 15
0
        public void TestMethodSimple()
        {
            Simple s = new Simple();

            s._a = 44;
            Assert.AreEqual(44, ReflectionUtil.CallMethod(s, "GetInt"));
            ReflectionUtil.CallMethod(s, "SetInt", 55);
            Assert.AreEqual(55, s._a);
        }
Ejemplo n.º 16
0
        public void ShouldReturnTrueIfBlobStreamExistsInDataStorage(BlobStreamExistsCommand sut, Guid blobId, [Modest] MemoryStream stream)
        {
            // arrange
            sut.DataStorage.GetBlobStream(blobId).Returns(stream);
            sut.Initialize(blobId);

            // act & assert
            ReflectionUtil.CallMethod(sut, "DoExecute").Should().Be(true);
        }
Ejemplo n.º 17
0
        private void ApplyCallbackUrlFix()
        {
            HttpContext current = HttpContext.Current;
            string      url     = current.Response.ApplyAppPathModifier(current.Request.RawUrl);
            string      str2    = System.Convert.ToString(ReflectionUtil.CallMethod(this._grid, "GetSaneId", true, true));
            var         str3    = new UrlString(url);

            str3.Add("Cart_" + str2 + "_Callback", "yes");
            this._grid.CallbackPrefix = str3.ToString();
        }
        public void ShouldReturnFalseIfNoItemFound(DeleteItemCommand sut, Item item, ID parentId)
        {
            // arrange
            sut.Initialize(item, parentId);

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

            // assert
            result.Should().BeFalse();
        }
Ejemplo n.º 19
0
        public void ShouldReturnEmptyListIfNoItemFound(GetChildrenCommand sut, Item item)
        {
            // arrange
            sut.Initialize(item);

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

            // assert
            children.Should().BeEmpty();
        }
Ejemplo n.º 20
0
        public void TestMethodGenericSimple2()
        {
            GenericOne <int> gi = new GenericOne <int> ();

            Assert.AreEqual(3, ReflectionUtil.CallMethod(gi, "GetInt", System.Reflection.BindingFlags.Public));
            Assert.AreEqual(4, ReflectionUtil.CallMethod(gi, "GetT", 4));
            Assert.AreEqual(4.3f, ReflectionUtil.CallMethod(gi, "GetS", new System.Type[] { typeof(float) }, 4.3f));

            Assert.AreEqual("hoge", ReflectionUtil.CallMethod(gi, "Get2", System.Reflection.BindingFlags.Public, new System.Type[] { typeof(string) }, "hoge", 5));
            Assert.AreEqual(5, gi._pa);
        }
Ejemplo n.º 21
0
        public void ShouldSetBlobStreamInDataStorage(SetBlobStreamCommand sut, Guid blobId, [Modest] MemoryStream stream)
        {
            // arrange
            sut.Initialize(stream, blobId);

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

            // assert
            sut.DataStorage.Received().SetBlobStream(blobId, stream);
        }
        public void ShouldResolveFirstItemId(ResolvePathCommand sut, DbItem item1, DbItem item2)
        {
            const string path = "/sitecore/content/home";

            item1.FullPath = path;
            item2.FullPath = path;
            sut.DataStorage.GetFakeItems().Returns(new[] { item1, item2 });
            sut.Initialize(path);

            ReflectionUtil.CallMethod(sut, "DoExecute").Should().Be(item1.ID);
        }
        public void ShouldGetEmptyVersionCollectionIfNoFakeItemFound(GetVersionsCommand sut, Item item, Language language, DbItem dbitem)
        {
            // arrange
            sut.Initialize(item, language);

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

            // assert
            versionCollection.Should().BeEmpty();
        }
        public FakeDataProviderTest()
        {
            var database = Database.GetDatabase("master");

            this.dataStorage = new DataStorage(database);
            this.dataStorage.FakeItems.Clear();
            this.dataStorage.FakeTemplates.Clear();

            this.dataProvider = new FakeDataProvider(this.dataStorage);
            ReflectionUtil.CallMethod(database, "AddDataProvider", new object[] { this.dataProvider });
        }
Ejemplo n.º 25
0
        public void ShouldGetItemFromDataStorage(GetItemCommand sut, Item item)
        {
            // arrange
            sut.DataStorage.GetSitecoreItem(item.ID, item.Language, item.Version).Returns(item);
            sut.Initialize(item.ID, item.Language, item.Version);

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

            // assert
            result.Should().Be(item);
        }
        public void ShouldIncreaseFakeItemVersionCount(AddVersionCommand sut, Item item, DbItem dbItem)
        {
            // arrange
            sut.DataStorage.GetFakeItem(item.ID).Returns(dbItem);
            sut.Initialize(item);

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

            // assert
            dbItem.GetVersionCount("en").Should().Be(1);
        }
Ejemplo n.º 27
0
        public void ShouldReturnRootItem(GetRootItemCommand sut, Item rootItem)
        {
            // arrange
            sut.DataStorage.GetSitecoreItem(ItemIDs.RootID, rootItem.Language).Returns(rootItem);
            sut.Initialize(LanguageManager.DefaultLanguage, Version.Latest);

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

            // assert
            result.Should().Be(rootItem);
        }
Ejemplo n.º 28
0
        public void ShouldReturnCreatedItem(AddFromTemplateCommand sut, Item item, Item destination)
        {
            // arrange
            sut.DataStorage.GetSitecoreItem(item.ID).Returns(item);
            sut.Initialize(item.Name, item.TemplateID, destination, item.ID);

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

            // assert
            result.Should().Be(item);
        }
 /// <summary>
 /// Removes the sitecore item from the ItemCache
 /// </summary>
 /// <remarks>
 /// Two of the cache levels for Sitecore is ItemCache and DataCache.
 /// The data level caches the data parts of the item.
 /// The item level caches the completed item.
 ///
 /// So when we return new data parts, we need to push the item out of the item cache
 /// to make Sitecore hit the Data cache with the updated data, the next time the item
 /// is requested.
 /// </remarks>
 /// <param name="itemId">The item id to remove from the Item cache.</param>
 /// <param name="context">The context.</param>
 private void RemoveItemFromSitecoresItemCache(ID itemId, Database context)
 {
     if (context.DataManager.DataSource.ItemExists(itemId))
     {
         // The method called using reflection is no longer private, but for backwards compatibility
         // We still call it the voodoo way.
         ReflectionUtil.CallMethod(
             typeof(ItemCache), CacheManager.GetItemCache(context.DataManager.Database),
             "RemoveItem", true, true, new object[] { itemId });
         //_log.Log<DataProviderMasterDatabase>("Called remove item from cache using reflection.");
     }
 }
        public void ShouldReturnNullIfNoParentFound(GetParentCommand sut, Item item)
        {
            // arrange
            sut.Initialize(item);

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

            // assert
            result.Should().BeNull();
            sut.DataStorage.DidNotReceiveWithAnyArgs().GetSitecoreItem(null, null);
        }