RegisterListener() public method

public RegisterListener ( IDocumentDeleteListener deleteListener ) : IDocumentStore
deleteListener IDocumentDeleteListener
return IDocumentStore
Esempio n. 1
0
        void InitializeDocumentStore()
        {
            _documentStore = _configuration.CreateDocumentStore();

            var keyGenerator = new SequentialKeyGenerator(_documentStore);
            _documentStore.Conventions.DocumentKeyGenerator = (a,b,c) => string.Format("{0}/{1}", CollectionName, keyGenerator.NextFor<IEvent>());
            //_documentStore.Conventions.IdentityTypeConvertors.Add(new ConceptTypeConverter<long>());
            //_documentStore.Conventions.IdentityTypeConvertors.Add(new ConceptTypeConverter<int>());
            //_documentStore.Conventions.IdentityTypeConvertors.Add(new ConceptTypeConverter<string>());
            //_documentStore.Conventions.IdentityTypeConvertors.Add(new ConceptTypeConverter<Guid>());
            //_documentStore.Conventions.IdentityTypeConvertors.Add(new ConceptTypeConverter<short>());

            _documentStore.Conventions.CustomizeJsonSerializer = s =>
            {
                s.Converters.Add(new MethodInfoConverter());
                s.Converters.Add(new EventSourceVersionConverter());
                s.Converters.Add(new ConceptConverter());
            };
            
           var originalFindTypeTagNam =  _documentStore.Conventions.FindTypeTagName;
           _documentStore.Conventions.FindTypeTagName = t =>
           {
               if (t.HasInterface<IEvent>() || t == typeof(IEvent)) return CollectionName;
               return originalFindTypeTagNam(t);
           };

            _documentStore.RegisterListener(new EventMetaDataListener(_eventMigrationHierarchyManager));
        }
Esempio n. 2
0
    static void Main()
    {
        Console.Title = "Samples.RavenDBCustomSagaFinder";
        using (new RavenHost())
        {
            BusConfiguration busConfiguration = new BusConfiguration();
            busConfiguration.EndpointName("Samples.RavenDBCustomSagaFinder");
            busConfiguration.UseSerialization<JsonSerializer>();
            busConfiguration.EnableInstallers();

            DocumentStore documentStore = new DocumentStore
            {
                Url = "http://localhost:32076",
                DefaultDatabase = "NServiceBus"
            };
            documentStore.RegisterListener(new UniqueConstraintsStoreListener());
            documentStore.Initialize();

            busConfiguration.UsePersistence<RavenDBPersistence>()
                .DoNotSetupDatabasePermissions() //Only required to simplify the sample setup
                .SetDefaultDocumentStore(documentStore);

            using (IBus bus = Bus.Create(busConfiguration).Start())
            {
                bus.SendLocal(new StartOrder
                {
                    OrderId = "123"
                });

                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
        }
    }
Esempio n. 3
0
    static async Task AsyncMain()
    {
        using (new RavenHost())
        {
            BusConfiguration busConfiguration = new BusConfiguration();
            busConfiguration.EndpointName("Samples.RavenDBCustomSagaFinder");
            busConfiguration.UseSerialization<JsonSerializer>();
            busConfiguration.EnableInstallers();
            busConfiguration.SendFailedMessagesTo("error");

            DocumentStore documentStore = new DocumentStore
            {
                Url = "http://localhost:32076",
                DefaultDatabase = "NServiceBus"
            };
            documentStore.RegisterListener(new UniqueConstraintsStoreListener());
            documentStore.Initialize();

            busConfiguration.UsePersistence<RavenDBPersistence>()
                .DoNotSetupDatabasePermissions() //Only required to simplify the sample setup
                .SetDefaultDocumentStore(documentStore);

            IEndpointInstance endpoint = await Endpoint.Start(busConfiguration);
            await endpoint.SendLocal(new StartOrder
            {
                OrderId = "123"
            });

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            await endpoint.Stop();
        }
    }
Esempio n. 4
0
		protected virtual void Initialize(RavenConnectionProvider connections, DocumentStore store)
		{
			store.Conventions.MaxNumberOfRequestsPerSession = 100;
			store.Conventions.FindIdentityProperty = pi => pi.Name == "ID";
			store.Conventions.JsonContractResolver = new ContentContractResolver();
			store.Conventions.FindTypeTagName = t => typeof(ContentItem).IsAssignableFrom(t) ? "ContentItem" : null;
			store.Conventions.SaveEnumsAsIntegers = true;
			store.Conventions.CustomizeJsonSerializer = (serializer) =>
			{
				serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
				serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
				serializer.ReferenceResolver = new ContentReferenceResolver(connections);
				serializer.Converters.Add(new DetailsJsonConverter());
				serializer.Converters.Add(new DetailCollectionsJsonConverter());
				serializer.TypeNameHandling = TypeNameHandling.All;
			};
			store.RegisterListener((IDocumentConversionListener)new Listener());
			store.RegisterListener((IDocumentDeleteListener)new Listener());
			store.RegisterListener((IDocumentQueryListener)new Listener());
			store.RegisterListener((IDocumentStoreListener)new Listener());
			store.Initialize();
		}
Esempio n. 5
0
        public IocRegistry()
        {
            Scan(scan =>
                    {
                        scan.TheCallingAssembly();
                        scan.WithDefaultConventions();
                    });

            //			For<IDependencyResolver>().Singleton().Use<StructureMapSignalrDependencyResolver>();
            //			For<IConnectionManager>().Singleton().Use(GlobalHost.ConnectionManager);

            For<IDocumentStore>()
                .Singleton()
                .Use(x =>
                        {
                            var store = new DocumentStore { ConnectionStringName = "Raven" };
                            store.RegisterListener(new DocumentStoreListener());
                            store.Initialize();

                            MvcMiniProfiler.RavenDb.Profiler.AttachTo(store);

                            return store;
                        })
                .Named("RavenDB Document Store");

            For<IDocumentSession>()
                .HttpContextScoped()
                .Use(x =>
                    {
                        var store = x.GetInstance<IDocumentStore>();
                        return store.OpenSession();
                    })
                .Named("RavenDb Session");

            For<IMetricTracker>()
                .Singleton()
                .Use(x =>
                     	{
                     		int port;
                     		int.TryParse(ConfigurationManager.AppSettings["Metrics:Port"], out port);
                     		return new MetricTracker(ConfigurationManager.AppSettings["Metrics:Host"], port);
                     	})
                .Named("Metric Tracker");

            For<ICacheClient>()
                .Singleton()
                .Use(x => new MemoryCacheClient());
        }
 internal IDocumentStore GetDocumentStore(string connectionName)
 {
     if (string.IsNullOrEmpty(connectionName))
     {
         throw new ArgumentNullException("connectionName");
     }
     var store = new DocumentStore();
     store.ConnectionStringName = connectionName;
     if (string.IsNullOrEmpty(store.DefaultDatabase))
     {
         store.DefaultDatabase = !string.IsNullOrEmpty(DatabaseName) ? DatabaseName : DefaultDatabaseName;
     }
     store.Initialize();
     store.RegisterListener(new CheckpointNumberIncrementListener(store));
     return store;
 }
            public MyApp()
            {
                var documentStore = new DocumentStore
                {
                    Url = "http://server"
                };

                documentStore.RegisterListener(new ContextualDocumentStoreListener<UserNameContext>());
                    // can be called after .Initialize(), doesn't matter
                documentStore.Initialize();

                using (new UserNameContext("Damian Hickey"))
                using (IDocumentSession session = documentStore.OpenSession())
                {
                    session.Store(new Doc());
                    session.SaveChanges();
                }
            }
Esempio n. 8
0
        public static DocumentStore GetDocStore(string ravenServerUrl, string defaultDatabase, string apiKey)
        {
            var ds = new DocumentStore
            {
                Url = ravenServerUrl,
                DefaultDatabase = defaultDatabase
            };
            if (string.IsNullOrEmpty(apiKey) == false)
            {
                ds.ApiKey = apiKey;
            }

            ds.Conventions.IdentityPartsSeparator = "-";
            ds.RegisterListener(new UniqueConstraintsStoreListener());
            ds.Conventions.SaveEnumsAsIntegers = true;

            ds.Initialize();
            return ds;
        }
Esempio n. 9
0
		public General()
		{
			using (var store = new DocumentStore())
			{
				#region register_listener
				store.RegisterListener(new SampleDocumentStoreListener());
				#endregion

				#region set_listeners
				store.SetListeners(new DocumentSessionListeners()
				{
					StoreListeners = new IDocumentStoreListener[]
					{
						new SampleDocumentStoreListener()
					},
					DeleteListeners = new IDocumentDeleteListener[]
					{
						new SampleDocumentDeleteListener()
					}
				});
				#endregion
			}
		} 
Esempio n. 10
0
		[InlineData("Name", null)] // exception on SaveChanges()
		public void Test_Remote(string name, string realm)
		{
			using(var ds = new DocumentStore
			               	{
			               		Url = "http://localhost:8079",
								Conventions =
									{
										FailoverBehavior = FailoverBehavior.FailImmediately
									}
			               	})
			{
				ds.RegisterListener(new UniqueConstraintsStoreListener());
				ds.Initialize();

				using (var raven = ds.OpenSession())
				{
					raven.Store(new App { Name = name, Realm = realm });
					raven.SaveChanges();
				}

				using (var raven = ds.OpenSession())
				{
					if (realm != null)
					{
						Assert.NotNull(raven.LoadByUniqueConstraint<App>(x => x.Realm, realm));
					}
				}

				using (var raven = ds.OpenSession())
				{
					if (name != null)
					{
						Assert.NotNull(raven.LoadByUniqueConstraint<App>(x => x.Name, name));
					}
				}
			}
		}
Esempio n. 11
0
        public void Saving_Document_With_Unique_Constraints_Throws_Object_Reference_Not_Set_Remote()
        {
            DocumentStore store = null;
            try
            {
                store = new DocumentStore
                    {
                        Url = "http://*****:*****@test.com",
                        FirstName = "User",
                        LastName = "Testing",
                        Password = "******",
                        Created = DateTimeOffset.Now,
                        LastModified = DateTimeOffset.Now
                    };
                    var check = session.CheckForUniqueConstraints(account);
                    if (check.ConstraintsAreFree())
                    {
                        session.Store(account);
                        session.SaveChanges();
                    }
                    Assert.True(account.Id != String.Empty);
                }
            }
            finally
            {
                if (store != null) { store.Dispose(); }
            }
        }
		public void Sample()
		{
			using (var store = new DocumentStore())
			{
				#region unique_constraints_1
				store.RegisterListener(new UniqueConstraintsStoreListener());
				#endregion

				using (var session = store.OpenSession())
				{
					#region unique_constraints_2
					User existingUser = session
						.LoadByUniqueConstraint<User>(x => x.Email, "*****@*****.**");
					#endregion
				}

				using (var session = store.OpenSession())
				{
					#region unique_constraints_3
					User user = new User { Name = "John", Email = "*****@*****.**" };
					UniqueConstraintCheckResult<User> checkResult = session.CheckForUniqueConstraints(user);

					// returns whether its constraints are available
					if (checkResult.ConstraintsAreFree())
					{
						session.Store(user);
					}
					else
					{
						User existingUser = checkResult.DocumentForProperty(x => x.Email);
					}
					#endregion
				}
			}

		}
Esempio n. 13
0
        internal DocumentStore CreateDocumentStore(Instance storeInstance, AccessMode accessMode)
        {
            var databaseName = storeInstance.Url.GetDatabaseName(throwIfNotFound: true);
            var store = new DocumentStore
            {
                Identifier = databaseName,
                DefaultDatabase = databaseName,
                Url = storeInstance.Url.ToString(),
                Conventions =
                {
                    FailoverBehavior = FailoverBehavior.AllowReadsFromSecondariesAndWritesToSecondaries
                }
            };

            if (accessMode == AccessMode.ReadOnly)
            {
                store.RegisterListener((IDocumentStoreListener)new ReadOnlyListener());
                store.RegisterListener((IDocumentDeleteListener)new ReadOnlyListener());
            }

            return store;
        }
Esempio n. 14
0
        private Container BuildContainer()
        {
            var documentStore = new DocumentStore
            {
                Url = "http://localhost:8080",
                DefaultDatabase = "Todo"
            };
            
            documentStore.Initialize();

            var container = new Container(cfg =>
            {
                cfg.Scan(scanner =>
                {
                    scanner.AssemblyContainingType<CreateTodoItem>();
                    scanner.AssemblyContainingType<IMediator>();
                    scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
                    scanner.AddAllTypesOf(typeof(IEventHandler<>));
                    scanner.AddAllTypesOf(typeof(IPreRequestHandler<>));
                    scanner.AddAllTypesOf(typeof(IPostRequestHandler<,>));
                    scanner.WithDefaultConventions();
                });
                cfg.For<IDocumentStore>()
                    .Use(documentStore).Singleton();

                cfg.For<IDocumentSession>()
                    .Use(ctx => ctx.GetInstance<IDocumentStore>()
                        .OpenSession());
                
                cfg.For<IManageUnitOfWork>()
                    .Use<RavenDbUnitOfWork>();

                //var handlerType = cfg.For(typeof(IRequestHandler<,>));                  
                //handlerType.DecorateAllWith(typeof(DomainEventDispatcherHandler<,>));

                cfg.For(typeof(IRequestHandler<,>))
                    .DecorateAllWith(typeof(MediatorPipeline<,>));

                var eventTracker = new EventTracker();

                cfg.For<IDocumentStoreListener>()
                    .Use(eventTracker);
                cfg.For<ITrackEvents>()
                    .Use(eventTracker);
                
                documentStore.RegisterListener(eventTracker);

                
            });

            return container;
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            using (var storeA = new DocumentStore
            {
                Url = "http://localhost:8080",
                DefaultDatabase = "DatabaseA"
            })
            using (var storeB = new DocumentStore
            {
                Url = "http://localhost:8080",
                DefaultDatabase = "DatabaseB",
            })
            {
                //storeB.RegisterListener(new LastModifiedConflictResolver());
                storeA.Initialize();
                storeB.Initialize();

                storeA.DatabaseCommands.GlobalAdmin.DeleteDatabase("DatabaseA", true);
                storeA.DatabaseCommands.GlobalAdmin.DeleteDatabase("DatabaseB", true);
                CreateDatabaseWithReplication("DatabaseA", storeA);
                CreateDatabaseWithReplication("DatabaseB", storeB);

                using (var sessionA = storeA.OpenSession())
                using (var sessionB = storeB.OpenSession())
                {
                    sessionA.Store(new User
                    {
                        Name = "John"
                    });

                    sessionB.Store(new User
                    {
                        Name = "Jane"
                    });

                    sessionA.SaveChanges();
                    sessionB.SaveChanges();
                }

                SetupReplication(storeA,"DatabaseA", "DatabaseB", "http://localhost:8080");
                SetupReplication(storeB, "DatabaseB", "DatabaseA", "http://localhost:8080");

                Console.WriteLine("Conflict created.");
                Console.ReadLine();

                try
                {
                    using (var session = storeB.OpenSession())
                    {
                        session.Load<dynamic>("users/1");
                    }
                }
                catch (ConflictException e)
                {
                    Console.WriteLine(e);
                }

                Console.ReadLine();

                storeB.RegisterListener(new LastModifiedConflictResolver());
                using (var session = storeB.OpenSession())
                {
                    var user = session.Load<dynamic>("users/1");
                    Console.WriteLine(user.Name);
                }
            }
        }
        /// <summary>
        ///     Configures the document store internal.
        /// </summary>
        /// <param name="documentStore">The document store.</param>
        private void ConfigureDocumentStoreInternal(DocumentStore documentStore)
        {
            documentStore.RegisterListener(new StoreListener(this.OnPagePublish, this.OnPageSave, this.OnPageUnPublish));
            documentStore.RegisterListener(new DeleteListener(this.OnDocumentDelete));

            IndexCreation.CreateIndexes(typeof (DefaultBrickPileBootstrapper).Assembly, documentStore);
        }