예제 #1
0
        public void SetUp()
        {
            var connectionFactory = new ConnectionFactoryWrapper(new ConnectionFactory
            {
                HostName = "localhost",
                VirtualHost = "/",
                UserName = "******",
                Password = "******"
            });

            var serializer = new JsonSerializer();
            var logger = new ConsoleLogger();
            var consumerErrorStrategy = new DefaultConsumerErrorStrategy(connectionFactory, serializer, logger);
            var conventions = new Conventions();

            advancedBus = new RabbitAdvancedBus(
                connectionFactory,
                TypeNameSerializer.Serialize,
                serializer,
                new QueueingConsumerFactory(logger, consumerErrorStrategy),
                logger,
                CorrelationIdGenerator.GetCorrelationId,
                conventions);

            while (!advancedBus.IsConnected)
            {
                Thread.Sleep(10);
            }
        }
예제 #2
0
 public static void AssertIsValidForSend(Type messageType, Conventions conventions)
 {
     if (conventions.IsEventType(messageType))
     {
         throw new InvalidOperationException("Events can have multiple recipient so they should be published");
     }
 }
예제 #3
0
        public void SetUp()
        {
            var mockModel = new MockModel
                            {
                                ExchangeDeclareAction = (exchangeName, type, durable, autoDelete, arguments) => createdExchangeName = exchangeName,
                                BasicPublishAction = (exchangeName, topic, properties, messageBody) =>
                                                     	{
                                                     		publishedToExchangeName = exchangeName;
                                                     		publishedToTopic = topic;
                                                     	}
                            };

            var customConventions = new Conventions
                              	{
                              		ExchangeNamingConvention = x => "CustomExchangeNamingConvention",
                              		QueueNamingConvention = (x, y) => "CustomQueueNamingConvention",
                              		TopicNamingConvention = x => "CustomTopicNamingConvention"
                              	};

            CreateBus(customConventions, mockModel);
            using (var publishChannel = bus.OpenPublishChannel())
            {
                publishChannel.Publish(new TestMessage());
            }
        }
예제 #4
0
        public static IBus CreateBus()
        {
            var connectionFactory = new InMemoryConnectionFactory();

            var serializer = new JsonSerializer();
            var logger = new ConsoleLogger();
            var conventions = new Conventions();
            var consumerErrorStrategy = new DefaultConsumerErrorStrategy(connectionFactory, serializer, logger, conventions);

            var advancedBus = new RabbitAdvancedBus(
                new ConnectionConfiguration(),
                connectionFactory,
                TypeNameSerializer.Serialize,
                serializer,
                new QueueingConsumerFactory(logger, consumerErrorStrategy),
                logger,
                CorrelationIdGenerator.GetCorrelationId,
                conventions);

            return new RabbitBus(
                TypeNameSerializer.Serialize,
                logger,
                conventions,
                advancedBus);
        }
예제 #5
0
 public static void AssertIsValidForReply(Type messageType, Conventions conventions)
 {
     if (conventions.IsCommandType(messageType) || conventions.IsEventType(messageType))
     {
         throw new InvalidOperationException("Reply is neither supported for Commands nor Events. Commands should be sent to their logical owner using bus.Send and bus. Events should be Published with bus.Publish.");
     }
 }
예제 #6
0
 public void IsCommandType_should_return_false_for_NServiceBus_types()
 {
     var conventions = new Conventions
     {
         IsCommandTypeAction = t => t.Assembly == typeof(Conventions).Assembly
     };
     Assert.IsFalse(conventions.IsCommandType(typeof(Conventions)));
 }
        internal AdvancedConfiguration()
        {
            Conventions = new Conventions
            {
                new FindByPolicyNameConvention(),
                new FindDefaultPolicyViolationHandlerByNameConvention()
            };

            SetDefaultResultsCacheLifecycle(Cache.DoNotCache);
        }
예제 #8
0
        static List<Type> GetMessageTypesHandledByThisEndpoint(MessageHandlerRegistry handlerRegistry, Conventions conventions, SubscribeSettings settings)
        {
            var messageTypesHandled = handlerRegistry.GetMessageTypes() //get all potential messages
                .Where(t => !conventions.IsInSystemConventionList(t)) //never auto-subscribe system messages
                .Where(t => !conventions.IsCommandType(t)) //commands should never be subscribed to
                .Where(conventions.IsEventType) //only events unless the user asked for all messages
                .Where(t => settings.AutoSubscribeSagas || handlerRegistry.GetHandlersFor(t).Any(handler => !typeof(Saga).IsAssignableFrom(handler.HandlerType))) //get messages with other handlers than sagas if needed
                .ToList();

            return messageTypesHandled;
        }
예제 #9
0
        public static void AssertIsValidForPubSub(Type messageType, Conventions conventions)
        {
            if (conventions.IsCommandType(messageType))
            {
                throw new InvalidOperationException("Pub/Sub is not supported for Commands. They should be be sent direct to their logical owner.");
            }

            if (!conventions.IsEventType(messageType))
            {
                Log.Info("You are using a basic message to do pub/sub, consider implementing the more specific ICommand and IEvent interfaces to help NServiceBus to enforce messaging best practices for you.");
            }
        }
 public void Apply(UnicastRoutingTable unicastRoutingTable, Conventions conventions)
 {
     var entries = new Dictionary<Type, RouteTableEntry>();
     foreach (var source in routeSources.OrderBy(x => x.Priority)) //Higher priority routes sources override lower priority.
     {
         foreach (var route in source.GenerateRoutes(conventions))
         {
             entries[route.MessageType] = route;
         }
     }
     unicastRoutingTable.AddOrReplaceRoutes("EndpointConfiguration", entries.Values.ToList());
 }
예제 #11
0
 private void CreateBus(Conventions conventions, IModel model)
 {
     bus = new RabbitBus(
         x => TypeNameSerializer.Serialize(x.GetType()),
         new JsonSerializer(),
         new MockConsumerFactory(),
         new MockConnectionFactory(new MockConnection(model)),
         new MockLogger(),
         CorrelationIdGenerator.GetCorrelationId,
         conventions
         );
 }
            public void Should_return_metadata_for_a_mapped_type()
            {
                var conventions = new Conventions();
                conventions.IsMessageTypeAction = type => type == typeof(int);

                var defaultMessageRegistry = new MessageMetadataRegistry(conventions);
                defaultMessageRegistry.RegisterMessageTypesFoundIn(new List<Type> { typeof(int) });

                var messageMetadata = defaultMessageRegistry.GetMessageMetadata(typeof(int));

                Assert.AreEqual(typeof(int), messageMetadata.MessageType);
                Assert.AreEqual(1, messageMetadata.MessageHierarchy.Count());
            }
예제 #13
0
        public void SetUp()
        {
            typeNameSerializer = new TypeNameSerializer();
            var customConventions = new Conventions(typeNameSerializer)
            {
                ExchangeNamingConvention = x => "CustomExchangeNamingConvention",
                QueueNamingConvention = (x, y) => "CustomQueueNamingConvention",
                TopicNamingConvention = x => "CustomTopicNamingConvention"
            };

            mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions));
            mockBuilder.Bus.Publish(new TestMessage());
        }
        public void Should_add_convention_for_predicate_to_instance()
        {
            // Arrange
            Func<PolicyResult, bool> expectedPredicate = x => true;
            var conventions = new Conventions();
            var expression = new ViolationHandlerExpression(new ViolationConfigurationExpression(conventions), expectedPredicate);

            // Act
            expression.IsHandledBy(() => new DefaultPolicyViolationHandler());

            // Assert
            Assert.That(conventions.Single().As<PredicateToPolicyViolationHandlerInstanceConvention<DefaultPolicyViolationHandler>>().Predicate, Is.EqualTo(expectedPredicate));
        }
예제 #15
0
        public CssProcessorTests()
        {
            conventions = new Conventions();

            var mappers = new List<IMapper>
                              {
                                  new BackgroundMapper(),
                                  new FontSizeMapper(),
                                  new FontFamilyMapper(),
                                  new MarginMapper()
                              };

            subject = new CssProcessor(new CssParser(), mappers);
        }
예제 #16
0
        public void SetUp()
        {
            var conventions = new Conventions(new TypeNameSerializer())
                {
                    ConsumerTagConvention = () => consumerTag
                };

            mockBuilder = new MockBuilder(x => x
                .Register<IConventions>(_ => conventions)
                //.Register<IEasyNetQLogger>(_ => new ConsoleLogger())
                );

            mockBuilder.Bus.Subscribe<MyMessage>(subscriptionId, message => { });
        }
예제 #17
0
        protected void SetUp()
        {
            ConsumerErrorStrategy = MockRepository.GenerateStub<IConsumerErrorStrategy>();

            IConventions conventions = new Conventions(new TypeNameSerializer())
                {
                    ConsumerTagConvention = () => ConsumerTag
                };
            MockBuilder = new MockBuilder(x => x
                    .Register(_ => conventions)
                    .Register(_ => ConsumerErrorStrategy)
                    //.Register<IEasyNetQLogger>(_ => new ConsoleLogger())
                );

            AdditionalSetUp();
        }
예제 #18
0
        public void SetUp()
        {
            var conventions = new Conventions
            {
                RpcExchangeNamingConvention = () => "rpc_exchange",
                RpcReturnQueueNamingConvention = () => "rpc_return_queue",
                ConsumerTagConvention = () => "the_consumer_tag"
            };

            mockBuilder = new MockBuilder(x => x
                .Register<IEasyNetQLogger>(_ => new ConsoleLogger())
                .Register<IConventions>(_ => conventions)
                );

            AdditionalSetup();
        }
예제 #19
0
        public void SetUp()
        {
            var customConventions = new Conventions
            {
                ExchangeNamingConvention = x => "CustomExchangeNamingConvention",
                QueueNamingConvention = (x, y) => "CustomQueueNamingConvention",
                TopicNamingConvention = x => "CustomTopicNamingConvention"
            };

            mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions));

            using (var publishChannel = mockBuilder.Bus.OpenPublishChannel())
            {
                publishChannel.Publish(new TestMessage());
            }
        }
예제 #20
0
        protected void SetUp()
        {
            ConsumerErrorStrategy = MockRepository.GenerateStub<IConsumerErrorStrategy>();
            ConsumerErrorStrategy.Stub(x => x.PostExceptionAckStrategy()).Return(PostExceptionAckStrategy.ShouldAck);

            IConventions conventions = new Conventions
                {
                    ConsumerTagConvention = () => ConsumerTag
                };
            MockBuilder = new MockBuilder(x => x
                    .Register(_ => conventions)
                    .Register(_ => ConsumerErrorStrategy)
                    //.Register<IEasyNetQLogger>(_ => new ConsoleLogger())
                );

            AdditionalSetUp();
        }
        public void Should_cache_the_message_convention()
        {
            var timesCalled = 0;
            conventions = new Conventions
            {
                IsMessageTypeAction = t =>
                {
                    timesCalled++;
                    return false;
                }
            };

            conventions.IsMessageType(GetType());
            Assert.AreEqual(1, timesCalled);

            conventions.IsMessageType(GetType());
            Assert.AreEqual(1, timesCalled);
        }
예제 #22
0
        public void SetUp()
        {
            messageWriter = new MockMessageWriter();
            queueRetrieval = new MockQueueRetrieval();
            messageReader = new MockMessageReader();
            queueInsertion = new MockQueueInsertion();
            errorRetry = new MockErrorRetry();
            conventions = new Conventions(new TypeNameSerializer());

            program = new Program(
                new ArgParser(),
                queueRetrieval,
                messageWriter,
                messageReader,
                queueInsertion,
                errorRetry,
                conventions);
        }
예제 #23
0
        public void SetUp()
        {
            var conventions = new Conventions
            {
                ConsumerTagConvention = () => consumerTag
            };

            mockBuilder = new MockBuilder(x => x
                .Register<IConventions>(_ => conventions)
                //.Register<IEasyNetQLogger>(_ => new ConsoleLogger())
                );

            var autoResetEvent = new AutoResetEvent(false);
            var handlerExecutionContext = (HandlerRunner)mockBuilder.ServiceProvider.Resolve<IHandlerRunner>();
            handlerExecutionContext.SynchronisationAction = () => autoResetEvent.Set();

            mockBuilder.Bus.Subscribe<MyMessage>(subscriptionId, message =>
            {
                deliveredMessage = message;
            });

            const string text = "Hello there, I am the text!";
            originalMessage = new MyMessage { Text = text };

            var body = new JsonSerializer().MessageToBytes(originalMessage);

            // deliver a message
            mockBuilder.Consumers[0].HandleBasicDeliver(
                consumerTag,
                deliveryTag,
                false, // redelivered
                typeName,
                "#",
                new BasicProperties
                {
                    Type = typeName,
                    CorrelationId = correlationId
                },
                body);

            // wait for the subscription thread to handle the message ...
            autoResetEvent.WaitOne(1000);
        }
예제 #24
0
        private void CreateBus(Conventions conventions, IModel model)
        {
            var advancedBus = new RabbitAdvancedBus(
                new ConnectionConfiguration(),
                new MockConnectionFactory(new MockConnection(model)),
                TypeNameSerializer.Serialize,
                new JsonSerializer(),
                new MockConsumerFactory(),
                new MockLogger(),
                CorrelationIdGenerator.GetCorrelationId,
                conventions,
                new DefaultMessageValidationStrategy(new MockLogger(), TypeNameSerializer.Serialize));

            bus = new RabbitBus(
                x => TypeNameSerializer.Serialize(x.GetType()),
                new MockLogger(),
                conventions,
                advancedBus
                );
        }
        public void Should_be_able_to_store_a_schedule_with_exchange()
        {
            var typeNameSerializer = new TypeNameSerializer();
            var conventions = new Conventions(typeNameSerializer);
            var jsonSerializer = new JsonSerializer(typeNameSerializer);
            var messageSerializationStrategy = new DefaultMessageSerializationStrategy(typeNameSerializer, jsonSerializer, new DefaultCorrelationIdGenerationStrategy());
            var testScheduleMessage = new TestScheduleMessage { Text = "Hello World" };

            var serializedMessage = messageSerializationStrategy.SerializeMessage(new Message<TestScheduleMessage>(testScheduleMessage));

            scheduleRepository.Store(new ScheduleMe
            {
                BindingKey = "",
                CancellationKey = "bcd",
                Exchange = conventions.ExchangeNamingConvention(typeof(TestScheduleMessage)),
                ExchangeType = ExchangeType.Topic,
                RoutingKey = "#",
                WakeTime = DateTime.UtcNow.AddMilliseconds(-1),
                InnerMessage = serializedMessage.Body,
                MessageProperties = serializedMessage.Properties
            });
        }
예제 #26
0
        static bool IsWcfService(Type t, Conventions conventions)
        {
            var args = t.GetGenericArguments();
            if (args.Length == 2)
            {
                if (conventions.IsMessageType(args[0]))
                {
                    var wcfType = typeof(WcfService<,>).MakeGenericType(args[0], args[1]);
                    if (wcfType.IsAssignableFrom(t))
                    {
                        return true;
                    }
                }
            }

            if (t.BaseType != null)
            {
                return IsWcfService(t.BaseType, conventions) && !t.IsAbstract;
            }

            return false;
        }
        public void Should_be_able_to_subscribe_to_error_messages()
        {
            var errorQueueName = new Conventions(new TypeNameSerializer()).ErrorQueueNamingConvention();

            var queue = bus.Advanced.QueueDeclare(errorQueueName);
            var autoResetEvent = new AutoResetEvent(false);

            bus.Advanced.Consume<SystemMessages.Error>(queue, (message, info) =>
            {
                var error = message.Body;

                Console.Out.WriteLine("error.DateTime = {0}", error.DateTime);
                Console.Out.WriteLine("error.Exception = {0}", error.Exception);
                Console.Out.WriteLine("error.Message = {0}", error.Message);
                Console.Out.WriteLine("error.RoutingKey = {0}", error.RoutingKey);

                autoResetEvent.Set();
                return Task.Factory.StartNew(() => { });
            });

            autoResetEvent.WaitOne(1000);
        }
        public void Queue_should_not_be_deleted_if_expires_is_not_set()
        {
            var bus = RabbitHutch.CreateBus("host=localhost");

            var subscriptionId = "TestSubscriptionWithoutExpires";
            var conventions = new Conventions(new TypeNameSerializer());
            var queueName = conventions.QueueNamingConvention(typeof(MyMessage), subscriptionId);
            var client = new ManagementClient("http://localhost", "guest", "guest");
            var vhost = new Vhost { Name = "/" };

            bus.Subscribe<MyMessage>(subscriptionId, message => { });

            var queue = client.GetQueue(queueName, vhost);
            queue.ShouldNotBeNull();

            // this will abandon the queue... poor queue!
            bus.Dispose();

            Thread.Sleep(1500);

            queue = client.GetQueue(queueName, vhost);
            queue.ShouldNotBeNull();
        }
예제 #29
0
 public DirectRoutingTopology(Conventions conventions, bool useDurableExchanges)
 {
     this.conventions         = conventions;
     this.useDurableExchanges = useDurableExchanges;
 }
예제 #30
0
            public Subscriber()
            {
                EndpointSetup <DefaultServer>(b =>
                {
                    var publisherEndpoint = Conventions.EndpointNamingConvention(typeof(LegacyPublisher));

                    var transport = b.UseTransport <SqlServerTransport>();
                    transport.DefaultSchema("receiver").UseSchemaForEndpoint(publisherEndpoint, "sender");
                    transport.SubscriptionSettings().SubscriptionTableName("SubscriptionRouting", "dbo");

                    transport.EnableMessageDrivenPubSubCompatibilityMode().RegisterPublisher(typeof(Event), Conventions.EndpointNamingConvention(typeof(LegacyPublisher)));
                });
            }
예제 #31
0
        /// <summary>
        /// Creates a <see cref="SagaMetadata" /> from a specific Saga type.
        /// </summary>
        /// <param name="sagaType">A type representing a Saga. Must be a non-generic type inheriting from <see cref="Saga" />.</param>
        /// <param name="availableTypes">Additional available types, used to locate saga finders and other related classes.</param>
        /// <param name="conventions">Custom conventions to use while scanning types.</param>
        /// <returns>An instance of <see cref="SagaMetadata" /> describing the Saga.</returns>
        public static SagaMetadata Create(Type sagaType, IEnumerable <Type> availableTypes, Conventions conventions)
        {
            Guard.AgainstNull(nameof(sagaType), sagaType);
            Guard.AgainstNull(nameof(availableTypes), availableTypes);
            Guard.AgainstNull(nameof(conventions), conventions);
            if (!IsSagaType(sagaType))
            {
                throw new Exception(sagaType.FullName + " is not a saga");
            }

            var genericArguments = GetBaseSagaType(sagaType).GetGenericArguments();

            if (genericArguments.Length != 1)
            {
                throw new Exception($"'{sagaType.Name}' saga type does not implement Saga<T>");
            }

            var saga   = (Saga)FormatterServices.GetUninitializedObject(sagaType);
            var mapper = new SagaMapper();

            saga.ConfigureHowToFindSaga(mapper);

            var sagaEntityType = genericArguments.Single();

            ApplyScannedFinders(mapper, sagaEntityType, availableTypes, conventions);

            var finders = new List <SagaFinderDefinition>();


            var propertyMappings = mapper.Mappings.Where(m => !m.HasCustomFinderMap)
                                   .GroupBy(m => m.SagaPropName)
                                   .ToList();

            if (propertyMappings.Count > 1)
            {
                var messageTypes = string.Join(",", propertyMappings.SelectMany(g => g.Select(m => m.MessageType.FullName)).Distinct());
                throw new Exception($"Sagas can only have mappings that correlate on a single saga property. Use custom finders to correlate {messageTypes} to saga {sagaType.Name}");
            }

            CorrelationPropertyMetadata correlationProperty = null;

            if (propertyMappings.Any())
            {
                var mapping = propertyMappings.Single().First();
                correlationProperty = new CorrelationPropertyMetadata(mapping.SagaPropName, mapping.SagaPropType);
            }

            var associatedMessages = GetAssociatedMessages(sagaType)
                                     .ToList();

            foreach (var mapping in mapper.Mappings)
            {
                var associatedMessage = associatedMessages.FirstOrDefault(m => mapping.MessageType.IsAssignableFrom(m.MessageType));
                if (associatedMessage == null)
                {
                    var msgType = mapping.MessageType.FullName;
                    if (mapping.HasCustomFinderMap)
                    {
                        throw new Exception($"Custom saga finder {mapping.CustomFinderType.FullName} maps message type {msgType} for saga {sagaType.Name}, but the saga does not handle that message. If {sagaType.Name} is supposed to handle this message, it should implement IAmStartedByMessages<{msgType}> or IHandleMessages<{msgType}>.");
                    }
                    throw new Exception($"Saga {sagaType.FullName} contains a mapping for {msgType} in the ConfigureHowToFindSaga method, but does not handle that message. If {sagaType.Name} is supposed to handle this message, it should implement IAmStartedByMessages<{msgType}> or IHandleMessages<{msgType}>.");
                }
                SetFinderForMessage(mapping, sagaEntityType, finders);
            }

            foreach (var messageType in associatedMessages)
            {
                if (messageType.IsAllowedToStartSaga)
                {
                    var match = mapper.Mappings.FirstOrDefault(m => m.MessageType.IsAssignableFrom(messageType.MessageType));
                    if (match == null)
                    {
                        var simpleName = messageType.MessageType.Name;
                        throw new Exception($"Message type {simpleName} can start the saga {sagaType.Name} (the saga implements IAmStartedByMessages<{simpleName}>) but does not map that message to saga data. In the ConfigureHowToFindSaga method, add a mapping using:{Environment.NewLine}    mapper.ConfigureMapping<{simpleName}>(message => message.SomeMessageProperty).ToSaga(saga => saga.MatchingSagaProperty);");
                    }
                }
            }

            return(new SagaMetadata(sagaType.FullName, sagaType, sagaEntityType.FullName, sagaEntityType, correlationProperty, associatedMessages, finders));
        }
예제 #32
0
 public EncryptionMutator(IEncryptionService encryptionService, Conventions conventions)
 {
     this.encryptionService = encryptionService;
     this.conventions       = conventions;
 }
예제 #33
0
        public IEnumerable <MigrationMetadata> FindMigrations()
        {
            IEnumerable <Type> matchedTypes = Assembly.GetExportedTypes().Where(t => Conventions.TypeIsMigration(t) &&
                                                                                (Conventions.TypeHasMatchingTags(t, TagsToMatch) || !Conventions.TypeHasTags(t)));

            if (!string.IsNullOrEmpty(Namespace))
            {
                Func <Type, bool> shouldInclude = t => t.Namespace == Namespace;
                if (LoadNestedNamespaces)
                {
                    string matchNested = Namespace + ".";
                    shouldInclude = t => t.Namespace == Namespace || t.Namespace.StartsWith(matchNested);
                }

                matchedTypes = matchedTypes.Where(shouldInclude);
            }

            foreach (Type type in matchedTypes)
            {
                yield return(Conventions.GetMetadataForMigration(type));
            }
        }
        public Task <T[]> LoadAsync <T>(params ValueType[] ids)
        {
            var documentKeys = ids.Select(id => Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(T), false));

            return(LoadAsyncInternal <T>(documentKeys.ToArray()));
        }
예제 #35
0
 protected override string GenerateKey(object entity)
 {
     return(Conventions.GenerateDocumentKey(dbName, DatabaseCommands, entity));
 }
        /// <summary>
        /// Stores the specified entity in the session. The entity will be saved when SaveChanges is called.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Store(object entity)
        {
            if (null == entity)
            {
                throw new ArgumentNullException("entity");
            }

            string id = null;

            if (entity is IDynamicMetaObjectProvider)
            {
                if (TryGetIdFromDynamic(entity, out id) == false)
                {
                    id = Conventions.DocumentKeyGenerator(entity);

                    if (id != null)
                    {
                        // Store it back into the Id field so the client has access to to it
                        ((dynamic)entity).Id = id;
                    }
                }
            }
            else
            {
                id = GetOrGenerateDocumentKey(entity);

                TrySetIdentity(entity, id);
            }

            // we make the check here even if we just generated the key
            // users can override the key generation behavior, and we need
            // to detect if they generate duplicates.
            if (id != null &&
                id.EndsWith("/") == false &&              // not a prefix id
                entitiesByKey.ContainsKey(id))
            {
                if (ReferenceEquals(entitiesByKey[id], entity))
                {
                    return;                     // calling Store twice on the same reference is a no-op
                }
                throw new NonUniqueObjectException("Attempted to associated a different object with id '" + id + "'.");
            }

            var tag      = documentStore.Conventions.GetTypeTagName(entity.GetType());
            var metadata = new RavenJObject();

            if (tag != null)
            {
                metadata.Add(Constants.RavenEntityName, tag);
            }
            entitiesAndMetadata.Add(entity, new DocumentMetadata
            {
                Key              = id,
                Metadata         = metadata,
                OriginalMetadata = new RavenJObject(),
                ETag             = UseOptimisticConcurrency ? (Guid?)Guid.Empty : null,
                OriginalValue    = new RavenJObject()
            });
            if (id != null)
            {
                entitiesByKey[id] = entity;
            }
        }
예제 #37
0
        public Task <T[]> LoadAsync <T>(IEnumerable <ValueType> ids, CancellationToken token = default(CancellationToken))
        {
            var documentKeys = ids.Select(id => Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(T), false));

            return(LoadAsyncInternal <T>(documentKeys.ToArray(), token));
        }
예제 #38
0
 protected override Task <string> GenerateKeyAsync(object entity)
 {
     return(Conventions.GenerateDocumentKeyAsync(AsyncDatabaseCommands, entity));
 }
예제 #39
0
        Lazy <T[]> ILazySessionOperations.Load <T>(IEnumerable <ValueType> ids, Action <T[]> onEval)
        {
            var documentKeys = ids.Select(id => Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(T), false));

            return(LazyLoadInternal(documentKeys.ToArray(), new KeyValuePair <string, Type> [0], onEval));
        }
예제 #40
0
        /// <summary>
        /// Loads the specified entities with the specified id after applying
        /// conventions on the provided id to get the real document id.
        /// </summary>
        /// <remarks>
        /// This method allows you to call:
        /// Load{Post}(1)
        /// And that call will internally be translated to
        /// Load{Post}("posts/1");
        ///
        /// Or whatever your conventions specify.
        /// </remarks>
        Lazy <TResult> ILazySessionOperations.Load <TResult>(ValueType id, Action <TResult> onEval)
        {
            var documentKey = Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(TResult), false);

            return(Lazily.Load <TResult>(documentKey));
        }
예제 #41
0
        /// <summary>
        /// Loads the specified entities with the specified id after applying
        /// conventions on the provided id to get the real document id.
        /// </summary>
        /// <remarks>
        /// This method allows you to call:
        /// Load{Post}(new List&lt;int&gt;(){1,2,3})
        /// And that call will internally be translated to
        /// Load{Post}("posts/1","posts/2","posts/3");
        ///
        /// Or whatever your conventions specify.
        /// </remarks>
        public T[] Load <T>(IEnumerable <ValueType> ids)
        {
            var documentKeys = ids.Select(id => Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(T), false));

            return(Load <T>(documentKeys));
        }
예제 #42
0
        static List <Type> GetMessageTypesHandledByThisEndpoint(MessageHandlerRegistry handlerRegistry, Conventions conventions, SubscribeSettings settings)
        {
            var messageTypesHandled = handlerRegistry.GetMessageTypes()                                                                                                                 //get all potential messages
                                      .Where(t => !conventions.IsInSystemConventionList(t))                                                                                             //never auto-subscribe system messages
                                      .Where(t => !conventions.IsCommandType(t))                                                                                                        //commands should never be subscribed to
                                      .Where(conventions.IsEventType)                                                                                                                   //only events unless the user asked for all messages
                                      .Where(t => settings.AutoSubscribeSagas || handlerRegistry.GetHandlersFor(t).Any(handler => !typeof(Saga).IsAssignableFrom(handler.HandlerType))) //get messages with other handlers than sagas if needed
                                      .ToList();

            return(messageTypesHandled);
        }
예제 #43
0
        public override void PreInitialize()
        {
            IocManager.Register <IShaNHibernateModuleConfiguration, ShaNHibernateModuleConfiguration>();
            Configuration.ReplaceService <IUnitOfWorkFilterExecuter, NhUnitOfWorkFilterExecuter>(DependencyLifeStyle.Transient);
            IocManager.IocContainer.Register(Component.For <IInterceptor>().ImplementedBy <SheshaNHibernateInterceptor>().LifestyleTransient());

            Configuration.Modules.AbpAspNetCore().CreateControllersForAppServices(
                this.GetType().Assembly,
                moduleName: "Shesha",
                useConventionalHttpVerbs: true);

            if (!SkipDbContextRegistration)
            {
                _nhConfig = Configuration.Modules.ShaNHibernate().NhConfiguration
                            .DataBaseIntegration(db =>
                {
                    db.ConnectionString = !string.IsNullOrWhiteSpace(ConnectionString)
                            ? ConnectionString
                            : NHibernateUtilities.ConnectionString;

                    db.Dialect <MsSql2012Dialect>();
                    db.Driver <Sql2008ClientDriver>();
                    db.Timeout = 150;

                    /*
                     * db.Timeout = string.IsNullOrEmpty(ConfigurationManager.AppSettings["SqlTimeoutInSeconds"])
                     *  ? (byte)150
                     *  : (byte)int.Parse(ConfigurationManager.AppSettings["SqlTimeoutInSeconds"]);
                     */

                    db.LogFormattedSql = true;
                })
                            .SetProperty("hbm2ddl.keywords", "auto-quote")
                            .CurrentSessionContext <UnitOfWorkSessionContext>();

                // register filters
                _nhConfig.AddFilterDefinition(SoftDeleteFilter.GetDefinition());
                _nhConfig.AddFilterDefinition(MayHaveTenantFilter.GetDefinition());
                _nhConfig.AddFilterDefinition(MustHaveTenantFilter.GetDefinition());

                var conventions       = new Conventions();
                var mappingAssemblies = new Dictionary <Assembly, string>
                {
                    { typeof(UserToken).Assembly, "Abp" },
                    { typeof(UserLogin).Assembly, "Abp" }
                };
                foreach (var item in mappingAssemblies)
                {
                    conventions.AddAssembly(item.Key, item.Value);
                }

                var assembliesWithEntities = _assembleFinder.GetAllAssemblies()
                                             .Distinct(new AssemblyFullNameComparer())
                                             .Where(a => !a.IsDynamic &&
                                                    a.GetTypes().Any(t => MappingHelper.IsEntity(t))
                                                    )
                                             .ToList();
                foreach (var assembly in assembliesWithEntities)
                {
                    if (!conventions.AssemblyAdded(assembly))
                    {
                        conventions.AddAssembly(assembly, assembly.GetCustomAttribute <TablePrefixAttribute>()?.Prefix);
                    }
                }

                conventions.Compile(_nhConfig);
            }
        }
예제 #44
0
        public Task <T> LoadAsync <T>(ValueType id, CancellationToken token = default(CancellationToken))
        {
            var documentKey = Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(T), false);

            return(LoadAsync <T>(documentKey, token));
        }
예제 #45
0
 protected void AddMap <TSource>(Expression <Func <IEnumerable <TSource>, IEnumerable> > expression)
 {
     maps.Add(() =>
     {
         string querySource = typeof(TSource) == typeof(object) ? "docs" : "docs." + Conventions.GetTypeTagName(typeof(TSource));
         return(IndexDefinitionHelper.PruneToFailureLinqQueryAsStringToWorkableCode <TSource, TReduceResult>(expression, Conventions, querySource, translateIdentityProperty: true));
     });
 }
예제 #46
0
 protected override Task <string> GenerateIdAsync(object entity)
 {
     return(Conventions.GenerateDocumentIdAsync(DatabaseName, entity));
 }
예제 #47
0
        static void ApplyScannedFinders(SagaMapper mapper, Type sagaEntityType, IEnumerable <Type> availableTypes, Conventions conventions)
        {
            var actualFinders = availableTypes.Where(t => typeof(IFinder).IsAssignableFrom(t) && t.IsClass)
                                .ToList();

            foreach (var finderType in actualFinders)
            {
                foreach (var interfaceType in finderType.GetInterfaces())
                {
                    var args = interfaceType.GetGenericArguments();
                    //since we don't want to process the IFinder type
                    if (args.Length != 2)
                    {
                        continue;
                    }

                    var entityType = args[0];
                    if (entityType != sagaEntityType)
                    {
                        continue;
                    }

                    var messageType = args[1];
                    if (!conventions.IsMessageType(messageType))
                    {
                        var error = $"A custom IFindSagas must target a valid message type as defined by the message conventions. Change '{messageType.FullName}' to a valid message type or add it to the message conventions. Finder name '{finderType.FullName}'.";
                        throw new Exception(error);
                    }

                    var existingMapping = mapper.Mappings.SingleOrDefault(m => m.MessageType == messageType);
                    if (existingMapping != null)
                    {
                        var bothMappingAndFinder = $"A custom IFindSagas and an existing mapping where found for message '{messageType.FullName}'. Either remove the message mapping or remove the finder. Finder name '{finderType.FullName}'.";
                        throw new Exception(bothMappingAndFinder);
                    }
                    mapper.ConfigureCustomFinder(finderType, messageType);
                }
            }
        }
예제 #48
0
        Lazy <T[]> ILazySessionOperations.Load <T>(IEnumerable <ValueType> ids)
        {
            var documentKeys = ids.Select(id => Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(T), false));

            return(Lazily.Load <T>(documentKeys, null));
        }
예제 #49
0
 static string GetEndpointNameForRun(EndpointBehavior endpointBehavior)
 {
     return(Conventions.EndpointNamingConvention(endpointBehavior.EndpointBuilderType));
 }
        public void Should_add_convention_for_predicate_to_type()
        {
            // Arrange
            var conventions = new Conventions();
            var expression = new ViolationHandlerExpression<IgnorePolicy>(new ViolationConfigurationExpression(conventions));

            // Act
            expression.IsHandledBy<DefaultPolicyViolationHandler>();

            // Assert
            Assert.That(conventions.Single(), Is.InstanceOf<PolicyTypeToPolicyViolationHandlerTypeConvention<IgnorePolicy, DefaultPolicyViolationHandler>>());
        }
예제 #51
0
        /// <summary>
        /// Loads the specified entities with the specified id after applying
        /// conventions on the provided id to get the real document id.
        /// </summary>
        /// <remarks>
        /// This method allows you to call:
        /// Load{Post}(1)
        /// And that call will internally be translated to
        /// Load{Post}("posts/1");
        ///
        /// Or whatever your conventions specify.
        /// </remarks>
        public Task <T> LoadAsync <T>(ValueType id)
        {
            var documentKey = Conventions.FindFullDocumentKeyFromNonStringIdentifier(id, typeof(T), false);

            return(LoadAsync <T>(documentKey));
        }
예제 #52
0
        public void SetUp()
        {
            var conventions = new Conventions(new TypeNameSerializer())
            {
                ConsumerTagConvention = () => consumerTag
            };

            consumerErrorStrategy = MockRepository.GenerateStub<IConsumerErrorStrategy>();
            consumerErrorStrategy.Stub(x => x.HandleConsumerError(null, null))
                .IgnoreArguments()
                .WhenCalled(i =>
                {
                    basicDeliverEventArgs = (ConsumerExecutionContext)i.Arguments[0];
                    raisedException = (Exception) i.Arguments[1];
                }).Return(AckStrategies.Ack);

            mockBuilder = new MockBuilder(x => x
                .Register<IConventions>(_ => conventions)
                .Register(_ => consumerErrorStrategy)
                //.Register<IEasyNetQLogger>(_ => new ConsoleLogger())
                );

            mockBuilder.Bus.Subscribe<MyMessage>(subscriptionId, message =>
            {
                throw originalException;
            });

            const string text = "Hello there, I am the text!";
            originalMessage = new MyMessage { Text = text };

            var body = new JsonSerializer(new TypeNameSerializer()).MessageToBytes(originalMessage);

            // deliver a message
            mockBuilder.Consumers[0].HandleBasicDeliver(
                consumerTag,
                deliveryTag,
                false, // redelivered
                typeName,
                "#",
                new BasicProperties
                {
                    Type = typeName,
                    CorrelationId = correlationId
                },
                body);

            // wait for the subscription thread to handle the message ...
            var autoResetEvent = new AutoResetEvent(false);
            mockBuilder.EventBus.Subscribe<AckEvent>(x => autoResetEvent.Set());
            autoResetEvent.WaitOne(1000);
        }
예제 #53
0
 protected override void PrepareForLoad()
 {
     Conventions.AddRange(new MugenConvetion[] { new ServiceConvention(Injector) });
 }