Inheritance: IDisposable
Exemple #1
0
		public void CanGetFullUrlWithSlashOnTheEnd()
		{
			using (var store = NewDocumentStore())
			{
				store.Configuration.Port = 8079;
				using (var server = new HttpServer(store.Configuration, store.DocumentDatabase))
				{
					server.StartListening();
					using (var documentStore = new DocumentStore
					{
						Url = "http://localhost:8079/"
					}.Initialize())
					{

						var session = documentStore.OpenSession();

						var entity = new LinqIndexesFromClient.User();
						session.Store(entity);

						Assert.Equal("http://localhost:8079/docs/users/1",
						             session.Advanced.GetDocumentUrl(entity));
					}
				}
			}
		}
		public static void Init()
		{
			if (database != null)
				return;

			lock (locker)
			{
				if (database != null)
					return;

				try
				{
					var ravenConfiguration = new RavenConfiguration();
					HttpEndpointRegistration.RegisterHttpEndpointTarget();
					database = new DocumentDatabase(ravenConfiguration);
					database.SpinBackgroundWorkers();
					server = new HttpServer(ravenConfiguration, database);
					server.Init();
				}
				catch
				{
					if (database != null)
					{
						database.Dispose();
						database = null;
					}
					if (server != null)
					{
						server.Dispose();
						server = null;
					}
					throw;
				}
			}
		}
		public void Initialize(Func<DocumentDatabase> databaseGetter, Func<InMemoryRavenConfiguration> settingsGetter, Func<string> tenantIdGetter, HttpServer theServer)
		{
			server = theServer;
			database = databaseGetter;
			settings = settingsGetter;
			tenantId = tenantIdGetter;
		}
        public static void Init()
        {
            if (database != null)
                return;

            lock (locker)
            {
                if (database != null)
                    return;

                try
                {
                    var ravenConfiguration = new RavenConfiguration();
                    if (RoleEnvironment.IsAvailable)
                    {
                        ravenConfiguration.RunInMemory = true;
                        // Mount Cloud drive and set it as Data Directory
                        //var currentConfiguredRavenDataDir = ConfigurationManager.AppSettings["Raven/DataDir"] ?? string.Empty;
                        //string azureDrive = @"D:\"; // Environment.GetEnvironmentVariable(RavenDriveConfiguration.AzureDriveEnvironmentVariableName, EnvironmentVariableTarget.Machine);
                        //if (string.IsNullOrWhiteSpace(azureDrive))
                        //{
                        //    throw new ArgumentException("RavenDb drive environment variable is not yet set by worker role. Please, retry in a couple of seconds");
                        //}

                        //string azurePath = Path.Combine(azureDrive,
                        //    currentConfiguredRavenDataDir.StartsWith(@"~\")
                        //        ? currentConfiguredRavenDataDir.Substring(2)
                        //        : "Data");
                        //ravenConfiguration.DataDirectory = azurePath;

                        // Read port number specified for this Raven instance and set it in configuration
                        var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Raven"];
                        ravenConfiguration.Port = endpoint.IPEndpoint.Port;

                        // When mounting drives in emulator only Munin storage is supported, since drive is not actually present and low level access to it failes (Esent mode)
                    }
                    HttpEndpointRegistration.RegisterHttpEndpointTarget();
                    database = new DocumentDatabase(ravenConfiguration);
                    database.SpinBackgroundWorkers();
                    server = new HttpServer(ravenConfiguration, database);
                    server.Init();
                }
                catch
                {
                    if (database != null)
                    {
                        database.Dispose();
                        database = null;
                    }
                    if (server != null)
                    {
                        server.Dispose();
                        server = null;
                    }
                    throw;
                }

                HostingEnvironment.RegisterObject(new ReleaseRavenDBWhenAppDomainIsTornDown());
            }
        }
		static ForwardToRavenRespondersFactory()
		{
			lock (locker)
			{
				if (database != null)
					return;
				

				database = new DocumentDatabase(ravenConfiguration);
				database.SpinBackgroundWorkers();
				server = new HttpServer(ravenConfiguration, database);
			}
		}
		public static void Shutdown()
		{
			if (database == null)
				return;
			lock (locker)
			{
				if (database == null)
					return;

				server.Dispose();
				database.Dispose();

				server = null;
				database = null;
			}
		}
		public static void Init()
		{
			if (database != null)
				return;
			lock (locker)
			{
				if (database != null)
					return;

				var ravenConfiguration = new RavenConfiguration();
				HttpServer.RegisterHttpEndpointTarget();
				database = new DocumentDatabase(ravenConfiguration);
				database.SpinBackgroundWorkers();
				server = new HttpServer(ravenConfiguration, database);
			}
		}
        public static void Init()
        {
            if (database != null)
                return;

            lock (locker)
            {
                if (database != null)
                    return;

                log.Info("Setting up RavenDB Http Integration to the ASP.Net Pipeline");
                try
                {
                    var ravenConfiguration = new RavenConfiguration();
                    HttpEndpointRegistration.RegisterHttpEndpointTarget();
                    database = new DocumentDatabase(ravenConfiguration);
                    database.SpinBackgroundWorkers();
                    server = new HttpServer(ravenConfiguration, database);
                    server.Init();
                }
                catch
                {
                    if (database != null)
                    {
                        database.Dispose();
                        database = null;
                    }
                    if (server != null)
                    {
                        server.Dispose();
                        server = null;
                    }
                    throw;
                }

                shutdownDetector = new ShutdownDetector(log);
                shutdownDetector.Initialize();

                shutdownDetector.Token.Register(OnShutdown);
            }
        }
Exemple #9
0
        public static void WaitForUserToContinueTheTest(EmbeddableDocumentStore documentStore)
        {
            if (!Debugger.IsAttached)
                return;

            documentStore.DatabaseCommands.Put("Pls Delete Me", null,
                                               RavenJObject.FromObject(new {StackTrace = new StackTrace(true)}),
                                               new RavenJObject());

            documentStore.Configuration.AnonymousUserAccessMode = AnonymousUserAccessMode.All;
            using (var server = new HttpServer(documentStore.Configuration, documentStore.DocumentDatabase))
            {
                server.StartListening();
                Process.Start(documentStore.Configuration.ServerUrl); // start the server

                do
                {
                    Thread.Sleep(100);
                } while (documentStore.DatabaseCommands.Get("Pls Delete Me") != null && (Debugger.IsAttached));
            }
        }
		public static void Init()
		{
			if (database != null)
				return;

			lock (locker)
			{
				if (database != null)
					return;

				log.Info("Setting up RavenDB Http Integration to the ASP.Net Pipeline");
				try
				{
					var ravenConfiguration = new RavenConfiguration();
					HttpEndpointRegistration.RegisterHttpEndpointTarget();
					database = new DocumentDatabase(ravenConfiguration);
					database.SpinBackgroundWorkers();
					server = new HttpServer(ravenConfiguration, database);
					server.Init();
				}
				catch
				{
					if (database != null)
					{
						database.Dispose();
						database = null;
					}
					if (server != null)
					{
						server.Dispose();
						server = null;
					}
					throw;
				}

				HostingEnvironment.RegisterObject(new ReleaseRavenDBWhenAppDomainIsTornDown());
			}
		}
        private void StartRaven()
        {
            try
            {
                Trace.TraceInformation("RavenDb: Starting...");

                AnonymousUserAccessMode anonymousUserAccessMode;
                if (!Enum.TryParse(RoleEnvironment.GetConfigurationSettingValue("AnonymousUserAccessMode"), true, out anonymousUserAccessMode))
                    anonymousUserAccessMode = AnonymousUserAccessMode.Get;
                Trace.TraceInformation("Raven Configuration AnonymousUserAccessMode: {0}", anonymousUserAccessMode);

                var httpCompression = Boolean.Parse(RoleEnvironment.GetConfigurationSettingValue("HttpCompression"));
                Trace.TraceInformation("Raven Configuration HttpCompression: {0}", httpCompression);

                var defaultStorageTypeName = RoleEnvironment.GetConfigurationSettingValue("DefaultStorageTypeName");
                Trace.TraceInformation("Raven Configuration DefaultStorageTypeName: {0}", defaultStorageTypeName);

                var port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Raven"].IPEndpoint.Port;
                Trace.TraceInformation("Raven Configuration Port: {0}", port);

                Trace.TraceInformation("RavenDb: Ensure Can ListenTo When In Non Admin Context...");
                NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(port);

                var config = new RavenConfiguration
                {
                    DataDirectory = _dataDrive.LocalPath.EndsWith("\\")
                                        ? _dataDrive.LocalPath + "Data\\"
                                        : _dataDrive.LocalPath + "\\Data\\",
                    AnonymousUserAccessMode = anonymousUserAccessMode,
                    HttpCompression = httpCompression,
                    DefaultStorageTypeName = defaultStorageTypeName,
                    Port = port,
                    PluginsDirectory = "Plugins"
                };
                _database = new DocumentDatabase(config);

                Trace.TraceInformation("RavenDb: Spin Background Workers...");
                _database.SpinBackgroundWorkers();

                _server = new HttpServer(config, _database);
                try
                {
                    Trace.TraceInformation("Http Server: Initializing ...");
                    _server.Init();
                    Trace.TraceInformation("Http Server: Start Listening ...");
                    _server.StartListening();
                }
                catch (Exception)
                {
                    _server.Dispose();
                    _server = null;
                    throw;
                }

                Trace.TraceInformation("RavenDb: Started.");
            }
            catch (Exception)
            {
                if (_database != null)
                {
                    _database.Dispose();
                    _database = null;
                }
                throw;
            }
        }
        public static void Shutdown()
        {
            lock (locker)
            {
                if (server != null)
                    server.Dispose();

                if (database != null)
                    database.Dispose();

                server = null;
                database = null;
            }
        }
Exemple #13
0
        private void StartTheServer()
        {
            try
            {
                var ravenConfiguration = new RavenConfiguration
                {
                    AnonymousUserAccessMode = AnonymousUserAccessMode.All,
                    Port = _endPoint.Port,
                    ListenerProtocol = ListenerProtocol.Tcp,
                    DataDirectory = _ravenDrivePath
                };

                _documentDatabase = new DocumentDatabase(ravenConfiguration);
                _documentDatabase.SpinBackgroundWorkers();

                _ravenHttpServer = new HttpServer(ravenConfiguration, _documentDatabase);
                _ravenHttpServer.Start();
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
            }
        }
 static ForwardToRavenRespondersFactory()
 {
     database = new DocumentDatabase(ravenConfiguration);
     server = new HttpServer(ravenConfiguration, database);
 }
		public static void Shutdown()
		{
			lock (locker)
			{
				log.Info("Disposing of RavenDB Http Integration to the ASP.Net Pipeline");
				if (server != null)
					server.Dispose();

				if (database != null)
					database.Dispose();

				server = null;
				database = null;
			}
		}
		static ForwardToRavenRespondersFactory()
		{
			database = new DocumentDatabase(ravenConfiguration);
			database.SpinBackgroundWorkers();
			server = new HttpServer(ravenConfiguration, database);
		}
		/// <summary>
		/// Initialize the document store access method to RavenDB
		/// </summary>
		protected override void InitializeInternal()
		{
			if (configuration != null && Url == null)
			{
				configuration.PostInit();
				if(configuration.RunInMemory || configuration.RunInUnreliableYetFastModeThatIsNotSuitableForProduction)
				{
					ResourceManagerId = Guid.NewGuid(); // avoid conflicts
				}
				DocumentDatabase = new DocumentDatabase(configuration);
				DocumentDatabase.SpinBackgroundWorkers();
				if (UseEmbeddedHttpServer)
				{
					httpServer = new HttpServer(configuration, DocumentDatabase);
					httpServer.StartListening();
				}
				databaseCommandsGenerator = () => new EmbeddedDatabaseCommands(DocumentDatabase, Conventions, currentSessionId);
			}
			else
			{
				base.InitializeInternal();
			}
		}
Exemple #18
0
 public void Initialize(Func <DocumentDatabase> databaseGetter, Func <InMemoryRavenConfiguration> settingsGetter, Func <string> tenantIdGetter, HttpServer theServer)
 {
     server   = theServer;
     database = databaseGetter;
     settings = settingsGetter;
     tenantId = tenantIdGetter;
 }
		public void CanProjectFromIndex()
		{
			using (var documentStore = NewDocumentStore())
			using (var httpServer = new HttpServer(documentStore.Configuration, documentStore.DocumentDatabase))
			{
				httpServer.StartListening();
				documentStore.DatabaseCommands.PutIndex("ImagesByTag",
														new IndexDefinitionBuilder<Image, ImageByTagSearchModel>
														{
															Map = images => from image in images
																		from tag in image.Tags
																		select new 
																		{
																			TagName = tag,
																			Images = new[] { image.Id }
																		},
															Reduce = results => from result in results
																				group result by result.TagName
																				into g
																				select new
																				{
																					TagName = g.Key,
																					Images = g.SelectMany(x => x.Images).Distinct()
																				},
															Stores =

																{
																	{x => x.TagName, FieldStorage.Yes},
																	{x => x.Images, FieldStorage.Yes}
																}
															,
															Indexes =

																{
																	{x => x.TagName, FieldIndexing.NotAnalyzed},
																	{x => x.Images, FieldIndexing.No}
																}
														},true);

				using(var s = documentStore.OpenSession())
				{
					s.Store(new Image
					{
						Id = "images/123",
						Tags = new[]
						{
							"sport", "footbool"
						}
					});

					s.Store(new Image
					{
						Id = "images/234",
						Tags = new[]
						{
							"footbool", "live"
						}
					});

					s.SaveChanges();
				}

				using (var s = documentStore.OpenSession())
				{
					var imageByTagSearchModels = s.Advanced.LuceneQuery<ImageByTagSearchModel>("ImagesByTag")
						.OrderBy("TagName")
						.WaitForNonStaleResults()
						.ToList();

					Assert.Equal("footbool", imageByTagSearchModels[0].TagName);
					Assert.Equal(2, imageByTagSearchModels[0].Images.Length);

					Assert.Equal("live", imageByTagSearchModels[1].TagName);
					Assert.Equal(1, imageByTagSearchModels[1].Images.Length);

					Assert.Equal("sport", imageByTagSearchModels[2].TagName);
					Assert.Equal(1, imageByTagSearchModels[2].Images.Length);
				}
			}
		}
Exemple #20
0
			public void Execute(HttpServer server)
			{
				var message = new MailMessage("*****@*****.**", "*****@*****.**")
					{
						Subject = "RavenDB server started.",
						Body = "Start at: " + DateTime.Now.ToShortDateString()
					};

				using (var smtpClient = new SmtpClient("mail.myhost.com"))
				{
					smtpClient.Send(message);
				}
			}
		public ForwardToRavenResponders(HttpServer server)
		{
			this.server = server;
		}
		/// <summary>
		/// Initialize the document store access method to RavenDB
		/// </summary>
		protected override void InitializeInternal()
		{
			if (string.IsNullOrEmpty(Url) == false && string.IsNullOrEmpty(DataDirectory) == false)
				throw new InvalidOperationException("You cannot specify both Url and DataDirectory at the same time. Url implies running in client/server mode against the remote server. DataDirectory implies running in embedded mode. Those two options are incompatible");

			if (string.IsNullOrEmpty(DataDirectory) == false && string.IsNullOrEmpty(DefaultDatabase) == false)
				throw new InvalidOperationException("You cannot specify DefaultDatabase value when the DataDirectory has been set, running in Embedded mode, the Default Database is not a valid option.");

			if (configuration != null && Url == null)
			{
				configuration.PostInit();
				if (configuration.RunInMemory || configuration.RunInUnreliableYetFastModeThatIsNotSuitableForProduction)
				{
					ResourceManagerId = Guid.NewGuid(); // avoid conflicts
				}
				configuration.SetSystemDatabase();
				DocumentDatabase = new DocumentDatabase(configuration);
				DocumentDatabase.SpinBackgroundWorkers();
				if (UseEmbeddedHttpServer)
				{
					SetStudioConfigToAllowSingleDb();
					httpServer = new HttpServer(configuration, DocumentDatabase);
					httpServer.StartListening();
				}
				else // we need to setup our own idle timer
				{
					idleTimer = new Timer(state =>
					{
						try
						{
							DocumentDatabase.RunIdleOperations();
						}
						catch (Exception e)
						{
							log.WarnException("Error during database idle operations", e);
						}
					},null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
				}
				databaseCommandsGenerator = () => new EmbeddedDatabaseCommands(DocumentDatabase, Conventions, currentSessionId);
				asyncDatabaseCommandsGenerator = () => new EmbeddedAsyncServerClient(DatabaseCommands);
			}
			else
			{
				base.InitializeInternal();
			}
		}
        public void TemporalVersioning_OneEdit_OverHttp()
        {
            using (var embeddedDocumentStore = this.GetTemporalDocumentStore())
            {
                embeddedDocumentStore.Configuration.AnonymousUserAccessMode = AnonymousUserAccessMode.All;
                using (var server = new HttpServer(embeddedDocumentStore.Configuration, embeddedDocumentStore.DocumentDatabase))
                {
                    server.StartListening();

                    var documentStore = new DocumentStore { Url = "http://localhost:8080" };
                    documentStore.Initialize();
                    documentStore.InitializeTemporalVersioning();

                    const string id = "employees/1";
                    var effectiveDate1 = new DateTimeOffset(new DateTime(2012, 1, 1));
                    using (var session = documentStore.OpenSession())
                    {
                        var employee = new Employee { Id = id, Name = "John", PayRate = 10 };
                        session.Effective(effectiveDate1).Store(employee);

                        session.SaveChanges();
                    }

                    // Make some changes
                    var effectiveDate2 = new DateTimeOffset(new DateTime(2012, 2, 1));
                    using (var session = documentStore.OpenSession())
                    {
                        var employee = session.Effective(effectiveDate2).Load<Employee>(id);
                        employee.PayRate = 20;

                        session.SaveChanges();
                    }

                    // Check the results
                    using (var session = documentStore.OpenSession())
                    {
                        var current = session.Load<Employee>(id);
                        Assert.Equal(id, current.Id);
                        Assert.Equal(20, current.PayRate);

                        var currentTemporal = session.Advanced.GetTemporalMetadataFor(current);
                        Assert.Equal(TemporalStatus.Current, currentTemporal.Status);
                        Assert.Equal(2, currentTemporal.RevisionNumber);

                        var revisions = session.Advanced.GetTemporalRevisionsFor<Employee>(id, 0, 10);
                        Assert.Equal(2, revisions.Length);

                        Assert.Equal(id, revisions[0].Id);
                        Assert.Equal(id, revisions[1].Id);
                        Assert.Equal(10, revisions[0].PayRate);
                        Assert.Equal(20, revisions[1].PayRate);

                        var version1Temporal = session.Advanced.GetTemporalMetadataFor(revisions[0]);
                        Assert.Equal(TemporalStatus.Revision, version1Temporal.Status);
                        Assert.False(version1Temporal.Deleted);
                        Assert.Equal(effectiveDate1, version1Temporal.EffectiveStart);
                        Assert.Equal(effectiveDate2, version1Temporal.EffectiveUntil);
                        Assert.Equal(1, version1Temporal.RevisionNumber);

                        var version2Temporal = session.Advanced.GetTemporalMetadataFor(revisions[1]);
                        Assert.Equal(TemporalStatus.Revision, version2Temporal.Status);
                        Assert.False(version2Temporal.Deleted);
                        Assert.Equal(effectiveDate2, version2Temporal.EffectiveStart);
                        Assert.Equal(DateTimeOffset.MaxValue, version2Temporal.EffectiveUntil);
                        Assert.Equal(2, version2Temporal.RevisionNumber);
                    }
                }
            }
        }
Exemple #24
0
        public IDocumentSession GetSession()
        {
            lock (isStoreSet)
            {
                if (!(bool)isStoreSet)
                {
                    RavenConfiguration ravenConfiguration = null;

                    bool webUIEnabled = false;
                    int webUIPort = 0;

                    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    var serviceConfigurationSection = config.GetSection("ServiceConfigurationSection") as ServiceConfigurationSection;
                    if (serviceConfigurationSection != null)
                    {
                        ravenConfiguration = serviceConfigurationSection.ravendb;
                        if (ravenConfiguration != null)
                        {
                            webUIEnabled = ravenConfiguration.WebUIEnabled;
                            webUIPort = ravenConfiguration.WebUIPort;

                            if (webUIEnabled)
                            {
                                if (webUIPort < 0 || webUIPort > 65535)
                                {
                                    webUIEnabled = false;
                                }
                                else
                                {
                                    webUIEnabled = CheckPortIsAvailable(webUIPort);
                                }
                            }
                        }
                    }

                    documentStore = new EmbeddableDocumentStore();
                    documentStore.Configuration.DataDirectory = "Data\\RavenDB";
                    documentStore.Configuration.DefaultStorageTypeName = typeof(Raven.Storage.Esent.TransactionalStorage).AssemblyQualifiedName;
                    documentStore.Conventions.FindIdentityProperty = x => x.Name == "Oid";
                    documentStore.Conventions.MaxNumberOfRequestsPerSession = 1000;
                    documentStore.Initialize();
                    
                    IndexCreation.CreateIndexes(GetType().Assembly, documentStore);

                    if (webUIEnabled)
                    {
                        documentStore.Configuration.Port = webUIPort;
                        var httpServer = new HttpServer(documentStore.Configuration, documentStore.DocumentDatabase);
                        httpServer.Init();
                        httpServer.StartListening();
                    }

                    isStoreSet = true;
                }
            }

            return documentStore.OpenSession();
        }
		public ChangesCurrentDatabaseForwardingHandler(HttpServer server, CancellationToken token)
		{
			this.server = server;
		    this.token = token;
		}