Beispiel #1
0
        public bool EntityChanged(FileHeader fileHeader)
        {
            if (fileHeader == null)
                return true;

            return RavenJToken.DeepEquals(fileHeader.Metadata, fileHeader.OriginalMetadata, null) == false;
        }
Beispiel #2
0
        private static void EnsurePreviousValueMatchCurrentValue(PatchRequest patchCmd, RavenJToken property)
        {
            var prevVal = patchCmd.PrevVal;

            if (prevVal == null)
            {
                return;
            }
            switch (prevVal.Type)
            {
            case JTokenType.Undefined:
                if (property != null)
                {
                    throw new ConcurrencyException();
                }
                break;

            default:
                if (property == null)
                {
                    throw new ConcurrencyException();
                }
                if (RavenJToken.DeepEquals(property, prevVal) == false)
                {
                    throw new ConcurrencyException();
                }
                break;
            }
        }
Beispiel #3
0
        private static void EnsurePreviousValueMatchCurrentValue(PatchRequest patchCmd, RavenJToken property)
        {
            var prevVal = patchCmd.PrevVal;

            if (prevVal == null || prevVal.Type == JTokenType.Null)
            {
                return;
            }

            switch (prevVal.Type)
            {
            case JTokenType.Undefined:
                if (property != null)
                {
                    throw new OptimisticConcurrencyViolationException(
                              $"Previous value is {prevVal} (type: undefined) but new value is {property} (type: {property.Type})");
                }
                break;

            default:
                if (property == null)
                {
                    throw new OptimisticConcurrencyViolationException(
                              $"Previous value is {prevVal} (type: {prevVal.Type}) but new value is null");
                }
                if (RavenJToken.DeepEquals(property, prevVal) == false)
                {
                    throw new OptimisticConcurrencyViolationException(
                              $"Previous value is {prevVal} (type: {prevVal.Type}) " +
                              $"but expected value is {property} (type: {property.Type})");
                }
                break;
            }
        }
Beispiel #4
0
        public void SmugglerTransformShouldRecognizeNumericPropertiesEvenThoughTheyHaveTheSameNames()
        {
            var helper = new SmugglerJintHelper();

            helper.Initialize(new SmugglerOptions
            {
                TransformScript = emptyTransform
            });

            var testObject = new RavenJObject
            {
                { "Range", new RavenJArray {
                      new RavenJObject {
                          { "Min", 2.4 }
                      }
                  } },
                { "Min", 1 }
            };

            var transformedObject = helper.Transform(emptyTransform, testObject);

            Assert.Equal(testObject["Min"].Type, transformedObject["Min"].Type);
            Assert.Equal(((RavenJObject)((RavenJArray)testObject["Range"])[0])["Min"].Type, ((RavenJObject)((RavenJArray)transformedObject["Range"])[0])["Min"].Type);

            Assert.True(RavenJToken.DeepEquals(testObject, transformedObject));
        }
Beispiel #5
0
        private bool IsTheSameDocument(JsonDocument doc, JsonDocument existingDoc)
        {
            if (existingDoc == null)
            {
                return(false);
            }

            if (RavenJToken.DeepEquals(doc.DataAsJson, existingDoc.DataAsJson) == false)
            {
                return(false);
            }

            var existingMetadata = (RavenJObject)existingDoc.Metadata.CloneToken();
            var newMetadata      = (RavenJObject)doc.Metadata.CloneToken();

            // in order to compare metadata we need to remove metadata records created by triggers
            foreach (var trigger in Database.PutTriggers)
            {
                var metadataToIgnore = trigger.Value.GeneratedMetadataNames;

                if (metadataToIgnore == null)
                {
                    continue;
                }

                foreach (var toIgnore in metadataToIgnore)
                {
                    existingMetadata.Remove(toIgnore);
                    newMetadata.Remove(toIgnore);
                }
            }

            return(RavenJToken.DeepEquals(newMetadata, existingMetadata));
        }
Beispiel #6
0
		/// <summary>
		/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
		/// </summary>
		/// <returns>
		/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
		/// </returns>
		/// <param name="other">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>. </param><filterpriority>2</filterpriority>
		public override bool Equals(object other)
		{
			var dynamicJsonObject = other as DynamicJsonObject;
			if (dynamicJsonObject != null)
				return RavenJToken.DeepEquals(inner, dynamicJsonObject.inner);
			return base.Equals(other);
		}
Beispiel #7
0
        public async Task SmugglerTransformShouldRecognizeNumericPropertiesEvenThoughTheyHaveTheSameNames()
        {
            using (var stream = new MemoryStream())
            {
                var testObject = new RavenJObject
                {
                    { "Range", new RavenJArray {
                          new RavenJObject {
                              { "Min", 2.4 }
                          }
                      } },
                    { "Min", 1 }
                };

                using (var store = NewDocumentStore())
                {
                    store.DatabaseCommands.Put("docs/1", null, testObject, new RavenJObject());

                    var smuggler = new DatabaseDataDumper(store.DocumentDatabase, new SmugglerDatabaseOptions
                    {
                        TransformScript = EmptyTransform
                    });

                    await smuggler.ExportData(new SmugglerExportOptions <RavenConnectionStringOptions>
                    {
                        From = new EmbeddedRavenConnectionStringOptions
                        {
                            DefaultDatabase = store.DefaultDatabase
                        },
                        ToStream = stream
                    });
                }

                stream.Position = 0;

                using (var store = NewDocumentStore())
                {
                    var smuggler = new DatabaseDataDumper(store.DocumentDatabase, new SmugglerDatabaseOptions
                    {
                        TransformScript = EmptyTransform
                    });

                    await smuggler.ImportData(new SmugglerImportOptions <RavenConnectionStringOptions>
                    {
                        FromStream = stream,
                        To         = new EmbeddedRavenConnectionStringOptions
                        {
                            DefaultDatabase = store.DefaultDatabase
                        }
                    });

                    var doc = store.DatabaseCommands.Get("docs/1").DataAsJson;
                    Assert.NotNull(doc);
                    Assert.Equal(testObject["Min"].Type, doc["Min"].Type);
                    Assert.Equal(((RavenJObject)((RavenJArray)testObject["Range"])[0])["Min"].Type, ((RavenJObject)((RavenJArray)doc["Range"])[0])["Min"].Type);

                    Assert.True(RavenJToken.DeepEquals(testObject, doc));
                }
            }
        }
Beispiel #8
0
        internal bool UpdateKey(RavenJToken key, Guid txId)
        {
            Guid existing;

            if (keysModifiedInTx.TryGetValue(key, out existing) && existing != txId)
            {
                return(false);
            }

            var readResult = Read(key, txId);

            if (readResult != null && RavenJToken.DeepEquals(key, readResult.Key))
            {
                return(true);                // no need to do anything, user wrote the same data as is already in, hence, no op
            }
            operationsInTransactions.GetOrAdd(txId, new List <Command>())
            .Add(new Command
            {
                Key          = key,
                Position     = readResult == null ? -1 : readResult.Position,
                Size         = readResult == null ? 0 : readResult.Size,
                DictionaryId = TableId,
                Type         = CommandType.Put
            });

            if (existing != txId)             // otherwise we are already there
            {
                keysModifiedInTx.TryAdd(key, txId);
            }

            return(true);
        }
Beispiel #9
0
        /// <summary>
        /// Determines if the entity have changed.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="documentMetadata">The document metadata.</param>
        /// <returns></returns>
        protected bool EntityChanged(object entity, DocumentMetadata documentMetadata)
        {
            if (documentMetadata == null)
            {
                return(true);
            }

            string id;

            if (TryGetIdFromInstance(entity, out id) &&
                string.Equals(documentMetadata.Key, id, StringComparison.InvariantCultureIgnoreCase) == false)
            {
                return(true);
            }

            // prevent saves of a modified read only entity
            if (documentMetadata.OriginalMetadata.ContainsKey(Constants.RavenReadOnly) &&
                documentMetadata.OriginalMetadata.Value <bool>(Constants.RavenReadOnly) &&
                documentMetadata.Metadata.ContainsKey(Constants.RavenReadOnly) &&
                documentMetadata.Metadata.Value <bool>(Constants.RavenReadOnly))
            {
                return(false);
            }

            var newObj = ConvertEntityToJson(entity, documentMetadata.Metadata);

            return(RavenJToken.DeepEquals(newObj, documentMetadata.OriginalValue) == false ||
                   RavenJToken.DeepEquals(documentMetadata.Metadata, documentMetadata.OriginalMetadata) == false);
        }
Beispiel #10
0
        private static bool IsNotModified(RavenJToken patchedDocClone, RavenJToken existingDocClone)
        {
            patchedDocClone.Value <RavenJObject>(Constants.Metadata).Remove(Constants.LastModified);
            existingDocClone.Value <RavenJObject>(Constants.Metadata).Remove(Constants.LastModified);

            return(RavenJToken.DeepEquals(patchedDocClone, existingDocClone));
        }
Beispiel #11
0
        public void RavenJToken_DeepEquals_Array_Test()
        {
            var original = new { Tokens = new[] { "Token-1", "Token-2", "Token-3" } };
            var modified = new { Tokens = new[] { "Token-1", "Token-3" } };

            // In modified object we deleted one item "Token-2"

            var difference = new List <DocumentsChanges>();

            if (!RavenJToken.DeepEquals(RavenJObject.FromObject(modified), RavenJObject.FromObject(original), difference))
            {
                // OK
                // 1 difference - "Token-2" value removed
            }

            // Expecting one difference - "Token-2" ArrayValueRemoved
            Assert.True(difference.Count == 1 && difference.SingleOrDefault(x => x.Change == DocumentsChanges.ChangeType.ArrayValueRemoved &&
                                                                            x.FieldOldValue == "Token-2") != null);

            var originalDoc = new Doc {
                Names = new List <PersonName> {
                    new PersonName {
                        Name = "Tom1"
                    }, new PersonName {
                        Name = "Tom2"
                    }, new PersonName {
                        Name = "Tom3"
                    }
                }
            };
            var modifiedDoc = new Doc {
                Names = new List <PersonName> {
                    new PersonName {
                        Name = "Tom1"
                    }, new PersonName {
                        Name = "Tom3"
                    }
                }
            };

            // In modified object we deleted one item "Tom2"

            difference = new List <DocumentsChanges>();
            if (!RavenJToken.DeepEquals(RavenJObject.FromObject(modifiedDoc), RavenJObject.FromObject(originalDoc), difference))
            {
                // SOMETHING WRONG?
                // 3 differences - "Tom1", "Tom2", "Tom3" objects removed
            }

            // Expecting one difference - "Tom2" ArrayValueRemoved
            Assert.True(difference.Count == 1 && difference.SingleOrDefault(x => x.Change == DocumentsChanges.ChangeType.ArrayValueRemoved &&
                                                                            x.FieldOldValue == "{\r\n  \"Name\": \"Tom2\"\r\n}") != null);
        }
Beispiel #12
0
        private static bool MatchCriteria(SubscriptionCriteria criteria, JsonDocument doc)
        {
            if (criteria.BelongsToAnyCollection != null &&
                criteria.BelongsToAnyCollection.Contains(doc.Metadata.Value <string>(Constants.RavenEntityName), StringComparer.InvariantCultureIgnoreCase) == false)
            {
                return(false);
            }

            if (criteria.KeyStartsWith != null && doc.Key.StartsWith(criteria.KeyStartsWith) == false)
            {
                return(false);
            }

            if (criteria.PropertiesMatch != null)
            {
                foreach (var match in criteria.PropertiesMatch)
                {
                    var tokens = doc.DataAsJson.SelectTokenWithRavenSyntaxReturningFlatStructure(match.Key).Select(x => x.Item1).ToArray();

                    foreach (var curVal in tokens)
                    {
                        if (RavenJToken.DeepEquals(curVal, match.Value) == false)
                        {
                            return(false);
                        }
                    }

                    if (tokens.Length == 0)
                    {
                        return(false);
                    }
                }
            }

            if (criteria.PropertiesNotMatch != null)
            {
                foreach (var match in criteria.PropertiesNotMatch)
                {
                    var tokens = doc.DataAsJson.SelectTokenWithRavenSyntaxReturningFlatStructure(match.Key).Select(x => x.Item1).ToArray();

                    foreach (var curVal in tokens)
                    {
                        if (RavenJToken.DeepEquals(curVal, match.Value) == true)
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
        private static bool MatchCriteria(SubscriptionCriteria criteria, JsonDocument doc)
        {
            if (criteria.BelongsToAnyCollection != null &&
                criteria.BelongsToAnyCollection.Contains(doc.Metadata.Value <string>(Constants.RavenEntityName), StringComparer.InvariantCultureIgnoreCase) == false)
            {
                return(false);
            }

            if (criteria.KeyStartsWith != null && doc.Key.StartsWith(criteria.KeyStartsWith) == false)
            {
                return(false);
            }

            if (criteria.PropertiesMatch != null)
            {
                foreach (var match in criteria.PropertiesMatch)
                {
                    var value = doc.DataAsJson.SelectToken(match.Key);

                    if (value == null)
                    {
                        return(false);
                    }

                    if (RavenJToken.DeepEquals(value, match.Value) == false)
                    {
                        return(false);
                    }
                }
            }

            if (criteria.PropertiesNotMatch != null)
            {
                foreach (var notMatch in criteria.PropertiesNotMatch)
                {
                    var value = doc.DataAsJson.SelectToken(notMatch.Key);

                    if (value != null)
                    {
                        if (RavenJToken.DeepEquals(value, notMatch.Value))
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Beispiel #14
0
        public void DeepEqualsWorksWithTimeSpan()
        {
            var content = new MusicContent
            {
                Title = String.Format("Song # {0}", 1),
                Album = String.Format("Album # {0}", 1)
            };

            content.Keywords.Add("new");

            var obj    = RavenJToken.FromObject(content);
            var newObj = RavenJToken.FromObject(content);

            Assert.True(RavenJToken.DeepEquals(obj, newObj));
        }
Beispiel #15
0
        private void RemoveValue(PatchRequest patchCmd, string propName, RavenJToken token)
        {
            EnsurePreviousValueMatchCurrentValue(patchCmd, token);
            if (token == null)
            {
                token = new RavenJArray();
                document[propName] = token;
            }
            var array = GetArray(token, propName);

            if (array.IsSnapshot)
            {
                array = new RavenJArray(array);
                document[propName] = array;
            }

            var position = patchCmd.Position;
            var value    = patchCmd.Value;

            if (position == null && (value == null || value.Type == JTokenType.Null))
            {
                throw new InvalidOperationException("Cannot remove value from  '" + propName + "' because position element does not exists or not an integer and no value was present");
            }
            if (position != null && value != null && value.Type != JTokenType.Null)
            {
                throw new InvalidOperationException("Cannot remove value from  '" + propName + "' because both a position and a value are set");
            }
            if (position != null && (position.Value < 0 || position.Value >= array.Length))
            {
                throw new IndexOutOfRangeException("Cannot remove value from  '" + propName +
                                                   "' because position element is out of bound bounds");
            }

            if (value != null && value.Type != JTokenType.Null)
            {
                foreach (var ravenJToken in array.Where(x => RavenJToken.DeepEquals(x, value)).ToList())
                {
                    array.Remove(ravenJToken);
                }

                return;
            }

            if (position != null)
            {
                array.RemoveAt(position.Value);
            }
        }
Beispiel #16
0
        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);
        }
Beispiel #17
0
        internal static async Task AfterExecuteAsync(IAsyncDatabaseCommands asyncDatabaseCommands, string indexName, ScriptedIndexResults scripts, CancellationToken token)
        {
            var documentId = GetScriptedIndexResultsDocumentId(indexName);

            scripts.Id = documentId;

            var oldDocument = await asyncDatabaseCommands.GetAsync(documentId, token).ConfigureAwait(false);

            var newDocument = RavenJObject.FromObject(scripts);

            if (oldDocument != null && RavenJToken.DeepEquals(oldDocument.DataAsJson, newDocument))
            {
                return;
            }

            await asyncDatabaseCommands.PutAsync(documentId, null, newDocument, null, token).ConfigureAwait(false);

            await asyncDatabaseCommands.ResetIndexAsync(indexName, token).ConfigureAwait(false);
        }
Beispiel #18
0
        /// <summary>
        /// Determines if the entity have changed.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="documentMetadata">The document metadata.</param>
        /// <returns></returns>
        protected bool EntityChanged(object entity, DocumentMetadata documentMetadata)
        {
            if (documentMetadata == null)
            {
                return(true);
            }

            // prevent saves of a modified read only entity
            if (documentMetadata.OriginalMetadata.ContainsKey(Constants.RavenReadOnly) &&
                documentMetadata.OriginalMetadata.Value <bool>(Constants.RavenReadOnly) &&
                documentMetadata.Metadata.ContainsKey(Constants.RavenReadOnly) &&
                documentMetadata.Metadata.Value <bool>(Constants.RavenReadOnly))
            {
                return(false);
            }

            var newObj = ConvertEntityToJson(entity, documentMetadata.Metadata);

            return(RavenJToken.DeepEquals(newObj, documentMetadata.OriginalValue) == false ||
                   RavenJToken.DeepEquals(documentMetadata.Metadata, documentMetadata.OriginalMetadata) == false);
        }
 private static bool HasAnyReferencedPropertyChanged(RavenJObject original, RavenJObject current, UpdateCascadeSetting setting)
 {
     return(setting.DenormalizedReferencePropertyNames.Any(pn => !RavenJToken.DeepEquals(original[pn], current[pn])));
 }