Beispiel #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CartOperationInfo"/>.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="status"></param>
        /// <param name="exception">
        /// The <see cref="Exception"/> related to the failure.
        /// Important: if <paramref name="status"/> is <see cref="CartOperationStatus.Error"/> then this
        /// field must not be <code>null</code>, otherwise <see cref="ArgumentNullException"/> will be thrown.
        /// </param>
        public CartOperationInfo(CartOperationType type, CartOperationStatus status, Exception exception = null)
        {
            this.Type      = type;
            this.Status    = status;
            this.Exception = exception;

            if ((exception == null && status == CartOperationStatus.Error) ||
                (exception != null && status == CartOperationStatus.Successful))
            {
                throw new ArgumentNullException(nameof(exception),
                                                "Necessary and sufficient condition for exception to be present is that the message is set as error");
            }
        }
        public Task AddOrRemoveAsync(
            CartOperationType cartOperationType,
            string userId,
            int productId)
        {
            return(Task.Run(() =>
            {
                if (!_memoryCache.TryGetValue(userId, out CartDto cartDto))
                {
                    cartDto = new CartDto
                    {
                        UserId = userId,
                        ProductIds = new List <int>(),
                    };
                }

                switch (cartOperationType)
                {
                case CartOperationType.Add:
                    {
                        cartDto.ProductIds.Add(productId);
                    }
                    break;

                case CartOperationType.Remove:
                    {
                        cartDto.ProductIds.Remove(productId);
                    }
                    break;

                case CartOperationType.Unknown:
                    break;

                default:
                    break;
                }

                _memoryCache.Set(
                    userId,
                    cartDto,
                    new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(TimeSpan.FromMinutes(60)));
            }));
        }