public void TestDiffDocuments()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var jdp = new JsonDiffPatch();

            var person1       = new Person("Tord", "Yvel");
            var person1Jtoken = JToken.FromObject(person1);

            var person2       = new Person("Tord", "Yvels");
            var person2Jtoken = JToken.FromObject(person2);

            var person3       = new Person("Romeo", "Olsson");
            var person3Jtoken = JToken.FromObject(person3);

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            JToken patch1       = jdp.Diff(person1Jtoken, person2Jtoken);
            JToken patch2       = jdp.Diff(person2Jtoken, person3Jtoken);
            var    unpatch2     = jdp.Unpatch(person3Jtoken, patch2);
            var    restoredVer2 = unpatch2.ToObject(typeof(Person));
            var    unpatch1     = jdp.Unpatch(unpatch2, patch1);
            var    restoredVer1 = unpatch1.ToObject(typeof(Person));

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            restoredVer1.Should().BeEquivalentTo(person1);
            restoredVer2.Should().BeEquivalentTo(person2);
        }
Beispiel #2
0
        private bool UpdateVersionedObservationObject(VersionedDocumentObservation <T> versionedObservation, T updatedObservation)
        {
            var    previousVersionNumber = versionedObservation.Version;
            JToken jtokenCurrentDoc      = versionedObservation.Current == null
                ? JToken.Parse("{}")
                : JToken.FromObject(versionedObservation.Current);

            JToken diff = _jdp.Diff(jtokenCurrentDoc, JToken.FromObject(updatedObservation));

            if (diff == null)
            {
                return(false);              // no change
            }
            versionedObservation.Current = updatedObservation;
            VersionHistory versionHistory = new VersionHistory(diff.ToString(Formatting.None))
            {
                Version = previousVersionNumber,
                UtcDate = versionedObservation.UtcDate,
                Type    = versionedObservation.Type,
            };

            versionedObservation.UtcDate = DateTime.UtcNow;
            versionedObservation.Prev.Add(versionHistory);
            versionedObservation.Version   = previousVersionNumber + 1;
            versionedObservation.IsDeleted = false;
            versionedObservation.Type      = updatedObservation.GetType().ToString();
            return(true);
        }
Beispiel #3
0
        public void Format_EmptyDiffIsEmpty_Success()
        {
            var left       = JObject.Parse(@"{}");
            var right      = JObject.Parse(@"{}");
            var patch      = Differ.Diff(left, right);
            var operations = Formatter.Format(patch);

            Assert.AreEqual(0, operations.Count);
        }
        public async Task <VersionedDocument <T> > InsertDocumentAsync(
            ObjectId objectId,
            T doc)
        {
            VersionedDocument <T> currentDocument = null;

            if (objectId != ObjectId.Empty)
            {
                currentDocument = await(await Collection.FindAsync(x => x.Id == objectId)).FirstOrDefaultAsync();
            }

            if (currentDocument == null)
            {
                var versionedDoc = new VersionedDocument <T>(doc);
                Collection.InsertOne(versionedDoc);
                return(versionedDoc);
            }

            var    previousVersionNumber = currentDocument.Version;
            JToken jtokenCurrentDoc      = currentDocument.Current == null
                ? JToken.Parse("{}")
                : JToken.FromObject(currentDocument.Current);

            JToken diff = _jdp.Diff(jtokenCurrentDoc, JToken.FromObject(doc));

            if (diff == null)
            {
                return(null);              // no change
            }
            currentDocument.Current = doc;
            VersionHistory versionHistory = new VersionHistory(diff.ToString(Formatting.None))
            {
                Version = previousVersionNumber,
                UtcDate = currentDocument.UtcDate,
                Type    = currentDocument.Type
            };

            currentDocument.UtcDate = DateTime.UtcNow;
            currentDocument.Prev.Add(versionHistory);
            currentDocument.Version   = previousVersionNumber + 1;
            currentDocument.IsDeleted = false;
            currentDocument.Type      = doc.GetType().ToString();
            var result = Collection.ReplaceOne(item => item.Id == objectId, currentDocument);

            if (result.ModifiedCount != 1) // the number of modified documents
            {
                // print("Someone must have gotten there first, re-fetch the new document, try again");
                // todo - är det här något som kan uppstå?
            }

            return(null);
        }
Beispiel #5
0
        public Task Publish <T, TClean>(Result <T, TClean> result)
        {
            // only care about sensitive data results
            if (typeof(T) != typeof(IEnumerable <DataWithSomeSensitiveStuff>))
            {
                return(Task.CompletedTask);
            }

            Log($"Publishing results for experiment '{result.ExperimentName}'");
            Log("Context:");
            foreach (var(key, value) in result.Contexts)
            {
                Log($"{key}: {value}");
            }
            Log($"Result: {(result.Matched ? "MATCH" : "MISMATCH")}");
            Log($"Control duration: {result.Control.Duration}");

            foreach (var observation in result.Candidates)
            {
                var jdp = new JsonDiffPatch();
                Log($"Candidate name: {observation.Name}");
                Log($"Candidate duration: {observation.Duration}");
                Log($"Candidate diff:");
                Log(jdp.Diff(Serialize(result.Control.CleanedValue), Serialize(observation.CleanedValue)));
            }

            return(Task.FromResult(0));
        }
        public void Run(string inputFileName, string outputFileName)
        {
            TestCaseCollection testCaseCollection = JsonConvert.DeserializeObject <TestCaseCollection>(File.ReadAllText(inputFileName));

            _testOutputHelper?.WriteLine($"file: '{inputFileName}' found with {testCaseCollection.TestCases.Length} test cases");

            foreach (var testCase in testCaseCollection.TestCases)
            {
                _testOutputHelper?.WriteLine($"\n\n\nRunning test case : '{testCase.TestCaseName}' with params: " +
                                             $"{string.Join(", ", testCase.Params)}");



                int exitCode = _appRunner.Run(testCase.Params);

                exitCode.Should().Be(testCase.ExpectedExitCode, $"app should return {testCase.ExpectedExitCode} exit code");

                if (testCase.ValidateOutputJson)
                {
                    JsonDiffPatch jsonDiffPatch = new JsonDiffPatch();

                    var diff = jsonDiffPatch.Diff(testCase.ExpectedOutput.ToString(), File.ReadAllText(outputFileName));

                    _testOutputHelper?.WriteLine(diff != null ? $"diff found : {diff}" : "no diff found");

                    diff.Should().BeNull();

                    _testOutputHelper?.WriteLine($"test case '{testCase.TestCaseName}' passed");
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Return the comparison of the 2 Jsons based on the data received by parameter
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ResultDiff GetDiff(Data data)
        {
            // Decode the Jsons
            byte[] leftJsonByte  = Convert.FromBase64String(data.LeftSide);
            byte[] rightJsonByte = Convert.FromBase64String(data.RightSide);
            var    leftJson      = Encoding.UTF8.GetString(leftJsonByte);
            var    rightJson     = Encoding.UTF8.GetString(rightJsonByte);

            var result = new ResultDiff(); // Creates an object to manipulate the result of the comparison

            // Validates if the both Jsons are equal
            if (leftJson.SequenceEqual(rightJson))
            {
                result.AreEqual = true; // add the value into the object indicating that the Jsons are equal
                result.SameSize = true; // add the value into the object indicating that the Jsons have the same size
            }
            else
            {
                // Validate if the Jsons have the same size
                if (leftJsonByte.Length.Equals(rightJsonByte.Length))
                {
                    result.SameSize = true;                                         // add the value into the object indicating that the Jsons have the same size
                }
                var diffPatch = new JsonDiffPatch();                                // Creates an object of a nuget package extension responsible for compare the Jsons
                var diffObj   = JObject.Parse(diffPatch.Diff(leftJson, rightJson)); // Get the difference between the Jsons
                result.Diffs = diffObj;                                             // Add the differences into the object
            }
            // Add the Size of the Jsons into the object
            result.LetfSize  = leftJson.Length;
            result.RightSize = rightJson.Length;

            return(result); // Return the result of the comparison
        }
        protected async Task AssertQueryReturnsExpectedDataAsync(string query, [CallerFilePath] string filePath = null, [CallerMemberName] string methodName = null)
        {
            using var result = await Client.PostAsJsonAsync(string.Empty, new { query });

            Assert.AreEqual(System.Net.HttpStatusCode.OK, result.StatusCode);

            Assert.IsNotNull(result.Content);

            var jToken = await result.Content.ReadAsAsync <JToken>();

            Assert.IsNotNull(jToken);
            Assert.IsInstanceOfType(jToken, typeof(JObject));
            var errors = jToken.SelectToken("errors") as JArray;

            Assert.IsNull(errors, errors?.ToString(Formatting.Indented));

            var data = jToken.SelectToken("data") as JObject;

            Assert.IsNotNull(data);

            JToken expected = GetExpectedJson(filePath, methodName);

            var patch = new JsonDiffPatch();

            var diff = patch.Diff(expected, data);

            Assert.IsNull(diff, "Json Had the following differences:\n\n:" + diff?.ToString(Formatting.Indented));
        }
Beispiel #9
0
        public void StructureTest(StructureTestData testData)
        {
            using (var sr = new StringReader(testData.Ftl))
            {
                var  resource     = new Parser().Parse(sr);
                var  resourceJson = AstToJson.ToJson(resource);
                bool resultsEqual = JToken.DeepEquals(resourceJson, testData.Expected);
                if (!resultsEqual)
                {
                    Console.WriteLine("parsed =");
                    Console.WriteLine(resourceJson);
                    Console.WriteLine("expected =");
                    Console.WriteLine(testData.Expected);
                    var jdp  = new JsonDiffPatch();
                    var diff = jdp.Diff(resourceJson, testData.Expected);
                    Console.WriteLine("diff =");
                    Console.WriteLine(diff);
                }
                resultsEqual.Should().BeTrue();

                // doesn't seem to work -- just returns true
                // resourceJson.Should().BeEquivalentTo(testData.Expected,
                //    options => options.AllowingInfiniteRecursion().RespectingRuntimeTypes());
            }
        }
        public void DetermineDelta(FullDeltaReportModel?fullDeltaReportModel)
        {
            _ = fullDeltaReportModel ?? throw new ArgumentNullException(nameof(fullDeltaReportModel));

            logger.LogInformation("Identifying delta for report");

            if (fullDeltaReportModel.DeltaReportSocs != null && fullDeltaReportModel.DeltaReportSocs.Any())
            {
                var jdp = new JsonDiffPatch();

                foreach (var deltaReportSoc in fullDeltaReportModel.DeltaReportSocs.Where(w => w.PublishedJobGroup != null && w.DraftJobGroup != null))
                {
                    var publishedJobGroupToDelta = mapper.Map <JobGroupToDeltaModel>(deltaReportSoc.PublishedJobGroup);
                    var draftJobGroupToDelta     = mapper.Map <JobGroupToDeltaModel>(deltaReportSoc.DraftJobGroup);
                    var published = JToken.Parse(JsonConvert.SerializeObject(publishedJobGroupToDelta));
                    var draft     = JToken.Parse(JsonConvert.SerializeObject(draftJobGroupToDelta));
                    var delta     = jdp.Diff(published, draft);

                    if (delta != null)
                    {
                        deltaReportSoc.Delta = delta.ToString();
                    }
                }
            }

            fullDeltaReportModel.SocImportedCount = fullDeltaReportModel.DeltaReportSocs !.Count;
            fullDeltaReportModel.SocAdditionCount = (from a in fullDeltaReportModel.DeltaReportSocs where a.DraftJobGroup != null && a.PublishedJobGroup == null select a).Count();
            fullDeltaReportModel.SocUpdateCount   = (from a in fullDeltaReportModel.DeltaReportSocs where a.DraftJobGroup != null && a.PublishedJobGroup != null && !string.IsNullOrWhiteSpace(a.Delta) select a).Count();
            fullDeltaReportModel.SocDeletionCount = (from a in fullDeltaReportModel.DeltaReportSocs where a.DraftJobGroup == null && a.PublishedJobGroup != null select a).Count();

            logger.LogInformation($"Imported {fullDeltaReportModel.SocImportedCount} SOCs for report");
            logger.LogInformation($"Identified {fullDeltaReportModel.SocAdditionCount} additions for report");
            logger.LogInformation($"Identified {fullDeltaReportModel.SocUpdateCount} updates for report");
            logger.LogInformation($"Identified {fullDeltaReportModel.SocDeletionCount} deletions for report");
        }
Beispiel #11
0
        public EventRequest <T> Prepare()
        {
            if (Metadata == null)
            {
                Metadata = new ExpandoObject();
            }

            dynamic expando = Data as ExpandoObject;

            if (expando != null)
            {
                var dict = (IDictionary <string, object>)expando;
                if (dict.ContainsKey("new") && dict.ContainsKey("old"))
                {
                    var oldJson = JsonConvert.SerializeObject(dict["old"]);
                    var newJson = JsonConvert.SerializeObject(dict["new"]);
                    if (oldJson == "{}" || newJson == "{}")
                    {
                        return(this);
                    }
                    var oldImage = JToken.Parse(oldJson);
                    var newImage = JToken.Parse(newJson);

                    var diff = _jsonDiffer.Diff(oldImage, newImage);

                    Metadata.diff = diff;
                }
            }
            return(this);
        }
        public void Diff_EfficientArrayDiffHugeArrays_NoStackOverflow()
        {
            const int ARRAY_SIZE = 1000;
            Func <int, int, JToken> hugeArrayFunc = (startIndex, count) =>
            {
                var builder = new StringBuilder("[");
                foreach (var i in Enumerable.Range(startIndex, count))
                {
                    builder.Append($"{i},");
                }
                builder.Append("]");

                return(JToken.Parse(builder.ToString()));
            };

            var jdp   = new JsonDiffPatch();
            var left  = hugeArrayFunc(0, ARRAY_SIZE);
            var right = hugeArrayFunc(ARRAY_SIZE / 2, ARRAY_SIZE);

            JToken diff   = null;
            var    thread = new Thread(() => diff = jdp.Diff(left, right), 128 * 2014);

            thread.Start();
            thread.Join();

            var restored = jdp.Patch(left, diff);

            Assert.That(JToken.DeepEquals(restored, right));
        }
Beispiel #13
0
        public void SimplePatchTest()
        {
            var a1 = new Authentication
            {
                AuthProperties = new Dictionary <string, string>
                {
                    { "Test", "value" }
                }
            };

            var a2 = new Authentication
            {
                AuthProperties = new Dictionary <string, string>
                {
                    { "Test", "value2" }
                }
            };

            var    jdp   = new JsonDiffPatch();
            var    left  = JToken.FromObject(a1);
            var    right = JToken.FromObject(a2);
            JToken patch = jdp.Diff(left, right);

            var output = jdp.Patch(left, patch);

            Assert.Equal(output.ToString(), right.ToString());
        }
        static void Main(string[] args)
        {
            try
            {
                var app1 = new Application();
                var app2 = new Application();
                app2.Name = "moi";
                app2.Date = DateTime.Today;
                app2.InnerData.Roles[1] = "Super admin";
                app2.InnerData.Roles.Add("User");
                app2.AnotherInnerData      = new InnerData();
                app2.AnotherInnerData.Text = "New inner data set";

                var token1 = JToken.FromObject(app1);
                var token2 = JToken.FromObject(app2);

                var diff = new JsonDiffPatch();
                var res  = diff.Diff(token1, token2);

                foreach (var operation in res)
                {
                    var data = JsonConvert.SerializeObject(operation);
                    Console.WriteLine(data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                throw;
            }

            Console.ReadLine();
        }
Beispiel #15
0
        public static Result <T> Merge <T>(this JsonDiffPatch self, T originalObj, T variant1, T variant2)
        {
            var res = new Result <T>();

            res.original      = JToken.FromObject(originalObj);
            res.variant1      = JToken.FromObject(variant1);
            res.variant2      = JToken.FromObject(variant2);
            res.patch2        = self.Diff(res.original, res.variant2);
            res.mergeOf2Into1 = self.Patch(res.variant1, res.patch2);
            res.patch1        = self.Diff(res.original, res.variant1);
            res.mergeOf1Into2 = self.Patch(res.variant2, res.patch1);
            if (!JToken.DeepEquals(res.mergeOf2Into1, res.mergeOf1Into2))
            {
                res.conflicts = self.Diff(res.mergeOf1Into2, res.mergeOf2Into1);
            }
            return(res);
        }
Beispiel #16
0
        public static bool AreEqual(String expected, String actual)
        {
            JsonDiffPatch jsonDiffPatch = new JsonDiffPatch();

            String difference = jsonDiffPatch.Diff(actual, expected);

            return(String.IsNullOrEmpty(difference));
        }
Beispiel #17
0
        // compare two jsons, able to compare two JArray with the same content but different order
        public static JToken JsonDeepCompare(JToken left, JToken right)
        {
            var jdp = new JsonDiffPatch();

            JToken patch = jdp.Diff(left, right);

            return(patch);
        }
Beispiel #18
0
        public static async Task LogChanges(this FinoSaborContext context, IAspNetUser appuser)
        {
            //var logTime = DateTime.Now;
            const string emptyJson = "{}";
            const string idColumn  = "id";

            Guid?user = null;

            if (!string.IsNullOrEmpty(appuser.ObterUserId().ToString()))
            {
                user = appuser.ObterUserId();
            }

            var changes = context.ChangeTracker.Entries()
                          .Where(x => entityStates.Contains(x.State) && x.Entity.GetType().IsSubclassOf(typeof(EntityBase)))
                          .ToList();

            var jdp = new JsonDiffPatch();

            foreach (var item in changes)
            {
                var original     = emptyJson;
                var updated      = JsonConvert.SerializeObject(item.CurrentValues.Properties.ToDictionary(pn => pn.Name, pn => item.CurrentValues[pn]));
                var creationDate = DateTime.Now;

                if (item.State == EntityState.Modified)
                {
                    var dbValues = await item.GetDatabaseValuesAsync();

                    if (dbValues != null)
                    {
                        original = JsonConvert.SerializeObject(dbValues.Properties.ToDictionary(pn => pn.Name, pn => dbValues[pn]));
                        //creationDate = dbValues.GetValue<DateTime>("DataCadastro");
                    }
                }

                //item.Property("DataCadastro").CurrentValue = creationDate;

                string jsonDiff = jdp.Diff(original, updated);

                if (string.IsNullOrWhiteSpace(jsonDiff) == false)
                {
                    var EntityDiff = JToken.Parse(jsonDiff).ToString(Formatting.None);

                    var log = new Log()
                    {
                        nome_entidade = item.Entity.GetType().Name,
                        id_entidade   = new Guid(item.CurrentValues[idColumn].ToString()),
                        //LogDateTime = logTime,
                        operacao          = item.State.ToString(),
                        id_usuario        = user,
                        valores_alterados = EntityDiff,
                    };

                    context.log.Add(log);
                }
            }
        }
Beispiel #19
0
        public static async Task LogChanges(this ApplicationDbContext context)
        {
            var          logTime   = DateTime.Now;
            const string emptyJson = "{}";
            const string idColumn  = "Id";

            Guid?user = null;

            if (!string.IsNullOrEmpty(Thread.CurrentPrincipal?.Identity?.Name))
            {
                user = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
            }

            var changes = context.ChangeTracker.Entries()
                          .Where(x => entityStates.Contains(x.State) && x.Entity.GetType().IsSubclassOf(typeof(BaseEntity)))
                          .ToList();

            var jdp = new JsonDiffPatch();

            foreach (var item in changes)
            {
                var original     = emptyJson;
                var updated      = JsonConvert.SerializeObject(item.CurrentValues.Properties.ToDictionary(pn => pn.Name, pn => item.CurrentValues[pn]));
                var creationDate = DateTime.Now;

                if (item.State == EntityState.Modified)
                {
                    var dbValues = await item.GetDatabaseValuesAsync();

                    if (dbValues != null)
                    {
                        original     = JsonConvert.SerializeObject(dbValues.Properties.ToDictionary(pn => pn.Name, pn => dbValues[pn]));
                        creationDate = dbValues.GetValue <DateTime>("CreationDate");
                    }
                }

                item.Property("CreationDate").CurrentValue = creationDate;

                string jsonDiff = jdp.Diff(original, updated);

                if (string.IsNullOrWhiteSpace(jsonDiff) == false)
                {
                    var EntityDiff = JToken.Parse(jsonDiff).ToString(Formatting.None);

                    var logEntry = new LogEntry()
                    {
                        EntityName    = item.Entity.GetType().Name,
                        EntityId      = new Guid(item.CurrentValues[idColumn].ToString()),
                        LogDateTime   = logTime,
                        Operation     = item.State.ToString(),
                        UserId        = user,
                        ValuesChanges = EntityDiff,
                    };

                    context.LogEntries.Add(logEntry);
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Diffs two <see cref="JsonNode"/> trees.
        /// </summary>
        /// <returns>
        /// A JSON string representation of the diff.
        /// </returns>
        public static string PrintTreeDiff(JsonNode rootA, JsonNode rootB)
        {
            var jsonA = Serialize(rootA);
            var jsonB = Serialize(rootB);

            var diff = s_jdp.Diff(JToken.Parse(jsonA), JToken.Parse(jsonB));

            return(diff == null ? string.Empty : diff.ToString());
        }
		public void Diff_EmptyObjects_EmptyPatch()
		{
			var jdp = new JsonDiffPatch();
			var empty = JObject.Parse(@"{}");

			JToken result = jdp.Diff(empty, empty);

			Assert.IsNull(result);
		}
Beispiel #22
0
        public static Result <T> Merge <T>(this JsonDiffPatch self, T originalObj, T variant1, T variant2)
        {
            var res = new Result <T>();
            var s   = JsonSerializer.Create(JsonNetSettings.defaultSettings);

            res.original      = ToJToken(originalObj, s);
            res.variant1      = ToJToken(variant1, s);
            res.variant2      = ToJToken(variant2, s);
            res.patch2        = self.Diff(res.original, res.variant2);
            res.mergeOf2Into1 = self.Patch(res.variant1, res.patch2);
            res.patch1        = self.Diff(res.original, res.variant1);
            res.mergeOf1Into2 = self.Patch(res.variant2, res.patch1);
            if (!JToken.DeepEquals(res.mergeOf2Into1, res.mergeOf1Into2))
            {
                res.conflicts = self.Diff(res.mergeOf1Into2, res.mergeOf2Into1);
            }
            return(res);
        }
Beispiel #23
0
        public void Diff_EmptyObjects_EmptyPatch()
        {
            var jdp   = new JsonDiffPatch();
            var empty = JObject.Parse(@"{}");

            JToken result = jdp.Diff(empty, empty);

            Assert.IsNull(result);
        }
Beispiel #24
0
        public void Diff_RightNull_Exception()
        {
            var jdp = new JsonDiffPatch();
            var obj = JObject.Parse(@"{ }");

            JToken result = jdp.Diff(obj, null);

            Assert.AreEqual(JTokenType.Array, result.Type);
        }
		public void Diff_EqualBooleanProperty_NoDiff()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{""p"": true }");
			var right = JObject.Parse(@"{""p"": true }");

			JToken result = jdp.Diff(left, right);

			Assert.IsNull(result);
		}
Beispiel #26
0
        public void Diff_EqualBooleanProperty_NoDiff()
        {
            var jdp   = new JsonDiffPatch();
            var left  = JObject.Parse(@"{""p"": true }");
            var right = JObject.Parse(@"{""p"": true }");

            JToken result = jdp.Diff(left, right);

            Assert.IsNull(result);
        }
Beispiel #27
0
 private void FormLoaded(object sender, EventArgs e)
 {
     Looper = new frmLooper(this);
     if (!string.IsNullOrEmpty(_this.NewValue) && !string.IsNullOrEmpty(_this.OldValue))
     {
         var    jdp        = new JsonDiffPatch();
         JToken diffResult = jdp.Diff(_this.OldValue, _this.NewValue);
         txtDiff.Text = diffResult.ToString(Formatting.Indented).Replace("\\r\\n", "");
     }
 }
Beispiel #28
0
        public JsonResult Get()
        {
            var doc1 = _db.Set <ModuleVersion>().Find(1).Document;   // one facility
            var doc2 = _db.Set <ModuleVersion>().Find(2).Document;   // two facilities
            var doc3 = _db.Set <ModuleVersion>().Find(3).Document;   // change timezone and facilitygroup of first facility

            // case 1: add facility
            // case 2: add 2 facilities
            // case 3: remove facility
            // case 4: edit facility

            // need to nest at least one more level

            // wrap this in jsondiffer type
            var jdp     = new JsonDiffPatch();
            var diffStr = jdp.Diff(doc1, doc3);
            var jDiffs  = JsonConvert.DeserializeObject <JObject>(diffStr); // diffStr contains an array where each delta set has a number key starting from 0

            var diffs = new List <Diff>();

            //var diffCount = 0;
            foreach (var jDiff in jDiffs.Children().Skip(1))
            {
                foreach (var jDiff2 in jDiff.Children <JObject>())
                {
                    diffs.AddRange(jDiff2.Properties().Select(p => new Diff
                    {
                        Field  = p.Name,
                        Before = JsonConvert.SerializeObject(jDiff2[p.Name][0], Formatting.Indented),
                        After  = JsonConvert.SerializeObject(jDiff2[p.Name][1], Formatting.Indented)
                    }));
                }
            }

            //while (jDiffs.(diffCount.ToString(), out JToken jDiff))
            //{
            //    var n = jDiff.Children<JObject>().SelectMany(jd => jd.Properties());
            //    var a = jDiff["FacilityGroup"][0];
            //    var b = jDiff["FacilityGroup"][1];


            //    diffCount++;
            //}

            //return Json(jDiffs);

            //var diffs = new List<dynamic>()
            //{
            //    JsonConvert.DeserializeObject(jdp.Diff(doc1, doc2)),
            //    JsonConvert.DeserializeObject(jdp.Diff(doc2, doc3)),
            //    JsonConvert.DeserializeObject(jdp.Diff(doc1, doc3))
            //};
            return(Json(diffs));
        }
        public void Unpatch_Bug17EfficienText_Success()
        {
            var    jdp   = new JsonDiffPatch();
            var    left  = JToken.Parse("{ \"key\": \"aaaa aaaaaa aaaa aaaaaaa: aaaaaaaaa aaaa aaaaaaaa aaaa: 31-aaa-2017 aaaaa aaaaa aaaaaaa aaaa aaaaaaaa aaaa: 31-aaa-2017aaaaaa aaaaaa: aaaaaaaaa aaaaaa: aaaaaa aaaaa aaaaa aaaaaaa aaaaaa: aaaaaaaaaa aaaaaaaa aaaaaaa: aaaa(aaaa aaaaaa/aaaaaaaaaaaa)-aaaaaaa(aaaaaaaaaa/aaaaaaaaaa aaaa aaaaaa)aaaaa aaaaa aaaaaaa:aaaaaa aaaaaaa: aaaaaaaa aaaaaaaaaa aaaaaaa: aaaaaaaaaaaa aaaaaaaaaa: aaaaaaaa-aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaaa: aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaa: aaaaaaaa aaaaa-aaaaa aaaaaaaaaa, aaaaa aaaaaaa aa aaaaaaa aaaaaaaaaaaa aaaaa aaaaaaaaaaa (aaaaaa), aaaaa a 100 aaaaa aa aaa aaaaaaa.aaa aaaa: aaaaaaaaaaaaaaaa: aaaaaaaaaaaa aaaaaaaa: aaa aaaaa aaaaa:aaaaaaa aaaaaaa: 31-aaa-2014aaaaaa aaaaa: 16-aaa-2016aaaaaa aaaaa: 30-aaa-2017aaaaaa aaaaa: 27-aaa-2017aaaaaa aaaaa: 31-aaa-2017aa aaaaaaaaaa aaaaaaaaaa, (aaaaa aa aaaa aa a 52.67 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaa), aaaaa 100 aa aaaa aaaaaaa.aaaaaaa aaaaaaa: 16-aaa-2016aaaa aaaaaaa aa 100 aaaaa aa aaaa aaa aaaa aaaaaa aaa aa aaaaaaaaaa aaa aaaaaaaaaa, a 88.02 aaaaaaaaaa aa aaaa aaa aaaa aaaaaa aaaaaa.aaaaaaa aaaaaaa: 30-aaa-2017aaaa aaaaaaa aa 100 aaaaa aa aaa-aaaa aaaaaa, aaaaa aa 100 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaa aaa, aaaaa aa aaaa aa 65.656 aaaaa aa aaaa aaa aaaa aaaaaa aaa aa aaaaaaaaaa aaa aaaaaaaaaa aaa 34.343 aa aaaa aaa aaaa aaaaaa aaaaaa. aaaa aaa aaaa aaaaaa aaa aa aaaaaaaaaa aaa aaaaaaaaaa aa 88.02 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaa.aaaaaaa aaaaaaa: 27-aaa-2017aaaa aaaaaaa aa 100 aaaaa aa aaa-aaaa aaaaaa, aaaaa\" }");
            var    right = JToken.Parse("{ \"key\": \"aaaa aaaaaa aaaa aaaaaaa: aaaaaaaaa aaaa aaaaaaaa aaaa: 17-aaa-2017 aaaaa aaaaa aaaaaaa aaaa aaaaaaaa aaaa: 17-aaa-2017aaaaaa aaaaaa: aaaaaaaaa aaaaaa: aaaaaa aaaaa aaaaa aaaaaaa aaaaaa: aaaaaaaaaa aaaaaaaa aaaaaaa: aaaa(aaaa aaaaaa/aaaaaaaaaaaa)-aaaaaaa(aaaaaaaaaa/aaaaaaaaaa aaaa aaaaaa)aaaaa aaaaa aaaaaaa:aaaaaa aaaaaaa: aaaaaaaa aaaaaaaaaa aaaaaaa: aaaaaaaaaaaa aaaaaaaaaa: aaaaaaaa-aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaaa: aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaa aaaa: -2016aaaaaaaaa aaaaaaaaaa aaaaa: aaaa aaaaaaa aa 100 aaaaa aa aaa-aaaa aaaaaa aaa, aaaaaaaa aaaaaaaaaa aa aaaaaa.aaaaaaaaa aaaaaaaaaa: aaaaaaaa-aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaaa: aaaaaaaaaaaaa aaaaaaaaaa aa aaaa: -2016aaaaaaaaa aaaaaaaaaa aaaaa: aaaaaaaa aaaaa-aaaaa aaaaaaaaaa, aaaaa aaaaaaa aa aaaaaaa aaaaaaaaaaaa aaaaa aaaaaaaaaaa (aaaaaa), aaaaa a 100 aaaaa aa aaa aaaaaaa.aaa aaaa: aaaaaaaaaaaaaaaa: aaaaaaaaaaaa aaaaaaaa: aaa aaaaa aaaaa:aaaaaaa aaaaaaa: 31-aaa-2014aaaaaa aaaaa: 16-aaa-2016aaaaaa aaaaa: 30-aaa-2017aaaaaa aaaaa: 27-aaa-2017aaaaaa aaaaa: 31-aaa-2017aaaaaa aaaaa: 16-aaa-2017aa aaaaaaaaaa aaaaaaaaaa, (aaaaa aa aaaa aa a 52.67 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaa), aaaaa 100 aa aaaa aaaaaaa.aaaaaaa aaaaaaa: 16-aaa-2016aaaa\" }");
            JToken patch = jdp.Diff(left, right);

            var patched = jdp.Unpatch(right, patch);

            Assert.IsTrue(JToken.DeepEquals(left.ToString(), patched.ToString()));
        }
        public void Patch_NestedComplexEditDifferentLeft_Success()
        {
            var jdp   = new JsonDiffPatch();
            var left  = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 2 }, ""j"": [0, 2, 4], ""k"": [1] }");
            var right = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 3 }, ""j"": [0, 2, 3], ""k"": null }");
            var patch = jdp.Diff(JObject.Parse(@"{ ""k"": { ""i"": [1] } }"), right);

            var patched = jdp.Patch(left, patch);

            Assert.AreEqual(right.ToString(), patched.ToString());
        }
Beispiel #31
0
        public void Diff_EfficientArrayDiffSame_NullDiff()
        {
            var jdp = new JsonDiffPatch(new Options {
                ArrayDiff = ArrayDiffMode.Efficient
            });
            var array = JToken.Parse(@"[1,2,3]");

            JToken diff = jdp.Diff(array, array);

            Assert.IsNull(diff);
        }
Beispiel #32
0
        public static void CompareFiles(this string sourcefile, string targetfile, string difffilepath, TransformType transformType)
        {
            var jdp = new JsonDiffPatch();

            try {
                if (transformType == TransformType.appsettingjson)
                {
                    var left  = JToken.Parse(sourcefile.readFile());
                    var right = JToken.Parse(targetfile.readFile());

                    JToken patch = jdp.Diff(left, right);
                    if (patch != null)
                    {
                        File.WriteAllText(difffilepath, patch.ToString());
                    }
                    else
                    {
                        File.WriteAllText(difffilepath, "Files are identical");
                    }
                }
                else
                {
                    var left  = JToken.Parse(sourcefile.readXMLFileToJSON());
                    var right = JToken.Parse(targetfile.readXMLFileToJSON());

                    JToken patch = jdp.Diff(left, right);
                    if (patch != null)
                    {
                        File.WriteAllText(difffilepath, patch.ToString());
                    }
                    else
                    {
                        File.WriteAllText(difffilepath, "Files are identical");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
		public void Unpatch_ObjectApplyAdd_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ }");
			var right = JObject.Parse(@"{ ""p"" : true }");
			var patch = jdp.Diff(left, right);

			var unpatched = jdp.Unpatch(right, patch) as JObject;

			Assert.IsNotNull(unpatched, "Patched object");
			Assert.AreEqual(0, unpatched.Properties().Count(), "Property Deleted");
		}
		public void Patch_ObjectApplyEditText_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""p"" : ""bla1h111111111111112312weldjidjoijfoiewjfoiefjefijfoejoijfiwoejfiewjfiwejfowjwifewjfejdewdwdewqwertyqwertifwiejifoiwfei"" }");
			var right = JObject.Parse(@"{ ""p"" : ""blah1"" }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch) as JObject;

			Assert.IsNotNull(patched, "Patched object");
			Assert.AreEqual(1, patched.Properties().Count(), "Property");
			Assert.AreEqual(JTokenType.String, patched.Property("p").Value.Type, "String Type");
			Assert.AreEqual("blah1", patched.Property("p").Value.ToString(), "String value");
		}
		public void Unpatch_ObjectApplyEdit_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""p"" : false }");
			var right = JObject.Parse(@"{ ""p"" : true }");
			var patch = jdp.Diff(left, right);

			var unpatched = jdp.Unpatch(right, patch) as JObject;

			Assert.IsNotNull(unpatched, "Patched object");
			Assert.AreEqual(1, unpatched.Properties().Count(), "Property");
			Assert.AreEqual(JTokenType.Boolean, unpatched.Property("p").Value.Type);
			Assert.IsFalse(unpatched.Property("p").Value.ToObject<bool>(), "Patched Property");
		}
		public void Diff_BooleanPropertyAdded_ValidPatch()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ }");
			var right = JObject.Parse(@"{ ""p"": true }");

			JToken result = jdp.Diff(left, right);

			Assert.AreEqual(JTokenType.Object, result.Type);
			JObject obj = (JObject)result;
			Assert.IsNotNull(obj.Property("p"), "Property Name");
			Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
			Assert.AreEqual(1, ((JArray)obj.Property("p").Value).Count, "Array Length");
			Assert.IsTrue(((JArray)obj.Property("p").Value)[0].ToObject<bool>(), "Array Added Value");
		}
		public void Patch_NestedObjectApplyEdit_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""i"": { ""p"" : false } }");
			var right = JObject.Parse(@"{ ""i"": { ""p"" : true } }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch) as JObject;

			Assert.IsNotNull(patched, "Patched object");
			Assert.AreEqual(1, patched.Properties().Count(), "Property");
			Assert.AreEqual(JTokenType.Object, patched.Property("i").Value.Type);
			Assert.AreEqual(1, ((JObject)patched.Property("i").Value).Properties().Count());
			Assert.AreEqual(JTokenType.Boolean, ((JObject)patched.Property("i").Value).Property("p").Value.Type);
			Assert.IsTrue(((JObject)patched.Property("i").Value).Property("p").Value.ToObject<bool>());
		}
		public void Diff_EfficientArrayDiffDifferentHeadTailAdded_ValidDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,2,3,4]");
			var right = JToken.Parse(@"[0,1,2,3,4,5]");

			JObject diff = jdp.Diff(left, right) as JObject;

			Assert.IsNotNull(diff);
			Assert.AreEqual(3, diff.Properties().Count());
			Assert.IsNotNull(diff["0"]);
			Assert.IsNotNull(diff["5"]);
		}
		public void Patch_ArrayPatchModify_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,3,{""p"":false}]");
			var right = JToken.Parse(@"[1,4,{""p"": [1] }]");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch);

			Assert.AreEqual(right.ToString(), patched.ToString());
		}
		public void Diff_IntStringDiff_ValidPatch()
		{
			var jdp = new JsonDiffPatch();
			var left = JToken.Parse(@"1");
			var right = JToken.Parse(@"""hello""");

			JToken result = jdp.Diff(left, right);

			Assert.AreEqual(JTokenType.Array, result.Type);
			JArray array = (JArray)result;
			Assert.AreEqual(2, array.Count);
			Assert.AreEqual(left, array[0]);
			Assert.AreEqual(right, array[1]);
		}
		public void Diff_EfficientArrayDiffSameWithObject_NoDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"
{
	""@context"": [
		""http://www.w3.org/ns/csvw"",
		{
			""@language"": ""en"",
			""@base"": ""http://example.org""
		}
	]
}");
			var right = left.DeepClone();

			JToken diff = jdp.Diff(left, right);

			Assert.IsNull(diff);
		}
		public void Patch_NestedComplexEdit_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 2 }, ""j"": [0, 2, 4], ""k"": [1] }");
			var right = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 3 }, ""j"": [0, 2, 3], ""k"": null }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch);

			Assert.AreEqual(right.ToString(), patched.ToString());
		}
		public void Diff_EfficientArrayDiffSame_NullDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var array = JToken.Parse(@"[1,2,3]");

			JToken diff = jdp.Diff(array, array);

			Assert.IsNull(diff);
		}
		public void Diff_EfficientArrayDiffSameLengthNested_ValidDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,2,{""p"":false},4]");
			var right = JToken.Parse(@"[1,2,{""p"":true},4]");

			JObject diff = jdp.Diff(left, right) as JObject;

			Assert.IsNotNull(diff);
			Assert.AreEqual(2, diff.Properties().Count());
			Assert.IsNotNull(diff["2"]);
		}
		public void Unpatch_ArrayUnpatchComplex_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"{""p"": [1,2,[1],false,""11111"",3,{""p"":false},10,10] }");
			var right = JToken.Parse(@"{""p"": [1,2,[1,3],false,""11112"",3,{""p"":true},10,10] }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Unpatch(right, patch);

			Assert.AreEqual(left.ToString(), patched.ToString());
		}
		public void Diff_EfficientStringDiff_ValidPatch()
		{
			var jdp = new JsonDiffPatch(new Options { TextDiff = TextDiffMode.Efficient });
			var left = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");
			var right = JObject.Parse(@"{ ""p"": ""blah1"" }");

			JToken result = jdp.Diff(left, right);

			Assert.AreEqual(JTokenType.Object, result.Type);
			JObject obj = (JObject)result;
			Assert.IsNotNull(obj.Property("p"), "Property Name");
			Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
			Assert.AreEqual(3, ((JArray)obj.Property("p").Value).Count, "Array Length");
			Assert.AreEqual("@@ -1,64 +1,5 @@\n-lp.Value.ToString().Length %3e _options.MinEfficientTextDiffLength\n+blah1\n", ((JArray)obj.Property("p").Value)[0].ToString(), "Array Added Value");
			Assert.AreEqual(0, ((JArray)obj.Property("p").Value)[1].ToObject<int>(), "Array Added Value");
			Assert.AreEqual(2, ((JArray)obj.Property("p").Value)[2].ToObject<int>(), "Array String Diff Indicator");
		}
		public void Diff_RightNull_Exception()
		{
			var jdp = new JsonDiffPatch();
			var obj = JObject.Parse(@"{ }");

			JToken result = jdp.Diff(obj, null);

			Assert.AreEqual(JTokenType.Array, result.Type);
		}
		public void Unpatch_ArrayUnpatchAdd_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,2,3]");
			var right = JToken.Parse(@"[1,2,3,4]");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Unpatch(right, patch);

			Assert.AreEqual(left.ToString(), patched.ToString());
		}
		public void Diff_EfficientStringDiff_NoChanges()
		{
			var jdp = new JsonDiffPatch(new Options { TextDiff = TextDiffMode.Efficient });
			var left = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");
			var right = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");

			JToken result = jdp.Diff(left, right);

			Assert.IsNull(result, "No Changes");
		}