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 ShouldReturnTrueIfHasChildren()
        {
            // arrange
            var itemId = ID.NewID;
            var item   = ItemHelper.CreateInstance(this.database, itemId);
            var fakeItemWithChildren = new DbItem("parent", itemId)
            {
                new DbItem("child")
            };

            this.dataStorage.GetSitecoreItem(itemId, item.Language).Returns(item);
            this.dataStorage.GetFakeItem(itemId).Returns(fakeItemWithChildren);

            var command = new OpenHasChildrenCommand {
                Engine = new DataEngine(this.database)
            };

            command.Initialize(item);
            command.Initialize(this.dataStorage);

            // act
            var result = command.DoExecute();

            // assert
            result.Should().BeTrue();
        }
Exemplo n.º 3
0
        protected override void DoInteraction(IClient iClient, IItemInventory item)
        {
            base.DoInteraction(iClient, item);

            Client client = iClient as Client;

            if (client == null)
            {
                return;
            }

            if (item != null && !ItemHelper.IsVoid(item))
            {
                if (item.Type == (short)BlockData.Items.Raw_Fish && !Data.IsTamed)
                {
                    FishUntilTamed--;
                    client.Owner.Inventory.RemoveItem(item.Slot); // consume the item

                    if (FishUntilTamed <= 0)
                    {
                        Data.IsTamed = true;
                        Data.TamedBy = client.Username;
                        Health       = MaxHealth;
                        // TODO: begin following this.Data.TamedBy
                        SendMetadataUpdate();
                    }
                }
            }
        }
Exemplo n.º 4
0
    //设置图表
    private void GetChartInfo()
    {
        DataTable dt  = new DataTable();
        DateTime  now = DateTime.Now.Date;

        if (curDate != "")
        {
            now = Convert.ToDateTime(curDate).Date;
        }

        switch (chartType)
        {
        case "datechart":
            decimal priceMax = 0m;
            dt        = month_bll.GetItemDateTopList(userId, now, "chart", out priceMax);
            chartDate = ItemHelper.GetChartData(dt, "ItemBuyDate");
            chartUrl  = "/Web2015/ItemDateChartJson.aspx?date=" + curDate;
            break;

        case "numchart":
            dt        = month_bll.GetItemNumTopList(userId, now);
            chartDate = ItemHelper.GetChartData(dt, "ChartUrl");
            chartUrl  = "/Web2015/ItemNumChartJson.aspx?date=" + curDate;
            break;

        case "pricechart":
            dt        = month_bll.GetItemPriceTopList(userId, now);
            chartDate = ItemHelper.GetChartData(dt, "ItemBuyDate");
            chartUrl  = "/Web2015/ItemPriceChartJson.aspx?date=" + curDate;
            break;
        }
    }
        public static void DemoNegativeCaseError()
        {
            Item result = ItemHelper.CreateItem("Part", string.Empty);

            // We add fake responce for negative case in the begining
            // of list (with highest priority)
            applyProcessor.AddFirst(item =>
            {
                if (item.getType() != "Part" ||
                    item.getAction() != "get" ||
                    item.getAttribute("select") != "id" ||
                    item.getProperty("name") != "PRE-*")
                {
                    return(null);
                }

                result.loadAML(
                    "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                    "<SOAP-ENV:Body>" +
                    "<SOAP-ENV:Fault xmlns:af=\"http://www.aras.com/InnovatorFault\">" +
                    "<faultcode>SOAP-ENV:Server.PermissionsNoCanGetFoundException</faultcode>" +
                    "<faultstring>" +
                    "<![CDATA[Get access is denied for Part.]]>" +
                    "</faultstring>" +
                    "</SOAP-ENV:Fault>" +
                    "</SOAP-ENV:Body>" +
                    "</SOAP-ENV:Envelope>");
                return(result);
            });

            Item error = Assert.Throws <TestedMethod.InnovatorItemException>(() => businessLogic.Run(null)).ErrorItem;

            Assert.AreEqual(error, result);
        }
        public void ShouldDeleteItemFromParentsChildrenCollection()
        {
            // arrange
            var itemId   = ID.NewID;
            var parentId = ID.NewID;

            var item = new DbItem("item", itemId)
            {
                ParentID = parentId
            };
            var parent = new DbItem("parent", parentId);

            parent.Children.Add(item);

            this.dataStorage.FakeItems.Add(itemId, item);
            this.dataStorage.FakeItems.Add(parentId, parent);

            this.command.Initialize(ItemHelper.CreateInstance(this.database, itemId), ID.NewID);

            // act
            this.command.DoExecute();

            // assert
            this.dataStorage.FakeItems[parentId].Children.Should().BeEmpty();
        }
Exemplo n.º 7
0
        public void Run_InvalidFlagValue_ShouldThrowItemException(string flagValue)
        {
            //arrange
            const string expectedError   = "Unknown flag value";
            Item         fakeContextItem = ItemHelper.CreateItem("GAG_GECO ChangeControlled", string.Empty);

            Item fakeAffectedItem = ItemHelper.CreateItem("GAG_GrammerChangeControlled", "get");

            fakeAffectedItem.setProperty("gag_migration_edit_flag", flagValue);

            IDataAccessLayer fakeDal = Substitute.For <IDataAccessLayer>();

            fakeDal.ApplyItem(Arg.Any <Item>()).Returns(fakeAffectedItem);
            fakeDal.NewItem("GAG_GrammerChangeControlled", "get").Returns(fakeAffectedItem);
            fakeDal.NewError(Arg.Any <string>()).Returns(ci =>
            {
                Item error = ItemHelper.CreateItem(string.Empty, string.Empty);
                error.loadAML(string.Format(CultureInfo.CurrentCulture, ErrorResultTemplate, ci.ArgAt <string>(0)));
                return(error);
            });
            var testClass = new TestClass(fakeDal);

            //act
            //assert
            ItemException exception   = Assert.Throws <ItemException>(() => testClass.Run(fakeContextItem));
            string        actualError = exception?.ErrorItem?.getErrorString();

            Assert.AreEqual(actualError, expectedError);
        }
Exemplo n.º 8
0
        public async Task GiftAsync(SocketUser user, string dataId)
        {
            Context.Data.Users.TryGet(user.Id, out ArcadeUser account);

            if (await CatchEmptyAccountAsync(account))
            {
                return;
            }

            ItemData data = ItemHelper.GetItemData(Context.Account, dataId);

            if (data == null)
            {
                await Context.Channel.SendMessageAsync(Format.Warning("Could not find a data reference."));

                return;
            }

            if (account.Id == Context.Account.Id)
            {
                await Context.Channel.SendMessageAsync(Format.Warning("You can't send a gift to yourself."));

                return;
            }

            Item item = ItemHelper.GetItem(data.Id);

            // Next, check if the item can be gifted.
            if (!ItemHelper.CanGift(data.Id, data))
            {
                await Context.Channel.SendMessageAsync(Format.Warning("This item cannot be gifted."));

                return;
            }

            // Otherwise, Take the item away from the invoker
            // If the item has a limited gift count, add one to the gift counter and give it to the user.

            Context.Account.Items.Remove(data);

            if (data.Seal != null)
            {
                data.Seal.SenderId = Context.Account.Id;
            }

            if (item.TradeLimit.HasValue)
            {
                bool hasGiftCounter = data.Data?.TradeCount.HasValue ?? false;

                if (hasGiftCounter)
                {
                    ItemHelper.DataOf(account, item).Data.TradeCount++;
                }
            }

            account.Items.Add(data);
            await Context.Channel.SendMessageAsync($"> 🎁 Gave **{account.Username}** {(data.Seal != null ? "an item" : $"**{ItemHelper.NameOf(data.Id)}**")}.");

            Context.Account.AddToVar(Stats.ItemsGifted);
        }
Exemplo n.º 9
0
        protected override void DoDeath(EntityBase killedBy)
        {
            var             killedByMob = killedBy as Mob;
            UniversalCoords coords      = UniversalCoords.FromAbsWorld(Position.X, Position.Y, Position.Z);
            ItemInventory   item;

            if (killedByMob != null && killedByMob.Type == MobType.Skeleton)
            {
                // If killed by a skeleton drop a music disc
                sbyte count = 1;

                if (Server.Rand.Next(2) > 1)
                {
                    item = ItemHelper.GetInstance(BlockData.Items.Disc13);
                }
                else
                {
                    item = ItemHelper.GetInstance(BlockData.Items.DiscCat);
                }
                item.Count      = count;
                item.Durability = 0;
                Server.DropItem(World, coords, item);
            }
            else
            {
                sbyte count = (sbyte)Server.Rand.Next(2);
                if (count > 0)
                {
                    item       = ItemHelper.GetInstance(BlockData.Items.Gunpowder);
                    item.Count = count;
                    Server.DropItem(World, coords, item);
                }
            }
            base.DoDeath(killedBy);
        }
        public void Handle_WhenValidationContextDoesNotHaveRelationshipItems_ShouldThrowInvalidOperationException()
        {
            //arrange
            var relationshipItems = new Dictionary <string, IEnumerable <Item> >()
            {
                { TestRelationshipName, Array.Empty <Item>() },
            };

            var validationContext = new ValidationContext(relationshipItems)
            {
                CurrentGECO = ItemHelper.CreateItem(string.Empty, string.Empty),
                RootItem    = ItemHelper.CreateItem(string.Empty, string.Empty),
            };

            IRelationshipNameProvider relationshipNameProvider = Substitute.For <IRelationshipNameProvider>();

            relationshipNameProvider.TabName.Returns("Another relationship name");

            string[] availableClassifications = { "Release & Change/CAD Document" };
            var      testClass = new TestClass(nameof(TestClass), Substitute.For <IGECOProvider>(), relationshipNameProvider, availableClassifications, Array.Empty <string>());

            //act
            //assert
            Assert.Throws <InvalidOperationException>(() => testClass.Handle(validationContext));
        }
Exemplo n.º 11
0
        public void AddToItemDescription()
        {
            string   message, description, itemID, originalDes;
            ItemType item;
            bool     isSuccess;

            Assert.IsNotNull(TestData.NewItem2, "Failed because no item available -- requires successful AddItem test");
            AddToItemDescriptionCall api = new AddToItemDescriptionCall(this.apiContext);

            itemID      = TestData.NewItem2.ItemID;
            originalDes = TestData.NewItem2.Description;
            description = "SDK appended text.";

            DetailLevelCodeTypeCollection detailLevel = new DetailLevelCodeTypeCollection();
            DetailLevelCodeType           type        = DetailLevelCodeType.ReturnAll;

            detailLevel.Add(type);
            api.DetailLevelList = detailLevel;
            // Make API call.
            api.AddToItemDescription(itemID, description);

            System.Threading.Thread.Sleep(3000);
            //check whether the call is success.
            Assert.IsTrue(api.ApiResponse.Ack == AckCodeType.Success || api.ApiResponse.Ack == AckCodeType.Warning, "do not success!");
            isSuccess = ItemHelper.GetItem(TestData.NewItem2, this.apiContext, out message, out item);
            Assert.IsTrue(isSuccess, message);
            Assert.IsTrue(message == string.Empty, message);

            Assert.IsNotNull(item.Description, "the item description is null");
            Assert.Greater(item.Description.Length, originalDes.Length);
        }
        public void ShouldCreateItem()
        {
            // arrange
            var itemId     = ID.NewID;
            var templateId = ID.NewID;

            var item        = ItemHelper.CreateInstance(this.database);
            var destination = ItemHelper.CreateInstance(this.database);

            this.dataStorage.GetSitecoreItem(itemId).Returns(item);

            var command = new OpenCreateItemCommand()
            {
                Engine = new DataEngine(this.database)
            };

            command.Initialize(itemId, "home", templateId, destination);
            command.Initialize(this.dataStorage);

            // act
            var result = command.DoExecute();

            // assert
            result.Should().Be(item);
            this.dataStorage.Received().Create("home", itemId, templateId, destination);
        }
        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));
        }
        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");
        }
Exemplo n.º 15
0
        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            //ItemHelper.setItemsGrid(dgItems);

            ItemHelper.LoadItemsGrid(dgItems);

            //List<Item> items = new List<Item>();

            //string request = Properties.Resources.base_url + "item/list";

            //string response = Functions.readRequest(request);

            //JArray jsonArray = JArray.Parse(response);

            //foreach (JObject item in jsonArray)
            //{
            //    //string str = item.ToString();
            //    //Item newItem = parseItem(str);
            //    Item newItem = ItemHelper.parseItem(item);
            //    if (newItem != null)
            //    {
            //        items.Add(newItem);
            //        MessageBox.Show(newItem.ToString());
            //    }
            //}
            //dgItems.ItemsSource = items;
        }
Exemplo n.º 16
0
        public static bool InventoryContainsDragonball(int whichDragonball, Item[] inventory)
        {
            for (var i = 0; i < inventory.Length; i++)
            {
                var item = inventory[i];
                if (item == null)
                {
                    continue;
                }

                if (item.modItem == null)
                {
                    continue;
                }

                if (!(item.modItem is DragonBallItem))
                {
                    continue;
                }

                var dbItem = item.modItem as DragonBallItem;
                // assume this runs before the inventory loop that turns stone balls into real ones - we don't care which it is, if it's legit, we don't want to spawn dragonballs replacing it.
                if (dbItem.item.type == ItemHelper.GetItemTypeFromName(DragonBallItem.GetStoneBallFromNumber(whichDragonball)) && dbItem.WorldDragonBallKey == GetWorld().WorldDragonBallKey)
                {
                    return(true);
                }
                if (dbItem.item.type == ItemHelper.GetItemTypeFromName(DragonBallItem.GetDragonBallItemTypeFromNumber(whichDragonball)) && dbItem.WorldDragonBallKey == GetWorld().WorldDragonBallKey)
                {
                    return(true);
                }
            }
            return(false);
        }
        public void ShouldDeleteItemDescendants()
        {
            // arrange
            var itemId  = ID.NewID;
            var desc1Id = ID.NewID;
            var desc2Id = ID.NewID;

            var item  = new DbItem("item", itemId);
            var desc1 = new DbItem("descendant1", desc1Id);
            var desc2 = new DbItem("descendant2", desc2Id);

            item.Children.Add(desc1);
            desc1.Children.Add(desc2);

            this.dataStorage.FakeItems.Add(itemId, item);
            this.dataStorage.FakeItems.Add(desc1Id, desc1);
            this.dataStorage.FakeItems.Add(desc2Id, desc2);

            this.command.Initialize(ItemHelper.CreateInstance(this.database, itemId), ID.NewID);

            // act
            this.command.DoExecute();

            // assert
            this.dataStorage.FakeItems.Should().NotContainKey(desc1Id);
            this.dataStorage.FakeItems.Should().NotContainKey(desc2Id);
        }
Exemplo n.º 18
0
        public void Apply(ArcadeContainer container)
        {
            foreach ((ulong userId, PlayerResult result) in UserIds)
            {
                if (!container.Users.TryGet(userId, out ArcadeUser user))
                {
                    continue;
                }

                if (result.Money > 0)
                {
                    user.Give(result.Money);
                }

                // NOTE: No exp yet, formulas not implemented
                foreach (StatUpdatePacket packet in result.Stats)
                {
                    packet.Apply(user);
                }

                foreach (ItemUpdatePacket packet in result.Items)
                {
                    ItemHelper.GiveItem(user, packet.Id, packet.Amount);
                }

                container.Users.AddOrUpdate(userId, user);
            }
        }
Exemplo n.º 19
0
        protected override void DropItems(EntityBase who, StructBlock block, List <ItemInventory> overridedLoot = null)
        {
            var world  = block.World;
            var server = world.Server;

            overridedLoot = new List <ItemInventory>();
            // TODO: Fully grown drops 1 Wheat & 0-3 Seeds. 0 seeds - very rarely
            if (block.MetaData == 7)
            {
                ItemInventory item = ItemHelper.GetInstance((short)BlockData.Items.Wheat);
                item.Count = 1;
                overridedLoot.Add(item);
                sbyte seeds = (sbyte)server.Rand.Next(3);
                if (seeds > 0)
                {
                    item       = ItemHelper.GetInstance((short)BlockData.Items.Seeds);
                    item.Count = seeds;
                    overridedLoot.Add(item);
                }
            }
            else if (block.MetaData >= 5)
            {
                var seeds = (sbyte)server.Rand.Next(3);
                if (seeds > 0)
                {
                    ItemInventory item = ItemHelper.GetInstance((short)BlockData.Items.Seeds);
                    item.Count = seeds;
                    overridedLoot.Add(item);
                }
            }
            base.DropItems(who, block, overridedLoot);
        }
        public void ShouldGetItemVersionsCount()
        {
            // arrange
            var itemId        = ID.NewID;
            var versionedItem = new DbItem("item");

            versionedItem.VersionsCount.Add("en", 2);

            this.dataStorage.GetFakeItem(itemId).Returns(versionedItem);

            var item     = ItemHelper.CreateInstance(this.database, itemId);
            var language = Language.Parse("en");

            var command = new OpenGetVersionsCommand();

            command.Initialize(item, language);
            command.Initialize(this.dataStorage);

            // act
            var versionCollection = command.DoExecute();

            // assert
            versionCollection.Count.Should().Be(2);
            versionCollection.Should().BeEquivalentTo(new[] { new Version(1), new Version(2) });
        }
        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));
        }
Exemplo n.º 22
0
        public void TurnEngine_DetermineCriticalMissProblem_Attacker_Sword_Roll_1_Should_Return_Sword_Broke()
        {
            MockForms.Init();

            // Turn off random numbers
            // Set random to 1, and to hit to 1
            GameGlobals.SetForcedRandomNumbers(1, 1);
            GameGlobals.ForcedRandomValue = 1;

            var myTurnEngine = new TurnEngine();

            var myCharacter = new Character(DefaultModels.CharacterDefault());

            var itemGuid = ItemHelper.AddItemForAttribute(AttributeEnum.Attack, ItemLocationEnum.PrimaryHand, 1000).Guid;
            var myItem   = ItemsViewModel.Instance.GetItem(itemGuid);

            myCharacter.PrimaryHand = itemGuid; // Nothing in the hand, so nothing to drop...

            var Actual = myTurnEngine.DetermineCriticalMissProblem(myCharacter);

            var Expected = " Item " + myItem.Name + " from " + ItemLocationEnum.PrimaryHand + " Broke, and lost forever";

            // Reset
            GameGlobals.ToggleRandomState();

            Assert.AreEqual(Expected, Actual, TestContext.CurrentContext.Test.Name);
        }
        public static void DemoNegativeCaseNoItems()
        {
            // We add fake responce for negative case in the begining
            // of list (with highest priority)
            applyProcessor.AddFirst(item =>
            {
                if (item.getType() != "Part" ||
                    item.getAction() != "get" ||
                    item.getAttribute("select") != "id" ||
                    item.getProperty("name") != "PRE-*")
                {
                    return(null);
                }

                Item result = ItemHelper.CreateItem("Part", string.Empty);
                result.loadAML(
                    "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                    "<SOAP-ENV:Body>" +
                    "<SOAP-ENV:Fault xmlns:af=\"http://www.aras.com/InnovatorFault\">" +
                    "<faultcode>0</faultcode>" +
                    "<faultstring>" +
                    "<![CDATA[No items of type Part found.]]>" +
                    "</faultstring>" +
                    "</SOAP-ENV:Fault>" +
                    "</SOAP-ENV:Body>" +
                    "</SOAP-ENV:Envelope>");
                return(result);
            });

            Item actualResult = businessLogic.Run(null);

            Assert.AreEqual(actualResult.getResult(), "0");
        }
Exemplo n.º 24
0
        public void UseItem(IPokemon pokemon, int id)
        {
            int quantity = EquipmentList.Where(i => i.Key.ID == id).FirstOrDefault().Value;

            EquipmentList[EquipmentList.Where(i => i.Key.ID == id).FirstOrDefault().Key] = quantity - 1;
            ItemHelper.UseItem(pokemon, id);
        }
        public static void SetupEachTest()
        {
            // Before each test execution we reinitialize fake DAL and businessLogic
            // so tests won't conflict between themselves
            fakeDataAccessLayer = Substitute.For <TestedMethod.IDataAccessLayer>();
            businessLogic       = new TestedMethod.BusinessLogic(fakeDataAccessLayer);
            innovator           = ItemHelper.CreateInnovator();

            fakeDataAccessLayer.NewItem(Arg.Any <string>(), Arg.Any <string>())
            .Returns(@params => ItemHelper.CreateItem((string)@params[0], (string)@params[1]));

            fakeDataAccessLayer.NewResult(Arg.Any <string>())
            .Returns(@params => innovator.newResult((string)@params[0]));

            // We use applyProcessor List to store fake AML responces
            applyProcessor = InitializeApplyProcessor();
            fakeDataAccessLayer.ApplyItem(Arg.Any <Item>())
            .Returns(@params =>
            {
                Item paramItem = (Item)@params[0];
                foreach (Func <Item, Item> processor in applyProcessor)
                {
                    Item result = processor(paramItem);
                    if (result != null)
                    {
                        return(result);
                    }
                }
                return(null);
            });
        }
        public void ShouldAddVersionToFakeDbFieldsUsingItemLanguage()
        {
            // arrange
            var itemId = ID.NewID;
            var dbitem = new DbItem("item")
            {
                Fields = { new DbField("Title")
                           {
                               { "en", "Hello!" }, { "da", "Hej!" }
                           } }
            };

            this.dataStorage.GetFakeItem(itemId).Returns(dbitem);

            var item = ItemHelper.CreateInstance(this.database, itemId);

            var command = new OpenAddVersionCommand();

            command.Initialize(item);
            command.Initialize(this.dataStorage);

            // act
            command.DoExecute();

            // assert
            dbitem.Fields.Single().Values["en"][1].Should().Be("Hello!");
            dbitem.Fields.Single().Values["en"][2].Should().Be("Hello!");
            dbitem.Fields.Single().Values["da"][1].Should().Be("Hej!");
            dbitem.Fields.Single().Values["da"].ContainsKey(2).Should().BeFalse();
        }
Exemplo n.º 27
0
        public static SmeltingRecipe[] FromFile(string file)
        {
            var lines = File.ReadAllLines(file);
            var recs  = new List <string>();

            for (int i = 0; i < lines.Length; i++)
            {
                string l = lines[i];
                if (l.StartsWith("#") || !l.Contains(','))
                {
                    continue;
                }
                recs.Add(lines[i]);
            }

            var recipes = new List <SmeltingRecipe>();

            foreach (string r in recs)
            {
                string[] rec        = r.Split(',');
                var      result     = ItemHelper.Parse(rec[1]);
                var      ingredient = ItemHelper.Parse(rec[0]);
                recipes.Add(new SmeltingRecipe(result, ingredient));
            }

            return(recipes.ToArray());
        }
        public void ShouldGetNewItemVersion()
        {
            // arrange
            var itemId = ID.NewID;
            var dbitem = new DbItem("home")
            {
                { "Title", "Hello!" }
            };

            this.dataStorage.GetFakeItem(itemId).Returns(dbitem);

            var originalItem       = ItemHelper.CreateInstance(this.database, itemId);
            var itemWithNewVersion = ItemHelper.CreateInstance(this.database, itemId);

            this.dataStorage.GetSitecoreItem(itemId, Language.Parse("en"), Version.Parse(2)).Returns(itemWithNewVersion);

            var command = new OpenAddVersionCommand();

            command.Initialize(originalItem);
            command.Initialize(this.dataStorage);

            // act
            var result = command.DoExecute();

            // assert
            result.Should().BeSameAs(itemWithNewVersion);
        }
Exemplo n.º 29
0
        private void Discount_Num_ValueChanged(object sender, EventArgs e)
        {
            this.Discount_Label.Text = ItemHelper.GetFormattedPrice(this.Discount_Num.Value);
            this.Invoice.Discount    = this.Discount_Num.Value;

            this.PopulateListView();
        }
        public void Run_WhenLatestItemNotFound_ShouldReturnContextItem()
        {
            //arrange
            Item fakeContextItem = ItemHelper.CreateItem("CAD", string.Empty);

            fakeContextItem.setProperty("gag_migration_edit_flag", "1");
            fakeContextItem.setProperty("config_id", GenerateConfigId());
            fakeContextItem.setNewID();

            Item errorItem = ItemHelper.CreateItem(string.Empty, string.Empty);

            errorItem.loadAML(EmptyResult);

            IDataAccessLayer fakeDal = Substitute.For <IDataAccessLayer>();

            fakeDal.NewItem(Arg.Any <string>(), Arg.Any <string>()).Returns(ItemHelper.CreateItem("CAD", string.Empty));
            fakeDal.ApplyItem(Arg.Any <Item>()).Returns(errorItem);
            var testClass = new TestClass(fakeDal);

            //act
            Item actualItem = testClass.Run(fakeContextItem);

            //assert
            Assert.AreEqual(actualItem.getID(), fakeContextItem.getID());
        }