public void NeverHaveToBeSold() { var sulfuras = new List <Item> { _itemFactory.Create("Sulfuras", 80, 0) }; var items = new Items(sulfuras); for (int i = 0; i < 10; i++) { _itemUpdater.Update(items); Assert.Equal(0, items.First().SellIn); } }
/// <summary> /// Adds parsed content elements to this container. /// </summary> /// <param name="logger">A reference to the logger in use.</param> /// <param name="itemFactory">A reference to the item factory in use.</param> /// <param name="contentElements">The content elements to add.</param> public void AddContent(ILogger logger, IItemFactory itemFactory, IEnumerable <IParsedElement> contentElements) { logger.ThrowIfNull(nameof(logger)); itemFactory.ThrowIfNull(nameof(itemFactory)); contentElements.ThrowIfNull(nameof(contentElements)); foreach (var element in contentElements) { if (element.IsFlag) { // A flag is unexpected in this context. logger.Warning($"Unexpected flag {element.Attributes?.First()?.Name}, ignoring."); continue; } IItem item = itemFactory.Create((ushort)element.Id); if (item == null) { logger.Warning($"Item with id {element.Id} not found in the catalog, skipping."); continue; } item.SetAttributes(logger.ForContext <IItem>(), itemFactory, element.Attributes); // TODO: we should be able to go over capacity here. this.AddContent(itemFactory, item, 0xFF); } }
public int Add(int id, string name) { var newItem = _itemFactory.Create(id, name); _dbContext.Items.Add(newItem); return(newItem.Id); }
public virtual Guid WriteNewItem(Guid destTemplateId, SCItem parentItem, string itemName, MetadataTemplate metadataTemplate = null) { var destItem = _itemFactory.Create(destTemplateId, parentItem, itemName, metadataTemplate); _destMasterRepository.AddOrUpdateSitecoreItem(destItem); return(destItem.ID); }
public async Task <IActionResult> Update([FromRoute] Guid?domainId, [FromRoute] string code, [FromBody] dynamic itemData) { IActionResult result = null; try { if (result == null && (!domainId.HasValue || Guid.Empty.Equals(domainId.Value))) { result = BadRequest("Missing domain id parameter value"); } if (result == null && string.IsNullOrEmpty(code)) { result = BadRequest("Missing item code parameter value"); } if (result == null) { using ILifetimeScope scope = _container.BeginLifetimeScope(); SettingsFactory settingsFactory = scope.Resolve <SettingsFactory>(); CoreSettings settings = settingsFactory.CreateCore(_settings.Value); IItemFactory factory = scope.Resolve <IItemFactory>(); IItem innerItem = null; Func <CoreSettings, IItemSaver, IItem, Task> save = (sttngs, svr, lkup) => svr.Update(sttngs, lkup); if (!(await VerifyDomainAccount(domainId.Value, settingsFactory, _settings.Value, scope.Resolve <IDomainService>()))) { result = StatusCode(StatusCodes.Status401Unauthorized); } if (result == null) { innerItem = await factory.GetByCode(settings, domainId.Value, code); } if (result == null && innerItem == null) { innerItem = factory.Create(domainId.Value, code); save = (sttngs, svr, lkup) => svr.Create(sttngs, lkup); } if (result == null && innerItem != null) { innerItem.Data = itemData; await save(settings, scope.Resolve <IItemSaver>(), innerItem); IMapper mapper = MapperConfigurationFactory.CreateMapper(); result = Ok( mapper.Map <Item>(innerItem) ); } } } catch (Exception ex) { using (ILifetimeScope scope = _container.BeginLifetimeScope()) { await LogException(ex, scope.Resolve <IExceptionService>(), scope.Resolve <SettingsFactory>(), _settings.Value); } result = StatusCode(StatusCodes.Status500InternalServerError); } return(result); }
public void DegradeTwiceAsFastAsNormalItems() { var quality = 8; var sellIn = 4; var conjuredItems = new List <Item> { _itemFactory.Create("Conjured Mana Cake", quality, sellIn), }; var items = new Items(conjuredItems); for (int i = 0; i < 4; i++) { _itemUpdater.Update(items); quality -= 2; Assert.Equal(quality, items.First().Quality); } }
public void DecreaseBy1WhenQualityIsGreaterThan0() { var quality = 40; var sellIn = 40; var regularItems = new List <Item> { _itemFactory.Create("Elixir of the Mongoose", quality, sellIn), }; var items = new Items(regularItems); for (int i = 0; i < 40; i++) { _itemUpdater.Update(items); quality--; Assert.Equal(quality, items.First().Quality); } }
public string AddItemToHero(IList <string> arguments) { string result = string.Empty; string heroName = arguments[1]; IItem newItem = itemFactory.Create(arguments); this.heroes[heroName].Inventory.AddCommonItem(newItem); result = string.Format(Constants.ItemCreateMessage, newItem.Name, heroName); return(result); }
public override bool Parse(IItemFactory itemFactory, ITextProvider text, ITokenStream stream) { if (stream.Current.Type == TokenType.Identifier && IsValidNamedRange(text.GetText(stream.Current.Start, stream.Current.Length))) { AnimationBegin = Children.AddCurrentAndAdvance(stream, SassClassifierType.Keyword); } else if (stream.Current.Type == TokenType.Number && stream.Peek(1).Type == TokenType.PercentSign) { ParseItem begin = itemFactory.Create <PercentageUnit>(this, text, stream); if (begin.Parse(itemFactory, text, stream)) { AnimationBegin = begin; Children.Add(begin); if (stream.Current.Type == TokenType.Comma) { Comma = Children.AddCurrentAndAdvance(stream, SassClassifierType.Punctuation); } ParseItem end = itemFactory.Create <PercentageUnit>(this, text, stream); if (end.Parse(itemFactory, text, stream)) { AnimationEnd = end; Children.Add(end); } } } if (AnimationBegin != null) { var block = itemFactory.CreateSpecific <RuleBlock>(this, text, stream); if (block.Parse(itemFactory, text, stream)) { Body = block; Children.Add(block); } } return(Children.Count > 0); }
public override bool Parse(IItemFactory itemFactory, ITextProvider text, ITokenStream stream) { if (stream.Current.Type == TokenType.Identifier && IsValidNamedRange(text.GetText(stream.Current.Start, stream.Current.Length))) { AnimationBegin = Children.AddCurrentAndAdvance(stream, SassClassifierType.Keyword); } else if (stream.Current.Type == TokenType.Number && stream.Peek(1).Type == TokenType.PercentSign) { ParseItem begin = itemFactory.Create<PercentageUnit>(this, text, stream); if (begin.Parse(itemFactory, text, stream)) { AnimationBegin = begin; Children.Add(begin); if (stream.Current.Type == TokenType.Comma) Comma = Children.AddCurrentAndAdvance(stream, SassClassifierType.Punctuation); ParseItem end = itemFactory.Create<PercentageUnit>(this, text, stream); if (end.Parse(itemFactory, text, stream)) { AnimationEnd = end; Children.Add(end); } } } if (AnimationBegin != null) { var block = itemFactory.CreateSpecific<RuleBlock>(this, text, stream); if (block.Parse(itemFactory, text, stream)) { Body = block; Children.Add(block); } } return Children.Count > 0; }
public void IncreaseInValueAsItGetsOlder() { var quality = 5; var sellIn = 0; var itemCollection = new List <Item> { _itemFactory.Create("Aged Brie", quality, sellIn) }; var items = new Items(itemCollection); for (int i = 0; i < 5; i++) { _itemUpdater.Update(items); quality++; Assert.Equal(quality, items.First().Quality); } var assert = new zAssert(); //assert.OnEachCycle().That(20).IsEqualTo(20).For(20).Assert(); //assert.That(items.First().Quality).IsEqualTo(quality++).While(() => _itemUpdater.Update(items)).Runs().Times(50); }
public override List <SCItem> ConvertValueElementToItems(SCField scField, string elementValue, MetadataTemplate metadataTemplate, SCItem sourceItem) { List <SCItem> convertedItems = new List <SCItem>(); var decodedElementValue = Uri.UnescapeDataString(elementValue).Replace("+", " "); var queryElements = XmlHelper.GetXmlElementNodeList(decodedElementValue, "query"); if (queryElements != null && queryElements.Count > 0) { foreach (XmlNode queryElement in queryElements) { if (queryElement.Attributes != null && queryElement.Attributes["t"] != null) { var queryType = queryElement.Attributes["t"].Value; if (string.Equals(queryType, "default", StringComparison.InvariantCultureIgnoreCase)) { var value = XmlHelper.GetXmlElementValue(queryElement.InnerXml, "value"); var displayName = value; var queryChildrenElements = XmlHelper.GetXmlElementNames(queryElement.InnerXml); foreach (string queryChildrenElementName in queryChildrenElements) { if (!string.Equals(queryChildrenElementName, "value", StringComparison.InvariantCultureIgnoreCase)) { displayName = XmlHelper.GetXmlElementValue(queryElement.InnerXml, queryChildrenElementName); } } if (!string.IsNullOrEmpty(value)) { // Set item value metadataTemplate.fields.newFields .First(field => field.destFieldId == new Guid("{3A07C171-9BCA-464D-8670-C5703C6D3F11}")).value = value; // Set display name metadataTemplate.fields.newFields .First(field => field.destFieldId == new Guid("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}")).value = displayName; SCItem convertedItem = _itemFactory.Create(metadataTemplate.destTemplateId, sourceItem, value, metadataTemplate); convertedItems.Add(convertedItem); } } } } } return(convertedItems); }
public void Validate(IWorld world, IItemFactory itemFactory, string title) { foreach (var blue in itemFactory.Blueprints) { try { var item = itemFactory.Create(world, blue); var room = new Room("Test Room", world, 't'); world.Map[new Point3(0, 0, 0)] = room; world.Player.CurrentLocation = room; ValidateItem(world, item, room); } catch (Exception e) { AddError($"Error creating ItemBlueprint for ItemFactory '{title}'. Error was in {blue}", e); } } }
public void CreateValidItem() { var itemName = "magic beans"; var quality = 10; var sellIn = 10; var item = _itemFactory.Create(itemName, quality, sellIn); Assert.Equal(itemName, item.Name); Assert.Equal(quality, item.Quality); Assert.Equal(sellIn, item.SellIn); }
public void IncreaseBy1WhenThereAreMoreThan10DaysLeft() { var quality = 10; var sellIn = 15; var itemCollection = new List <Item> { _itemFactory.Create("Backstage passes to a TAFKAL80ETC concert", quality, sellIn) }; var items = new Items(itemCollection); for (int i = 0; i < 5; i++) { _itemUpdater.Update(items); quality++; Assert.Equal(quality, items.First().Quality); } }
public void Add(string itemName, int sellin, int quality) { var item = itemFactory.Create(itemName, sellin, quality); items.Add(item); }
/// <summary> /// Adds parsed content elements to this tile. /// </summary> /// <param name="logger">A reference to the logger in use.</param> /// <param name="itemFactory">A reference to the item factory in use.</param> /// <param name="contentElements">The content elements to add.</param> public void AddContent(ILogger logger, IItemFactory itemFactory, IEnumerable <IParsedElement> contentElements) { logger.ThrowIfNull(nameof(logger)); itemFactory.ThrowIfNull(nameof(itemFactory)); contentElements.ThrowIfNull(nameof(contentElements)); // load and add tile flags and contents. foreach (var e in contentElements) { foreach (var attribute in e.Attributes) { if (attribute.Name.Equals("Content")) { if (attribute.Value is IEnumerable <IParsedElement> elements) { var thingStack = new Stack <IThing>(); foreach (var element in elements) { if (element.IsFlag) { // A flag is unexpected in this context. logger.Warning($"Unexpected flag {element.Attributes?.First()?.Name}, ignoring."); continue; } IItem item = itemFactory.Create((ushort)element.Id); if (item == null) { logger.Warning($"Item with id {element.Id} not found in the catalog, skipping."); continue; } item.SetAttributes(logger.ForContext <IItem>(), itemFactory, element.Attributes); thingStack.Push(item); } // Add them in reversed order. while (thingStack.Count > 0) { var thing = thingStack.Pop(); this.AddContent(itemFactory, thing); thing.ParentCylinder = this; } } } else { // it's a flag if (Enum.TryParse(attribute.Name, out TileFlag flagMatch)) { this.SetFlag(flagMatch); } else { logger.Warning($"Unknown flag [{attribute.Name}] found on tile at location {this.Location}."); } } } } }
/// <summary> /// Attempts to add an item to this tile. /// </summary> /// <param name="itemFactory">A reference to the item factory in use.</param> /// <param name="thing">The thing to add to the tile.</param> /// <param name="index">Optional. The index at which to add the thing. Defaults to 0xFF, which instructs to add the thing at any index.</param> /// <returns>A tuple with a value indicating whether the attempt was successful, and false otherwise. The remainder part of the result is not in use for this implementation, as any cummulative remainder is recursively added to the tile.</returns> public (bool result, IThing remainder) AddContent(IItemFactory itemFactory, IThing thing, byte index = 0xFF) { itemFactory.ThrowIfNull(nameof(itemFactory)); if (thing is ICreature creature) { lock (this.creatureIdsOnTile) { this.creatureIdsOnTile.Push(creature.Id); } } else if (thing is IItem item) { if (item.IsGround) { this.Ground = item; } else if (item.StaysOnTop) { lock (this.stayOnTopItems) { this.stayOnTopItems.Push(item); } } else if (item.StaysOnBottom) { lock (this.stayOnBottomItems) { this.stayOnBottomItems.Push(item); } } else { lock (this.itemsOnTile) { var remainingAmountToAdd = item.Amount; while (remainingAmountToAdd > 0) { if (!item.IsCumulative) { this.itemsOnTile.Push(item); break; } var existingItem = this.itemsOnTile.Count > 0 ? this.itemsOnTile.Peek() as IItem : null; // Check if there is an existing top item and if it is of the same type. if (existingItem == null || existingItem.Type != item.Type || existingItem.Amount >= IItem.MaximumAmountOfCummulativeItems) { this.itemsOnTile.Push(item); break; } remainingAmountToAdd += existingItem.Amount; // Modify the existing item with the new amount, or the maximum permitted. var newExistingAmount = Math.Min(remainingAmountToAdd, IItem.MaximumAmountOfCummulativeItems); existingItem.SetAmount(newExistingAmount); remainingAmountToAdd -= newExistingAmount; if (remainingAmountToAdd == 0) { break; } item = itemFactory.Create(item.Type.TypeId); item.SetAmount(remainingAmountToAdd); item.ParentCylinder = this; } } } // Update the tile's version so that it invalidates the cache. // TOOD: if we start caching creatures, move to outer scope. this.LastModified = DateTimeOffset.UtcNow; } if (thing != null) { thing.ParentCylinder = this; } return(true, null); }
/// <summary> /// Attempts to remove an item from this tile. /// </summary> /// <param name="itemFactory">A reference to the item factory in use.</param> /// <param name="thing">The thing to remove from the tile.</param> /// <param name="index">Optional. The index from which to remove the thing. Defaults to 0xFF, which instructs to remove the thing if found at any index.</param> /// <param name="amount">Optional. The amount of the <paramref name="thing"/> to remove.</param> /// <returns>A tuple with a value indicating whether the attempt was at least partially successful, and false otherwise. If the result was only partially successful, a remainder of the item may be returned.</returns> public (bool result, IThing remainder) RemoveContent(IItemFactory itemFactory, IThing thing, byte index = 0xFF, byte amount = 1) { if (amount == 0) { throw new ArgumentException($"Invalid {nameof(amount)} zero."); } IItem remainder = null; if (thing is ICreature creature) { return(this.RemoveCreature(creature.Id), null); } else if (thing is IItem item) { if (item.IsGround) { this.Ground = null; } else if (item.StaysOnTop) { if (amount > 1) { throw new ArgumentException($"Invalid {nameof(amount)} while removing a stay-on-top item: {amount}."); } return(this.InternalRemoveStayOnTopItem(thing), null); } else if (item.StaysOnBottom) { if (amount > 1) { throw new ArgumentException($"Invalid {nameof(amount)} while removing a stay-on-bottom item: {amount}."); } return(this.InternalRemoveStayOnBottomItem(thing), null); } else { lock (this.itemsOnTile) { if ((!item.IsCumulative && amount > 1) || (item.IsCumulative && item.Amount < amount)) { return(false, null); } // At this point we know we have enough amount in the current item to remove. // Remove the item from the tile. this.itemsOnTile.Pop(); if (item.IsCumulative && item.Amount > amount) { // We're removing less than the entire amount, so we need to calculate the remainder to add back. var newExistingAmount = (byte)(item.Amount - amount); item.SetAmount(amount); // Create a new item as the remainder. remainder = itemFactory.Create(item.Type.TypeId); remainder.SetAmount(newExistingAmount); } } // Add any remainder back to the tile. if (remainder != null) { this.AddContent(itemFactory, remainder); } } } else { throw new InvalidCastException($"Thing did not cast to either a {nameof(ICreature)} or {nameof(IItem)}."); } // Update the tile's version so that it invalidates the cache. this.LastModified = DateTimeOffset.UtcNow; return(true, remainder); }
public override IItem Create() { return(_factory.Create(_requirements)); }
public override List <SCItem> ConvertValueElementToItems(SCField scField, string elementValue, MetadataTemplate metadataTemplate, SCItem sourceItem) { List <SCItem> convertedItems = new List <SCItem>(); var decodedElementValue = Uri.UnescapeDataString(elementValue).Replace("+", " "); XmlNodeList queryElements = null; try { queryElements = XmlHelper.GetXmlElementNodeList(decodedElementValue, "query", true); } catch (Exception ex) { _logger.Log(new LogEntry(LoggingEventType.Error, string.Format("ConvertValueElementToItems - Failed to parse Xml value. ItemID = {0} - FieldID = {1} - ElementName = {2} - ElementValue_Decoded = {3}", scField.ItemId, scField.Id, "query", decodedElementValue), ex)); } if (queryElements != null && queryElements.Count > 0) { foreach (XmlNode queryElement in queryElements) { if (queryElement.Attributes != null && queryElement.Attributes["t"] != null) { var queryType = queryElement.Attributes["t"].Value; if (string.Equals(queryType, "default", StringComparison.InvariantCultureIgnoreCase)) { var value = XmlHelper.GetXmlElementValue(queryElement.InnerXml, "value"); var displayName = value; var displayNames = new Dictionary <Tuple <string, int>, string>(); var queryChildrenElements = XmlHelper.GetXmlElementNames(queryElement.InnerXml); foreach (string queryChildrenElementName in queryChildrenElements) { if (!string.Equals(queryChildrenElementName, "value", StringComparison.InvariantCultureIgnoreCase)) { displayName = XmlHelper.GetXmlElementValue(queryElement.InnerXml, queryChildrenElementName); displayNames.Add(new Tuple <string, int>(queryChildrenElementName, 1), displayName); } } if (!string.IsNullOrEmpty(value)) { // Set item value metadataTemplate.fields.newFields .First(field => field.destFieldId == new Guid("{3A07C171-9BCA-464D-8670-C5703C6D3F11}")).value = value; // Set display name if (displayNames.Any()) { metadataTemplate.fields.newFields .First(field => field.destFieldId == new Guid("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}")).values = displayNames; } else { metadataTemplate.fields.newFields .First(field => field.destFieldId == new Guid("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}")).value = displayName; } SCItem convertedItem = _itemFactory.Create(metadataTemplate.destTemplateId, sourceItem, value, metadataTemplate); convertedItems.Add(convertedItem); } } } } } return(convertedItems); }