예제 #1
0
        private IDisposable Consume(
            IQueue queue,
            Func <byte[], MessageProperties, MessageReceivedInfo, Task> onMessage,
            Action <IConsumerConfiguration> configure)
        {
            GuardHelper.ArgumentNotNull(() => queue);
            GuardHelper.ArgumentNotNull(() => onMessage);
            if (disposed)
            {
                throw new ZRabbitMqException("This bus has been disposed");
            }

            var consumerConfiguration = new ConsumerConfiguration(RabbitMqConfiguration.PrefetchCount);

            if (configure != null)
            {
                configure(consumerConfiguration);
            }

            var consumerFactory = ServiceLocator.GetInstance <IConsumerFactory>();
            var consumer        = consumerFactory.CreateConsumer(queue, (body, properties, receviedInfo) =>
            {
                var rawMessage = ProduceConsumeInterceptor.OnConsume(new RawMessage(properties, body));
                return(onMessage(rawMessage.Body, rawMessage.Properties, receviedInfo));
            }, connection, consumerConfiguration);

            return(consumer.StartConsuming());
        }
예제 #2
0
        public static IRedisConfiguration GetConfig(string redisConfigName)
        {
            GuardHelper.ArgumentNotNull(() => redisConfigName);

            var handler = ConfigurationManager.GetSection("redisConfig") as RedisConfigurationHandler;

            GuardHelper.ArgumentNotNull(() => handler);
            RedisHostGroup group = null;

            foreach (RedisHostGroup item in handler.HostGroups)
            {
                if (item.Name.Equals(redisConfigName, StringComparison.OrdinalIgnoreCase))
                {
                    group = item;
                    break;
                }
            }

            if (group == null)
            {
                throw new Exception(string.Format("Redis配置错误,根據服務器配置組名:{0}找不到Redis服務器组", redisConfigName));
            }

            return(group);
        }
예제 #3
0
        public void InvokeChannelAction(Action <IModel> channelAction)
        {
            GuardHelper.ArgumentNotNull(() => channelAction);
            var startTime    = DateTime.UtcNow;
            var retryTimeout = TimeSpan.FromMilliseconds(50);

            while (!IsTimedOut(startTime))
            {
                try
                {
                    var channel = OpenChannel();
                    channelAction(channel);
                    return;
                }
                catch (OperationInterruptedException)
                {
                    CloseChannel();
                }
                catch (ZRabbitMqException)
                {
                    CloseChannel();
                }

                Thread.Sleep(retryTimeout);

                retryTimeout = retryTimeout.Double();
            }
            Logger.Error("Channel action timed out. Throwing exception to client.");
            throw new TimeoutException("The operation requested on PersistentChannel timed out.");
        }
예제 #4
0
 public Message(T body)
 {
     GuardHelper.ArgumentNotNull(() => body);
     Body        = body;
     Properties  = new MessageProperties();
     MessageType = body.GetType();
 }
예제 #5
0
        public DefaultLifetimeScopeProvider(ILifetimeScopeAccessor accessor)
        {
            GuardHelper.ArgumentNotNull(() => accessor);

            this._accessor = accessor;
            AutofacRequestLifetimeHttpModule.SetLifetimeScopeProvider(this);
        }
예제 #6
0
        public virtual IServiceRegister Register <TService>(
            Func <IServiceProvider, TService> serviceFactory,
            DependencyLifecycle lifecycle = DependencyLifecycle.Singleton)
            where TService : class
        {
            GuardHelper.ArgumentNotNull(() => serviceFactory);
            CheckDependencyLifecycle(lifecycle);
            var serviceType = typeof(TService);

            if (ServiceIsRegistered(serviceType))
            {
                return(this);
            }
            lock (syncLock)
            {
                if (lifecycle == DependencyLifecycle.Singleton)
                {
                    var service = serviceFactory(this);
                    instances.TryAdd(serviceType, service);
                }
                else
                {
                    factories.TryAdd(serviceType, serviceFactory);
                }
            }
            return(this);
        }
예제 #7
0
        /// <summary>
        /// Gets a value indicating whether the given min. required app version is assumed
        /// to be compatible with the current app version
        /// </summary>
        /// <remarks>
        /// A plugin is generally compatible when both app version and plugin's
        /// <c>MinorAppVersion</c> are equal, OR - when app version is greater - it is
        /// assumed to be compatible when no breaking changes occured since <c>MinorAppVersion</c>.
        /// </remarks>
        /// <param name="minAppVersion">The min. app version to check for</param>
        /// <returns><c>true</c> when the extension's version is assumed to be compatible</returns>
        public static bool IsAssumedCompatible(Version minAppVersion)
        {
            GuardHelper.ArgumentNotNull(() => minAppVersion);

            if (ZSharpVersion.Version == minAppVersion)
            {
                return(true);
            }

            if (ZSharpVersion.Version < minAppVersion)
            {
                return(false);
            }

            bool compatible = true;

            foreach (var version in ZSharpVersion.BreakingChangesHistory)
            {
                if (version > minAppVersion)
                {
                    // there was a breaking change in a version greater
                    // than plugin's MinorAppVersion.
                    compatible = false;
                    break;
                }

                if (version <= minAppVersion)
                {
                    break;
                }
            }

            return(compatible);
        }
예제 #8
0
 public BaseResolver(IUnityContainer container)
 {
     if (container == null)
     {
         GuardHelper.ArgumentNotNull(() => container);
     }
     this.container = container;
 }
예제 #9
0
 public Message(T body, MessageProperties properties)
 {
     GuardHelper.ArgumentNotNull(() => body);
     GuardHelper.ArgumentNotNull(() => properties);
     Body        = body;
     Properties  = properties;
     MessageType = body.GetType();
 }
예제 #10
0
        public DefaultLifetimeScopeAccessor(ILifetimeScope rootContainer)
        {
            GuardHelper.ArgumentNotNull(() => rootContainer);

            //rootContainer.ChildLifetimeScopeBeginning += OnScopeBeginning;

            this._rootContainer = rootContainer;
            this._state         = new ContextState <ILifetimeScope>("CustomLifetimeScopeProvider.WorkScope");
        }
예제 #11
0
        public static IMessage CreateInstance(Type messageType, object body)
        {
            GuardHelper.ArgumentNotNull(() => messageType);
            GuardHelper.ArgumentNotNull(() => body);

            var genericType = genericMessageTypesMap.GetOrAdd(messageType, t => typeof(Message <>).MakeGenericType(messageType));
            var message     = ReflectionHelper.CreateInstance(genericType, body);

            return((IMessage)message);
        }
예제 #12
0
        public PricingService(ISeatTypeViewRepository repository)
        {
            if (repository == null)
            {
                GuardHelper.ArgumentNotNull(() => repository);
                throw new ArgumentNullException("repository");
            }

            this.repository = repository;
        }
예제 #13
0
        public RedisCache(ISerializer serializer, IRedisWrapper redisWrapper = null)
        {
            GuardHelper.ArgumentNotNull(() => serializer);
            if (redisWrapper == null)
            {
                redisWrapper = RedisFactory.GetRedisWrapper();
            }

            this.serializer   = serializer;
            this.redisWrapper = redisWrapper;
        }
예제 #14
0
        public async Task PublishAsync <T>(T message, string topic) where T : class
        {
            GuardHelper.ArgumentNotNull(() => message);
            GuardHelper.ArgumentNotEmpty(() => topic);
            var messageType   = typeof(T);
            var rabbitMessage = GetRabbitMessage(message, messageType);
            var exchange      = await publishExchangeDeclareStrategy.DeclareExchangeAsync(
                advancedBus, messageType, ExchangeType.Topic).ConfigureAwait(false);

            await advancedBus.PublishAsync(exchange, topic, rabbitMessage).ConfigureAwait(false);
        }
예제 #15
0
        public void Publish <T>(T message, string topic) where T : class
        {
            GuardHelper.ArgumentNotNull(() => message);

            var         messageType   = typeof(T);
            Message <T> rabbitMessage = GetRabbitMessage(message, messageType);
            var         exchange      = publishExchangeDeclareStrategy.DeclareExchange(
                advancedBus, messageType, ExchangeType.Topic);

            advancedBus.Publish(exchange, topic, rabbitMessage);
        }
예제 #16
0
        public LogSetting(Type type, NameValueCollection nvList)
        {
            GuardHelper.ArgumentNotNull(() => type);
            var msg = string.Format("Type {0} does not implement {1}",
                                    type.AssemblyQualifiedName, typeof(ILoggerAdapter).FullName);

            GuardHelper.Implements <ILoggerAdapter>(type, msg);

            factoryAdapterType = type;
            properties         = nvList;
        }
예제 #17
0
        private void PreparePublish(IExchange exchange, string routingKey, IMessage <T> message)
        {
            GuardHelper.ArgumentNotNull(() => exchange);
            GuardHelper.ArgumentNotNull(() => routingKey);
            GuardHelper.ArgumentNotNull(() => message);
            this.exchange   = exchange;
            this.routingKey = routingKey;

            mandatory = RabbitMqConfiguration.Mandatory;
            SerializeMessage(message);
        }
예제 #18
0
        public IHandlerRegistration Add <T>(Func <IMessage <T>, MessageReceivedInfo, Task> handler) where T : class
        {
            GuardHelper.ArgumentNotNull(() => handler);

            if (handlers.ContainsKey(typeof(T)))
            {
                throw new ZRabbitMqException("There is already a handler for message type '{0}'", typeof(T).Name);
            }

            handlers.Add(typeof(T), (iMessage, messageReceivedInfo) => handler((IMessage <T>)iMessage, messageReceivedInfo));
            return(this);
        }
예제 #19
0
        public static bool HasDefaultConstructor(this Type type)
        {
            GuardHelper.ArgumentNotNull(() => type);

            if (type.IsValueType)
            {
                return(true);
            }

            return(type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)
                   .Any(ctor => ctor.GetParameters().Length == 0));
        }
 public bool TryStoreIconToFile(ImageSource icon, string storageFolder, out string iconID, out string iconPath)
 {
     GuardHelper.ArgumentNotNull(icon, "icon");
     byte[] iconBytes = null;
     try {
         iconBytes = ImageLoader2.ImageToByteArray(icon, baseUri);
     } catch (Exception) {
         iconID   = null;
         iconPath = null;
         return(false);
     }
     iconID   = NativeResourceManager.CreateFileName(GetImageHash(iconBytes)) + ".ico";
     iconPath = UnpackIcon(Path.Combine(storageFolder, iconID), iconBytes);
     return(iconPath != null);
 }
예제 #21
0
        private Message <T> PrepareSend <T>(string queue, T message) where T : class
        {
            GuardHelper.ArgumentNotEmpty(() => queue);
            GuardHelper.ArgumentNotNull(() => message);
            DeclareQueue(queue);
            var wrappedMessage = new Message <T>(message)
            {
                Properties =
                {
                    DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(typeof(T))
                }
            };

            return(wrappedMessage);
        }
예제 #22
0
        public string Serialize(Type type)
        {
            GuardHelper.ArgumentNotNull(() => type);

            return(serializedTypes.GetOrAdd(type, t =>
            {
                var typeName = t.FullName + ":" + t.Assembly.GetName().Name;
                if (typeName.Length > 255)
                {
                    throw new FrameworkException("The serialized name of type '{0}' exceeds the AMQP " +
                                                 "maximum short string length of 255 characters.", t.Name);
                }
                return typeName;
            }));
        }
예제 #23
0
        public void RegisterAction(IJumpAction jumpAction, string commandLineArgumentPrefix, Func <string> launcherPath)
        {
            GuardHelper.ArgumentNotNull(jumpAction, "jumpAction");
            if (!updating)
            {
                throw new InvalidOperationException();
            }
            RegisterInstance();
            RegisteredJumpAction registeredjumpAction = PrepareJumpActionToRegister(jumpAction, commandLineArgumentPrefix, launcherPath);

            AddAction(registeredjumpAction);
            if (ShouldExecute(jumpAction.CommandId, commandLineArgumentPrefix))
            {
                ExecuteCore(jumpAction.CommandId);
            }
        }
예제 #24
0
        /// <summary>
        /// Implement this method to execute your handler processing.
        /// </summary>
        /// <remarks>
        ///  2014年01月10日 10:49 Created By iceStone
        /// </remarks>
        /// <param name="input">Inputs to the current call to the target.</param>
        /// <param name="getNext">Delegate to execute to get the next delegate in the handler
        /// chain.</param>
        /// <returns>Return value from the target.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            //if (input == null) throw new ArgumentNullException("input");
            //if (getNext == null) throw new ArgumentNullException("getNext");
            GuardHelper.ArgumentNotNull(input, "input");
            GuardHelper.ArgumentNotNull(getNext, "getNext");
            //开始执行
            var result = getNext()(input, getNext);

            //执行结果没有异常,直接返回执行结果
            if (result.Exception == null)
            {
                return(result);
            }
            //否则记录日志信息
            LogHelper.WriteErrorLog("TracingCallHandler", result.Exception.Message, result.Exception);
            //处理异常
            result.Exception = null;
            return(result);
        }
예제 #25
0
        public RabbitMqConfiguration(string rabbitMqConfigName)
        {
            GuardHelper.ArgumentNotNull(() => rabbitMqConfigName);
            var configuration = RabbitMqConfigurationHandler.GetConfig(rabbitMqConfigName);

            VirtualHost          = configuration.VirtualHost;
            UserName             = configuration.UserName;
            Password             = configuration.UserName;
            RequestedHeartbeat   = configuration.RequestedHeartbeat;
            Timeout              = configuration.Timeout;
            PublisherConfirms    = configuration.PublisherConfirms;
            PersistentMessages   = configuration.PersistentMessages;
            CancelOnHaFailover   = configuration.CancelOnHaFailover;
            UseBackgroundThreads = configuration.UseBackgroundThreads;
            Mandatory            = configuration.Mandatory;
            PrefetchCount        = configuration.PrefetchCount;
            ClientProperties     = configuration.ClientProperties;
            RabbitMqHosts        = configuration.RabbitMqHosts;

            SetClientDefaultProperties();
        }
예제 #26
0
        public static string EnsureEndsWith(this string value, string endWith)
        {
            GuardHelper.ArgumentNotNull(() => value);
            GuardHelper.ArgumentNotNull(() => endWith);

            if (value.Length >= endWith.Length)
            {
                if (string.Compare(value, value.Length - endWith.Length, endWith, 0, endWith.Length, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return(value);
                }

                string trimmedString = value.TrimEnd(null);

                if (string.Compare(trimmedString, trimmedString.Length - endWith.Length, endWith, 0, endWith.Length, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return(value);
                }
            }

            return(value + endWith);
        }
예제 #27
0
        public ISubscriptionResult SubscribeAsync <T>(string subscriptionId, Func <T, Task> onMessage)
            where T : class
        {
            GuardHelper.ArgumentNotEmpty(() => subscriptionId);
            GuardHelper.ArgumentNotNull(() => onMessage);

            var    queueName    = Conventions.QueueNamingConvention(typeof(T), subscriptionId);
            var    exchangeName = Conventions.ExchangeNamingConvention(typeof(T));
            IQueue queue        = QueueDeclare(queueName);
            var    exchange     = ExchangeDeclare(exchangeName);

            foreach (var topic in subConfigure.Topics.DefaultIfEmpty("#"))
            {
                advancedBus.Bind(exchange, queue, topic);
            }

            var consumerCancellation = advancedBus.Consume <T>(
                queue,
                (message, messageReceivedInfo) => onMessage(message.Body),
                x => { InitIConsumerConfiguration(x); });

            return(new SubscriptionResult(exchange, queue, consumerCancellation));
        }
        public static IRabbitMqConfiguration GetConfig(string rabbitMqConfigName)
        {
            GuardHelper.ArgumentNotNull(() => rabbitMqConfigName);
            var section = ConfigurationManager.GetSection("rabbitMqConfig");
            var handler = section as RabbitMqConfigurationHandler;

            GuardHelper.ArgumentNotNull(() => handler);
            RabbitMqHostGroup group = null;

            foreach (RabbitMqHostGroup item in handler.HostGroups)
            {
                if (item.VirtualHost.Equals(rabbitMqConfigName, StringComparison.OrdinalIgnoreCase))
                {
                    group = item;
                    break;
                }
            }
            if (group == null)
            {
                throw new Exception(string.Format("RabbitMq配置错误,根據配置名:{0}找不到RabbitMq服務器组", rabbitMqConfigName));
            }

            return(group);
        }
        public static IRedisConfiguration GetConfig(AppCodeType?appCodeType = null)
        {
            var configName = string.Empty;

            if (appCodeType == null)
            {
                var codeType = ConfigurationManager.AppSettings["AppCodeType"];
                GuardHelper.ArgumentNotNull(() => codeType);
                configName = codeType.ToString();
            }
            else
            {
                configName = appCodeType.Value.GetDescription();
            }

            var handler = ConfigurationManager.GetSection("redisConfig") as RedisConfigurationHandler;

            GuardHelper.ArgumentNotNull(() => handler);
            RedisHostGroup group = null;

            foreach (RedisHostGroup item in handler.HostGroups)
            {
                if (item.Name.Equals(configName, StringComparison.OrdinalIgnoreCase))
                {
                    group = item;
                    break;
                }
            }

            if (group == null)
            {
                throw new Exception(string.Format("Redis配置错误,根據服務器配置組名:{0}找不到Redis服務器组", configName));
            }

            return(group);
        }
 public ApplicationJumpPathWrap(ApplicationJumpPathInfo applicationJumpPath)
 {
     GuardHelper.ArgumentNotNull(applicationJumpPath, "applicationJumpPath");
     ApplicationJumpPath = applicationJumpPath;
 }