Dispose() public méthode

public Dispose ( ) : void
Résultat void
 static void Main(string[] args)
 {
     var input = "";
     do
     {
         var database = "";
         IDocumentStore ds;
         while (!Uri.IsWellFormedUriString(database, UriKind.Absolute))
         {
             Console.WriteLine("Please enter a valid absolute url for the database");
             database = Console.ReadLine();
         }
         Console.WriteLine("Enter the DB to test");
         var defaultdb = Console.ReadLine();
         RunDBTest(database, defaultdb);
         Console.WriteLine("Again? Y/N or B to Begin Stuffing the Bird");
         input = Console.ReadLine().ToLower();
         // pressing B will throw in 100,000 documents or run until an error is generated by Raven
         if (input == "b")
         {
             ds = new DocumentStore { Url = database, DefaultDatabase = defaultdb };
             ds.Initialize();
             for (int i = 0; i < 5000; i++)
                 BeginFill(database, defaultdb, i, ds);
             ds.Dispose();
         }
     } while (input == "y");
 }
Exemple #2
0
        public void CanShutdown()
        {
            DocumentStore docStore;
            using (var store = new EmbeddableDocumentStore { UseEmbeddedHttpServer = true, RunInMemory = true })
            {
                store.Configuration.Port = 8079;

                store.Initialize();

                docStore = new DocumentStore
                {
                    Url = "http://127.0.0.1:8079/",
                    DefaultDatabase = "test"
                };
                docStore.Initialize();
                new RavenDocumentsByEntityName().Execute(docStore);

                docStore.DatabaseCommands.EnsureDatabaseExists("database");

                using (docStore.OpenSession("database"))
                {
                }
            }
            docStore.Dispose();
        }
        public override bool InitBackup()
        {
            parameters.ServerUrl = parameters.ServerUrl.TrimEnd('/');
            try //precaution - to show error properly just in case
            {
                var serverUri = new Uri(parameters.ServerUrl);
                if ((String.IsNullOrWhiteSpace(serverUri.PathAndQuery) || serverUri.PathAndQuery.Equals("/")) &&
                    String.IsNullOrWhiteSpace(parameters.Database))
                    parameters.Database = Constants.SystemDatabase;

                var serverHostname = serverUri.Scheme + Uri.SchemeDelimiter + serverUri.Host + ":" + serverUri.Port;

                store = new DocumentStore { Url = serverHostname, DefaultDatabase = parameters.Database, ApiKey = parameters.ApiKey, Credentials = parameters.Credentials };
                store.Initialize();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
                try
                {
                    store.Dispose();
                }
                // ReSharper disable once EmptyGeneralCatchClause
                catch (Exception) { }
                return false;
            }


            var backupRequest = new
            {
                BackupLocation = parameters.BackupPath.Replace("\\", "\\\\"),
            };

           
            var json = RavenJObject.FromObject(backupRequest).ToString();

            var url = "/admin/backup";
            if (parameters.Incremental)
                url += "?incremental=true";
            try
            {
                using (var req = CreateRequest(url, "POST"))
                {
                    req.WriteAsync(json).Wait();

                    Console.WriteLine("Sending json {0} to {1}", json, parameters.ServerUrl);

                    var response = req.ReadResponseJson();
                    Console.WriteLine(response);
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
                return false;
            }

            return true;
        }
		public void SilverlightSupport()
		{
			#region silverlight_support
			var documentStore = new DocumentStore { Url = "http://myravendb.mydomain.com/" };
			documentStore.Initialize();

			#endregion

			documentStore.Dispose();
		}
		public void RunningInServerMode()
		{
			#region running_in_server_mode
			var documentStore = new DocumentStore { Url = "http://myravendb.mydomain.com/" };
			documentStore.Initialize();

			#endregion

			documentStore.Dispose();
		}
		public void UsingConnectionString()
		{
			#region using_connection_string
			var documentStore = new DocumentStore
				                    {
					                    ConnectionStringName = "MyRavenConStr"
				                    };

			#endregion

			documentStore.Dispose();
		}
		public static void Main(string[] args)
		{
			var store1 = new DocumentStore
							 {
								 Url = Url1,
								 Conventions =
									 {
										 FailoverBehavior = FailoverBehavior.ReadFromAllServers
									 }
							 };

			var store2 = new DocumentStore
							 {
								 Url = Url2
							 };

			store1.Initialize();
			store2.Initialize();

			CreateDatabase(store1, DatabaseName);
			Console.WriteLine("Created {0} database on {1}.", DatabaseName, store1.Url);
			CreateDatabase(store2, DatabaseName);
			Console.WriteLine("Created {0} database on {1}.", DatabaseName, store2.Url);

			CreateReplication(store1, DatabaseName, Url2, DatabaseName);
			Console.WriteLine("Created Replication document on {0}.", store1.Url);

			var replicationInformerForDatabase = store1.GetReplicationInformerForDatabase(DatabaseName);
			replicationInformerForDatabase.RefreshReplicationInformation((ServerClient)store1.DatabaseCommands.ForDatabase(DatabaseName));

			using (var session = store1.OpenSession(DatabaseName))
			{
				session.Store(new User { Name = "Ayende" }, "users/ayende");
				session.SaveChanges();
			}

			WaitForDocument(store2.DatabaseCommands.ForDatabase(DatabaseName), "users/ayende");

			Console.WriteLine("Document users/ayende successfully replicated to {0}, ready for {1} server failure.", store2.Url, store1.Url);
			Console.WriteLine("Press any key to continue...");
			Console.ReadLine();

			for (int i = 0; i < 12; i++)
			{
				using (var session = store1.OpenSession(DatabaseName))
				{
					session.Load<User>("users/ayende");
				}
			}

			store1.Dispose();
			store2.Dispose();
		}
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            DocumentStore = new DocumentStore() { ConnectionStringName = "RavenDBServer" };
            DocumentStore.Initialize();

            IKernel kernel = new StandardKernel(new PairTrackerModule());
            var presenter = kernel.Get<PairTrackerPresenter>();

            Application.Run((Form)presenter.view);

            DocumentStore.Dispose();
        }
Exemple #9
0
        private static void Main(string[] args)
        {
            _store = new DocumentStore
                         {
                             Url = "http://localhost:8080/"
                         };
            _store.Initialize();
              /*  IndexCreation.CreateIndexes(typeof(FindSchoolByName).Assembly, _store);
            new StopIndexing().Execute(_store);
            new ImportFromCsvCommand().Execute(_store);
            new StartIndexing().Execute(_store);
              */
            new CheckProximityCommand().Execute(_store);
            _store.Dispose();

            Console.ReadLine();
        }
Exemple #10
0
        static void Main(string[] args)
        {
            var store = new DocumentStore { Url = "http://localhost:8080" };
            store.Initialize();

            using (var session = store.OpenSession())
            {
                var product = new Product
                {
                    Cost = 3.99m,
                    Name = "Milk",
                };

                session.Store(product);
                session.SaveChanges();

                Console.WriteLine("Product: ${0} - {1}", product.Cost, product.Name);

                var order = new Order
                {
                    Customer = "customers/ayende",
                    OrderLines = {
                        new OrderLine {
                            ProductId = product.Id,
                            Quantity = 3
                        }
                    }
                };

                Console.WriteLine("Order: {0} Quantity={1}",
                    order.Customer,
                    order.OrderLines[0].Quantity);

                session.Store(order);
                session.SaveChanges();
            }

            store.Dispose();

            Console.WriteLine("Press any key...");
            Console.ReadKey(true);
        }
Exemple #11
0
        protected void ValidateThatServerIsUpAndDatabaseExists(RavenConnectionStringOptions options, DocumentStore s)
        {
            var shouldDispose = false;

            try
            {
                var commands = !string.IsNullOrEmpty(options.DefaultDatabase)
                                   ? s.DatabaseCommands.ForDatabase(options.DefaultDatabase)
                                   : s.DatabaseCommands;

                commands.GetStatistics(); // check if database exist
            }
            catch (Exception e)
            {
                shouldDispose = true;

                var responseException = e as ErrorResponseException;
                if (responseException != null && responseException.StatusCode == HttpStatusCode.ServiceUnavailable && responseException.Message.StartsWith("Could not find a database named"))
                    throw new InvalidOperationException(
                        string.Format(
                            "Migration tool does not support database creation (database '{0}' on server '{1}' must exist before running this tool).",
                            options.DefaultDatabase,
                            s.Url), e);


                if (e.InnerException != null)
                {
                    var webException = e.InnerException as WebException;
                    if (webException != null)
                    {
                        throw new InvalidOperationException(string.Format("Migration tool encountered a connection problem: '{0}'.", webException.Message), webException);
                    }
                }

                throw new InvalidOperationException(string.Format("Migration tool encountered a connection problem: '{0}'.", e.Message), e);
            }
            finally
            {
                if (shouldDispose)
                    s.Dispose();
            }
        }
Exemple #12
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(); }
            }
        }
Exemple #13
0
		static void Main()
		{
			var store1 = new DocumentStore
							 {
								 Url = Url1
							 };

			var store2 = new DocumentStore
							 {
								 Url = Url2
							 };

			store1.Initialize();
			store2.Initialize();

			CreateDatabase(store1, DatabaseName);
			Console.WriteLine("Created {0} database on {1}.", DatabaseName, store1.Url);
			CreateDatabase(store2, DatabaseName);
			Console.WriteLine("Created {0} database on {1}.", DatabaseName, store2.Url);

			using (var session1 = store1.OpenSession(DatabaseName))
			{
				session1.Store(new User { Id = "users/ayende", Name = "Ayende" });
				session1.SaveChanges();
			}

			Console.WriteLine("Created document users/ayende on {0}.", store1.Url);

			using (var session2 = store2.OpenSession(DatabaseName))
			{
				session2.Store(new User { Id = "users/ayende", Name = "Oren" });
				session2.SaveChanges();
			}

			Console.WriteLine("Created document users/ayende on {0}.", store2.Url);

			CreateReplication(store1, DatabaseName, Url2, DatabaseName);
			Console.WriteLine("Created Replication document on {0}.", store1.Url);

			Console.WriteLine("Press any key to continue...");
			Console.ReadLine();

			using (var session2 = store2.OpenSession(DatabaseName))
			{
				try
				{
					session2.Load<User>("users/ayende");
				}
				catch (ConflictException e)
				{
					Console.WriteLine("Found conflict in users/ayende on {0}. Choose which document you want to preserve:", Url2);
					var list = new List<JsonDocument>();
					for (int i = 0; i < e.ConflictedVersionIds.Length; i++)
					{
						var doc = store2.DatabaseCommands.ForDatabase(DatabaseName).Get(e.ConflictedVersionIds[i]);
						list.Add(doc);
						Console.WriteLine("{0}. {1}", i, doc.DataAsJson);
					}

					var select = int.Parse(Console.ReadLine());
					var resolved = list[select];
					store2.DatabaseCommands.ForDatabase(DatabaseName).Put("users/ayende", null, resolved.DataAsJson, resolved.Metadata);
				}
			}

			Console.WriteLine("Conflict resolved...");
			Console.WriteLine("Press any key to continue...");
			Console.ReadLine();

			using (var session = store2.OpenSession(DatabaseName))
			{
				var user = session.Load<User>("users/ayende");
				Console.WriteLine(user.Name);
				user.Name = "Ayende Rahien";
				session.SaveChanges();
			}

			store1.Dispose();
			store2.Dispose();
		}
Exemple #14
0
        static void Main(string[] args)
        {
            ds = new DocumentStore { Url = "http://localhost:8085", DefaultDatabase = "SoftModel" };
            ds.Initialize();

            Out("-- Metadata --");
            // Out("Creating supported field types");
            // CreateSupportedFieldTypes();

            Out("-- Schema --");
            Out("Creating record schema");
            CreateSampleRecordDescriptor();

            Out("Creating form definition");
            CreateSampleFormDefinition();

            Out("Creating record schema");
            CreateSampleRecordDescriptor();

            Out("Creating user dashboard");
            CreateSampleUserDashboard();

            Out("-- Sample Data --");
            Out("Creating persons");
            CreateSamplePersons();

            // Initialize indexes
            IndexCreation.CreateIndexes(typeof(Schema_Search).Assembly, ds);
            // Test();

            ds.Dispose();

            Out("Done");
            Console.ReadLine();
        }
        static void RunDBTest(string database, string defaultdb)
        {
            var store = new DocumentStore { Url = database, DefaultDatabase = defaultdb };
            store.Initialize();
            IDocumentSession session = store.OpenSession();

            try
            {
                var json = ((ServerClient)store.DatabaseCommands).CreateRequest("GET", "/debug/user-info").ReadResponseJson();

                foreach (var s in json.Values())
                    Console.WriteLine(s.ToString());
            }
            catch (Exception ex)
                {
                    Console.WriteLine("Error trying to get user permissions. Error given is: ");
                    Console.WriteLine(ex.Message);
                }

            session.SaveChanges();
            session.Dispose();
            store.Dispose();
        }
Exemple #16
0
		static void Main(string[] args)
		{
			var port = 0;

			Console.Out.WriteLine("Run a local server, make sure to set \"AnonymousAccess\" to \"None\"  ");
			Console.Out.WriteLine("Enter server's port here (leave empty to use 8080): ");

			while (port == 0)
			{
				var line = Console.In.ReadLine();
				if (string.IsNullOrEmpty(line))
					port = 8080;
				else if (int.TryParse(line, out port) == false)
					Console.Out.WriteLine("Port must be a number, enter port (leave empty to use 8080): ");
			}

			Console.Out.WriteLine("Follow these instructions:");
			Console.Out.WriteLine("1) Open the browser");
			Console.Out.WriteLine("2) Navigate to: http://localhost:" + port);
			Console.Out.WriteLine("3) Make sure there is a database named \"ApiKeySample\", if there isn't one, create it");
			Console.Out.WriteLine("4) Go to the Databases section and select \"System Database\" (on the top right)");
			Console.Out.WriteLine("5) Go to the settings (press the cog wheel next to the database name)");
			Console.Out.WriteLine("6) In the Api Keys section Add a new key, select a name, generate a secret and add a database settings for \"ApiKeySample\"");
			Console.Out.WriteLine("7) Don't forget to click the \"Save Changes\" button");
			Console.Out.WriteLine("8) Right-click on the full api key and copy it");

			Console.Out.WriteLine("Paste here the full api key: ");
			var apiKey = Console.In.ReadLine();

			Console.Out.WriteLine("");
			Console.Out.WriteLine("Press Enter to try and save with correct api key");
			Console.In.ReadLine();
			Console.Out.WriteLine("Trying to save a document with the correct api key");

			#region apikeys1
			var store = new DocumentStore
				                       {
					                       Url = "http://localhost:" + port,
					                       DefaultDatabase = "ApiKeySample",
					                       ApiKey = apiKey
				                       }.Initialize();
			#endregion

			using (var session = store.OpenSession())
			{
				session.Store(new SampleData
				{
					Id = "SampleData/1",
					Name = "Rhinos"
				});
				session.SaveChanges();
				Console.Out.WriteLine("Document saved");
			}

			store.Dispose();

			Console.Out.WriteLine("");
			Console.Out.WriteLine("Press Enter to try and load with correct api key");
			Console.In.ReadLine();
			Console.Out.WriteLine("Trying to load the document with the correct api key");

			store = new DocumentStore
			{
				Url = "http://localhost:" + port,
				DefaultDatabase = "ApiKeySample",
				ApiKey = apiKey
			}.Initialize();

			using (var session = store.OpenSession())
			{
				var data = session.Load<SampleData>("SampleData/1");

				Console.Out.WriteLine("Name: " + data.Name + ", Created At: " + data.StoredAt);
			}

			store.Dispose();

			Console.Out.WriteLine("");
			Console.Out.WriteLine("Press Enter to try and load with wrong api key");
			Console.In.ReadLine();
			Console.Out.WriteLine("Trying to load the document with the wrong api key");
			try
			{
				store = new DocumentStore
					        {
						        Url = "http://localhost:" + port,
						        DefaultDatabase = "ApiKeySample",
						        ApiKey = "NotApiKey"
					        }.Initialize();

				using (var session = store.OpenSession())
				{
					var data = session.Load<SampleData>("SampleData/1");

					Console.Out.WriteLine("Name: " + data.Name + ", Created At: " + data.StoredAt);
				}
			}
			catch (Exception e)
			{
				Console.Out.WriteLine("Process failed, error message: " + e.Message);
			}

			store.Dispose();
		}
Exemple #17
0
	    private void ValidateThatServerIsUpAndDatabaseExists(DocumentStore s)
	    {
	        var shouldDispose = false;

	        try
	        {
	            var commands = !string.IsNullOrEmpty(ConnectionStringOptions.DefaultDatabase)
	                               ? s.DatabaseCommands.ForDatabase(ConnectionStringOptions.DefaultDatabase)
	                               : s.DatabaseCommands;

	            commands.GetStatistics(); // check if database exist
	        }
	        catch (WebException e)
	        {
	            shouldDispose = true;

	            var httpWebResponse = e.Response as HttpWebResponse;
	            if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound)
	                throw new SmugglerException(
	                    string.Format(
	                        "Smuggler does not support database creation (database '{0}' on server '{1}' must exist before running Smuggler).",
	                        ConnectionStringOptions.DefaultDatabase,
	                        s.Url), e);

	            throw new SmugglerException(string.Format("Smuggler encountered a connection problem: '{0}'.", e.Message), e);
	        }
	        finally
	        {
	            if (shouldDispose)
                    s.Dispose();
	        }
	    }
        public void ShouldKeepPullingDocsAfterServerRestart()
        {
            var dataPath = NewDataPath("RavenDB_2627_after_restart");

            IDocumentStore store = null;
            try
            {
                var serverDisposed = false;

                var server = GetNewServer(dataDirectory: dataPath, runInMemory: false);

                store = new DocumentStore()
                {
                    Url = "http://*****:*****@id"));
            }
            finally
            {
                if(store != null)
                    store.Dispose();
            }
        }
        private static void ShowOccasionalSlowGETsUsingRavenClient()
        {
            var store = new DocumentStore
                                    {
                                        Url = remoteRavenFromGit,
                                        MaxNumberOfCachedRequests = 0
                                    };
            store.Initialize();

            Console.WriteLine("GET larger documents using raven client's method");
            var doc = File.ReadAllText("largedoc.json");
            Put(remoteRavenFromGit, doc);
            for (int i = 0; i < 100; i++)
            {
                var stopwatch = Stopwatch.StartNew();
                store.DatabaseCommands.Get("thedoc");
                Console.WriteLine("GET: " + stopwatch.ElapsedMilliseconds);
            }

            store.Dispose();
        }