Exemplo n.º 1
0
		/// <summary>
		/// Initializes a new instance of the <see cref="HiLoKeyGenerator"/> class.
		/// </summary>
		public HiLoKeyGenerator(IDatabaseCommands databaseCommands, string tag, long capacity)
		{
			this.databaseCommands = databaseCommands;
			this.tag = tag;
			this.capacity = capacity;
			current = 0;
		}
Exemplo n.º 2
0
		public string GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention conventions, object entity)
		{
			var shardId = shardedDocumentStore.ShardStrategy.ShardResolutionStrategy.MetadataShardIdFor(entity);
			if (shardId == null)
				throw new InvalidOperationException(string.Format(
					"ShardResolutionStrategy.MetadataShardIdFor cannot return null. You must specify where to store the metadata documents for the entity type '{0}'.", entity.GetType().FullName));

			MultiTypeHiLoKeyGenerator value;
			if (generatorsByShard.TryGetValue(shardId, out value))
			{
				
				return value.GenerateDocumentKey(databaseCommands, conventions, entity);
			}

			lock (this)
			{
				if (generatorsByShard.TryGetValue(shardId, out value) == false)
				{
					value = new MultiTypeHiLoKeyGenerator(capacity);
					generatorsByShard = new Dictionary<string, MultiTypeHiLoKeyGenerator>(generatorsByShard)
					                    	{
					                    		{shardId, value}
					                    	};
				}
			}

			return value.GenerateDocumentKey(databaseCommands, conventions, entity);
		}
		/// <summary>
		/// Generates the document key.
		/// </summary>
		/// <param name="conventions">The conventions.</param>
		/// <param name="entity">The entity.</param>
		/// <returns></returns>
		public string GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention conventions, object entity)
		{
         var typeTagName = conventions.GetDynamicTagName(entity);
			if (string.IsNullOrEmpty(typeTagName)) //ignore empty tags
				return null;
			var tag = conventions.TransformTypeTagNameToDocumentKeyPrefix(typeTagName);
			HiLoKeyGenerator value;
			if (keyGeneratorsByTag.TryGetValue(tag, out value))
				return value.GenerateDocumentKey(databaseCommands, conventions, entity);

			lock(generatorLock)
			{
				if (keyGeneratorsByTag.TryGetValue(tag, out value))
					return value.GenerateDocumentKey(databaseCommands, conventions, entity);

				value = new HiLoKeyGenerator(tag, capacity);
				// doing it this way for thread safety
				keyGeneratorsByTag = new Dictionary<string, HiLoKeyGenerator>(keyGeneratorsByTag)
				{
					{tag, value}
				};
			}

			return value.GenerateDocumentKey(databaseCommands, conventions, entity);
		}
Exemplo n.º 4
0
		/// <summary>
		/// Creates the indexes found in the specified catalog
		/// </summary>
		/// <param name="catalogToGetnIndexingTasksFrom">The catalog to get indexing tasks from.</param>
		public static void CreateIndexes(ExportProvider catalogToGetnIndexingTasksFrom, IDatabaseCommands databaseCommands, DocumentConvention conventions)
		{
			var tasks = catalogToGetnIndexingTasksFrom.GetExportedValues<AbstractIndexCreationTask>();
			foreach (var task in tasks)
			{
				task.Execute(databaseCommands, conventions);
			}
		}
Exemplo n.º 5
0
 public HiLoKeyGenerator(IDatabaseCommands commands, string tag, long capacity)
 {
     currentHi = 0;
     this.commands = commands;
     this.tag = tag;
     this.capacity = capacity;
     currentLo = capacity + 1;
 }
Exemplo n.º 6
0
 public WhatAreCommands()
 {
     using (var store = new DocumentStore())
     {
         #region what_are_commands_1
         IDatabaseCommands      commands      = store.DatabaseCommands;
         IAsyncDatabaseCommands asyncCommands = store.AsyncDatabaseCommands;
         #endregion
     }
 }
        public static Operation DeleteByIndex <T>(
            this IDatabaseCommands databaseCommands,
            IndexQuery queryToDelete,
            BulkOperationOptions options = null)
            where T : AbstractIndexCreationTask
        {
            var indexName = typeof(T).Name.Replace("_", "/");

            return(databaseCommands.DeleteByIndex(indexName, queryToDelete, options));
        }
Exemplo n.º 8
0
        protected bool WaitForDocument(IDatabaseCommands commands, string expectedId, int timeoutInMs)
        {
            var cts         = new CancellationTokenSource();
            var waitingTask = Task.Run(() => WaitForDocument(commands, expectedId, null, cts.Token), cts.Token);

            Task.WaitAny(waitingTask, Task.Delay(timeoutInMs, cts.Token));

            cts.Cancel();
            return(AsyncHelpers.RunSync(() => waitingTask.ContinueWith(t => commands.Head(expectedId) != null)));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Executes the index creation against the specified document database using the specified conventions
        /// </summary>
        public virtual void Execute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention)
        {
            Conventions = documentConvention;
            var indexDefinition = CreateIndexDefinition();

            // This code take advantage on the fact that RavenDB will turn an index PUT
            // to a noop of the index already exists and the stored definition matches
            // the new defintion.
            databaseCommands.PutIndex(IndexName, indexDefinition, true);
        }
Exemplo n.º 10
0
        public static void WaitForDocument(IDatabaseCommands databaseCommands, string id)
        {
            var done = SpinWait.SpinUntil(() =>
            {
                var doc = databaseCommands.Get(id);
                return(doc != null);
            }, TimeSpan.FromMinutes(1));

            Assert.True(done);
        }
Exemplo n.º 11
0
		public BulkInsertOperation(string database, IDocumentStore documentStore, DocumentSessionListeners listeners, BulkInsertOptions options)
		{
			this.documentStore = documentStore;
			databaseCommands = database == null
				                   ? documentStore.DatabaseCommands.ForSystemDatabase()
				                   : documentStore.DatabaseCommands.ForDatabase(database);

			generateEntityIdOnTheClient = new GenerateEntityIdOnTheClient(documentStore, entity => documentStore.Conventions.GenerateDocumentKey(database, databaseCommands, entity));
			operation = databaseCommands.GetBulkInsertOperation(options);
			entityToJson = new EntityToJson(documentStore, listeners);
		}
Exemplo n.º 12
0
        /// <summary>
        /// Executes the index creation using in side-by-side mode.
        /// </summary>
        /// <param name="databaseCommands"></param>
        /// <param name="documentConvention"></param>
        /// <param name="minimumEtagBeforeReplace">The minimum etag after which indexes will be swapped.</param>
        /// <param name="replaceTimeUtc">The minimum time after which indexes will be swapped.</param>
        public virtual void SideBySideExecute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention, Etag minimumEtagBeforeReplace = null, DateTime?replaceTimeUtc = null)
        {
            Conventions = documentConvention;
            var indexDefinition = CreateIndexDefinition();

            var replaceIndexName = Constants.SideBySideIndexNamePrefix + IndexName;
            //check if side by side index exists
            var sideBySideDef = databaseCommands.GetIndex(replaceIndexName);

            if (sideBySideDef != null)
            {
                if (CurrentOrLegacyIndexDefinitionEquals(documentConvention, sideBySideDef, indexDefinition))
                {
                    return;
                }

                UpdateSideBySideIndex(databaseCommands, minimumEtagBeforeReplace, replaceTimeUtc, replaceIndexName, indexDefinition, documentConvention);
                return;
            }

            //check if "regular" index exists
            var serverDef = databaseCommands.GetIndex(IndexName);

            if (serverDef != null)
            {
                if (CurrentOrLegacyIndexDefinitionEquals(documentConvention, serverDef, indexDefinition))
                {
                    return;
                }

                switch (serverDef.LockMode)
                {
                case IndexLockMode.SideBySide:
                    //keep the SideBySide lock mode from the replaced index
                    indexDefinition.LockMode = IndexLockMode.SideBySide;
                    break;

                case IndexLockMode.LockedIgnore:
                    //Nothing to do we just ignore this index
                    return;

                case IndexLockMode.LockedError:
                    throw new InvalidOperationException(string.Format("Can't replace locked index {0} its lock mode is set to: LockedError", serverDef.IndexId));
                }

                UpdateSideBySideIndex(databaseCommands, minimumEtagBeforeReplace, replaceTimeUtc, replaceIndexName, indexDefinition, documentConvention);
            }
            else
            {
                // since index doesn't exist yet - create it in normal mode
                databaseCommands.PutIndex(IndexName, indexDefinition);
                AfterExecute(databaseCommands, documentConvention);
            }
        }
Exemplo n.º 13
0
        protected void WaitForDocument(IDatabaseCommands databaseCommands, string id)
        {
            var done = SpinWait.SpinUntil(() =>
            {
                // We expect to get the doc from the <system> database
                var doc = databaseCommands.Get(id);
                return(doc != null);
            }, TimeSpan.FromMinutes(5));

            Assert.True(done);
        }
Exemplo n.º 14
0
 static WindowsAuthDocument GetWindowsAuthDocument(IDatabaseCommands systemCommands)
 {
     var existing = systemCommands.Get("Raven/Authorization/WindowsSettings");
     if (existing == null)
     {
         return new WindowsAuthDocument();
     }
     return existing
         .DataAsJson
         .JsonDeserialization<WindowsAuthDocument>();
 }
Exemplo n.º 15
0
 public SwitchCommandsCredentials()
 {
     using (var store = new DocumentStore())
     {
         #region with_2
         IDatabaseCommands commands = store
                                      .DatabaseCommands
                                      .With(new NetworkCredential("otherUserName", "otherPassword"));
         #endregion
     }
 }
Exemplo n.º 16
0
        public BulkInsertOperation(string database, IDocumentStore documentStore, DocumentSessionListeners listeners, BulkInsertOptions options)
        {
            this.documentStore = documentStore;
            databaseCommands   = database == null
                                                   ? documentStore.DatabaseCommands.ForSystemDatabase()
                                                   : documentStore.DatabaseCommands.ForDatabase(database);

            generateEntityIdOnTheClient = new GenerateEntityIdOnTheClient(documentStore, entity => documentStore.Conventions.GenerateDocumentKey(database, databaseCommands, entity));
            operation    = databaseCommands.GetBulkInsertOperation(options);
            entityToJson = new EntityToJson(documentStore, listeners);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Generates the document key.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public string GenerateDocumentKey(IDatabaseCommands databaseCommands, object entity)
        {
            var type = entity.GetType();

            foreach (var typeToRegisteredIdConvention in listOfRegisteredIdConventions
                     .Where(typeToRegisteredIdConvention => typeToRegisteredIdConvention.Item1.IsAssignableFrom(type)))
            {
                return(typeToRegisteredIdConvention.Item2(databaseCommands, entity));
            }
            return(DocumentKeyGenerator(databaseCommands, entity));
        }
Exemplo n.º 18
0
 protected void SetupReplication(IDatabaseCommands source, IEnumerable <RavenJObject> destinations)
 {
     Assert.NotEmpty(destinations);
     source.Put(Constants.RavenReplicationDestinations,
                null, new RavenJObject
     {
         {
             "Destinations", new RavenJArray(destinations)
         }
     }, new RavenJObject());
 }
Exemplo n.º 19
0
		private static void WaitForDocument(IDatabaseCommands commands, string expectedId)
		{
			for (int i = 0; i < RetriesCount; i++)
			{
				if (commands.Head(expectedId) != null)
					break;
				Thread.Sleep(100);
			}

			if(commands.Head(expectedId) == null)
				throw new Exception("Document not replicated");
		}
Exemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentQuery{T}"/> class.
        /// </summary>
        public DocumentQuery(InMemoryDocumentSessionOperations session
#if !SILVERLIGHT
                             , IDatabaseCommands databaseCommands
#endif
                             , IAsyncDatabaseCommands asyncDatabaseCommands, string indexName, string[] fieldsToFetch, string[] projectionFields, IDocumentQueryListener[] queryListeners)
            : base(session
#if !SILVERLIGHT
                   , databaseCommands
#endif
                   , asyncDatabaseCommands, indexName, fieldsToFetch, projectionFields, queryListeners)
        {
        }
		/// <summary>
		/// Executes the index creation against the specified document database using the specified conventions
		/// </summary>
		public virtual void Execute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention)
		{
			Conventions = documentConvention;
			var transformerDefinition = CreateTransformerDefinition();
			// This code take advantage on the fact that RavenDB will turn an index PUT
			// to a noop of the index already exists and the stored definition matches
			// the new definition.
			databaseCommands.PutTransformer(TransformerName, transformerDefinition);

			UpdateIndexInReplication(databaseCommands, documentConvention, (commands, url) =>
				commands.PutTransformer(TransformerName, transformerDefinition));
		}
Exemplo n.º 22
0
        static WindowsAuthDocument GetWindowsAuthDocument(IDatabaseCommands systemCommands)
        {
            var existing = systemCommands.Get("Raven/Authorization/WindowsSettings");

            if (existing == null)
            {
                return(new WindowsAuthDocument());
            }
            return(existing
                   .DataAsJson
                   .JsonDeserialization <WindowsAuthDocument>());
        }
Exemplo n.º 23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncDocumentQuery{T}"/> class.
        /// </summary>
        public AsyncDocumentQuery(InMemoryDocumentSessionOperations session,
#if !SILVERLIGHT
                                  IDatabaseCommands databaseCommands,
#endif
                                  IAsyncDatabaseCommands asyncDatabaseCommands, string indexName, string[] fieldsToFetch, string[] projectionFields, IDocumentQueryListener[] queryListeners, bool isMapReduce)
            : base(session,
#if !SILVERLIGHT
                   databaseCommands,
#endif
                   asyncDatabaseCommands, indexName, fieldsToFetch, projectionFields, queryListeners, isMapReduce)
        {
        }
Exemplo n.º 24
0
    public static void AddUserToDatabase(IDocumentStore documentStore, string username)
    {
        IDatabaseCommands systemCommands = documentStore
                                           .DatabaseCommands
                                           .ForSystemDatabase();
        WindowsAuthDocument windowsAuthDocument = GetWindowsAuthDocument(systemCommands);

        AddOrUpdateAuthUser(windowsAuthDocument, username, "<system>");

        RavenJObject ravenJObject = RavenJObject.FromObject(windowsAuthDocument);

        systemCommands.Put("Raven/Authorization/WindowsSettings", null, ravenJObject, new RavenJObject());
    }
Exemplo n.º 25
0
        protected void UpdateReplication(IDatabaseCommands source, params DocumentStore[] destinations)
        {
            Assert.NotEmpty(destinations);


            var destinationDocs = destinations.Select(destination => new RavenJObject
            {
                { "Url", destination.Url },
                { "Database", destination.DefaultDatabase }
            }).ToList();

            UpdateReplication(source, destinationDocs);
        }
Exemplo n.º 26
0
		private static void SetupReplication(IDatabaseCommands source, params string[] urls)
		{
			source.Put(Constants.RavenReplicationDestinations,
			           null, new RavenJObject
				                 {
					                 {
						                 "Destinations", new RavenJArray(urls.Select(url => new RavenJObject
							                                                                    {
								                                                                    {"Url", url}
							                                                                    }))
					                 }
				                 }, new RavenJObject());
		}
Exemplo n.º 27
0
        /// <summary>
        /// Executes the index creation against the specified document database using the specified conventions
        /// </summary>
        public virtual void Execute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention)
        {
            Conventions = documentConvention;
            var transformerDefinition = CreateTransformerDefinition(documentConvention.PrettifyGeneratedLinqExpressions);

            // This code take advantage on the fact that RavenDB will turn an index PUT
            // to a noop of the index already exists and the stored definition matches
            // the new definition.
            databaseCommands.PutTransformer(TransformerName, transformerDefinition);

            UpdateIndexInReplication(databaseCommands, documentConvention, (commands, url) =>
                                     commands.PutTransformer(TransformerName, transformerDefinition));
        }
        public SwitchCommandsToDifferentDatabase()
        {
            using (var store = new DocumentStore())
            {
                #region for_database_3
                IDatabaseCommands commands = store.DatabaseCommands.ForDatabase("otherDatabase");
                #endregion

                #region for_database_4
                IDatabaseCommands systemCommands = store.DatabaseCommands.ForSystemDatabase();
                #endregion
            }
        }
        internal static void AfterExecute(IDatabaseCommands databaseCommands, string indexName, ScriptedIndexResults scripts)
        {
            var documentId = GetScriptedIndexResultsDocumentId(indexName);
            scripts.Id = documentId;

            var oldDocument = databaseCommands.Get(documentId);
            var newDocument = RavenJObject.FromObject(scripts);
            if (oldDocument != null && RavenJToken.DeepEquals(oldDocument.DataAsJson, newDocument))
                return;

            databaseCommands.Put(documentId, null, newDocument, null);
            databaseCommands.ResetIndex(indexName);
        }
Exemplo n.º 30
0
 protected void RemoveReplication(IDatabaseCommands source)
 {
     source.Put(
         Constants.RavenReplicationDestinations,
         null,
         new RavenJObject
     {
         {
             "Destinations", new RavenJArray()
         }
     },
         new RavenJObject());
 }
Exemplo n.º 31
0
 private static void SetupReplication(IDatabaseCommands source, params string[] urls)
 {
     source.Put(Constants.RavenReplicationDestinations,
                null, new RavenJObject
     {
         {
             "Destinations", new RavenJArray(urls.Select(url => new RavenJObject
             {
                 { "Url", url }
             }))
         }
     }, new RavenJObject());
 }
Exemplo n.º 32
0
        protected void SetupReplication(IDatabaseCommands source, Dictionary <string, string> specifiedCollections, params DocumentStore[] destinations)
        {
            Assert.NotEmpty(destinations);

            var destinationDocs = destinations.Select(destination => new RavenJObject
            {
                { "Url", destination.Url },
                { "Database", destination.DefaultDatabase },
                { "SpecifiedCollections", RavenJObject.FromObject(specifiedCollections) }
            }).ToList();

            SetupReplication(source, destinationDocs);
        }
Exemplo n.º 33
0
 protected void SetupReplication(IDatabaseCommands source, params string[] urls)
 {
     Assert.NotEmpty(urls);
     source.Put(replication::Raven.Bundles.Replication.ReplicationConstants.RavenReplicationDestinations,
                null, new RavenJObject
     {
         {
             "Destinations", new RavenJArray(urls.Select(url => new RavenJObject
             {
                 { "Url", url }
             }))
         }
     }, new RavenJObject());
 }
Exemplo n.º 34
0
        private void UpdateSideBySideIndex(IDatabaseCommands databaseCommands, Etag minimumEtagBeforeReplace, DateTime?replaceTimeUtc, string replaceIndexName, IndexDefinition indexDefinition, DocumentConvention documentConvention)
        {
            databaseCommands.PutIndex(replaceIndexName, indexDefinition, true);

            databaseCommands
            .Put(Constants.IndexReplacePrefix + replaceIndexName,
                 null,
                 RavenJObject.FromObject(new IndexReplaceDocument {
                IndexToReplace = IndexName, MinimumEtagBeforeReplace = minimumEtagBeforeReplace, ReplaceTimeUtc = replaceTimeUtc
            }),
                 new RavenJObject());

            AfterExecute(databaseCommands, documentConvention);
        }
Exemplo n.º 35
0
 public virtual IQueryable <T> GetAll()
 {
     using (IDocumentStore store = new DocumentStore
     {
         Url = "http://localhost:8080/"
     }.Initialize())
     {
         IDatabaseCommands commands = store.DatabaseCommands;
         using (IDocumentSession session = store.OpenSession())
         {
             return(session.Query <T>());
         }
     }
 }
Exemplo n.º 36
0
        public void WaitForDelete(IDatabaseCommands commands, string key, TimeSpan?timeout = null)
        {
            var done = SpinWait.SpinUntil(() =>
            {
                // We expect to get the doc from the <system> database
                var doc = commands.Get(key);
                return(doc == null);
            }, timeout ?? TimeSpan.FromMinutes(5));

            if (!done)
            {
                throw new Exception("WaitForDelete failed");
            }
        }
Exemplo n.º 37
0
        protected virtual void WaitForDocument(IDatabaseCommands databaseCommands, string id)
        {
            var done = SpinWait.SpinUntil(() =>
            {
                // We expect to get the doc from the <system> database
                var doc = databaseCommands.Get(id);
                return(doc != null);
            }, TimeSpan.FromMinutes(5));

            if (!done)
            {
                throw new Exception("WaitForDocument failed");
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Executes the index creation against the specified document database using the specified conventions
        /// </summary>
        public virtual void Execute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention)
        {
            Conventions = documentConvention;
            var transformerDefinition = CreateTransformerDefinition(documentConvention.PrettifyGeneratedLinqExpressions);

            // This code take advantage on the fact that RavenDB will turn an index PUT
            // to a noop of the index already exists and the stored definition matches
            // the new definition.
            databaseCommands.PutTransformer(TransformerName, transformerDefinition);

            if (documentConvention.IndexAndTransformerReplicationMode.HasFlag(IndexAndTransformerReplicationMode.Transformers))
            {
                ReplicateTransformerIfNeeded(databaseCommands);
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentSession"/> class.
        /// </summary>
        public DocumentSession(DocumentStore documentStore,
                               DocumentSessionListeners listeners,
                               Guid id,
                               IDatabaseCommands databaseCommands
#if !NET_3_5
                               , IAsyncDatabaseCommands asyncDatabaseCommands
#endif
                               )
            : base(documentStore, listeners, id)
        {
#if !NET_3_5
            this.asyncDatabaseCommands = asyncDatabaseCommands;
#endif
            DatabaseCommands = databaseCommands;
        }
Exemplo n.º 40
0
        protected override void WaitForDocument(IDatabaseCommands commands, string expectedId)
        {
            for (int i = 0; i < RetriesCount; i++)
            {
                if (commands.Head(expectedId) != null)
                {
                    break;
                }
                Thread.Sleep(100);
            }

            var jsonDocumentMetadata = commands.Head(expectedId);

            Assert.NotNull(jsonDocumentMetadata);
        }
Exemplo n.º 41
0
 static bool InvokePut(IDatabaseCommands systemCommands, RavenJObject ravenJObject)
 {
     try
     {
         systemCommands.Put("Raven/Authorization/WindowsSettings", null, ravenJObject, new RavenJObject());
         return true;
     }
     catch (ErrorResponseException exception)
     {
         if (exception.Message.Contains("Cannot setup Windows Authentication without a valid commercial license."))
         {
             throw new Exception("RavenDB requires a Commercial license to configure windows authentication. Please either install your RavenDB license or contact [email protected] if you need a copy of the RavenDB license.");
         }
         throw;
     }
 }
Exemplo n.º 42
0
 private static IDatabaseCommands SetupCommands(IDatabaseCommands databaseCommands, string database, ICredentials credentialsForSession, OpenSessionOptions options)
 {
     if (database != null)
     {
         databaseCommands = databaseCommands.ForDatabase(database);
     }
     if (credentialsForSession != null)
     {
         databaseCommands = databaseCommands.With(credentialsForSession);
     }
     if (options.ForceReadFromMaster)
     {
         databaseCommands.ForceReadFromMaster();
     }
     return(databaseCommands);
 }
Exemplo n.º 43
0
		/// <summary>
		/// Creates the indexes found in the specified catalog
		/// </summary>
		public static void CreateIndexes(ExportProvider catalogToGetnIndexingTasksFrom, IDatabaseCommands databaseCommands, DocumentConvention conventions)
		{
			var indexCompilationExceptions = new List<IndexCompilationException>();
			try
			{
				var tasks = catalogToGetnIndexingTasksFrom
					.GetExportedValues<AbstractIndexCreationTask>()
					.ToList();

				var indexesToAdd = tasks
					.Select(x => new IndexToAdd
					{
						Definition = x.CreateIndexDefinition(),
						Name = x.IndexName,
						Priority = x.Priority ?? IndexingPriority.Normal
					})
					.ToArray();

				databaseCommands.PutIndexes(indexesToAdd);

				foreach (var task in tasks)
					task.AfterExecute(databaseCommands, conventions);
			}
			// For old servers that don't have the new entrypoint for executing multiple indexes
			catch (Exception)
			{
				foreach (var task in catalogToGetnIndexingTasksFrom.GetExportedValues<AbstractIndexCreationTask>())
				{
					try
					{
						task.Execute(databaseCommands, conventions);
					}
					catch (IndexCompilationException e)
					{
						indexCompilationExceptions.Add(new IndexCompilationException("Failed to compile index name = " + task.IndexName, e));
					}

				}
			}
			foreach (var task in catalogToGetnIndexingTasksFrom.GetExportedValues<AbstractTransformerCreationTask>())
			{
				task.Execute(databaseCommands, conventions);
			}

			if (indexCompilationExceptions.Any())
				throw new AggregateException("Failed to create one or more indexes. Please see inner exceptions for more details.", indexCompilationExceptions);
		}
Exemplo n.º 44
0
		///<summary>
		/// Create the next id (numeric)
		///</summary>
		public long NextId(IDatabaseCommands commands)
		{
			while (true)
			{
				var myRange = Range; // thread safe copy

				var current = Interlocked.Increment(ref myRange.Current);
				if (current <= myRange.Max)
					return current;

				lock (generatorLock)
				{
					if (Range != myRange)
						// Lock was contended, and the max has already been changed. Just get a new id as usual.
						continue;

					Range = GetNextRange(commands);
				}
			}
		}
Exemplo n.º 45
0
		/// <summary>
		/// Creates the indexes found in the specified catalog
		/// </summary>
		public static void CreateIndexes(ExportProvider catalogToGetnIndexingTasksFrom, IDatabaseCommands databaseCommands, DocumentConvention conventions)
		{
			var indexCompilationExceptions = new List<IndexCompilationException>();
			foreach (var task in catalogToGetnIndexingTasksFrom.GetExportedValues<AbstractIndexCreationTask>())
			{
				try
				{
					task.Execute(databaseCommands, conventions);
				}
				catch (IndexCompilationException e)
				{
					indexCompilationExceptions.Add(new IndexCompilationException("Failed to compile index name = " + task.IndexName, e));
				}

			}

			foreach (var task in catalogToGetnIndexingTasksFrom.GetExportedValues<AbstractTransformerCreationTask>())
			{
				task.Execute(databaseCommands, conventions);
			}

			if (indexCompilationExceptions.Any())
				throw new AggregateException("Failed to create one or more indexes. Please see inner exceptions for more details.", indexCompilationExceptions);
		}
Exemplo n.º 46
0
 protected PeriodicExportStatus GetPerodicBackupStatus(IDatabaseCommands commands)
 {
     return GetPerodicBackupStatus(commands.Get);
 }
Exemplo n.º 47
0
		public void Execute(Guid myResourceManagerId, IDatabaseCommands commands)
		{
			var resourceManagersRequiringRecovery = new HashSet<Guid>();
			using (var store = IsolatedStorageFile.GetMachineStoreForDomain())
			{
				var filesToDelete = new List<string>();
				foreach (var file in store.GetFileNames("*.recovery-information"))
				{
					var txId = Guid.Empty;
					try
					{
						IsolatedStorageFileStream stream;
						try
						{
							stream = store.OpenFile(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
						}
						catch (Exception e)
						{
							logger.WarnException("Could not open recovery information: " + file +", this is expected if it is an active transaction / held by another server", e);
							continue;
						}
						using (stream)
						using(var reader = new BinaryReader(stream))
						{
							var resourceManagerId = new Guid(reader.ReadString());

							if(myResourceManagerId != resourceManagerId)
								continue; // it doesn't belong to us, ignore
							filesToDelete.Add(file);
							txId = new Guid(reader.ReadString());

							var db = reader.ReadString();

							var dbCmds = string.IsNullOrEmpty(db) == false ? 
								commands.ForDatabase(db) : 
								commands.ForSystemDatabase();

							TransactionManager.Reenlist(resourceManagerId, stream.ReadData(), new InternalEnlistment(dbCmds, txId));
							resourceManagersRequiringRecovery.Add(resourceManagerId);
							logger.Info("Recovered transaction {0}", txId);
						}
					}
					catch (Exception e)
					{
						logger.WarnException("Could not re-enlist in DTC transaction for tx: " + txId, e);
					}
				}

				foreach (var rm in resourceManagersRequiringRecovery)
				{
					try
					{
						TransactionManager.RecoveryComplete(rm);
					}
					catch (Exception e)
					{
						logger.WarnException("Could not properly complete recovery of resource manager: " + rm, e);
					}
				}

				var errors = new List<Exception>();
				foreach (var file in filesToDelete)
				{
					try
					{
						if (store.FileExists(file))
							store.DeleteFile(file);
					}
					catch (Exception e)
					{
						errors.Add(e);
					}
				}
				if (errors.Count > 0)
					throw new AggregateException(errors);
			}
		}
Exemplo n.º 48
0
			public InternalEnlistment(IDatabaseCommands database, Guid txId)
			{
				this.database = database;
				this.txId = txId;
			}
Exemplo n.º 49
0
		public object ExecuteEmbedded(IDatabaseCommands commands)
		{
			return commands.Suggest(index, suggestionQuery);
		}
Exemplo n.º 50
0
		private void PutDocument(IDatabaseCommands databaseCommands,JsonDocument document)
		{
			databaseCommands.Put(HiLoDocumentKey, document.Etag,
								 document.DataAsJson,
								 document.Metadata);
		}
Exemplo n.º 51
0
		private JsonDocument GetDocument(IDatabaseCommands databaseCommands)
		{
			var documents = databaseCommands.Get(new[] { HiLoDocumentKey, RavenKeyServerPrefix }, new string[0]);
			return HandleGetDocumentResult(documents);
		}
Exemplo n.º 52
0
        protected virtual void WaitForDocument(IDatabaseCommands databaseCommands, string id)
        {
            var done = SpinWait.SpinUntil(() =>
            {
                // We expect to get the doc from the <system> database
                var doc = databaseCommands.Get(id);
                return doc != null;
            }, TimeSpan.FromMinutes(5));

            if (!done) throw new Exception("WaitForDocument failed");
        }
		public string GenerateDocumentKey(string dbName, IDatabaseCommands databaseCommands, DocumentConvention conventions, object entity)
		{
			var multiTypeHiLoKeyGenerator = generators.GetOrAdd(dbName ?? Constants.SystemDatabase, s => new MultiTypeHiLoKeyGenerator(capacity));
			return multiTypeHiLoKeyGenerator.GenerateDocumentKey(databaseCommands, conventions, entity);
		}
Exemplo n.º 54
0
 protected void WaitForPeriodicExport(IDatabaseCommands commands, PeriodicExportStatus previousStatus)
 {
     WaitForPeriodicExport(commands.Get, previousStatus);
 }
Exemplo n.º 55
0
 private static IDatabaseCommands SetupCommands(IDatabaseCommands databaseCommands, string database, ICredentials credentialsForSession, OpenSessionOptions options)
 {
     if (database != null)
         databaseCommands = databaseCommands.ForDatabase(database);
     if (credentialsForSession != null)
         databaseCommands = databaseCommands.With(credentialsForSession);
     if (options.ForceReadFromMaster)
         databaseCommands.ForceReadFromMaster();
     return databaseCommands;
 }
Exemplo n.º 56
0
 protected void WaitForBackup(IDatabaseCommands commands, bool checkError)
 {
     WaitForBackup(commands.Get, checkError);
 }
Exemplo n.º 57
0
		/// <summary>
		/// Generates the document key.
		/// </summary>
		/// <param name="convention">The convention.</param>
		/// <param name="entity">The entity.</param>
		/// <returns></returns>
		public string GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention convention, object entity)
		{
			return GetDocumentKeyFromId(convention, NextId(databaseCommands));
		}
Exemplo n.º 58
0
        protected void WaitForRestore(IDatabaseCommands databaseCommands)
        {
            var systemDatabaseCommands = databaseCommands.ForSystemDatabase(); // need to be sure that we are checking system database

            var failureMessages = new[]
            {
                                      "Esent Restore: Failure! Could not restore database!", 
                                      "Error: Restore Canceled", 
                                      "Restore Operation: Failure! Could not restore database!"
                                  };

            var restoreFinishMessages = new[]
                {
                    "The new database was created",
                    "Esent Restore: Restore Complete", 
                    "Restore ended but could not create the datebase document, in order to access the data create a database with the appropriate name",
                };

            var done = SpinWait.SpinUntil(() =>
            {
                // We expect to get the doc from the <system> database
                var doc = systemDatabaseCommands.Get(RestoreStatus.RavenRestoreStatusDocumentKey);

                if (doc == null)
                    return false;

                var status = doc.DataAsJson.Deserialize<RestoreStatus>(new DocumentConvention());

                if (failureMessages.Any(status.Messages.Contains))
                    throw new InvalidOperationException("Restore failure: " + status.Messages.Aggregate(string.Empty, (output, message) => output + (message + Environment.NewLine)));

                return restoreFinishMessages.Any(status.Messages.Contains);
            }, TimeSpan.FromMinutes(5));

            if (!done) throw new Exception("WaitForRestore failed");
        }
Exemplo n.º 59
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MultiTypeHiLoKeyGenerator"/> class.
		/// </summary>
		public MultiTypeHiLoKeyGenerator(IDatabaseCommands databaseCommands, int capacity)
		{
			this.databaseCommands = databaseCommands;
			this.capacity = capacity;
		}
Exemplo n.º 60
0
		private RangeValue GetNextRange(IDatabaseCommands databaseCommands)
		{
#if !NETFX_CORE
			using (new TransactionScope(TransactionScopeOption.Suppress))
			{
#endif
				ModifyCapacityIfRequired();
				while (true)
				{
					try
					{
						var minNextMax = Range.Max;
						JsonDocument document;

						try
						{
							document = GetDocument(databaseCommands);
						}
						catch (ConflictException e)
						{
							// resolving the conflict by selecting the highest number
							var highestMax = e.ConflictedVersionIds
								.Select(conflictedVersionId => GetMaxFromDocument(databaseCommands.Get(conflictedVersionId), minNextMax))
								.Max();

							PutDocument(databaseCommands, new JsonDocument
							{
								Etag = e.Etag,
								Metadata = new RavenJObject(),
								DataAsJson = RavenJObject.FromObject(new { Max = highestMax }),
								Key = HiLoDocumentKey
							});

							continue;
						}

						long min, max;
						if (document == null)
						{
							min = minNextMax + 1;
							max = minNextMax + capacity;
							document = new JsonDocument
							{
								Etag = Etag.Empty,
								// sending empty etag means - ensure the that the document does NOT exists
								Metadata = new RavenJObject(),
								DataAsJson = RavenJObject.FromObject(new { Max = max }),
								Key = HiLoDocumentKey
							};
						}
						else
						{
							var oldMax = GetMaxFromDocument(document, minNextMax);
							min = oldMax + 1;
							max = oldMax + capacity;

							document.DataAsJson["Max"] = max;
						}
						PutDocument(databaseCommands, document);

						return new RangeValue(min, max);
					}
					catch (ConcurrencyException)
					{
						// expected, we need to retry
					}
				}
#if !NETFX_CORE
			}
#endif
		}