Example #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));
					}
				}
			}
		}
Example #2
0
		public RavenDbServer(InMemoryRavenConfiguration settings)
		{
			database = new DocumentDatabase(settings);

			try
			{
				database.SpinBackgroundWorkers();
				server = new HttpServer(settings, database);
				server.StartListening();
			}
			catch (Exception)
			{
				database.Dispose();
				database = null;
				
				throw;
			}
		}
Example #3
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));
            }
        }
		/// <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();
			}
		}
		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);
				}
			}
		}
		/// <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();
			}
		}
        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 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);
                    }
                }
            }
        }
Example #9
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();
        }
Example #10
0
		public static void WaitForUserToContinueTheTest(EmbeddableDocumentStore documentStore, bool debug = true)
		{
			if (debug && Debugger.IsAttached == false)
				return;

			documentStore.SetStudioConfigToAllowSingleDb();

			documentStore.DatabaseCommands.Put("Pls Delete Me", null,

											   RavenJObject.FromObject(new { StackTrace = new StackTrace(true) }),
											   new RavenJObject());

			documentStore.Configuration.AnonymousUserAccessMode = AnonymousUserAccessMode.Admin;
			using (var server = new HttpServer(documentStore.Configuration, documentStore.DocumentDatabase))
			{
				server.StartListening();

				try
				{
					Process.Start(documentStore.Configuration.ServerUrl); // start the server
				}
				catch (Win32Exception e)
				{
					Console.WriteLine("Failed to open the browser. Please open it manually at {0}. {1}", documentStore.Configuration.ServerUrl, e);
				}

				do
				{
					Thread.Sleep(100);
				} while (documentStore.DatabaseCommands.Get("Pls Delete Me") != null && (debug == false || Debugger.IsAttached));
			}
		}