protected virtual string GetString(Article product)
        {
            Throws.IfArgumentNull(product, _ => product);

            int typeId = default(int);

            var typeField = product.GetField("Type");

            var field = typeField as ExtensionArticleField;

            if (field != null)
            {
                if (!int.TryParse(field.Value, out typeId))
                {
                    typeId = 0;
                }
            }

            if (typeId <= 0)
            {
                _logger.Error("Product {productId} has no type", product.Id);
            }

            return(_service.GetControlDefinition(product.ContentId, typeId));
        }
Esempio n. 2
0
        public static void Merge(
            this IDictionary <string, object> instance,
            string name,
            object val,
            bool replaceExisting)
        {
            Throws.IfArgumentNull(instance, _ => instance);
            Throws.IfArgumentNot(!string.IsNullOrEmpty(name), _ => name);

            if (!instance.ContainsKey(name))
            {
                instance.Add(name, val);
                return;
            }

            if (instance.ContainsKey(name) & replaceExisting)
            {
                instance[name] = val;
                return;
            }

            if (instance.ContainsKey(name) & !replaceExisting)
            {
                instance[name] += " " + val;
                return;
            }
        }
Esempio n. 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="mode">режим работы</param>
        /// <param name="pollPeriod">интервал опроса бд</param>
        /// <param name="invalidator">объект, инвалидирующий кеш</param>
        /// <param name="connectionName">имя строки подключения</param>
        /// <param name="dueTime">отложенный запуск (ms)</param>
        /// <param name="onInvalidate">вызывается при удалении старых записей</param>
        public QPCacheItemWatcher(InvalidationMode mode, TimeSpan pollPeriod, IContentInvalidator invalidator,
                                  string connectionName = "qp_database",
                                  int dueTime           = 0,
                                  bool useTimer         = true,
                                  Func <Tuple <int[], string[]>, bool> onInvalidate = null)
        {
            Throws.IfArgumentNull(_ => connectionName);
            Throws.IfArgumentNull(_ => invalidator);

            _dueTime    = TimeSpan.FromMilliseconds(dueTime);
            _pollPeriod = pollPeriod;
            if (useTimer)
            {
                _timer = new Timer(OnTick, null, 0, Timeout.Infinite);
            }
            var connectionString = ConfigurationManager.ConnectionStrings[connectionName];

            try
            {
                _connectionString = connectionString.ConnectionString;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("access to _connectionString.ConnectionString caused an exception", ex);
            }

            Throws.IfArgumentNullOrEmpty(_connectionString, nameof(_connectionString));

            _trackers     = new ConcurrentBag <CacheItemTracker>();
            _mode         = mode;
            _invalidator  = invalidator;
            _onInvalidate = onInvalidate;
            Throws.IfArgumentNull(_ => _connectionString);
        }
        public UIElement GetControlForProduct(Article product)
        {
            Throws.IfArgumentNull(product, nameof(product));

            string baseDir = Path.Combine(_hostingEnvironment.WebRootPath, "/App_Data/");

            return(GetXaml(Path.Combine(baseDir, $"controls/{product.ContentId}.xaml")));
        }
Esempio n. 5
0
        /// <summary>
        /// Performs the given <see cref="Action{T}" /> on each item in the enumerable.
        /// </summary>
        /// <typeparam name="T">The type of item in the enumerable.</typeparam>
        /// <param name="items">The enumerable of items.</param>
        /// <param name="action">The action to perform on each item.</param>
        public static void ForEach <T>(this IEnumerable <T> items, Action <T> action)
        {
            Throws.IfArgumentNull(items, _ => items);
            Throws.IfArgumentNull(action, _ => action);

            foreach (T item in items)
            {
                action(item);
            }
        }
Esempio n. 6
0
        public ServiceResult RemoveMessage(int id)
        {
            return(RunAction(new UserContext(), null, () =>
            {
                Throws.IfArgumentNull(id, _ => id);
                var ctx = NotificationsModelDataContext.Get(_provider);
                var m = ctx.Messages.FirstOrDefault(x => x.Id == id);

                if (m != null)
                {
                    ctx.Messages.Remove(m);
                    ctx.SaveChanges();
                }
            }));
        }
Esempio n. 7
0
        public static void Merge(
            this IDictionary <string, object> instance,
            IDictionary <string, object> from,
            bool replaceExisting)
        {
            Throws.IfArgumentNull(instance, _ => instance);
            Throws.IfArgumentNull(from, _ => from);

            foreach (KeyValuePair <string, object> keyValuePair in (IEnumerable <KeyValuePair <string, object> >)from)
            {
                if (replaceExisting || !instance.ContainsKey(keyValuePair.Key))
                {
                    instance[keyValuePair.Key] = keyValuePair.Value;
                }
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Выполнение сервиса
        /// </summary>
        /// <param name="func">Функция, выполняющаяся при успешных проверках</param>
        /// <returns></returns>
        protected virtual ServiceResult <TResult> Run <TResult>(
            UserContext userContext,
            ISecurityContext securityContext,
            Func <TResult> func /*, [CallerMemberName] string caller = ""*/)
        {
            var result = new ServiceResult <TResult>();

            if (userContext == null)
            {
                Throws.IfArgumentNull(
                    UserContentNullExceptionMessage, userContext, "userContext");
            }

            try
            {
                result.Result      = func();
                result.IsSucceeded = true;
            }
            catch (OperationExecutionException ex)
            {
                result.IsSucceeded = false;
                result.Error       = new ServiceError {
                    ErrorCode = -1, Message = ex.Message, Type = ServiceErrorType.BusinessLogicMessage
                };
            }
            catch (DataException ex)
            {
                result.IsSucceeded = false;
                result.Error       = new ServiceError {
                    ErrorCode = -1, Message = ex.Message, Type = ServiceErrorType.BusinessLogicMessage
                };
            }
            catch (Exception ex)
            {
                result.IsSucceeded = false;
                result.Error       = new ServiceError {
                    ErrorCode = -1, Message = ex.Message
                };
                GetLogger()?.ErrorException(
                    GeneralServiceExceptionMessage
                    //+ this.GetType() + caller
                    , ex);
            }

            return(result);
        }
Esempio n. 9
0
        public TasksRunner(Func <string, int, ITask> taskFactoryMethod, Func <ITaskService> taskServiceFactoryMethod, IIdentityProvider identityProvider, TaskRunnerDelays delays, IFactory consolidationFactory)
        {
            State = StateEnum.Stopped;

            Throws.IfArgumentNull(_ => taskFactoryMethod);

            Throws.IfArgumentNull(_ => taskServiceFactoryMethod);

            _taskServiceFactoryMethod = taskServiceFactoryMethod;

            _taskFactoryMethod = taskFactoryMethod;

            _identityProvider = identityProvider;

            _delays = delays;

            _consolidationFactory = consolidationFactory;
        }
Esempio n. 10
0
        /// <summary>
        /// Выполнение действия сервиса
        /// </summary>
        /// <typeparam name="TResult">Тип сущности</typeparam>
        /// <param name="userContext">Контекст пользователя</param>
        /// <param name="func">Функция, выполняющаяся при успешных проверках</param>
        /// <returns></returns>
        protected virtual ServiceEnumerationResult <TResult> RunEnumeration <TResult>(
            UserContext userContext,
            ISecurityContext securityContext,
            Func <List <TResult> > func)
        {
            var result = new ServiceEnumerationResult <TResult>();

            if (userContext == null)
            {
                Throws.IfArgumentNull(
                    UserContentNullExceptionMessage, userContext, "userContext");
            }

            try
            {
                result.Result      = func();
                result.IsSucceeded = true;
            }
            catch (OperationExecutionException ex)
            {
                result.IsSucceeded = false;
                result.Error       = new ServiceError {
                    ErrorCode = -1, Message = ex.Message, Type = ServiceErrorType.BusinessLogicMessage
                };
            }
            catch (DataException ex)
            {
                result.IsSucceeded = false;
                result.Error       = new ServiceError {
                    ErrorCode = -1, Message = ex.Message, Type = ServiceErrorType.BusinessLogicMessage
                };
            }
            catch (Exception ex)
            {
                result.IsSucceeded = false;
                result.Error       = new ServiceError {
                    ErrorCode = -1, Message = ex.Message
                };
                GetLogger()?.ErrorException(
                    GeneralServiceExceptionMessage, ex);
            }

            return(result);
        }
Esempio n. 11
0
        override public async Task <ActionTaskResult> Process(ActionContext context)
        {
            Throws.IfArgumentNull(context, _ => context);
            string id = "id" + Guid.NewGuid();

            var products = DoWithLogging("_productService.GetProductsByIds", id,
                                         () => _productService.GetProductsByIds(context.ContentItemIds));

            try
            {
                await _notificationService.SendProductsAsync(products, true, context.UserName, context.UserId, false, false);
            }
            catch (Exception ex)
            {
                throw new ActionException("There are some errors occured. ", new[] { ex }, context);
            }

            return(null);
        }
Esempio n. 12
0
        public ServiceResult <List <Message> > GetMessagesToSend(string channel, int maxCount)
        {
            return(RunEnumeration <Message>(new UserContext(), null, () =>
            {
                Throws.IfArgumentNull(channel, _ => channel);
                Throws.IfArgumentNull(maxCount, _ => maxCount);

                var ctx = NotificationsModelDataContext.Get(_provider);

                return ctx.Messages
                .Where(x => x.Channel == channel &&
                       x.Created <=
                       DateTime.Now.AddSeconds(-10))          //чтобы не читать данные которые сейчас пишут
                .OrderBy(x => x.Created)
                .Take(maxCount)
                .ToList()
                .Select(x => new Message
                {
                    Channel = x.Channel, Created = x.Created, Id = x.Id, Method = x.Method,
                    Xml = x.Data, UserId = x.UserId, UserName = x.UserName, Key = x.DataKey
                }).ToList();
            }));
        }
Esempio n. 13
0
        public DelegateFilter(Func <Article, bool> match)
        {
            Throws.IfArgumentNull(match, _ => match);

            _match = match;
        }
Esempio n. 14
0
        public void PushNotifications(NotificationItem[] notifications, bool isStage, int userId, string userName, string method, string customerCode)
        {
            _identityProvider.Identity = new Identity(customerCode);

            RunAction(new UserContext(), null, () =>
            {
                Throws.IfArgumentNull(notifications, _ => notifications);

                List <NotificationChannel> channels = null;
                var provider = ObjectFactoryBase.Resolve <INotificationProvider>();
                if (notifications.Any(n => n.Channels == null))
                {
                    channels = provider.GetConfiguration().Channels;

                    if (channels == null)
                    {
                        var productIds = notifications.Where(n => n.Channels == null).Select(n => n.ProductId);
                        _logger.Error(
                            "Products {0} have not been enqueued because there are no channels for publishing",
                            string.Join(", ", string.Join(", ", productIds))
                            );
                        throw new Exception("No channels for publishing");
                    }
                }

                var messages = new List <DAL.Message>();

                foreach (var notification in notifications)
                {
                    if (notification.Channels == null)
                    {
                        foreach (var channel in channels.Where(c => c.IsStage == isStage))
                        {
                            if (channel.XPathFilterExpression == null || DocumentMatchesFilter(notification.Data, channel.XPathFilterExpression))
                            {
                                messages.Add(new DAL.Message
                                {
                                    Created  = DateTime.Now,
                                    Channel  = channel.Name,
                                    Data     = notification.Data,
                                    DataKey  = notification.ProductId,
                                    Method   = method,
                                    UserId   = userId,
                                    UserName = userName
                                });
                            }
                        }
                    }
                    else
                    {
                        foreach (var channel in notification.Channels)
                        {
                            messages.Add(new DAL.Message
                            {
                                Created  = DateTime.Now,
                                Channel  = channel,
                                Data     = notification.Data,
                                DataKey  = notification.ProductId,
                                Method   = method,
                                UserId   = userId,
                                UserName = userName
                            });
                        }
                    }
                }

                if (messages.Any())
                {
                    var ctx = NotificationsModelDataContext.Get(_connectionProvider);
                    ctx.Messages.AddRange(messages);

                    var productIds = notifications.Select(n => n.ProductId).Distinct();
                    _logger.Info()
                    .Message("Message {message} for products {productIds} is enqueueing",
                             method, string.Join(", ", productIds)
                             )
                    .Property("isStage", isStage)
                    .Write();

                    ctx.SaveChanges();
                }
            });
        }
Esempio n. 15
0
        /// <summary>
        /// Подключение пользовательского анализатора изменений в БД
        /// </summary>
        /// <param name="tracker"></param>
        public void AttachTracker(CacheItemTracker tracker)
        {
            Throws.IfArgumentNull(tracker, _ => tracker);

            _trackers.Add(tracker);
        }