public async Task ExchangeItemAsync_WithNewItemAvailableForShoppingListAndNotInBasket_ShouldRemoveOldItemAndAddNewItem()
        {
            // Arrange
            var local   = new LocalFixture();
            var service = local.CreateService();

            ShoppingListMock shoppingListMock = local.CreateShoppingListMockNotInBasket();
            var shopppingListStoreId          = shoppingListMock.Object.StoreId;

            IShoppingListItem oldShoppingListItem = shoppingListMock.GetRandomItem(local.CommonFixture, i => !i.IsInBasket);
            ItemId            oldItemId           = oldShoppingListItem.Id;

            IStoreItem newItem = local.CreateNewItemForStore(shopppingListStoreId);

            local.ShoppingListRepositoryMock.SetupFindActiveByAsync(oldItemId, shoppingListMock.Object.ToMonoList());

            // Act
            await service.ExchangeItemAsync(oldItemId, newItem, default);

            // Assert
            var sectionId = newItem.Availabilities.First(av => av.StoreId == shopppingListStoreId).DefaultSectionId;

            using (new AssertionScope())
            {
                shoppingListMock.VerifyRemoveItemOnce(oldItemId);
                local.ShoppingListRepositoryMock.VerifyStoreAsyncOnce(shoppingListMock.Object);
                local.AddItemToShoppingListServiceMock.VerifyAddItemToShoppingListOnce(shoppingListMock.Object,
                                                                                       newItem.Id, sectionId, oldShoppingListItem.Quantity);
                shoppingListMock.VerifyPutItemInBasketNever();
            }
        }
コード例 #2
0
        public async Task HandleAsync_WithValidDataAndManufacturerIdNull_ShouldCreateItem()
        {
            // Arrange
            var local = new LocalFixture();

            IStoreItem storeItem = local.StoreItemFixture.CreateValid();
            List <IStoreItemAvailability> availabilities = storeItem.Availabilities.ToList();

            var handler = local.CreateCommandHandler();
            var command = local.CreateCommandWithoutManufacturerId(availabilities);

            local.StoreItemFactoryMock.SetupCreate(command.ItemCreation, storeItem);

            // Act
            var result = await handler.HandleAsync(command, default);

            // Assert
            using (new AssertionScope())
            {
                result.Should().BeTrue();
                local.ItemRepositoryMock.VerifyStoreAsyncOnce(storeItem);
                local.ItemCategoryValidationServiceMock.VerifyValidateAsyncOnce(command.ItemCreation.ItemCategoryId);
                local.ManufacturerValidationServiceMock.VerifyValidateAsyncNever();
                local.AvailabilityValidationServiceMock.VerifyValidateOnce(availabilities);
            }
        }
コード例 #3
0
        public void MaybeStoreFile(IStoreItem file, byte[] data, byte[] coverData)
        {
            if (connection == null)
            {
                return;
            }
            if (!file.GetType().Attributes.HasFlag(TypeAttributes.Serializable))
            {
                return;
            }
            try {
                lock (connection) {
                    insertKey.Value  = file.Item.FullName;
                    insertSize.Value = file.Item.Length;
                    insertTime.Value = file.Item.LastWriteTimeUtc.Ticks;
                    insertData.Value = data;

                    insertCover.Value = coverData;
                    try {
                        insert.ExecuteNonQuery();
                    }
                    catch (DbException ex) {
                        _logger.Error("Failed to put file cover into store", ex);
                        return;
                    }
                }
            }
            catch (Exception ex) {
                _logger.Error("Failed to serialize an object of type " + file.GetType(), ex);
                throw;
            }
        }
コード例 #4
0
        public void MakePermanent_WithValidData_ShouldMakeItemPermanent()
        {
            // Arrange
            Fixture fixture = commonFixture.GetNewFixture();

            var           definition    = StoreItemDefinition.FromTemporary(true);
            IStoreItem    storeItem     = storeItemFixture.CreateValid(definition);
            PermanentItem permanentItem = fixture.Create <PermanentItem>();
            List <IStoreItemAvailability> availabilities = storeItemAvailabilityFixture.CreateManyValid().ToList();

            // Act
            storeItem.MakePermanent(permanentItem, availabilities);

            // Assert
            using (new AssertionScope())
            {
                storeItem.Name.Should().Be(permanentItem.Name);
                storeItem.Comment.Should().Be(permanentItem.Comment);
                storeItem.QuantityType.Should().Be(permanentItem.QuantityType);
                storeItem.QuantityInPacket.Should().Be(permanentItem.QuantityInPacket);
                storeItem.QuantityTypeInPacket.Should().Be(permanentItem.QuantityTypeInPacket);
                storeItem.Availabilities.Should().BeEquivalentTo(availabilities);
                storeItem.ItemCategoryId.Should().Be(permanentItem.ItemCategoryId);
                storeItem.ManufacturerId.Should().Be(permanentItem.ManufacturerId);
                storeItem.IsTemporary.Should().BeFalse();
            }
        }
        public async Task HandleAsync_WithValidOfflineId_ShouldPutItemInBasket()
        {
            // Arrange
            var local   = new LocalFixture();
            var handler = local.CreateCommandHandler();
            var command = local.CreateCommandWithOfflineId();

            IStoreItem storeItem = local.StoreItemFixture.CreateValid();

            var temporaryItemId       = new TemporaryItemId(command.OfflineTolerantItemId.OfflineId.Value);
            ShoppingListMock listMock = local.ShoppingListMockFixture.Create();

            local.ShoppingListRepositoryMock.SetupFindByAsync(command.ShoppingListId, listMock.Object);
            local.ItemRepositoryMock.SetupFindByAsync(temporaryItemId, storeItem);

            // Act
            bool result = await handler.HandleAsync(command, default);

            // Assert
            using (new AssertionScope())
            {
                result.Should().BeTrue();
                local.ItemRepositoryMock.VerifyFindByAsync(temporaryItemId);
                listMock.VerifyPutItemInBasketOnce(storeItem.Id);
                local.ShoppingListRepositoryMock.VerifyStoreAsyncOnce(listMock.Object);
            }
        }
コード例 #6
0
        public async Task WriteAsync(IDictionary <string, object> changes, CancellationToken cancellationToken = default)
        {
            if (changes == null)
            {
                throw new ArgumentNullException(nameof(changes));
            }
            using var redis = GetRedisConnection;
            var database = redis.GetDatabase(_settings.Database);

            foreach (KeyValuePair <string, object> change in changes)
            {
                object value = change.Value;
                string text  = null;
                var    json  = database.StringGet(new RedisKey(change.Key));

                if (json.TryToJObject(out var value2) && value2.TryGetValue("eTag", out JToken value3))
                {
                    text = value3.Value <string>();
                }
                JObject    jObject   = JObject.FromObject(value, StateJsonSerializer);
                IStoreItem storeItem = value as IStoreItem;
                if (storeItem != null)
                {
                    if (text != null && storeItem.ETag != "*" && storeItem.ETag != text)
                    {
                        throw new Exception("Etag conflict.\r\n\r\nOriginal: " + storeItem.ETag + "\r\nCurrent: " + text);
                    }
                    jObject["eTag"] = _eTag++.ToString();
                }

                await database.StringSetAsync(new RedisKey(change.Key), new RedisValue(jObject.ToString()), TimeSpan.FromDays(1));
            }
        }
コード例 #7
0
        /// <summary>
        /// Get the value of the specified property for the given item.
        /// </summary>
        /// <param name="httpContext">
        /// HTTP context of the current request.
        /// </param>
        /// <param name="item">
        /// Store item/collection for which the property should be obtained.
        /// </param>
        /// <param name="propertyName">
        /// Name of the property (including namespace).
        /// </param>
        /// <param name="skipExpensive">
        /// Flag indicating whether to skip the property if it is too expensive
        /// to compute.
        /// </param>
        /// <returns>
        /// A task that represents the get property operation. The task will
        /// return the property value or <see langword="null"/> if
        /// <paramref name="skipExpensive"/> is set to <see langword="true"/>
        /// and the parameter is expensive to compute.
        /// </returns>
        public Task <object> GetPropertyAsync(IHttpContext httpContext, IStoreItem item, XName propertyName, bool skipExpensive = false)
        {
            // Find the property
            DavProperty <TEntry> property;

            if (!_properties.TryGetValue(propertyName, out property))
            {
                return(Task.FromResult((object)null));
            }

            // Check if the property has a getter
            if (property.GetterAsync == null)
            {
                return(Task.FromResult((object)null));
            }

            // Skip expensive properties
            if (skipExpensive && property.IsExpensive)
            {
                return(Task.FromResult((object)null));
            }

            // Obtain the value
            return(property.GetterAsync(httpContext, (TEntry)item));
        }
コード例 #8
0
 public void Buy(IStoreItem item, IPlayer player)
 {
     player.Coins    -= item.NormalPrice;
     item.NormalPrice = CalculatePrice(item.Value, _purchaseMargin);
     player.Inventory.Add(item);
     Items.Remove(item);
 }
        public async Task <StoreItemReadModel> ConvertAsync(IStoreItem item, CancellationToken cancellationToken)
        {
            if (item is null)
            {
                throw new System.ArgumentNullException(nameof(item));
            }

            IItemCategory itemCategory = null;
            IManufacturer manufacturer = null;

            if (item.ItemCategoryId != null)
            {
                itemCategory = await itemCategoryRepository.FindByAsync(item.ItemCategoryId, cancellationToken);

                if (itemCategory == null)
                {
                    throw new DomainException(new ItemCategoryNotFoundReason(item.ItemCategoryId));
                }
            }
            if (item.ManufacturerId != null)
            {
                manufacturer = await manufacturerRepository.FindByAsync(item.ManufacturerId, cancellationToken);

                if (manufacturer == null)
                {
                    throw new DomainException(new ManufacturerNotFoundReason(item.ManufacturerId));
                }
            }

            var storeIds  = item.Availabilities.Select(av => av.StoreId);
            var storeDict = (await storeRepository.FindByAsync(storeIds, cancellationToken))
                            .ToDictionary(store => store.Id);

            return(ToReadModel(item, itemCategory, manufacturer, storeDict));
        }
コード例 #10
0
 public void SetupCreate(TemporaryItemCreation temporaryItemCreation, IStoreItem returnValue)
 {
     mock
     .Setup(i => i.Create(
                It.Is <TemporaryItemCreation>(obj => obj == temporaryItemCreation)))
     .Returns(returnValue);
 }
コード例 #11
0
ファイル: CopyHandler.cs プロジェクト: zivillian/nwebdav
        private async Task CopyAsync(IStoreItem source, IStoreCollection destinationCollection, string name, bool overwrite, int depth, IHttpContext httpContext, Uri baseUri, UriResultCollection errors)
        {
            // Determine the new base Uri
            var newBaseUri = UriHelper.Combine(baseUri, name);

            // Copy the item
            var copyResult = await source.CopyAsync(destinationCollection, name, overwrite, httpContext).ConfigureAwait(false);

            if (copyResult.Result != DavStatusCode.Created && copyResult.Result != DavStatusCode.NoContent)
            {
                errors.AddResult(newBaseUri, copyResult.Result);
                return;
            }

            // Check if the source is a collection and we are requested to copy recursively
            var sourceCollection = source as IStoreCollection;

            if (sourceCollection != null && depth > 0)
            {
                // The result should also contain a collection
                var newCollection = (IStoreCollection)copyResult.Item;

                // Copy all childs of the source collection
                foreach (var entry in await sourceCollection.GetItemsAsync(httpContext).ConfigureAwait(false))
                {
                    await CopyAsync(entry, newCollection, entry.Name, overwrite, depth - 1, httpContext, newBaseUri, errors).ConfigureAwait(false);
                }
            }
        }
コード例 #12
0
        public Task Write(StoreItems changes)
        {
            lock (_syncroot)
            {
                foreach (var change in changes)
                {
                    IStoreItem newValue = change.Value as IStoreItem;
                    IStoreItem oldValue = null;

                    if (_memory.TryGetValue(change.Key, out object x))
                    {
                        oldValue = x as IStoreItem;
                    }
                    if (oldValue == null ||
                        newValue.eTag == "*" ||
                        oldValue.eTag == newValue.eTag)
                    {
                        // clone and set etag
                        newValue            = FlexObject.Clone <IStoreItem>(newValue);
                        newValue.eTag       = (_eTag++).ToString();
                        _memory[change.Key] = newValue;
                    }
                    else
                    {
                        throw new Exception("etag conflict");
                    }
                }
            }
            return(Task.CompletedTask);
        }
        public async Task ExchangeItemAsync(ItemId oldItemId, IStoreItem newItem, CancellationToken cancellationToken)
        {
            if (oldItemId is null)
            {
                throw new System.ArgumentNullException(nameof(oldItemId));
            }
            if (newItem is null)
            {
                throw new System.ArgumentNullException(nameof(newItem));
            }

            var shoppingListsWithOldItem = (await shoppingListRepository
                                            .FindActiveByAsync(oldItemId, cancellationToken))
                                           .ToList();

            foreach (var list in shoppingListsWithOldItem)
            {
                IShoppingListItem oldListItem = list.Items
                                                .First(i => i.Id == oldItemId);
                list.RemoveItem(oldListItem.Id);
                if (newItem.IsAvailableInStore(list.StoreId))
                {
                    var sectionId = newItem.GetDefaultSectionIdForStore(list.StoreId);
                    await addItemToShoppingListService.AddItemToShoppingList(list, newItem.Id, sectionId,
                                                                             oldListItem.Quantity, cancellationToken);

                    if (oldListItem.IsInBasket)
                    {
                        list.PutItemInBasket(newItem.Id);
                    }
                }

                await shoppingListRepository.StoreAsync(list, cancellationToken);
            }
        }
コード例 #14
0
        public LockResult RefreshLock(IStoreItem item, bool recursiveLock, IEnumerable <int> timeouts, WebDavUri lockTokenUri)
        {
            var timeout      = timeouts.Cast <int?>().FirstOrDefault();
            var itemLockInfo = new ItemLockInfo(item, LockType.Write, LockScope.Exclusive, lockTokenUri, recursiveLock, null, timeout ?? -1);

            return(new LockResult(DavStatusCode.Ok, GetActiveLockInfo(itemLockInfo)));
        }
        public async Task HandleAsync_WithValidData_ShouldStoreItem()
        {
            // Arrange
            var local   = new LocalFixture();
            var handler = local.CreateCommandHandler();

            IStoreItem             storeItem    = local.StoreItemFixture.CreateValid();
            IStoreItemAvailability availability = local.CommonFixture.ChooseRandom(storeItem.Availabilities);

            var command = local.CreateCommand(availability);

            local.StoreItemFactoryMock.SetupCreate(command.TemporaryItemCreation, storeItem);

            // Act
            var result = await handler.HandleAsync(command, default);

            // Assert
            using (new AssertionScope())
            {
                result.Should().BeTrue();
                local.AvailabilityValidationServiceMock.VerifyValidateOnce(
                    command.TemporaryItemCreation.Availability.ToMonoList());
                local.ItemRepositoryMock.VerifyStoreAsyncOnce(storeItem);
            }
        }
コード例 #16
0
        private object[] NoItemCategory()
        {
            IStore        store        = storeFixture.CreateValid();
            var           list         = GetShoppingListContainingOneItem(store.Id, store.Sections.First().Id);
            IManufacturer manufacturer = manufaturerFixture.Create();

            var avavilabilityDef = new StoreItemAvailabilityDefinition
            {
                StoreId          = store.Id,
                DefaultSectionId = store.Sections.First().Id
            };
            var availability = storeItemAvailabilityFixture.Create(avavilabilityDef);

            var itemDef = new StoreItemDefinition
            {
                Id             = list.Sections.First().Items.First().Id,
                ItemCategoryId = null,
                ManufacturerId = manufacturer.Id,
                Availabilities = availability.ToMonoList()
            };

            IStoreItem item          = storeItemFixture.Create(itemDef);
            var        listReadModel = ToSimpleReadModel(list, store, item, null, manufacturer);

            return(new object[]
            {
                list,
                store,
                item.ToMonoList(),
                Enumerable.Empty <IItemCategory>(),
                manufacturer.ToMonoList(),
                listReadModel
            });
        }
コード例 #17
0
ファイル: MoveHandler.cs プロジェクト: tianyamoon/nwebdav
        private async Task MoveAsync(IStoreCollection sourceCollection, IStoreItem moveItem, IStoreCollection destinationCollection, string destinationName, bool overwrite, IHttpContext httpContext, Uri baseUri, UriResultCollection errors)
        {
            // Determine the new base URI
            var subBaseUri = UriHelper.Combine(baseUri, destinationName);

            // Obtain the actual item
            if (moveItem is IStoreCollection moveCollection && !moveCollection.SupportsFastMove(destinationCollection, destinationName, overwrite, httpContext))
            {
                // Create a new collection
                var newCollectionResult = await destinationCollection.CreateCollectionAsync(destinationName, overwrite, httpContext).ConfigureAwait(false);

                if (newCollectionResult.Result != DavStatusCode.Created && newCollectionResult.Result != DavStatusCode.NoContent)
                {
                    errors.AddResult(subBaseUri, newCollectionResult.Result);
                    return;
                }

                // Move all sub items
                foreach (var entry in await moveCollection.GetItemsAsync(httpContext).ConfigureAwait(false))
                {
                    await MoveAsync(moveCollection, entry, newCollectionResult.Collection, entry.Name, overwrite, httpContext, subBaseUri, errors).ConfigureAwait(false);
                }

                // Delete the source collection
                var deleteResult = await sourceCollection.DeleteItemAsync(moveItem.Name, httpContext).ConfigureAwait(false);

                if (deleteResult != DavStatusCode.Ok)
                {
                    errors.AddResult(subBaseUri, newCollectionResult.Result);
                }
            }
コード例 #18
0
        public void Modify_WithValidData_ShouldModifyItem()
        {
            // Arrange
            Fixture fixture = commonFixture.GetNewFixture();

            var        isTemporary = commonFixture.NextBool();
            var        definition  = StoreItemDefinition.FromTemporary(isTemporary);
            IStoreItem storeItem   = storeItemFixture.CreateValid(definition);
            ItemModify itemModify  = fixture.Create <ItemModify>();
            IEnumerable <IStoreItemAvailability> availabilities = storeItemAvailabilityFixture.CreateManyValid().ToList();

            // Act
            storeItem.Modify(itemModify, availabilities);

            // Assert
            using (new AssertionScope())
            {
                storeItem.Name.Should().Be(itemModify.Name);
                storeItem.Comment.Should().Be(itemModify.Comment);
                storeItem.QuantityType.Should().Be(itemModify.QuantityType);
                storeItem.QuantityInPacket.Should().Be(itemModify.QuantityInPacket);
                storeItem.QuantityTypeInPacket.Should().Be(itemModify.QuantityTypeInPacket);
                storeItem.Availabilities.Should().BeEquivalentTo(availabilities);
                storeItem.ItemCategoryId.Should().Be(itemModify.ItemCategoryId);
                storeItem.ManufacturerId.Should().Be(itemModify.ManufacturerId);
                storeItem.IsTemporary.Should().Be(isTemporary);
            }
        }
        public StoreItemReadModel ToReadModel(IStoreItem model, IItemCategory itemCategory,
                                              IManufacturer manufacturer, Dictionary <StoreId, IStore> stores)
        {
            var availabilityReadModels = new List <StoreItemAvailabilityReadModel>();

            foreach (var av in model.Availabilities)
            {
                var store   = stores[av.StoreId];
                var section = store.Sections.First(s => s.Id == av.DefaultSectionId);

                availabilityReadModels.Add(av.ToReadModel(store, section));
            }

            return(new StoreItemReadModel(
                       model.Id,
                       model.Name,
                       model.IsDeleted,
                       model.Comment,
                       model.IsTemporary,
                       model.QuantityType.ToReadModel(),
                       model.QuantityInPacket,
                       model.QuantityTypeInPacket.ToReadModel(),
                       itemCategory?.ToReadModel(),
                       manufacturer?.ToReadModel(),
                       availabilityReadModels));
        }
コード例 #20
0
 public void SetupCreate(ItemCreation itemCreation, IStoreItem returnValue)
 {
     mock
     .Setup(i => i.Create(
                It.Is <ItemCreation>(c => c == itemCreation)))
     .Returns(returnValue);
 }
コード例 #21
0
 public void Sell(IStoreItem item, IPlayer player)
 {
     player.Coins += item.NormalPrice;
     player.TakeOff(item);
     player.Inventory.Remove(item);
     item.NormalPrice = CalculatePrice(item.Value, _salesMargin);
     Items.Add(item);
 }
コード例 #22
0
        public LockResult Lock(IStoreItem item, LockType lockType, LockScope lockScope, XElement owner, WebDavUri lockRootUri,
                               bool recursiveLock, IEnumerable <int> timeouts)
        {
            var timeout      = timeouts.Cast <int?>().FirstOrDefault();
            var itemLockInfo = new ItemLockInfo(item, lockType, lockScope, lockRootUri, recursiveLock, owner, timeout ?? -1);

            return(new LockResult(DavStatusCode.Ok, GetActiveLockInfo(itemLockInfo)));
        }
コード例 #23
0
 public void VerifyStoreAsyncOnce(IStoreItem storeItem)
 {
     mock.Verify(
         i => i.StoreAsync(
             It.Is <IStoreItem>(item => item == storeItem),
             It.IsAny <CancellationToken>()),
         Times.Once);
 }
コード例 #24
0
 public void SetupFindByAsync(TemporaryItemId temporaryItemId, IStoreItem returnValue)
 {
     mock
     .Setup(i => i.FindByAsync(
                It.Is <TemporaryItemId>(id => id == temporaryItemId),
                It.IsAny <CancellationToken>()))
     .ReturnsAsync(returnValue);
 }
コード例 #25
0
 public Task <object> GetPropertyAsync(IHttpContext httpContext, IStoreItem item, XName propertyName, bool skipExpensive, CancellationToken cancellationToken)
 {
     if (propertyName == _contentType.Name)
     {
         return(Task.FromResult <object>(_contentType.Getter(httpContext, (Guru3Collection)item)));
     }
     return(_inner.GetPropertyAsync(httpContext, item, propertyName, skipExpensive, cancellationToken));
 }
コード例 #26
0
        public DavStatusCode Unlock(IStoreItem item, Uri lockTokenUri)
        {
            // Determine the actual lock token
            var lockToken = GetTokenFromLockToken(lockTokenUri);

            if (lockToken == null)
            {
                return(DavStatusCode.PreconditionFailed);
            }

            // Determine the item's key
            var key = item.UniqueKey;

            lock (_itemLocks)
            {
                // Make sure the item is in the dictionary
                ItemLockTypeDictionary itemLockTypeDictionary;
                if (!_itemLocks.TryGetValue(key, out itemLockTypeDictionary))
                {
                    return(DavStatusCode.PreconditionFailed);
                }

                // Scan both the dictionaries for the token
                foreach (var kv in itemLockTypeDictionary)
                {
                    var itemLockList = kv.Value;

                    // Remove this lock from the list
                    for (var i = 0; i < itemLockList.Count; ++i)
                    {
                        if (itemLockList[i].Token == lockToken.Value)
                        {
                            // Remove the item
                            itemLockList.RemoveAt(i);

                            // Check if there are any locks left for this type
                            if (!itemLockList.Any())
                            {
                                // Remove the type
                                itemLockTypeDictionary.Remove(kv.Key);

                                // Check if there are any types left
                                if (!itemLockTypeDictionary.Any())
                                {
                                    _itemLocks.Remove(key);
                                }
                            }

                            // Lock has been removed
                            return(DavStatusCode.NoContent);
                        }
                    }
                }
            }

            // Item cannot be unlocked (token cannot be found)
            return(DavStatusCode.PreconditionFailed);
        }
 private void ValidateItemIsAvailableAtStore(IStoreItem storeItem, StoreId storeId,
                                             out IStoreItemAvailability availability)
 {
     availability = storeItem.Availabilities.FirstOrDefault(av => av.StoreId == storeId);
     if (availability == null)
     {
         throw new DomainException(new ItemAtStoreNotAvailableReason(storeItem.Id, storeId));
     }
 }
コード例 #28
0
 public static async Task <bool> Remove(this Cloud cloud, IStoreItem item)
 {
     return(item switch
     {
         null => await Task.FromResult(false),
         LocalStoreItem storeItem => await cloud.Remove(storeItem.FileInfo),
         LocalStoreCollection storeCollection => await cloud.Remove(storeCollection.DirectoryInfo),
         _ => throw new ArgumentException(string.Empty, nameof(item))
     });
コード例 #29
0
        private void OnSelectionChanged(object sender, IStoreItem item)
        {
            myNotePad.Document = GetFlowDocument(item);

            if (!string.IsNullOrEmpty(myNavigation.SearchText))
            {
                myNotePad.Search(myNavigation.SearchText, SearchMode.All);
            }
        }
            public StoreItemReadModel ToSimpleReadModel(IStoreItem item, IItemCategory itemCategory,
                                                        IManufacturer manufacturer, IStore store)
            {
                var manufacturerReadModel = manufacturer == null
                ? null
                : new ManufacturerReadModel(
                    manufacturer.Id,
                    manufacturer.Name,
                    manufacturer.IsDeleted);

                var itemCategoryReadModel = itemCategory == null
                    ? null
                    : new ItemCategoryReadModel(
                    itemCategory.Id,
                    itemCategory.Name,
                    itemCategory.IsDeleted);

                var section = store.Sections.First();
                var storeSectionReadModel = new StoreSectionReadModel(
                    section.Id,
                    section.Name,
                    section.SortingIndex,
                    section.IsDefaultSection);

                var storeReadModel = new StoreItemStoreReadModel(
                    store.Id,
                    store.Name,
                    storeSectionReadModel.ToMonoList());

                var availability          = item.Availabilities.First();
                var availabilityReadModel = new StoreItemAvailabilityReadModel(
                    storeReadModel,
                    availability.Price,
                    storeSectionReadModel);

                return(new StoreItemReadModel(
                           item.Id,
                           item.Name,
                           item.IsDeleted,
                           item.Comment,
                           item.IsTemporary,
                           new QuantityTypeReadModel(
                               (int)item.QuantityType,
                               item.QuantityType.ToString(),
                               item.QuantityType.GetAttribute <DefaultQuantityAttribute>().DefaultQuantity,
                               item.QuantityType.GetAttribute <PriceLabelAttribute>().PriceLabel,
                               item.QuantityType.GetAttribute <QuantityLabelAttribute>().QuantityLabel,
                               item.QuantityType.GetAttribute <QuantityNormalizerAttribute>().Value),
                           item.QuantityInPacket,
                           new QuantityTypeInPacketReadModel(
                               (int)item.QuantityTypeInPacket,
                               item.QuantityTypeInPacket.ToString(),
                               item.QuantityTypeInPacket.GetAttribute <QuantityLabelAttribute>().QuantityLabel),
                           itemCategoryReadModel,
                           manufacturerReadModel,
                           availabilityReadModel.ToMonoList()));
            }
コード例 #31
0
ファイル: FileStore.cs プロジェクト: vitska/simpleDLNA
 public void MaybeStoreFile(IStoreItem file, byte[] data, byte[] coverData)
 {
     _logger.NoticeFormat("MaybeStoreFile [{0}][{1}][{2}]", file.Item.Name, (data == null)?0:data.Length, (coverData == null)?0:coverData.Length);
       _db.Set(file.Item.FullName, data);
       _db.Set(CoverPrefix + file.Item.FullName, coverData);
 }
コード例 #32
0
ファイル: FileStore.cs プロジェクト: vitska/simpleDLNA
 public byte[] MaybeGetCover(IStoreItem file)
 {
     byte[] data;
       _db.Get(CoverPrefix + file.Item.FullName, out data);
       return data;
 }
コード例 #33
0
 public void MaybeStoreFile(IStoreItem file, byte[] data, byte[] coverData)
 {
     _fileData = data;
     _coverData = coverData;
 }
コード例 #34
0
 public byte[] MaybeGetCover(IStoreItem file)
 {
     return _coverData;
 }
コード例 #35
0
 public bool HasCover(IStoreItem file)
 {
     return _coverData != null;
 }
コード例 #36
0
ファイル: FileStore.cs プロジェクト: vitska/simpleDLNA
        public byte[] MaybeGetCover(IStoreItem file)
        {
            if (connection == null) {
            return null;
              }

              var info = file.Item;
              //byte[] data;
              lock (connection) {
            selectCoverKey.Value = info.FullName;
            selectCoverSize.Value = info.Length;
            selectCoverTime.Value = info.LastWriteTimeUtc.Ticks;
            try {
              return selectCover.ExecuteScalar() as byte[];
            }
            catch (DbException ex) {
              _logger.Error("Failed to lookup file cover from store", ex);
              return null;
            }
              }
              //if (data == null) {
              //  return null;
              //}
              //try {
              //  using (var s = new MemoryStream(data)) {
              //    var ctx = new StreamingContext(
              //      StreamingContextStates.Persistence,
              //      new DeserializeInfo(null, info, DlnaMime.ImageJPEG)
              //      );
              //    var formatter = new BinaryFormatter(null, ctx) {
              //      TypeFormat = FormatterTypeStyle.TypesWhenNeeded,
              //      AssemblyFormat = FormatterAssemblyStyle.Simple
              //    };
              //    var rv = formatter.Deserialize(s) as Cover;
              //    return rv;
              //  }
              //}
              //catch (SerializationException ex) {
              //  Debug("Failed to deserialize a cover", ex);
              //  return null;
              //}
              //catch (Exception ex) {
              //  Fatal("Failed to deserialize a cover", ex);
              //  throw;
              //}
        }
コード例 #37
0
ファイル: FileStore.cs プロジェクト: vitska/simpleDLNA
        public void MaybeStoreFile(IStoreItem file, byte[] data, byte[] coverData)
        {
            if (connection == null) {
            return;
              }
              if (!file.GetType().Attributes.HasFlag(TypeAttributes.Serializable)) {
            return;
              }
              try {

              lock (connection) {
            insertKey.Value = file.Item.FullName;
            insertSize.Value = file.Item.Length;
            insertTime.Value = file.Item.LastWriteTimeUtc.Ticks;
            insertData.Value = data;

            insertCover.Value = coverData;
            try {
              insert.ExecuteNonQuery();
            }
            catch (DbException ex) {
              _logger.Error("Failed to put file cover into store", ex);
              return;
            }
              }

              }
              catch (Exception ex) {
            _logger.Error("Failed to serialize an object of type " + file.GetType(), ex);
            throw;
              }
        }
コード例 #38
0
ファイル: FileStore.cs プロジェクト: vitska/simpleDLNA
        public bool HasCover(IStoreItem file)
        {
            if (connection == null) {
            return false;
              }

              var info = file.Item;
              lock (connection) {
            selectCoverKey.Value = info.FullName;
            selectCoverSize.Value = info.Length;
            selectCoverTime.Value = info.LastWriteTimeUtc.Ticks;
            try {
              var data = selectCover.ExecuteScalar();
              return (data as byte[]) != null;
            }
            catch (DbException ex) {
              _logger.Error("Failed to lookup file cover existence from store", ex);
              return false;
            }
              }
        }
コード例 #39
0
ファイル: FileStore.cs プロジェクト: vitska/simpleDLNA
 public bool HasCover(IStoreItem file)
 {
     return MaybeGetCover(file) != null;
 }