Esempio n. 1
0
        public void CloningTestsWorksCorrectly()
        {
            var f = new RavenJObject();

            f["1"] = new RavenJValue(1);
            f["2"] = new RavenJValue(2);

            var f1 = (RavenJObject)f.CloneToken();

            f1["2"] = new RavenJValue(3);

            var val = (RavenJValue)f["2"];

            Assert.Equal(2, val.Value);
            val = (RavenJValue)f1["2"];
            Assert.Equal(3, val.Value);

            var f2 = (RavenJObject)f1.CloneToken();

            val = (RavenJValue)f2["2"];
            Assert.Equal(3, val.Value);

            f["2"] = f2;
            f1     = (RavenJObject)f.CloneToken();
            f.Remove("2");
            Assert.Null(f["2"]);
            Assert.NotNull(f1["2"]);
        }
Esempio n. 2
0
        public PatchResultData ApplyPatch(string docId, Etag etag,
                                          PatchRequest[] patchExistingDoc, PatchRequest[] patchDefaultDoc, RavenJObject defaultMetadata,
                                          TransactionInformation transactionInformation, bool debugMode = false, bool skipPatchIfEtagMismatch = false,
                                          IEnumerable <string> participatingIds = null)
        {
            if (docId == null)
            {
                throw new ArgumentNullException("docId");
            }
            return(ApplyPatchInternal(docId, etag, transactionInformation,
                                      jsonDoc => new JsonPatcher(jsonDoc.ToJson()).Apply(patchExistingDoc),
                                      () =>
            {
                if (patchDefaultDoc == null || patchDefaultDoc.Length == 0)
                {
                    return null;
                }

                var jsonDoc = new RavenJObject();
                jsonDoc[Constants.Metadata] = defaultMetadata.CloneToken() ?? new RavenJObject();
                return new JsonPatcher(jsonDoc).Apply(patchDefaultDoc);
            },
                                      () => null,
                                      () => null,
                                      debugMode,
                                      skipPatchIfEtagMismatch,
                                      participatingIds));
        }
Esempio n. 3
0
        public Tuple <PatchResultData, List <string> > ApplyPatch(string docId, Etag etag,
                                                                  ScriptedPatchRequest patchExisting, ScriptedPatchRequest patchDefault, RavenJObject defaultMetadata,
                                                                  TransactionInformation transactionInformation, bool debugMode = false, IEnumerable <string> participatingIds = null)
        {
            ScriptedJsonPatcher scriptedJsonPatcher        = null;
            DefaultScriptedJsonPatcherOperationScope scope = null;

            try
            {
                var applyPatchInternal = ApplyPatchInternal(docId, etag, transactionInformation,
                                                            jsonDoc =>
                {
                    scope = scope ?? new DefaultScriptedJsonPatcherOperationScope(Database, debugMode);
                    scriptedJsonPatcher = new ScriptedJsonPatcher(Database);
                    return(scriptedJsonPatcher.Apply(scope, jsonDoc.ToJson(), patchExisting, jsonDoc.SerializedSizeOnDisk, jsonDoc.Key));
                },
                                                            () =>
                {
                    if (patchDefault == null)
                    {
                        return(null);
                    }

                    scope = scope ?? new DefaultScriptedJsonPatcherOperationScope(Database, debugMode);

                    scriptedJsonPatcher         = new ScriptedJsonPatcher(Database);
                    var jsonDoc                 = new RavenJObject();
                    jsonDoc[Constants.Metadata] = defaultMetadata.CloneToken() ?? new RavenJObject();
                    return(scriptedJsonPatcher.Apply(scope, jsonDoc, patchDefault, 0, docId));
                },
                                                            () =>
                {
                    if (scope == null)
                    {
                        return(null);
                    }
                    return(scope
                           .GetPutOperations()
                           .ToList());
                },
                                                            () =>
                {
                    if (scope == null)
                    {
                        return(null);
                    }

                    return(scope.DebugActions);
                },
                                                            debugMode, participatingIds: participatingIds);
                return(Tuple.Create(applyPatchInternal, scriptedJsonPatcher == null ? new List <string>() : scriptedJsonPatcher.Debug));
            }
            finally
            {
                if (scope != null)
                {
                    scope.Dispose();
                }
            }
        }
Esempio n. 4
0
        public void SetCachedDocument(string key, Etag etag, RavenJObject doc, RavenJObject metadata, int size)
        {
            if (skipSettingDocumentInCache)
            {
                return;
            }

            var documentClone = ((RavenJObject)doc.CloneToken());

            documentClone.EnsureCannotBeChangeAndEnableSnapshotting();
            var metadataClone = ((RavenJObject)metadata.CloneToken());

            metadataClone.EnsureCannotBeChangeAndEnableSnapshotting();
            try
            {
                cachedSerializedDocuments.Set("Doc/" + key + "/" + etag, new CachedDocument
                {
                    Document = documentClone,
                    Metadata = metadataClone,
                    Size     = size
                }, new CacheItemPolicy
                {
                    SlidingExpiration = configuration.MemoryCacheExpiration,
                });
            }
            catch (OverflowException)
            {
                // this is a bug in the framework
                // http://connect.microsoft.com/VisualStudio/feedback/details/735033/memorycache-set-fails-with-overflowexception-exception-when-key-is-u7337-u7f01-u2117-exception-message-negating-the-minimum-value-of-a-twos-complement-number-is-invalid
                // in this case, we just threat it as uncachable
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Tracks the entity.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <param name="document">The document.</param>
        /// <param name="metadata">The metadata.</param>
        /// <returns></returns>
        public T TrackEntity <T>(string key, RavenJObject document, RavenJObject metadata)
        {
            document.Remove("@metadata");

            object entity;

            if (entitiesByKey.TryGetValue(key, out entity) == false)
            {
                entity = ConvertToEntity <T>(key, document, metadata);
            }
            else
            {
                // the local instance may have been changed, we adhere to the current Unit of Work
                // instance, and return that, ignoring anything new.
                return((T)entity);
            }
            var etag = metadata.Value <string>("@etag");

            if (metadata.Value <bool>("Non-Authoritative-Information") &&
                AllowNonAuthoritativeInformation == false)
            {
                throw new NonAuthoritativeInformationException("Document " + key +
                                                               " returned Non Authoritative Information (probably modified by a transaction in progress) and AllowNonAuthoritativeInformation  is set to false");
            }
            entitiesAndMetadata[entity] = new DocumentMetadata
            {
                OriginalValue    = document,
                Metadata         = metadata,
                OriginalMetadata = (RavenJObject)metadata.CloneToken(),
                ETag             = new Guid(etag),
                Key = key
            };
            entitiesByKey[key] = entity;
            return((T)entity);
        }
Esempio n. 6
0
		public void SetCachedDocument(string key, Etag etag, RavenJObject doc, RavenJObject metadata, int size)
		{
			if (skipSettingDocumentInCache)
				return;

			var documentClone = ((RavenJObject)doc.CloneToken());
			documentClone.EnsureCannotBeChangeAndEnableSnapshotting();
			var metadataClone = ((RavenJObject)metadata.CloneToken());
			metadataClone.EnsureCannotBeChangeAndEnableSnapshotting();
			try
			{
				cachedSerializedDocuments.Set("Doc/" + key + "/" + etag, new CachedDocument
				{
					Document = documentClone,
					Metadata = metadataClone,
					Size = size
				}, new CacheItemPolicy
				{
					SlidingExpiration = configuration.MemoryCacheExpiration,
				});
			}
			catch (OverflowException)
			{
				// this is a bug in the framework
				// http://connect.microsoft.com/VisualStudio/feedback/details/735033/memorycache-set-fails-with-overflowexception-exception-when-key-is-u7337-u7f01-u2117-exception-message-negating-the-minimum-value-of-a-twos-complement-number-is-invalid 
				// in this case, we just threat it as uncachable
			}

		}
        /// <summary>
        /// Tracks the entity.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <param name="document">The document.</param>
        /// <param name="metadata">The metadata.</param>
        /// <returns></returns>
        public T TrackEntity <T>(string key, RavenJObject document, RavenJObject metadata)
        {
            object entity;

            if (entitiesByKey.TryGetValue(key, out entity) == false)
            {
                entity = ConvertToEntity <T>(key, document, metadata);
            }
            else
            {
                // the local instnace may have been changed, we adhere to the current Unit of Work
                // instance, and return that, ignoring anything new.
                return((T)entity);
            }
            var etag = metadata.Value <string>("@etag");

            document.Remove("@metadata");
            entitiesAndMetadata[entity] = new DocumentMetadata
            {
                OriginalValue    = document,
                Metadata         = metadata,
                OriginalMetadata = (RavenJObject)metadata.CloneToken(),
                ETag             = new Guid(etag),
                Key = key
            };
            entitiesByKey[key] = entity;
            return((T)entity);
        }
Esempio n. 8
0
        public FileHeader(string key, RavenJObject metadata)
        {
            this.FullPath         = key;
            this.Metadata         = metadata;
            this.OriginalMetadata = (RavenJObject)metadata.CloneToken();

            SetFileSize();
        }
Esempio n. 9
0
 public void SetCachedDocument(string key, Guid etag, RavenJObject doc, RavenJObject metadata)
 {
     cachedSerializedDocuments["Doc/" + key + "/" + etag] = new CachedDocument
     {
         Document = ((RavenJObject)doc.CloneToken()).EnsureSnapshot(),
         Metadata = ((RavenJObject)metadata.CloneToken()).EnsureSnapshot()
     };
 }
Esempio n. 10
0
        public void SetCachedDocument(string key, Guid etag, RavenJObject doc, RavenJObject metadata)
        {
        	var documentClone = ((RavenJObject)doc.CloneToken());
			documentClone.EnsureSnapshot();
        	var metadataClone = ((RavenJObject)metadata.CloneToken());
			metadataClone.EnsureSnapshot();
        	cachedSerializedDocuments["Doc/" + key + "/" + etag] = new CachedDocument
            {
                Document = documentClone,
                Metadata = metadataClone
            };
        }
Esempio n. 11
0
        public void SetCachedDocument(string key, Guid etag, RavenJObject doc, RavenJObject metadata)
        {
            var documentClone = ((RavenJObject)doc.CloneToken());

            documentClone.EnsureSnapshot();
            var metadataClone = ((RavenJObject)metadata.CloneToken());

            metadataClone.EnsureSnapshot();
            cachedSerializedDocuments["Doc/" + key + "/" + etag] = new CachedDocument
            {
                Document = documentClone,
                Metadata = metadataClone
            };
        }
Esempio n. 12
0
		public void CloningTestsWorksCorrectly()
		{
			var f = new RavenJObject();
			f["1"] = new RavenJValue(1);
			f["2"] = new RavenJValue(2);

			var f1 = (RavenJObject)f.CloneToken();
			f1["2"] = new RavenJValue(3);

			var val = (RavenJValue) f["2"];
			Assert.Equal(2, val.Value);
			val = (RavenJValue)f1["2"];
			Assert.Equal(3, val.Value);

			var f2 = (RavenJObject)f1.CloneToken();
			val = (RavenJValue)f2["2"];
			Assert.Equal(3, val.Value);

			f["2"] = f2;
			f1 = (RavenJObject) f.CloneToken();
			f.Remove("2");
			Assert.Null(f["2"]);
			Assert.NotNull(f1["2"]);
		}
        private static void MergeReplicationHistories(string documentId, RavenJObject origin, RavenJObject external, ref RavenJObject result)
        {
            result = (RavenJObject)origin.CloneToken();
            RavenJToken originHistory;
            RavenJToken externalHisotry;
            var         originHasHistory   = origin.TryGetValue(Constants.RavenReplicationHistory, out originHistory);
            var         externalHasHistory = external.TryGetValue(Constants.RavenReplicationHistory, out externalHisotry);
            RavenJToken externalVersion;
            RavenJToken externalSource;

            //we are going to lose the external source and version if we don't add them here
            if (external.TryGetValue(Constants.RavenReplicationVersion, out externalVersion) &&
                external.TryGetValue(Constants.RavenReplicationSource, out externalSource))
            {
                if (externalHasHistory)
                {
                    externalHisotry = externalHisotry.CloneToken();
                }
                else
                {
                    externalHisotry = new RavenJArray();
                }
                var historyEntry = new RavenJObject();
                historyEntry[Constants.RavenReplicationVersion] = externalVersion;
                historyEntry[Constants.RavenReplicationSource]  = externalSource;
                ((RavenJArray)externalHisotry).Add(historyEntry);
                externalHasHistory = true;
            }
            RavenJArray mergedHistory = null;

            //need to merge histories
            if (originHasHistory)
            {
                mergedHistory = Historian.MergeReplicationHistories((RavenJArray)originHistory, (RavenJArray)externalHisotry, documentId);
                result[Constants.RavenReplicationMergedHistory] = true;
            }
            else if (externalHasHistory)
            {
                //this might be a snapshot if somehow there was an history but no version or source
                mergedHistory = (RavenJArray)(externalHisotry.IsSnapshot? externalHisotry.CloneToken(): externalHisotry);
            }

            //if the original has history and the external didn't we already cloned it.
            if (mergedHistory != null)
            {
                result[Constants.RavenReplicationHistory] = mergedHistory;
            }
        }
Esempio n. 14
0
        public PatchResultData ApplyPatch(string docId, Etag etag,
                                          PatchRequest[] patchExistingDoc, PatchRequest[] patchDefaultDoc, RavenJObject defaultMetadata,
                                          TransactionInformation transactionInformation, bool debugMode = false)
        {
            if (docId == null)
                throw new ArgumentNullException("docId");
            return ApplyPatchInternal(docId, etag, transactionInformation,
                                      jsonDoc => new JsonPatcher(jsonDoc.ToJson()).Apply(patchExistingDoc),
                                      () =>
                                      {
                                          if (patchDefaultDoc == null || patchDefaultDoc.Length == 0)
                                              return null;

                                          var jsonDoc = new RavenJObject();
                                          jsonDoc[Constants.Metadata] = defaultMetadata.CloneToken() ?? new RavenJObject();
                                          return new JsonPatcher(jsonDoc).Apply(patchDefaultDoc);
                                      },
                                      () => null, debugMode);
        }
Esempio n. 15
0
        public void ShouldBehaveNicelyInMultithreaded()
        {
            var obj = new RavenJObject
                        {
                            {"prop1", 2},
                            {"prop2", "123"}
                        };

            var copy = (RavenJObject)obj.CloneToken() ;
            copy["@id"] = "movies/1";

            Parallel.For(0, 10000, i =>
                                    {
                                        Assert.True(copy.ContainsKey("@id"));
                                        var foo = (RavenJObject)copy.CloneToken();
                                        Assert.True(foo.ContainsKey("@id"));
                                        Assert.True(copy.ContainsKey("@id"));
                                    });
        }
Esempio n. 16
0
        public void ShouldNotFail()
        {
            var root    = new RavenJObject();
            var current = root;

            for (int i = 0; i < 10000; i++)
            {
                var temp = new RavenJObject();
                current.Add("Inner", temp);
                current = temp;
            }

            var anotherRoot = (RavenJObject)root.CloneToken();

            do
            {
                anotherRoot["Inner"] = 0;
            } while ((anotherRoot = anotherRoot["Inner"] as RavenJObject) != null);
        }
Esempio n. 17
0
		public void SetCachedDocument(string key, Guid etag, RavenJObject doc, RavenJObject metadata)
		{
			if (skipSettingDocumentInCache)
				return;

			var documentClone = ((RavenJObject)doc.CloneToken());
			documentClone.EnsureSnapshot();
			var metadataClone = ((RavenJObject)metadata.CloneToken());
			metadataClone.EnsureSnapshot();
			cachedSerializedDocuments.Set("Doc/" + key + "/" + etag, new CachedDocument
			{
				Document = documentClone,
				Metadata = metadataClone
			}, new CacheItemPolicy
			{
				SlidingExpiration = TimeSpan.FromMinutes(5),
			});

		}
Esempio n. 18
0
        public void ShouldBehaveNicelyInMultithreaded()
        {
            var obj = new RavenJObject
            {
                { "prop1", 2 },
                { "prop2", "123" }
            };

            var copy = (RavenJObject)obj.CloneToken();

            copy["@id"] = "movies/1";

            Parallel.For(0, 10000, i =>
            {
                Assert.True(copy.ContainsKey("@id"));
                var foo = (RavenJObject)copy.CloneToken();
                Assert.True(foo.ContainsKey("@id"));
                Assert.True(copy.ContainsKey("@id"));
            });
        }
Esempio n. 19
0
		public void SetCachedDocument(string key, Guid etag, RavenJObject doc, RavenJObject metadata, int size)
		{
			if (skipSettingDocumentInCache)
				return;

			var documentClone = ((RavenJObject)doc.CloneToken());
			documentClone.EnsureSnapshot();
			var metadataClone = ((RavenJObject)metadata.CloneToken());
			metadataClone.EnsureSnapshot();
			cachedSerializedDocuments.Set("Doc/" + key + "/" + etag, new CachedDocument
			{
				Document = documentClone,
				Metadata = metadataClone,
				Size = size
			}, new CacheItemPolicy
			{
				SlidingExpiration = configuration.MemoryCacheExpiration,
			});

		}
Esempio n. 20
0
        /// <summary>
        /// Converts the json document to an entity.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id">The id.</param>
        /// <param name="documentFound">The document found.</param>
        /// <param name="metadata">The metadata.</param>
        /// <returns></returns>
        protected object ConvertToEntity <T>(string id, RavenJObject documentFound, RavenJObject metadata)
        {
            if (typeof(T) == typeof(RavenJObject))
            {
                return((T)(object)documentFound.CloneToken());
            }

            var entity = default(T);

            EnsureNotReadVetoed(metadata);
            var documentType = Conventions.GetClrType(id, documentFound, metadata);

            if (documentType != null)
            {
                var type = Type.GetType(documentType);
                if (type != null)
                {
                    entity = (T)documentFound.Deserialize(type, Conventions);
                }
            }
            if (Equals(entity, default(T)))
            {
                entity = documentFound.Deserialize <T>(Conventions);
#if !NET_3_5
                var document = entity as RavenJObject;
                if (document != null)
                {
                    entity = (T)(object)(new DynamicJsonObject(document));
                }
#endif
            }
            TrySetIdentity(entity, id);

            foreach (var documentConversionListener in listeners.ConversionListeners)
            {
                documentConversionListener.DocumentToEntity(entity, documentFound, metadata);
            }

            return(entity);
        }
Esempio n. 21
0
        public void SetCachedDocument(string key, Guid etag, RavenJObject doc, RavenJObject metadata)
        {
            if (skipSettingDocumentInCache)
            {
                return;
            }

            var documentClone = ((RavenJObject)doc.CloneToken());

            documentClone.EnsureSnapshot();
            var metadataClone = ((RavenJObject)metadata.CloneToken());

            metadataClone.EnsureSnapshot();
            cachedSerializedDocuments.Set("Doc/" + key + "/" + etag, new CachedDocument
            {
                Document = documentClone,
                Metadata = metadataClone
            }, new CacheItemPolicy
            {
                SlidingExpiration = configuration.MemoryCacheExpiration,
            });
        }
Esempio n. 22
0
 public FileHeader( string key, RavenJObject metadata )
 {
     this.FullPath = key;            
     this.Metadata = metadata;
     this.OriginalMetadata = (RavenJObject)metadata.CloneToken();
     
     SetFileSize();
 }
Esempio n. 23
0
		public Tuple<PatchResultData, List<string>> ApplyPatch(string docId, Etag etag,
															   ScriptedPatchRequest patchExisting, ScriptedPatchRequest patchDefault, RavenJObject defaultMetadata,
															   TransactionInformation transactionInformation, bool debugMode = false)
		{
			ScriptedJsonPatcher scriptedJsonPatcher = null;
			DefaultScriptedJsonPatcherOperationScope scope = null;

			try
			{
				var applyPatchInternal = ApplyPatchInternal(docId, etag, transactionInformation,
					jsonDoc =>
					{
						scope = scope ?? new DefaultScriptedJsonPatcherOperationScope(Database, debugMode);
						scriptedJsonPatcher = new ScriptedJsonPatcher(Database);
						return scriptedJsonPatcher.Apply(scope, jsonDoc.ToJson(), patchExisting, jsonDoc.SerializedSizeOnDisk, jsonDoc.Key);
					},
					() =>
					{
						if (patchDefault == null)
							return null;

						scope = scope ?? new DefaultScriptedJsonPatcherOperationScope(Database, debugMode);

						scriptedJsonPatcher = new ScriptedJsonPatcher(Database);
						var jsonDoc = new RavenJObject();
						jsonDoc[Constants.Metadata] = defaultMetadata.CloneToken() ?? new RavenJObject();
						return scriptedJsonPatcher.Apply(scope, jsonDoc, patchDefault, 0, docId);
					},
					() =>
					{
						if (scope == null)
							return null;
						return scope
							.GetPutOperations()
							.ToList();
					},
					() =>
					{
						if (scope == null)
							return null;

						return scope.DebugActions;
					},
					debugMode);
				return Tuple.Create(applyPatchInternal, scriptedJsonPatcher == null ? new List<string>() : scriptedJsonPatcher.Debug);
			}
			finally
			{
				if (scope != null)
					scope.Dispose();
			}
		}
Esempio n. 24
0
		public void ShouldNotFail()
		{
			var root = new RavenJObject();
			var current = root;
			for (int i = 0; i < 10000; i++)
			{
				var temp = new RavenJObject();
				current.Add("Inner", temp);
				current = temp;
			}

			var anotherRoot = (RavenJObject)root.CloneToken();
			do
			{
				anotherRoot["Inner"] = 0;
			} while ((anotherRoot = anotherRoot["Inner"] as RavenJObject) != null);
		}