Exemplo n.º 1
0
	public static void Main(string[] args) {
		Opts options = new Opts();
		options.ProcessArgs(args);
		
		if (options.RemainingArguments.Length < 2) {
			options.DoHelp();
			return;
		}
		
		Application.Init ();
		
		Window win = new Window("NDiff");
		win.DeleteEvent += new DeleteEventHandler(Window_Delete);
		win.SetDefaultSize(800, 600);
		
		DiffWidget.Options dopts = new DiffWidget.Options();
		dopts.SideBySide = options.sidebyside;

		if (options.RemainingArguments.Length == 2) {
			dopts.LeftName = options.RemainingArguments[0];
			dopts.RightName = options.RemainingArguments[1];
			Diff diff = new Diff(options.RemainingArguments[0], options.RemainingArguments[1], options.caseinsensitive, true);
			win.Add(new DiffWidget(diff, dopts));
		} else {
			Diff[] diffs = new Diff[options.RemainingArguments.Length-1];
			for (int i = 0; i < options.RemainingArguments.Length-1; i++)
				diffs[i] = new Diff(options.RemainingArguments[0], options.RemainingArguments[i+1], options.caseinsensitive, true);
			Merge merge = new Merge(diffs);
			win.Add(new DiffWidget(merge, dopts));
		}		

		win.ShowAll();
		Application.Run();
	}
Exemplo n.º 2
0
 // Mutator method - turns "b" into the original "a"
 public void ApplyDiff(byte[] b, Diff diff)
 {
     foreach (DiffPoint point in diff.Points)
     {
         b[point.Index] = point.OldValue;
     }
 }
Exemplo n.º 3
0
        /// <summary>Vypíše virtuální soubor diffu. Na základě hodnot třídy (ne)vypíše čísla řádků a barvičky</summary>
        /// <param name="file">Vypisovaný soubor</param>
        public static void write(Diff.DiffFile file)
        {
            // Počet cifer posledního číslá řádku
            // http://stackoverflow.com/a/1306751
            int width = (int)(Math.Log10(file.Content[file.Content.Count-1].Number)+1);

            // Pro vytvoření řetězce k uložení do souboru
            // Pokud jde výpis na STDOUT, rovnou se vypisuje
            //    (Příkazová řádká windows nepodporuje ANSI řídící znaky pro barvy,
            //     pouze přímou změnu barvy v konzoli)
            StringBuilder sb = new StringBuilder();

            foreach(Diff.DiffLine line in file.Content) {
                if(colored) {
                    Console.ForegroundColor = colorForSymbol(line.Symbol);
                }
                if(numberLines) {
                    // Zarovná čísla řádků do sloupečků (podle čísla s největším počtem cifer)
                    String f1 = line.Symbol.Equals(Diff.Diff.ADD_SYMBOL) ? "" : Convert.ToString(line.Number);
                    String f2 = line.Symbol.Equals(Diff.Diff.DEL_SYMBOL) ? "" : Convert.ToString(line.Number);
                    String s = String.Format("{0,-" + width + "} | {1,-" + width + "} | ", f1, f2);

                    if(output == null) write(s);
                    else sb.Append(s);
                }

                if(output == null) write(line.ToString() + Environment.NewLine);
                else sb.Append(line.ToString() + Environment.NewLine);
            }
            if (output != null)
                writeToFIle(sb.ToString(), output);
        }
 public UnifiedDiffViewModel(Diff diff)
     : this()
 {
     foreach (var section in diff.Sections)
     {
         Lines.AddRange(GetLinesFromSection(section));
     }
 }
Exemplo n.º 5
0
 static IEnumerable<object> BuildRemovedPublicTypes(Diff diff)
 {
     foreach (var definition in diff.RemovedPublicTypes())
     {
         yield return new
         {
             name = definition.GetName()
         };
     }
 }
Exemplo n.º 6
0
        public void Strings()
        {
            Console.WriteLine("Diff Strings");

            string[] ax = "H U M A N".Split(' ');
            string[] bx = "C H I M P A N Z E E".Split(' ');

            Diff<string> l = new Diff<string>( ax, bx );
            Console.WriteLine( "LCS {0} ", String.Join(" ", l.Sequence.ToArray() ) );
            Console.WriteLine("Changes");
            Console.WriteLine( l.ToString() );
        }
Exemplo n.º 7
0
		public void UnchangedTest()
		{
			var diff = new Diff(TEXT, TEXT);
			Assert.IsFalse(diff.HasDifferences);
			Assert.AreEqual(1, diff.Sections.Count());
			var section = diff.Sections.First();
			Assert.AreEqual(Diff.SectionStatus.Unchanged, section.Status);
			Assert.AreEqual(1, section.BeginA);
			Assert.AreEqual(1, section.BeginB);
			Assert.AreEqual(Text.NumberOfLines + 1, section.EndA);
			Assert.AreEqual(Text.NumberOfLines + 1, section.EndB);
		}
Exemplo n.º 8
0
 //删除试卷科目事件
 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
 {
     Diff Diff = new Diff();           //创建Diff对象
     int ID = int.Parse(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); //取出要删除记录的主键值
     if (Diff.DeleteByProc(ID))
     {
         Page.RegisterStartupScript("", "<script language=javascript>alert('成功删除试卷科目!')</script>");
     }
     else
     {
         Page.RegisterStartupScript("", "<script language=javascript>alert('删除试卷科目失败!')</script>");
     }
     GridView1.EditIndex = -1;
     InitData();
 }
Exemplo n.º 9
0
        /// <summary>
        /// Renders diff
        /// </summary>
        /// <param name="leftText">Earlier version of the text</param>
        /// <param name="rightText">Later version of the text</param>
        /// <param name="contextLines">Number of unchanged lines to show around changed ones</param>
        /// <returns>HTML diff</returns>
        public string GetDiff(string leftText, string rightText, int contextLines)
        {
            Result = new StringBuilder(500000);
            LeftLines = leftText.Split(new [] { "\r\n" }, StringSplitOptions.None);
            RightLines = rightText.Split(new [] { "\r\n" }, StringSplitOptions.None);
            ContextLines = contextLines;

            diff = new Diff(LeftLines, RightLines, true, true);
            foreach (Diff.Hunk h in diff)
            {
                if (h.Same) RenderContext(h);
                else RenderDifference(h);
            }
            return Result.ToString();
        }
Exemplo n.º 10
0
 //GridView控件RowUpdating事件
 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {
     int ID = int.Parse(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); //取出要删除记录的主键值
     Diff Diff = new Diff();           //创建Diff对象
     Diff.DiffName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName")).Text;
     if (Diff.UpdateByProc(ID))//使用Users类UpdateByProc方法修改用户信息
     {
         Page.RegisterStartupScript("", "<script language=javascript>alert('修改成功!')</script>");
     }
     else
     {
         Page.RegisterStartupScript("", "<script language=javascript>alert('修改失败!')</script>");
     }
     GridView1.EditIndex = -1;
     InitData();
 }
Exemplo n.º 11
0
        public void Ints()
        {
            Console.WriteLine("Diff Integers");

            int[] ax = new int[]{ 3,3,3,3,3,3 };
            int[] bx = new int[]{ 2,3,3,1,2 };

            Diff<int> l = new Diff<int>( ax, bx );
            Console.Out.Write("LCS ");
            foreach ( int x in l.Sequence ){
                Console.Out.Write( x.ToString() + " " );
            }
            Console.Out.Write("\n");
            Console.WriteLine("Changes");
            Console.WriteLine( l.ToString() );
        }
Exemplo n.º 12
0
        public void Chars()
        {
            Console.WriteLine("Diff Chars");

            char[] ax = "human".ToCharArray();
            char[] bx = "chimpanzee".ToCharArray();

            Diff<char> l = new Diff<char>( ax, bx );

            Console.Write("LCS ");
            foreach ( char c in l.Sequence ){
                Console.Write( c );
            }
            Console.Write("\n");
            Console.WriteLine("Changes");
            Console.WriteLine( l.ToString() );
        }
Exemplo n.º 13
0
	public static void Main(string[] args) {
		Opts opts = new Opts();
		opts.ProcessArgs(args);
		
		if (opts.left == null || opts.right == null) {
			Console.Error.WriteLine("The --left and --right arguments are required.");
			return;
		}
		
		IList file1, file2;
		
		if (opts.method == "lines") {
			file1 = LoadFileLines(opts.left);
			file2 = LoadFileLines(opts.right);
		} else if (opts.method == "chars") {
			file1 = LoadFileChars(opts.left);
			file2 = LoadFileChars(opts.right);
		} else {
			Console.Error.WriteLine("The method option must be either lines or chars.");
			return;
		}
		
		Diff diff = new Diff(file1, file2, 
			!opts.caseinsensitive ? null : CaseInsensitiveComparer.Default,
			!opts.caseinsensitive ? null : CaseInsensitiveHashCodeProvider.Default);
		
		if (!opts.interactive) {
			UnifiedDiff.WriteUnifiedDiff(diff, Console.Out);
		} else {
			foreach (Diff.Hunk hunk in diff) {
				if (hunk.Same) {
					WriteBlock(hunk.Left, opts);
				} else {
					Console.Error.WriteLine(hunk);
					Console.Error.Write("Enter 'r' to reject, or hit enter to accept. ");
					Console.Error.WriteLine();
					string choice = Console.In.ReadLine();
					if (choice == "r")
						WriteBlock(hunk.Left, opts);
					else
						WriteBlock(hunk.Right, opts);
				}
			}
		}
	}
Exemplo n.º 14
0
        void RenderDifference(Diff.Hunk hunk)
        {
            Range left = hunk.Left;
            Range right = hunk.Right;

            if (right.Start == 0) ContextHeader(0, 0);
            int changes = Math.Min(left.Count, right.Count);
            for (int i = 0; i < changes; i++)
            {
                LineChanged(left.Start + i, right.Start + i);
            }
            if (left.Count > right.Count)
                for (int i = changes; i < left.Count; i++)
                    LineDeleted(left.Start + i, right.Start + changes);
            else if (left.Count < right.Count)
                for (int i = changes; i < right.Count; i++)
                    LineAdded(right.Start + i);
        }
Exemplo n.º 15
0
        public static Diff GetDiff(byte[] a, byte[] b)
        {
            Diff diff = new Diff();
            if (a.Length != b.Length) {
                // cannot use this binary diff method
                // since the lengths have changes
                // assume this means we are dealing with text instead
                return null;
            }

            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] != b[i])
                {
                    diff.Points.Add(new DiffPoint(i, a[i], b[i]));
                }
            }
            return diff;
        }
Exemplo n.º 16
0
 public void DifferenceAtTheBeginning()
 {
     var diff = new Diff(TEXT, "Quote from Hamlet:\n\n" + TEXT);
     //DumpSections(diff);
     Assert.IsTrue(diff.HasDifferences);
     Assert.AreEqual(2, diff.Sections.Count());
     var section = diff.Sections.First();
     Assert.AreEqual(Diff.SectionStatus.Different, section.Status);
     Assert.AreEqual(1, section.BeginA);
     Assert.AreEqual(1, section.BeginB);
     Assert.AreEqual(1, section.EndA);
     Assert.AreEqual(3, section.EndB);
     section = diff.Sections.Skip(1).First();
     Assert.AreEqual(Diff.SectionStatus.Unchanged, section.Status);
     Assert.AreEqual(1, section.BeginA);
     Assert.AreEqual(3, section.BeginB);
     Assert.AreEqual(Text.NumberOfLines + 1, section.EndA);
     Assert.AreEqual(Text.NumberOfLines + 1 + 2, section.EndB);
 }
Exemplo n.º 17
0
 // Copy method - recreates "a" leaving "b" intact
 public byte[] ApplyDiffCopy(byte[] b, Diff diff)
 {
     byte[] a = new byte[b.Length];
     int startIndex = 0;
     foreach (DiffPoint point in diff.Points)
     {
         for (int i = startIndex; i < point.Index; i++)
         {
             a[i] = b[i];
         }
         a[point.Index] = point.OldValue;
         startIndex = point.Index + 1;
     }
     for (int j = startIndex; j < b.Length; j++)
     {
         a[j] = b[j];
     }
     return a;
 }
        public CommitDetailsViewModel(Repository repository, RepositoryNavigationRequest request, Commit commit)
            : this(repository, new RepositoryNavigationRequest(request) { Treeish = commit.Hash })
        {
            CurrentCommit = new CommitViewModel(repository, request, commit, true);

            foreach (var change in commit.Changes)
            {
                // PASTE-START : borrowed from GitSharp.Demo
                var a = (change.ReferenceObject != null ? (change.ReferenceObject as Blob).RawData : new byte[0]);
                var b = (change.ComparedObject != null ? (change.ComparedObject as Blob).RawData : new byte[0]);

                a = (Diff.IsBinary(a) == true ? Encoding.ASCII.GetBytes("Binary content\nFile size: " + a.Length) : a);
                b = (Diff.IsBinary(b) == true ? Encoding.ASCII.GetBytes("Binary content\nFile size: " + b.Length) : b);
                // PASTE-END : borrowed from GitSharp.Demo

                var diff = new Diff(a, b);
                Changes.Add(new ChangeViewModel(request, change, diff));
            }
        }
Exemplo n.º 19
0
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            Diff Diff = new Diff();               //创建试卷难度对象
            Diff.DiffName = txtName.Text;                 //设置试卷难度对象属性
            if (Diff.InsertByProc())                  //调用添加试卷难度方法添加试卷难度
            {
                lblMessage.Text = "成功添加该试卷难度!";
                txtName.Text = "";

            }
            else
            {
                lblMessage.Text = "添加该试卷难度失败!";
            }

        }
    }
Exemplo n.º 20
0
        public ChangeViewModel(RepositoryNavigationRequest request, Change change, Diff diff)
            : base(request)
        {
            Change = change;
            Treeish = change.ComparedCommit.Hash;
            Name = System.IO.Path.GetFileName(change.Path);
            Path = change.Path;
            Diff = new UnifiedDiffViewModel(diff);
            Summary = new SummaryViewModel();
            Summary.Inserts = Diff.Lines.Count(x =>
                x.LineType == GitSharp.Diff.EditType.Inserted ||
                (x.LineType == GitSharp.Diff.EditType.Replaced && x.LineB.HasValue) // new ones
            );

            Summary.Deletes = Diff.Lines.Count(x =>
                x.LineType == GitSharp.Diff.EditType.Deleted ||
                (x.LineType == GitSharp.Diff.EditType.Replaced && x.LineA.HasValue) // replaced with new one(s)
            );
        }
Exemplo n.º 21
0
        void RenderContext(Diff.Hunk hunk)
        {
            Range left = hunk.Left;
            Range right = hunk.Right;
            int displayed = 0;

            if (Result.Length > 0) // not the first hunk, adding context for previous change
            {
                displayed = Math.Min(ContextLines, right.Count);
                for (int i = 0; i < displayed; i++) ContextLine(right.Start + i);
            }

            int toDisplay = Math.Min(right.Count - displayed, ContextLines);
            if ((left.End < LeftLines.Length - 1 || right.End < RightLines.Length - 1) && toDisplay > 0)
            // not the last hunk, adding context for next change
            {
                if (right.Count > displayed + toDisplay) ContextHeader(left.End - toDisplay + 1, right.End - toDisplay + 1);
                for (int i = 0; i < toDisplay; i++) ContextLine(right.End - toDisplay + i + 1);
            }
        }
Exemplo n.º 22
0
        public static IEnumerable<BreakingChange> Find(Diff diff)
        {
            var breakingChanges = diff.RemovedPublicTypes().Select(t => new TypeRemoved(t))
                .ToList<BreakingChange>();

            breakingChanges.AddRange(diff.TypesChangedToNonPublic()
                .Select(typeDiff => new TypeMadeNonPublic(typeDiff)));
            breakingChanges.AddRange(diff.TypesChangedToNonPublic()
                .Select(typeDiff => new TypeMadeNonPublic(typeDiff)));

            foreach (var typeDiff in diff.MatchingTypeDiffs)
            {
                if (typeDiff.LeftType.HasObsoleteAttribute())
                {
                    continue;
                }
                if (typeDiff.RightType.HasObsoleteAttribute())
                {
                    continue;
                }

                if (!typeDiff.LeftType.IsPublic)
                {
                    continue;
                }
                if (!typeDiff.RightType.IsPublic)
                {
                    continue;
                }
                breakingChanges.AddRange(typeDiff.PublicFieldsRemoved().Select(field => new PublicFieldRemoved(typeDiff.LeftType, field)));
                breakingChanges.AddRange(typeDiff.PublicMethodsRemoved().Select(method => new PublicMethodRemoved(typeDiff.LeftType, method)));
                breakingChanges.AddRange(typeDiff.FieldsChangedToNonPublic().Select(field => new FieldChangedToNonPublic(typeDiff.LeftType, field.Left)));
                breakingChanges.AddRange(typeDiff.MethodsChangedToNonPublic().Select(method => new MethodChangedToNonPublic(typeDiff.LeftType, method.Left)));
         
            }

            return breakingChanges;
        }
Exemplo n.º 23
0
        public Diff Diff(Mapper input)
        {
            var outMapper = new Diff();

            foreach (var kvp in input)
            {
                var source = kvp.Key;

                log("Diff - Analyze {0} source '{1}'.",
                    source.Type, source.Url);

                var richSource = EnrichWithShas(source, true);

                foreach (var destination in kvp.Value)
                {
                    log("Diff - Analyze {0} target '{1}'.",
                        source.Type, destination.Url);

                    var richDestination = EnrichWithShas(destination, false);

                    if (richSource.Sha == richDestination.Sha)
                    {
                        log("Diff - No sync required. Matching sha ({0}) between target '{1}' and source '{2}.",
                            richSource.Sha.Substring(0, 7), destination.Url, source.Url);

                        continue;
                    }

                    log("Diff - {4} required. Non-matching sha ({0} vs {1}) between target '{2}' and source '{3}.",
                        richSource.Sha.Substring(0, 7), richDestination.Sha == null ? "NULL" : richDestination.Sha.Substring(0, 7), destination.Url, source.Url, richDestination.Sha == null ? "Creation" : "Updation");

                    outMapper.Add(richSource, richDestination);
                }
            }

            return outMapper;
        }
Exemplo n.º 24
0
 public void ShouldParseWhitespace() =>
 AreEqual(0, Diff.Parse(" ").Count());
            public void Remove()
            {
                var model1 = Model.Create(1);
                var model2 = Model.Create(2);
                var model3 = Model.Create(3);
                var source = new ObservableCollection <Model <int> >(
                    new[]
                {
                    model1,
                    model1,
                    model1,
                    model2,
                    model2,
                    model2,
                    model3,
                    model3,
                    model3,
                });

                using (var view = source.AsMappingView(CreateStrictMock, x => x.Object.Dispose()))
                {
                    using (var actual = view.SubscribeAll())
                    {
                        var mock = view[0];
                        source.RemoveAt(0);
                        mock.Verify(x => x.Dispose(), Times.Never);
                        CollectionAssert.AreEqual(source, view.Select(x => x.Object.Model));
                        var expected = new List <EventArgs>
                        {
                            CachedEventArgs.CountPropertyChanged,
                            CachedEventArgs.IndexerPropertyChanged,
                            Diff.CreateRemoveEventArgs(mock, 0)
                        };
                        CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                        source.RemoveAt(0);
                        mock.Verify(x => x.Dispose(), Times.Never);
                        CollectionAssert.AreEqual(source, view.Select(x => x.Object.Model));
                        expected.AddRange(new EventArgs[]
                        {
                            CachedEventArgs.CountPropertyChanged,
                            CachedEventArgs.IndexerPropertyChanged,
                            Diff.CreateRemoveEventArgs(mock, 0)
                        });
                        CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                        mock.Setup(x => x.Dispose());
                        source.RemoveAt(0);
                        mock.Verify(x => x.Dispose(), Times.Once);
                        CollectionAssert.AreEqual(source, view.Select(x => x.Object.Model));
                        expected.AddRange(new EventArgs[]
                        {
                            CachedEventArgs.CountPropertyChanged,
                            CachedEventArgs.IndexerPropertyChanged,
                            Diff.CreateRemoveEventArgs(mock, 0)
                        });
                        CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                        foreach (var toDispose in view)
                        {
                            toDispose.Setup(x => x.Dispose());
                        }
                    }
                }
            }
Exemplo n.º 26
0
        public void Go()
        {
            while (_queue.Any())
                lock (this)
                {
                    if (!_queue.Any()) continue;
                    var current = _queue.First();
                    if (!current.Key.Directory.Exists)
                    {
                        CreateDirectoryTree(current.Value.Source.Directory, current.Key.Directory);
                    }
                    using (Stream src = current.Value.Source.OpenRead())
                    {
                        if (src.Length <= 0)
                        {
                            // Diff/New file is empty, skip it.
                            _queue.Remove(current.Key);
                            continue;
                        }
                        if (current.Key.Exists) // trying to merge/apply data diff
                            if (Diff.IsBinary(src) || _copyAsBinary) // binary blobs are copied whole
                                using (Stream dest = current.Key.Open(FileMode.Truncate, FileAccess.ReadWrite))
                                    src.CopyTo(dest);
                            else
                                using (Stream dest = current.Key.Open(FileMode.Open, FileAccess.ReadWrite))
                                {
                                    var srcBytes = src.toArray();
                                    Patch P = new Patch();

                                    if (P.ParseHunks(srcBytes) == 0)
                                    {
                                        // No diff hunks in the file.
                                        // Diff file not a diff, and not empty.  Handle it as a binary file overwrite.
                                        dest.SetLength(0);
                                        src.CopyTo(dest);
                                        _queue.Remove(current.Key);
                                        continue;
                                    }

                                    var newBytes = P.SimpleApply(dest.toArray());
                                        // Replace this call with a more sophisticated (read "intellegent") diff application method.

                                    dest.Position = 0;
                                    dest.Write(newBytes, 0, newBytes.Length);
                                    dest.SetLength(newBytes.Length);

                                    /*
                                    MergeResult mr = current.Value.Base == null
                                                         ? MergeAlgorithm.merge(new RawText(dest.toArray()),
                                                                                new RawText(src.toArray()),
                                                                                new RawText(dest.toArray())) // use the base as "theirs"
                                                         : MergeAlgorithm.merge(new RawText(dest.toArray()),
                                                                                new RawText(src.toArray()),
                                                                                new RawText(
                                                                                    current.Value.Base.OpenRead()
                                                                                           .toArray()));
                                    bool conflicts = mr.containsConflicts();
                                    bool blurb = conflicts;

                                    */
                                }

                        else
                            using (var dest = current.Key.Create())
                                if (current.Value.Base == null || !current.Value.Base.Exists || Diff.IsBinary(src) ||
                                    _copyAsBinary)
                                    src.CopyTo(dest);
                                else
                                {
                                    byte[] baseBytes = current.Value.Base.OpenRead().toArray();
                                    byte[] srcBytes = src.toArray();
                                    // string baseStr = baseBytes.Aggregate(String.Empty, (current1, b) => current1 + (char) b);
                                    // string srcStr = srcBytes.Aggregate(String.Empty, (current1, b) => current1 + (char)b);

                                    var diff = new Diff(baseBytes, srcBytes);

                                    if (diff.HasDifferences)
                                    {
                                        var df = new DiffFormatter();
                                        df.FormatEdits(dest, new RawText(baseBytes), new RawText(srcBytes),
                                                       diff.GetEdits());
                                        /*
                                        Stream diffStream = new MemoryStream();
                                        df.FormatEdits(diffStream, new RawText(baseBytes), new RawText(srcBytes), diff.GetEdits());
                                        var fh = new CombinedFileHeader(Patch.ReadFully(diffStream), 0);
                                        var outStr = fh.getScriptText();
                                        byte[] bytes = outStr.Cast<byte>().ToArray();
                                        dest.Write(bytes, 0, bytes.Length);
                                        */
                                    }
                                    else // Not really different, just different metadata.  skip it.
                                    {
                                        dest.Close();
                                        current.Key.Delete();
                                        _queue.Remove(current.Key);
                                        continue;
                                    }
                                }
                    }

                    // set the attributes and file timestamps (and ACLs if it's ntfs...)
                    current.Key.Attributes = current.Value.Source.Attributes;
                    if (current.Key.FileSystem is NtfsFileSystem)
                    {
                        var D = (NtfsFileSystem) current.Key.FileSystem;
                        var S = (NtfsFileSystem) current.Value.Source.FileSystem;
                        D.SetSecurity(current.Key.FullName, S.GetSecurity(current.Value.Source.FullName));

                        D.SetFileStandardInformation(current.Key.FullName,
                                                     S.GetFileStandardInformation(current.Value.Source.FullName));
                    }
                    else
                    {
                        current.Key.CreationTimeUtc = current.Value.Source.CreationTimeUtc;
                        current.Key.LastWriteTimeUtc = current.Value.Source.LastWriteTimeUtc;
                        current.Key.LastAccessTimeUtc = current.Value.Source.LastAccessTimeUtc;
                    }

                    _queue.Remove(current.Key);
                }
        }
Exemplo n.º 27
0
        public void GetAllXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <consolidate>
        <bookid>USD Books</bookid>
        <reportingperiodname>Month Ended June 2016</reportingperiodname>
        <offline>true</offline>
        <updatesucceedingperiods>false</updatesucceedingperiods>
        <changesonly>true</changesonly>
        <email>[email protected]</email>
        <entities>
            <csnentity>
                <entityid>VT</entityid>
                <bsrate>0.0000483500</bsrate>
                <warate>0.0000485851</warate>
            </csnentity>
        </entities>
    </consolidate>
</function>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            ConsolidationCreate rate = new ConsolidationCreate("unittest")
            {
                ReportingBookId         = "USD Books",
                ReportingPeriodName     = "Month Ended June 2016",
                ProcessOffline          = true,
                ChangesOnly             = true,
                UpdateSucceedingPeriods = false,
                NotificationEmail       = "*****@*****.**",
            };


            ConsolidationEntity entity = new ConsolidationEntity();

            entity.EntityId            = "VT";
            entity.EndingSpotRate      = 0.0000483500M;
            entity.WeightedAverageRate = 0.0000485851M;

            rate.Entities.Add(entity);

            rate.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
Exemplo n.º 28
0
        /*
         * private static bool DiffAwareGridViewCompare<T>(DiffAwareGridView<T> o1, DiffAwareGridView<T> o2)
         *  where T : struct
         *  => GridViewCompare(o1.BaseGrid, o2.BaseGrid) && ElementWiseEquality(o1.Diffs, o2.Diffs) &&
         *     o1.AutoCompress == o2.AutoCompress && o1.CurrentDiffIndex == o2.CurrentDiffIndex;
         *
         * private static bool DiffAwareGridViewSerializedCompare<T>(DiffAwareGridViewSerialized<T> o1,
         *                                                        DiffAwareGridViewSerialized<T> o2)
         *  where T : struct
         *  => o1.AutoCompress == o2.AutoCompress && ElementWiseEquality(o1.Diffs, o2.Diffs) &&
         *     GridViewCompare(o1.BaseGrid, o2.BaseGrid) && o1.CurrentDiffIndex == o2.CurrentDiffIndex;
         */


        // This comparison doesn't work in all cases.  The serialization actually checks to see if the re-serialized
        // version is compressed; so if the original was compressed but not KNOWN to be as such (so marked as false)
        // then the comparison will fail.  This is relatively rare, however, and our test cases avoid it.
        private static bool DiffCompare <T>(Diff <T> o1, Diff <T> o2)
            where T : struct
        => ElementWiseEquality(o1.Changes, o2.Changes) && o1.IsCompressed == o2.IsCompressed;
Exemplo n.º 29
0
 Check(Diff(a, a, false, false));
Exemplo n.º 30
0
 public static DiffWithOrigin Remote(Diff diff) =>
     new DiffWithOrigin
     {
         Diff = diff,
         Origin = OriginEnum.Remote
     };
Exemplo n.º 31
0
 public void ShouldParseNull() =>
 AreEqual(0, Diff.Parse(null).Count());
Exemplo n.º 32
0
/// <summary>
/// start a self- / box-test for some diff cases and report to the debug output.
/// </summary>
/// <param name="args">not used</param>
/// <returns>always 0</returns>
    public static int Main(string[] args)
    {
        StringBuilder ret = new StringBuilder();
        string        a, b;

        System.Diagnostics.ConsoleTraceListener ctl = new System.Diagnostics.ConsoleTraceListener(false);
        System.Diagnostics.Debug.Listeners.Add(ctl);

        System.Console.WriteLine("Diff Self Test...");

// test all changes
        a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n');
        b = "0,1,2,3,4,5,6,7,8,9".Replace(',', '\n');
        System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
                                        == "12.10.0.0*",
                                        "all-changes test failed.");
        System.Diagnostics.Debug.WriteLine("all-changes test passed.");
// test all same
        a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n');
        b = a;
        System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
                                        == "",
                                        "all-same test failed.");
        System.Diagnostics.Debug.WriteLine("all-same test passed.");

// test snake
        a = "a,b,c,d,e,f".Replace(',', '\n');
        b = "b,c,d,e,f,x".Replace(',', '\n');
        System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
                                        == "1.0.0.0*0.1.6.5*",
                                        "snake test failed.");
        System.Diagnostics.Debug.WriteLine("snake test passed.");

// 2002.09.20 - repro
        a = "c1,a,c2,b,c,d,e,g,h,i,j,c3,k,l".Replace(',', '\n');
        b = "C1,a,C2,b,c,d,e,I1,e,g,h,i,j,C3,k,I2,l".Replace(',', '\n');
        System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
                                        == "1.1.0.0*1.1.2.2*0.2.7.7*1.1.11.13*0.1.13.15*",
                                        "repro20020920 test failed.");
        System.Diagnostics.Debug.WriteLine("repro20020920 test passed.");

// 2003.02.07 - repro
        a = "F".Replace(',', '\n');
        b = "0,F,1,2,3,4,5,6,7".Replace(',', '\n');
        System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
                                        == "0.1.0.0*0.7.1.2*",
                                        "repro20030207 test failed.");
        System.Diagnostics.Debug.WriteLine("repro20030207 test passed.");

// Muegel - repro
        a = "HELLO\nWORLD";
        b = "\n\nhello\n\n\n\nworld\n";
        System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
                                        == "2.8.0.0*",
                                        "repro20030409 test failed.");
        System.Diagnostics.Debug.WriteLine("repro20030409 test passed.");

// test some differences
        a = "a,b,-,c,d,e,f,f".Replace(',', '\n');
        b = "a,b,x,c,e,f".Replace(',', '\n');
        System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
                                        == "1.1.2.2*1.0.4.4*1.0.6.5*",
                                        "some-changes test failed.");
        System.Diagnostics.Debug.WriteLine("some-changes test passed.");

        System.Diagnostics.Debug.WriteLine("End.");
        System.Diagnostics.Debug.Flush();

        return(0);
    }
Exemplo n.º 33
0
        void LineChanged(int leftLine, int rightLine)
        {
            // some kind of glitch with the diff engine
            if (LeftLines[leftLine] == RightLines[rightLine])
            {
                ContextLine(rightLine);
                return;
            }

            StringBuilder left = new StringBuilder();
            StringBuilder right = new StringBuilder();

            List<Word> leftList = Word.SplitString(LeftLines[leftLine]);
            List<Word> rightList = Word.SplitString(RightLines[rightLine]);

            Diff diff = new Diff(leftList, rightList, Word.Comparer, Word.Comparer);

            foreach (Diff.Hunk h in diff)
            {
                if (h.Same)
                {
                    for (int i = 0; i < h.Left.Count; i++)
                    {
                        WhitespaceDiff(left, rightList[h.Right.Start + i], leftList[h.Left.Start + i]);
                        WhitespaceDiff(right, leftList[h.Left.Start + i], rightList[h.Right.Start + i]);
                    }
                }
                else
                {
                    WordDiff(left, h.Left, h.Right, leftList, rightList);

                    WordDiff(right, h.Right, h.Left, rightList, leftList);
                }
            }

            Result.AppendFormat(@"<tr onclick='window.external.GoTo({1})' ondblclick='window.external.UndoChange({0},{1})'>
  <td>-</td>
  <td class='diff-deletedline'>", leftLine, rightLine);
            Result.Append(left);
            Result.Append(@"  </td>
  <td>+</td>
  <td class='diff-addedline'>");
            Result.Append(right);
            Result.Append(@"  </td>
		</tr>");
        }
        // diffLocation - desired output location. Filename will NOT be appended
        public void diffReports(string firstReportLocation, string secondReportLocation, string diffLocation)
        {
            // create reader & open file
            TextReader tr1 = new StreamReader(firstReportLocation);
            TextReader tr2 = new StreamReader(secondReportLocation);

            // read a files
            string file1 = tr1.ReadToEnd();
            string file2 = tr2.ReadToEnd();

            string[] file1Lines = Regex.Split(file1, "\r|\n|(\r\n)");
            string[] file2Lines = Regex.Split(file2, "\r|\n|(\r\n)");

            // close the stream
            tr1.Close();
            tr2.Close();

            // get diffs
            //string reportString = "";
            Diff diffUtil = new Diff();

            Diff.Item[] diffs = diffUtil.DiffText(file1, file2);

            // initialize the list that we will use to insert new lines and build diff IFQ
            List <string> mergeList = new List <string>();
            int           pos       = 0;

            for (int n = 0; n < diffs.Length; n++)
            {
                Diff.Item it = diffs[n];

                // write unchanged lines
                while ((pos < it.StartB) && (pos < file2Lines.Length))
                {
                    mergeList.Add(file2Lines[pos]);
                    pos++;
                } // while
                if (it.deletedA != it.insertedB)
                {
                    // write deleted chars
                    if (it.deletedA > 0)
                    {
                        mergeList.Add("<div style='color: #ff0000; text-decoration: line-through';>");
                        for (int m = 0; m < it.deletedA; m++)
                        {
                            mergeList.Add(file1Lines[it.StartA + m]);
                        } // for
                        mergeList.Add("</div>");
                    }
                }

                // write inserted chars
                if (pos < it.StartB + it.insertedB)
                {
                    mergeList.Add("<div style='color: #008E00'>");
                    while (pos < it.StartB + it.insertedB)
                    {
                        mergeList.Add(file2Lines[pos]);
                        pos++;
                    } // while
                    mergeList.Add("</div>");
                }     // if
            }         // while

            // write rest of unchanged chars
            while (pos < file2Lines.Length)
            {
                mergeList.Add(file2Lines[pos]);
                pos++;
            }

            /*  Saving Output */
            FileStream fStream = new FileStream(
                diffLocation,
                FileMode.Create,
                FileAccess.Write,
                FileShare.Read);
            StreamWriter sw = new StreamWriter(fStream);

            string[] reportStrings = mergeList.ToArray();
            sw.Write(string.Join("\n", reportStrings));
            sw.Close();      // Close the Stream
            fStream.Close(); // Close the File
        }
Exemplo n.º 35
0
        public static IEnumerable <Diff> Diffs(IReadOnlyList <TypeDefinition> olderTypes, IReadOnlyList <TypeDefinition> newerTypes)
        {
            var oSet = olderTypes.ToImmutableHashSet <TypeDefinition>(SameTypeComparer.Instance);
            var nSet = newerTypes.ToImmutableHashSet <TypeDefinition>(SameTypeComparer.Instance);

            foreach (var t in oSet.Union(nSet).OrderBy(x => x.FullName))
            {
                var inO   = oSet.TryGetValue(t, out var o);
                var inN   = nSet.TryGetValue(t, out var n);
                var oType = inO ? o.TypeType() : TypeType.None;
                var nType = inN ? n.TypeType() : TypeType.None;
                if (inO && inN && o.IsExported() && n.IsExported())
                {
                    // Both types present and exported; check for differences.
                    if (oType != nType)
                    {
                        // Type of type changed.
                        yield return(Diff.Major(Cause.TypeTypeChanged, $"'{o.Show()}' changed type from {oType.Show()} to {nType.Show()}."));
                    }
                    else
                    {
                        // Types both exported, and both same. Check inside.
                        IEnumerable <Diff> typeDiffs;
                        switch (oType)
                        {
                        case TypeType.Class: typeDiffs = Class.Diffs(o, n); break;

                        case TypeType.Interface: typeDiffs = Interface.Diffs(o, n); break;

                        case TypeType.Enum: typeDiffs = Enum.Diffs(o, n); break;

                        case TypeType.Delegate:
                        case TypeType.Struct:
                            // TODO!
                            typeDiffs = Enumerable.Empty <Diff>();
                            break;

                        default:
                            throw new InvalidOperationException($"Cannot diff types of type: {oType}.");
                        }
                        foreach (var typeDiff in typeDiffs)
                        {
                            yield return(typeDiff);
                        }
                    }
                }
                else
                {
                    // Presence/visibility changes.
                    if (inO && o.IsExported())
                    {
                        yield return(inN ?
                                     Diff.Major(Cause.TypeMadeNotExported, $"{oType.Show()} '{o.Show()}' made non-public.") :
                                     Diff.Major(Cause.TypeRemoved, $"{oType.Show()} '{o.Show()}' removed."));
                    }
                    else if (inN && n.IsExported())
                    {
                        yield return(inO ?
                                     Diff.Minor(Cause.TypeMadeExported, $"{nType.Show()} '{n.Show()}' made public.") :
                                     Diff.Minor(Cause.TypeAdded, $"{nType.Show()} '{n.Show()}' added."));;
                    }
                }
            }
        }
        public void GetAllXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<ictransitem>
    <itemid>26323</itemid>
    <itemdesc>Item Description</itemdesc>
    <warehouseid>93294</warehouseid>
    <quantity>2340</quantity>
    <unit>593</unit>
    <cost>32.35</cost>
    <locationid>SF</locationid>
    <departmentid>Purchasing</departmentid>
    <itemdetails>
        <itemdetail>
            <quantity>52</quantity>
            <lotno>3243</lotno>
        </itemdetail>
    </itemdetails>
    <customfields>
        <customfield>
            <customfieldname>customfield1</customfieldname>
            <customfieldvalue>customvalue1</customfieldvalue>
        </customfield>
    </customfields>
    <projectid>235</projectid>
    <customerid>23423434</customerid>
    <vendorid>797656</vendorid>
    <employeeid>90295</employeeid>
    <classid>243609</classid>
    <contractid>9062</contractid>
</ictransitem>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            InventoryTransactionLineCreate record = new InventoryTransactionLineCreate()
            {
                ItemId          = "26323",
                ItemDescription = "Item Description",
                WarehouseId     = "93294",
                Quantity        = 2340,
                Unit            = "593",
                Cost            = 32.35M,
                LocationId      = "SF",
                DepartmentId    = "Purchasing",
                ProjectId       = "235",
                CustomerId      = "23423434",
                VendorId        = "797656",
                EmployeeId      = "90295",
                ClassId         = "243609",
                ContractId      = "9062",
                CustomFields    = new Dictionary <string, dynamic>
                {
                    { "customfield1", "customvalue1" }
                }
            };

            TransactionItemDetail detail1 = new TransactionItemDetail()
            {
                Quantity  = 52,
                LotNumber = "3243",
            };

            record.ItemDetails.Add(detail1);

            record.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
Exemplo n.º 37
0
 public void ShouldParseEmptyString() =>
 AreEqual(0, Diff.Parse(string.Empty).Count());
            public void Remove()
            {
                var source = new ObservableCollection <int>
                {
                    1,
                    1,
                    1,
                    2,
                    2,
                    2,
                    3,
                    3,
                    3,
                };

                using (var view = source.AsMappingView(CreateStrictMock, WithIndex, x => x.Object.Dispose()))
                {
                    using (var actual = view.SubscribeAll())
                    {
                        var mock = view[0];
                        mock.Setup(x => x.Dispose());
                        source.RemoveAt(0);
                        mock.Verify(x => x.Dispose(), Times.Once);
                        CollectionAssert.AreEqual(source, view.Select(x => x.Object.Value));
                        CollectionAssert.AreEqual(source.Select((_, i) => i), view.Select(x => x.Object.Index));
                        var expected = new List <EventArgs>
                        {
                            CachedEventArgs.CountPropertyChanged,
                            CachedEventArgs.IndexerPropertyChanged,
                            Diff.CreateRemoveEventArgs(mock, 0),
                        };
                        CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                        mock = view[0];
                        mock.Setup(x => x.Dispose());
                        source.RemoveAt(0);
                        mock.Verify(x => x.Dispose(), Times.Once);
                        CollectionAssert.AreEqual(source, view.Select(x => x.Object.Value));
                        CollectionAssert.AreEqual(source.Select((_, i) => i), view.Select(x => x.Object.Index));
                        expected.AddRange(new EventArgs[]
                        {
                            CachedEventArgs.CountPropertyChanged,
                            CachedEventArgs.IndexerPropertyChanged,
                            Diff.CreateRemoveEventArgs(mock, 0),
                        });
                        CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                        mock = view[0];
                        mock.Setup(x => x.Dispose());
                        source.RemoveAt(0);
                        mock.Verify(x => x.Dispose(), Times.Once);
                        CollectionAssert.AreEqual(source, view.Select(x => x.Object.Value));
                        CollectionAssert.AreEqual(source.Select((_, i) => i), view.Select(x => x.Object.Index));
                        expected.AddRange(new EventArgs[]
                        {
                            CachedEventArgs.CountPropertyChanged,
                            CachedEventArgs.IndexerPropertyChanged,
                            Diff.CreateRemoveEventArgs(mock, 0),
                        });
                        CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);
                    }

                    foreach (var mock in view)
                    {
                        mock.Setup(x => x.Dispose());
                    }
                }
            }
        private void AnalyzeDiffs()
        {
            if (this.Inserts == 0 || this.Deletes == 0)
            {
                return;
            }

            var differences = this.Differences.Where(d => d.operation != Operation.EQUAL).ToList();

            bool hasChanges = false;

            bool hasMirror = false;

            do
            {
                hasChanges = false;

                Diff first  = null;
                Diff mirror = null;

                for (int index = 0; index < differences.Count; index++)
                {
                    var item = differences[index];

                    var invertOp = InvertOperation(item.operation);

                    Diff mirrorItem = differences.Skip(index + 1).FirstOrDefault(d => d.operation == invertOp && string.Equals(d.text, item.text));

                    if (mirrorItem != null)
                    {
                        first  = item;
                        mirror = mirrorItem;
                        break;
                    }
                }

                if (first != null && mirror != null)
                {
                    hasMirror  = true;
                    hasChanges = true;

                    differences.Remove(first);
                    differences.Remove(mirror);
                }
            } while (hasChanges);

            if (hasMirror)
            {
                if (differences.Count == 0)
                {
                    this.IsMirror = true;
                }
                else if (differences.All(d => d.operation == Operation.INSERT))
                {
                    this.IsMirrorWithInserts = true;
                }
                else if (differences.All(d => d.operation == Operation.DELETE))
                {
                    this.IsMirrorWithDeletes = true;
                }
                else
                {
                    this.IsMirrorWithComplex = true;
                }
            }
        }
Exemplo n.º 40
0
        private void UpdateSelectedFileViewers(bool force = false)
        {
            var selectedRevisions = FileChanges.GetSelectedRevisions();

            if (selectedRevisions.Count == 0)
            {
                return;
            }

            GitRevision revision = selectedRevisions[0];
            var         children = FileChanges.GetRevisionChildren(revision.ObjectId);

            var fileName = revision.Name;

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = FileName;
            }

            SetTitle(fileName);

            if (revision.IsArtificial)
            {
                tabControl1.SelectedTab = DiffTab;

                CommitInfoTabPage.Parent = null;
                BlameTab.Parent          = null;
                ViewTab.Parent           = null;
            }
            else
            {
                if (CommitInfoTabPage.Parent == null)
                {
                    tabControl1.TabPages.Insert(0, CommitInfoTabPage);
                }

                if (ViewTab.Parent == null)
                {
                    var index = tabControl1.TabPages.IndexOf(DiffTab);
                    Debug.Assert(index != -1, "TabControl should contain diff tab page");
                    tabControl1.TabPages.Insert(index + 1, ViewTab);
                }

                if (BlameTab.Parent == null)
                {
                    var index = tabControl1.TabPages.IndexOf(ViewTab);
                    Debug.Assert(index != -1, "TabControl should contain view tab page");
                    tabControl1.TabPages.Insert(index + 1, BlameTab);
                }
            }

            if (tabControl1.SelectedTab == BlameTab)
            {
                Blame.LoadBlame(revision, children, fileName, FileChanges, BlameTab, Diff.Encoding, force: force);
            }
            else if (tabControl1.SelectedTab == ViewTab)
            {
                View.Encoding = Diff.Encoding;
                View.ViewGitItemRevisionAsync(fileName, revision.ObjectId);
            }
            else if (tabControl1.SelectedTab == DiffTab)
            {
                var file = new GitItemStatus
                {
                    IsTracked   = true,
                    Name        = fileName,
                    IsSubmodule = GitModule.IsValidGitWorkingDir(_fullPathResolver.Resolve(fileName))
                };
                Diff.ViewChangesAsync(FileChanges.GetSelectedRevisions(), file, "You need to select at least one revision to view diff.");
            }
            else if (tabControl1.SelectedTab == CommitInfoTabPage)
            {
                CommitDiff.SetRevision(revision.ObjectId, fileName);
            }

            if (_buildReportTabPageExtension == null)
            {
                _buildReportTabPageExtension = new BuildReportTabPageExtension(() => Module, tabControl1, _buildReportTabCaption.Text);
            }

            _buildReportTabPageExtension.FillBuildReport(selectedRevisions.Count == 1 ? revision : null);
        }
        async Task <IImmutableDictionary <string, IModuleIdentity> > GetModuleIdentitiesAsync(Diff diff)
        {
            IList <string>       updatedModuleNames = diff.Updated.Select(m => ModuleIdentityHelper.GetModuleIdentityName(m.Name)).ToList();
            IEnumerable <string> removedModuleNames = diff.Removed.Select(m => ModuleIdentityHelper.GetModuleIdentityName(m));

            IImmutableDictionary <string, Identity> identities = (await this.identityManager.GetIdentities()).ToImmutableDictionary(i => i.ModuleId);

            // Create identities for all modules that are in the deployment but aren't in iotedged.
            IEnumerable <string> createIdentities = updatedModuleNames.Where(m => !identities.ContainsKey(m));

            // Update identities for all modules that are in the deployment and are in iotedged (except for Edge Agent which gets special
            // treatment in iotedged).
            //
            // NOTE: This update can potentiatlly be made more efficient by checking that an update is actually needed, i.e. if auth type
            // is not SAS and/or if the credentials are not what iotedged expects it to be.
            IEnumerable <Identity> updateIdentities = updatedModuleNames
                                                      .Where(m => identities.ContainsKey(m) && m != Constants.EdgeAgentModuleIdentityName)
                                                      .Select(m => identities[m]);

            // Remove identities which exist in iotedged but don't exist in the deployment anymore. We exclude however, identities that
            // aren't managed by Edge since these have been created by some out-of-band process and Edge doesn't "own" the identity.
            IEnumerable <string> removeIdentities = removedModuleNames.Where(
                m => identities.ContainsKey(m) &&
                Constants.ModuleIdentityEdgeManagedByValue.Equals(identities[m].ManagedBy, StringComparison.OrdinalIgnoreCase));

            // First remove identities (so that we don't go over the IoTHub limit).
            await Task.WhenAll(removeIdentities.Select(i => this.identityManager.DeleteIdentityAsync(i)));

            // Create/update identities.
            IEnumerable <Task <Identity> > createTasks = createIdentities.Select(i => this.identityManager.CreateIdentityAsync(i, Constants.ModuleIdentityEdgeManagedByValue));
            IEnumerable <Task <Identity> > updateTasks = updateIdentities.Select(i => this.identityManager.UpdateIdentityAsync(i.ModuleId, i.GenerationId, i.ManagedBy));

            Identity[] upsertedIdentities = await Task.WhenAll(createTasks.Concat(updateTasks));

            List <IModuleIdentity> moduleIdentities = upsertedIdentities.Select(m => this.GetModuleIdentity(m)).ToList();

            // Add the module identity for Edge Agent in the returned dictionary
            // because is was excluded from the update call.
            if (identities.ContainsKey(Constants.EdgeAgentModuleIdentityName))
            {
                moduleIdentities.Add(this.GetModuleIdentity(identities[Constants.EdgeAgentModuleIdentityName]));
            }

            return(moduleIdentities.ToImmutableDictionary(m => ModuleIdentityHelper.GetModuleName(m.ModuleId)));
        }
Exemplo n.º 42
0
        public void AddManyVisibleWhenFiltered()
        {
            var source    = new ObservableCollection <int>();
            var scheduler = new TestScheduler();

            using (var view = source.AsReadOnlyFilteredView(x => x % 2 == 0, scheduler))
            {
                scheduler.Start();
                CollectionAssert.IsEmpty(view);
                using (var actual = view.SubscribeAll())
                {
                    source.Add(1);
                    scheduler.Start();
                    CollectionAssert.IsEmpty(view);
                    var expected = new List <EventArgs>();
                    CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                    source.Add(2);
                    scheduler.Start();
                    CollectionAssert.AreEqual(new[] { 2 }, view);
                    expected.AddRange(
                        new EventArgs[]
                    {
                        CachedEventArgs.CountPropertyChanged,
                        CachedEventArgs.IndexerPropertyChanged,
                        Diff.CreateAddEventArgs(2, 0),
                    });
                    CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                    source.Add(3);
                    scheduler.Start();
                    CollectionAssert.AreEqual(new[] { 2 }, view);
                    CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                    source.Add(4);
                    scheduler.Start();
                    CollectionAssert.AreEqual(new[] { 2, 4 }, view);
                    expected.AddRange(
                        new EventArgs[]
                    {
                        CachedEventArgs.CountPropertyChanged,
                        CachedEventArgs.IndexerPropertyChanged,
                        Diff.CreateAddEventArgs(4, 1),
                    });
                    CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                    source.Add(5);
                    scheduler.Start();
                    CollectionAssert.AreEqual(new[] { 2, 4 }, view);
                    CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);

                    source.Add(6);
                    scheduler.Start();
                    CollectionAssert.AreEqual(new[] { 2, 4, 6 }, view);
                    expected.AddRange(
                        new EventArgs[]
                    {
                        CachedEventArgs.CountPropertyChanged,
                        CachedEventArgs.IndexerPropertyChanged,
                        Diff.CreateAddEventArgs(6, 2),
                    });
                    CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default);
                }
            }
        }
Exemplo n.º 43
0
 public virtual bool IsIncluded(SongEditableFields field)
 {
     return(Diff != null && Data != null && Diff.IsIncluded(field));
 }
Exemplo n.º 44
0
        public void Check5Test()
        {
            var db1 = new DataBase()
            {
                Tables = new Dictionary <string, Table>()
                {
                    {
                        "users", new Table()
                        {
                            Columns = new Dictionary <string, Column>()
                            {
                                {
                                    "id", new Column()
                                    {
                                        Id = true
                                    }
                                },
                                {
                                    "name", new Column()
                                    {
                                        Type    = "nvarchar",
                                        Length  = "100",
                                        NotNull = true
                                    }
                                }
                            },

                            /*Indices = new Dictionary<string, Index>()
                             * {
                             *  { "ix_name", new Index()
                             *  {
                             *      Columns = new Dictionary<string, string>(){ {"name", "asc" }}
                             *  }}
                             * }*/
                        }
                    }
                }
            };
            var db2 = new DataBase()
            {
                Tables = new Dictionary <string, Table>()
                {
                    {
                        "users", new Table()
                        {
                            Columns = new Dictionary <string, Column>()
                            {
                                {
                                    "id", new Column()
                                    {
                                        Id = true
                                    }
                                },
                                {
                                    "name", new Column()
                                    {
                                        Type    = "nvarchar",
                                        Length  = "100",
                                        NotNull = true
                                    }
                                }
                            },
                            Indexes = new Dictionary <string, Index>()
                            {
                                { "ix_name", new Index()
                                  {
                                      Columns = new Dictionary <string, string>()
                                      {
                                          { "name", "desc" }
                                      }
                                  } }
                            }
                        }
                    }
                }
            };

            var diff = new Diff(db1, db2);

            Assert.True(diff.HasDiff);
        }
Exemplo n.º 45
0
        public SQLBeforeAndAfterViewer(string sqlBefore, string sqlAfter, string headerTextForBefore, string headerTextForAfter, string caption, MessageBoxButtons buttons, string language = "mssql")
        {
            InitializeComponent();

            bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);

            if (designMode) //dont add the QueryEditor if we are in design time (visual studio) because it breaks
            {
                return;
            }

            QueryEditorBefore          = new ScintillaTextEditorFactory().Create();
            QueryEditorBefore.Text     = sqlBefore;
            QueryEditorBefore.ReadOnly = true;

            splitContainer1.Panel1.Controls.Add(QueryEditorBefore);


            QueryEditorAfter          = new ScintillaTextEditorFactory().Create();
            QueryEditorAfter.Text     = sqlAfter;
            QueryEditorAfter.ReadOnly = true;

            splitContainer1.Panel2.Controls.Add(QueryEditorAfter);


            //compute difference
            var highlighter = new ScintillaLineHighlightingHelper();

            highlighter.ClearAll(QueryEditorAfter);
            highlighter.ClearAll(QueryEditorBefore);

            if (sqlBefore == null)
            {
                sqlBefore = "";
            }
            if (sqlAfter == null)
            {
                sqlAfter = "";
            }

            Diff diff = new Diff();

            foreach (Diff.Item item in diff.DiffText(sqlBefore, sqlAfter))
            {
                for (int i = item.StartA; i < item.StartA + item.deletedA; i++)
                {
                    highlighter.HighlightLine(QueryEditorBefore, i, Color.Pink);
                }

                for (int i = item.StartB; i < item.StartB + item.insertedB; i++)
                {
                    highlighter.HighlightLine(QueryEditorAfter, i, Color.LawnGreen);
                }
            }

            switch (buttons)
            {
            case MessageBoxButtons.OK:
                btnYes.Visible = true;
                btnYes.Text    = "Ok";
                btnNo.Visible  = false;
                break;

            case MessageBoxButtons.YesNo:
                btnYes.Visible = true;
                btnNo.Visible  = true;
                break;

            default:
                throw new NotSupportedException("buttons");
            }

            lblBefore.Text = headerTextForBefore;
            lblAfter.Text  = headerTextForAfter;

            this.Text = caption;
        }
Exemplo n.º 46
0
        public void GetAllXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <update>
        <CUSTOMER>
            <CUSTOMERID>C1234</CUSTOMERID>
            <NAME>Intacct Corp</NAME>
            <DISPLAYCONTACT>
                <PRINTAS>Intacct Corporation</PRINTAS>
                <COMPANYNAME>Intacct Corp.</COMPANYNAME>
                <TAXABLE>true</TAXABLE>
                <TAXGROUP>CA</TAXGROUP>
                <PREFIX>Mr</PREFIX>
                <FIRSTNAME>Bill</FIRSTNAME>
                <LASTNAME>Smith</LASTNAME>
                <INITIAL>G</INITIAL>
                <PHONE1>12</PHONE1>
                <PHONE2>34</PHONE2>
                <CELLPHONE>56</CELLPHONE>
                <PAGER>78</PAGER>
                <FAX>90</FAX>
                <EMAIL1>[email protected]</EMAIL1>
                <EMAIL2>[email protected]</EMAIL2>
                <URL1>www.intacct.com</URL1>
                <URL2>us.intacct.com</URL2>
                <MAILADDRESS>
                    <ADDRESS1>300 Park Ave</ADDRESS1>
                    <ADDRESS2>Ste 1400</ADDRESS2>
                    <CITY>San Jose</CITY>
                    <STATE>CA</STATE>
                    <ZIP>95110</ZIP>
                    <COUNTRY>United States</COUNTRY>
                </MAILADDRESS>
            </DISPLAYCONTACT>
            <ONETIME>false</ONETIME>
            <STATUS>active</STATUS>
            <HIDEDISPLAYCONTACT>false</HIDEDISPLAYCONTACT>
            <CUSTTYPE>SaaS</CUSTTYPE>
            <PARENTID>C5678</PARENTID>
            <GLGROUP>Group</GLGROUP>
            <TERRITORYID>NE</TERRITORYID>
            <SUPDOCID>A1234</SUPDOCID>
            <TERMNAME>N30</TERMNAME>
            <OFFSETGLACCOUNTNO>1200</OFFSETGLACCOUNTNO>
            <ARACCOUNT>4000</ARACCOUNT>
            <SHIPPINGMETHOD>USPS</SHIPPINGMETHOD>
            <RESALENO>123</RESALENO>
            <TAXID>12-3456789</TAXID>
            <CREDITLIMIT>1234.56</CREDITLIMIT>
            <ONHOLD>false</ONHOLD>
            <DELIVERYOPTIONS>Print#~#E-Mail</DELIVERYOPTIONS>
            <CUSTMESSAGEID>hello</CUSTMESSAGEID>
            <COMMENTS>my comment</COMMENTS>
            <CURRENCY>USD</CURRENCY>
            <ARINVOICEPRINTTEMPLATEID>temp1</ARINVOICEPRINTTEMPLATEID>
            <OEQUOTEPRINTTEMPLATEID>temp2</OEQUOTEPRINTTEMPLATEID>
            <OEORDERPRINTTEMPLATEID>temp3</OEORDERPRINTTEMPLATEID>
            <OELISTPRINTTEMPLATEID>temp4</OELISTPRINTTEMPLATEID>
            <OEINVOICEPRINTTEMPLATEID>temp5</OEINVOICEPRINTTEMPLATEID>
            <OEADJPRINTTEMPLATEID>temp6</OEADJPRINTTEMPLATEID>
            <OEOTHERPRINTTEMPLATEID>temp7</OEOTHERPRINTTEMPLATEID>
            <CONTACTINFO>
                <CONTACTNAME>primary</CONTACTNAME>
            </CONTACTINFO>
            <BILLTO>
                <CONTACTNAME>bill to</CONTACTNAME>
            </BILLTO>
            <SHIPTO>
                <CONTACTNAME>ship to</CONTACTNAME>
            </SHIPTO>
            <OBJECTRESTRICTION>Restricted</OBJECTRESTRICTION>
            <RESTRICTEDLOCATIONS>100#~#200</RESTRICTEDLOCATIONS>
            <RESTRICTEDDEPARTMENTS>D100#~#D200</RESTRICTEDDEPARTMENTS>
            <CUSTOMFIELD1>Hello</CUSTOMFIELD1>
        </CUSTOMER>
    </update>
</function>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            CustomerUpdate record = new CustomerUpdate("unittest")
            {
                CustomerId            = "C1234",
                CustomerName          = "Intacct Corp",
                PrintAs               = "Intacct Corporation",
                CompanyName           = "Intacct Corp.",
                Taxable               = true,
                TaxId                 = "12-3456789",
                ContactTaxGroupName   = "CA",
                Prefix                = "Mr",
                FirstName             = "Bill",
                LastName              = "Smith",
                MiddleName            = "G",
                PrimaryPhoneNo        = "12",
                SecondaryPhoneNo      = "34",
                CellularPhoneNo       = "56",
                PagerNo               = "78",
                FaxNo                 = "90",
                PrimaryEmailAddress   = "*****@*****.**",
                SecondaryEmailAddress = "*****@*****.**",
                PrimaryUrl            = "www.intacct.com",
                SecondaryUrl          = "us.intacct.com",
                AddressLine1          = "300 Park Ave",
                AddressLine2          = "Ste 1400",
                City                                = "San Jose",
                StateProvince                       = "CA",
                ZipPostalCode                       = "95110",
                Country                             = "United States",
                OneTime                             = false,
                Active                              = true,
                ExcludedFromContactList             = false,
                CustomerTypeId                      = "SaaS",
                ParentCustomerId                    = "C5678",
                GlGroupName                         = "Group",
                TerritoryId                         = "NE",
                AttachmentsId                       = "A1234",
                PaymentTerm                         = "N30",
                OffsetArGlAccountNo                 = "1200",
                DefaultRevenueGlAccountNo           = "4000",
                ShippingMethod                      = "USPS",
                ResaleNumber                        = "123",
                CreditLimit                         = 1234.56M,
                OnHold                              = false,
                DeliveryMethod                      = "Print#~#E-Mail",
                DefaultInvoiceMessage               = "hello",
                Comments                            = "my comment",
                DefaultCurrency                     = "USD",
                PrintOptionArInvoiceTemplateName    = "temp1",
                PrintOptionOeQuoteTemplateName      = "temp2",
                PrintOptionOeOrderTemplateName      = "temp3",
                PrintOptionOeListTemplateName       = "temp4",
                PrintOptionOeInvoiceTemplateName    = "temp5",
                PrintOptionOeAdjustmentTemplateName = "temp6",
                PrintOptionOeOtherTemplateName      = "temp7",
                PrimaryContactName                  = "primary",
                BillToContactName                   = "bill to",
                ShipToContactName                   = "ship to",
                RestrictionType                     = "Restricted",
                RestrictedLocations                 = new List <string>()
                {
                    "100",
                    "200",
                },
                RestrictedDepartments = new List <string>()
                {
                    "D100",
                    "D200",
                },
                CustomFields = new Dictionary <string, dynamic>
                {
                    { "CUSTOMFIELD1", "Hello" }
                }
            };

            record.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
Exemplo n.º 47
0
 public PatchFromString(Diff patch)
     : this(string.Empty, patch.ToString())
 {
 }
Exemplo n.º 48
0
        public void NoChange()
        {
            var actual = Diff.CollectionChange(new[] { 1, 2, 3 }, new[] { 1, 2, 3 });

            Assert.IsNull(actual);
        }
Exemplo n.º 49
0
		public DiffWidget(Diff diff, Options options) : this(Hunkify(diff), options) {
		}
Exemplo n.º 50
0
        public void TestDiff(ModuleSet start, ModuleSet end, Diff expected)
        {
            Diff setDifference = end.Diff(start);

            Assert.Equal(setDifference, expected);
        }
        public void GetAllXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <create_aradjustment>
        <customerid>CUSTOMER1</customerid>
        <datecreated>
            <year>2015</year>
            <month>06</month>
            <day>30</day>
        </datecreated>
        <dateposted>
            <year>2015</year>
            <month>06</month>
            <day>30</day>
        </dateposted>
        <batchkey>20323</batchkey>
        <adjustmentno>234</adjustmentno>
        <action>Submit</action>
        <invoiceno>234235</invoiceno>
        <description>Some description</description>
        <externalid>20394</externalid>
        <basecurr>USD</basecurr>
        <currency>USD</currency>
        <exchratedate>
            <year>2016</year>
            <month>06</month>
            <day>30</day>
        </exchratedate>
        <exchratetype>Intacct Daily Rate</exchratetype>
        <nogl>false</nogl>
        <customfields>
            <customfield>
                <customfieldname>customfield1</customfieldname>
                <customfieldvalue>customvalue1</customfieldvalue>
            </customfield>
        </customfields>
        <aradjustmentitems>
            <lineitem>
                <glaccountno />
                <amount>76343.43</amount>
            </lineitem>
        </aradjustmentitems>
    </create_aradjustment>
</function>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            ArAdjustmentCreate record = new ArAdjustmentCreate("unittest")
            {
                CustomerId          = "CUSTOMER1",
                TransactionDate     = new DateTime(2015, 06, 30),
                GlPostingDate       = new DateTime(2015, 06, 30),
                SummaryRecordNo     = "20323",
                AdjustmentNumber    = "234",
                Action              = "Submit",
                InvoiceNumber       = "234235",
                Description         = "Some description",
                ExternalId          = "20394",
                BaseCurrency        = "USD",
                TransactionCurrency = "USD",
                ExchangeRateDate    = new DateTime(2016, 06, 30),
                ExchangeRateType    = "Intacct Daily Rate",
                DoNotPostToGL       = false,
                CustomFields        = new Dictionary <string, dynamic>
                {
                    { "customfield1", "customvalue1" }
                },
            };

            ArAdjustmentLineCreate line1 = new ArAdjustmentLineCreate();

            line1.TransactionAmount = 76343.43M;

            record.Lines.Add(line1);

            record.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
Exemplo n.º 52
0
        public void GetAllXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <update>
        <VENDOR>
            <VENDORID>V1234</VENDORID>
            <NAME>Intacct Corp</NAME>
            <DISPLAYCONTACT>
                <PRINTAS>Intacct Corporation</PRINTAS>
                <COMPANYNAME>Intacct Corp.</COMPANYNAME>
                <TAXABLE>true</TAXABLE>
                <TAXGROUP>CA</TAXGROUP>
                <PREFIX>Mr</PREFIX>
                <FIRSTNAME>Bill</FIRSTNAME>
                <LASTNAME>Smith</LASTNAME>
                <INITIAL>G</INITIAL>
                <PHONE1>12</PHONE1>
                <PHONE2>34</PHONE2>
                <CELLPHONE>56</CELLPHONE>
                <PAGER>78</PAGER>
                <FAX>90</FAX>
                <EMAIL1>[email protected]</EMAIL1>
                <EMAIL2>[email protected]</EMAIL2>
                <URL1>www.intacct.com</URL1>
                <URL2>us.intacct.com</URL2>
                <MAILADDRESS>
                    <ADDRESS1>300 Park Ave</ADDRESS1>
                    <ADDRESS2>Ste 1400</ADDRESS2>
                    <CITY>San Jose</CITY>
                    <STATE>CA</STATE>
                    <ZIP>95110</ZIP>
                    <COUNTRY>United States</COUNTRY>
                </MAILADDRESS>
            </DISPLAYCONTACT>
            <ONETIME>false</ONETIME>
            <STATUS>active</STATUS>
            <HIDEDISPLAYCONTACT>false</HIDEDISPLAYCONTACT>
            <VENDTYPE>SaaS</VENDTYPE>
            <PARENTID>V5678</PARENTID>
            <GLGROUP>Group</GLGROUP>
            <TAXID>12-3456789</TAXID>
            <NAME1099>INTACCT CORP</NAME1099>
            <FORM1099TYPE>MISC</FORM1099TYPE>
            <FORM1099BOX>3</FORM1099BOX>
            <SUPDOCID>A1234</SUPDOCID>
            <APACCOUNT>2000</APACCOUNT>
            <CREDITLIMIT>1234.56</CREDITLIMIT>
            <ONHOLD>false</ONHOLD>
            <DONOTCUTCHECK>false</DONOTCUTCHECK>
            <COMMENTS>my comment</COMMENTS>
            <CURRENCY>USD</CURRENCY>
            <CONTACTINFO>
                <CONTACTNAME>primary</CONTACTNAME>
            </CONTACTINFO>
            <PAYTO>
                <CONTACTNAME>pay to</CONTACTNAME>
            </PAYTO>
            <RETURNTO>
                <CONTACTNAME>return to</CONTACTNAME>
            </RETURNTO>
            <PAYMETHODKEY>Printed Check</PAYMETHODKEY>
            <MERGEPAYMENTREQ>true</MERGEPAYMENTREQ>
            <PAYMENTNOTIFY>true</PAYMENTNOTIFY>
            <BILLINGTYPE>openitem</BILLINGTYPE>
            <PAYMENTPRIORITY>Normal</PAYMENTPRIORITY>
            <TERMNAME>N30</TERMNAME>
            <DISPLAYTERMDISCOUNT>false</DISPLAYTERMDISCOUNT>
            <ACHENABLED>true</ACHENABLED>
            <ACHBANKROUTINGNUMBER>123456789</ACHBANKROUTINGNUMBER>
            <ACHACCOUNTNUMBER>1111222233334444</ACHACCOUNTNUMBER>
            <ACHACCOUNTTYPE>Checking Account</ACHACCOUNTTYPE>
            <ACHREMITTANCETYPE>CTX</ACHREMITTANCETYPE>
            <VENDORACCOUNTNO>9999999</VENDORACCOUNTNO>
            <DISPLAYACCTNOCHECK>false</DISPLAYACCTNOCHECK>
            <OBJECTRESTRICTION>Restricted</OBJECTRESTRICTION>
            <RESTRICTEDLOCATIONS>100#~#200</RESTRICTEDLOCATIONS>
            <RESTRICTEDDEPARTMENTS>D100#~#D200</RESTRICTEDDEPARTMENTS>
            <CUSTOMFIELD1>Hello</CUSTOMFIELD1>
        </VENDOR>
    </update>
</function>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            VendorUpdate record = new VendorUpdate("unittest")
            {
                VendorId              = "V1234",
                VendorName            = "Intacct Corp",
                PrintAs               = "Intacct Corporation",
                CompanyName           = "Intacct Corp.",
                Taxable               = true,
                TaxId                 = "12-3456789",
                ContactTaxGroupName   = "CA",
                Prefix                = "Mr",
                FirstName             = "Bill",
                LastName              = "Smith",
                MiddleName            = "G",
                PrimaryPhoneNo        = "12",
                SecondaryPhoneNo      = "34",
                CellularPhoneNo       = "56",
                PagerNo               = "78",
                FaxNo                 = "90",
                PrimaryEmailAddress   = "*****@*****.**",
                SecondaryEmailAddress = "*****@*****.**",
                PrimaryUrl            = "www.intacct.com",
                SecondaryUrl          = "us.intacct.com",
                AddressLine1          = "300 Park Ave",
                AddressLine2          = "Ste 1400",
                City                             = "San Jose",
                StateProvince                    = "CA",
                ZipPostalCode                    = "95110",
                Country                          = "United States",
                OneTime                          = false,
                Active                           = true,
                ExcludedFromContactList          = false,
                VendorTypeId                     = "SaaS",
                ParentVendorId                   = "V5678",
                GlGroupName                      = "Group",
                Form1099Name                     = "INTACCT CORP",
                Form1099Type                     = "MISC",
                Form1099Box                      = "3",
                AttachmentsId                    = "A1234",
                DefaultExpenseGlAccountNo        = "2000",
                CreditLimit                      = 1234.56M,
                OnHold                           = false,
                DoNotPay                         = false,
                Comments                         = "my comment",
                DefaultCurrency                  = "USD",
                PrimaryContactName               = "primary",
                PayToContactName                 = "pay to",
                ReturnToContactName              = "return to",
                PreferredPaymentMethod           = "Printed Check",
                MergePaymentRequests             = true,
                SendAutomaticPaymentNotification = true,
                VendorBillingType                = "openitem",
                PaymentPriority                  = "Normal",
                PaymentTerm                      = "N30",
                TermDiscountDisplayedOnCheckStub = false,
                AchEnabled                       = true,
                AchBankRoutingNo                 = "123456789",
                AchBankAccountNo                 = "1111222233334444",
                AchBankAccountType               = "Checking Account",
                AchBankAccountClass              = "CTX",
                VendorAccountNo                  = "9999999",
                LocationAssignedAccountNoDisplayedOnCheckStub = false,
                RestrictionType     = "Restricted",
                RestrictedLocations = new List <string>()
                {
                    "100",
                    "200",
                },
                RestrictedDepartments = new List <string>()
                {
                    "D100",
                    "D200",
                },
                CustomFields = new Dictionary <string, dynamic>
                {
                    { "CUSTOMFIELD1", "Hello" }
                }
            };

            record.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
Exemplo n.º 53
0
        static void WhitespaceDiff(StringBuilder res, Word left, Word right)
        {
            if (left.Whitespace == right.Whitespace) res.Append(HttpUtility.HtmlEncode(right.ToString()));
            else
            {
                res.Append(HttpUtility.HtmlEncode(right.TheWord));
                char[] leftChars = left.Whitespace.ToCharArray();
                char[] rightChars = right.Whitespace.ToCharArray();

                Diff diff = new Diff(leftChars, rightChars, Word.Comparer, Word.Comparer);
                foreach (Diff.Hunk h in diff)
                {
                    if (h.Same)
                        res.Append(rightChars, h.Right.Start, h.Right.Count);
                    else
                    {
                        res.Append("<span class='diffchange'>");
                        res.Append('\x00A0', h.Right.Count); // replace spaces with NBSPs to make 'em visible
                        res.Append("</span>");
                    }
                }
            }
        }
Exemplo n.º 54
0
        private void ShowTableDiff(Diff diff)
        {
            if (!diff.AddedTables.Any() && !diff.DeletedTableNames.Any() && !diff.ModifiedTables.Any())
            {
                return;
            }

            _output.WriteLine("* tables");
            foreach (var(tableName, table) in diff.AddedTables)
            {
                _output.SetColor(AddColor);
                _output.WriteLine($"  + {tableName}");
                _output.ClearColor();
            }

            foreach (var tableName in diff.DeletedTableNames)
            {
                _output.SetColor(DeleteColor);
                _output.WriteLine($"  - {tableName}");
                _output.ClearColor();
            }

            foreach (var(tableName, table) in diff.ModifiedTables)
            {
                _output.SetColor(ModifyColor);
                _output.WriteLine($"  # {tableName}");
                _output.ClearColor();

                foreach (var(columnName, column) in table.AddedColumns)
                {
                    _output.SetColor(AddColor);
                    _output.WriteLine($"    + {columnName}");
                    _output.ClearColor();
                }

                foreach (var columnName in table.DeletedColumnName)
                {
                    _output.SetColor(DeleteColor);
                    _output.WriteLine($"    - {columnName}");
                    _output.ClearColor();
                }

                foreach (var(columnName, column) in table.ModifiedColumns)
                {
                    var orgColumn = column[0];
                    var newColumn = column[1];
                    _output.SetColor(ModifyColor);
                    _output.WriteLine($"    # {columnName}");


                    if (orgColumn.Type != newColumn.Type || orgColumn.Length != newColumn.Length)
                    {
                        var orgType = orgColumn.Type;
                        if (orgColumn.LengthInt > 0 && !string.IsNullOrWhiteSpace(orgColumn.Length))
                        {
                            orgType += $"({orgColumn.Length})";
                        }

                        var newType = newColumn.Type;
                        if (newColumn.LengthInt > 0 && !string.IsNullOrWhiteSpace(newColumn.Length))
                        {
                            newType += $"({newColumn.Length})";
                        }


                        _output.WriteLine($"        type: {orgType} -> {newType}");
                    }

                    if (orgColumn.Pk != newColumn.Pk)
                    {
                        _output.WriteLine($"        pk: {orgColumn.Pk} -> {newColumn.Pk}");
                    }

                    if (orgColumn.NotNull != newColumn.NotNull)
                    {
                        _output.WriteLine($"        not null: {orgColumn.NotNull} -> {newColumn.NotNull}");
                    }

                    _output.ClearColor();
                }

                foreach (var(indexName, index) in table.AddedIndexes)
                {
                    _output.SetColor(AddColor);
                    _output.WriteLine($"    + {indexName}");
                    _output.ClearColor();
                }

                foreach (var indexName in table.DeletedIndexNames)
                {
                    _output.SetColor(DeleteColor);
                    _output.WriteLine($"    - {indexName}");
                    _output.ClearColor();
                }

                foreach (var(indexName, indices) in table.ModifiedIndexes)
                {
                    var orgIndex = indices[0];
                    var newIndex = indices[1];

                    _output.SetColor(ModifyColor);
                    _output.WriteLine($"    # {indexName}");


                    if (orgIndex.Type != newIndex.Type)
                    {
                        _output.WriteLine($"        type: {orgIndex.Type} -> {newIndex.Type}");
                    }

                    var orgIndexColumns = string.Join(",", orgIndex.Columns.Select(x => $"{x.Key} {x.Value}"));
                    var newIndexColumns = string.Join(",", newIndex.Columns.Select(x => $"{x.Key} {x.Value}"));
                    if (orgIndexColumns != newIndexColumns)
                    {
                        _output.WriteLine($"        columns: {orgIndexColumns} -> {newIndexColumns}");
                    }

                    if (orgIndex.Unique != newIndex.Unique)
                    {
                        _output.WriteLine($"        unique: ${orgIndex.Unique} -> ${newIndex.Unique}");
                    }

                    if (!(orgIndex.Spatial ?? new Spatial()).Equals(newIndex.Spatial ?? new Spatial()))
                    {
                        _output.WriteLine($"        spatial:");
                        _output.WriteLine(
                            $"          tessellationSchema: {orgIndex.Spatial?.TessellationSchema} -> {newIndex.Spatial?.TessellationSchema}");
                        _output.WriteLine($"          level1: {orgIndex.Spatial?.Level1} -> {newIndex.Spatial?.Level1}");
                        _output.WriteLine($"          level2: {orgIndex.Spatial?.Level2} -> {newIndex.Spatial?.Level2}");
                        _output.WriteLine($"          level3: {orgIndex.Spatial?.Level3} -> {newIndex.Spatial?.Level3}");
                        _output.WriteLine($"          level4: {orgIndex.Spatial?.Level4} -> {newIndex.Spatial?.Level4}");
                        _output.WriteLine(
                            $"          cellsPerObject: {orgIndex.Spatial?.CellsPerObject} -> {newIndex.Spatial?.CellsPerObject}");
                    }

                    _output.ClearColor();
                }
            }
        }
Exemplo n.º 55
0
 public void EasyMode()
 {
     difficultyMode = Diff.Ez;
 }
Exemplo n.º 56
0
    public static double[] sample_candidate(int chain_index, int chain_num, double[] cr,
                                            int cr_index, int cr_num, int gen_index, int gen_num,
                                            double[] jumprate_table, int jumpstep, double[] limits, int pair_num,
                                            int par_num, double[] z)

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    SAMPLE_CANDIDATE generates candidate parameter samples.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    01 May 2013
    //
    //  Author:
    //
    //    Original FORTRAN90 version by Guannan Zhang.
    //    C++ version by John Burkardt.
    //
    //  Reference:
    //
    //    Jasper Vrugt, CJF ter Braak, CGH Diks, Bruce Robinson, James Hyman,
    //    Dave Higdon,
    //    Accelerating Markov Chain Monte Carlo Simulation by Differential
    //    Evolution with Self-Adaptive Randomized Subspace Sampling,
    //    International Journal of Nonlinear Sciences and Numerical Simulation,
    //    Volume 10, Number 3, March 2009, pages 271-288.
    //
    //  Parameters:
    //
    //    Input, int CHAIN_INDEX, the chain index.
    //    0 <= CHAIN_INDEX < CHAIN_NUM.
    //
    //    Input, int CHAIN_NUM, the total number of chains.
    //    3 <= CHAIN_NUM.
    //
    //    Input, double CR[CR_NUM], the CR values.
    //
    //    Input, int CR_INDEX, the index of the chosen CR value.
    //    0 <= CR_INDEX < CR_NUM.
    //
    //    Input, int CR_NUM, the total number of CR values.
    //    1 <= CR_NUM.
    //
    //    Input, int GEN_INDEX, the current generation.
    //    0 <= GEN_INDEX < GEN_NUM.
    //
    //    Input, int GEN_NUM, the total number of generations.
    //    2 <= GEN_NUM.
    //
    //    Input, double JUMPRATE_TABLE[PAR_NUM], the jumprate table.
    //
    //    Input, int JUMPSTEP, forces a "long jump" every
    //    JUMPSTEP generations.
    //
    //    Input, double LIMITS[2*PAR_NUM], limits for the parameters.
    //
    //    Input, int PAIR_NUM, the number of pairs of
    //    crossover chains.
    //    0 <= PAIR_NUM.
    //
    //    Input, int PAR_NUM, the total number of parameters.
    //    1 <= PAR_NUM.
    //
    //    Input, double Z[PAR_NUM*CHAIN_NUM*GEN_NUM], the Markov chain
    //    sample data.
    //
    //    Output, double SAMPLE_CANDIDATE[PAR_NUM], a candidate parameter sample.
    //
    //  Local parameters:
    //
    //    Input, int JUMP_DIM[JUMP_NUM], the dimensions in which
    //    a jump is to be made.
    //
    //    Local, int JUMP_NUM, the number of dimensions in which
    //    a jump will be made.  0 <= JUMP_NUM <= PAR_NUM.
    //
    //    Local, double JUMPRATE, the jump rate.
    //
    {
        int    i;
        int    jump_num = 0;
        double jumprate = 0;

        int[] pair = new int[2];
        //
        //  Used to calculate E following a uniform distribution on (-B,+B).
        //  Because B is currently zero, the noise term is suppressed.
        //
        const double b = 0.0;

        //
        //  Pick pairs of other chains for crossover.
        //
        int[] r = new int[2 * pair_num];

        for (i = 0; i < pair_num; i++)
        {
            while (true)
            {
                double r2 = PDF.r8_uniform_01_sample();
                pair[0] = (int)(r2 * chain_num);
                r2      = PDF.r8_uniform_01_sample();
                pair[1] = (int)(r2 * chain_num);

                if (pair[0] != pair[1] &&
                    pair[0] != chain_index &&
                    pair[1] != chain_index)
                {
                    break;
                }
            }

            r[0 + i * 2] = pair[0];
            r[1 + i * 2] = pair[1];
        }

        //
        //  Determine the jump rate.
        //
        int[] jump_dim = new int[par_num];

        Jump.jumprate_choose(cr, cr_index, cr_num, gen_index, jump_dim, ref jump_num,
                             ref jumprate, jumprate_table, jumpstep, par_num);
        //
        //  Calculate E in equation 4 of Vrugt.
        //
        double[] noise_e = new double[par_num];

        for (i = 0; i < par_num; i++)
        {
            noise_e[i] = b * (2.0 * PDF.r8_uniform_01_sample() - 1.0);
        }

        //
        //  Get epsilon value from multinormal distribution
        //
        double[] eps = new double[par_num];

        const double av = 0.0;
        const double sd = 1.0E-10;

        for (i = 0; i < par_num; i++)
        {
            eps[i] = PDF.r8_normal_sample(av, sd);
        }

        //
        //  Generate the candidate sample ZP based on equation 4 of Vrugt.
        //
        double[] diff = Diff.diff_compute(chain_num, gen_index, gen_num, jump_dim, jump_num,
                                          pair_num, par_num, r, z);

        double[] zp = new double[par_num];

        for (i = 0; i < par_num; i++)
        {
            zp[i] = z[i + chain_index * par_num + (gen_index - 1) * par_num * chain_num];
        }

        for (i = 0; i < par_num; i++)
        {
            zp[i] = zp[i] + (1.0 + noise_e[i]) * jumprate * diff[i] + eps[i];
        }

        //
        //  Enforce limits on the sample ZP.
        //
        sample_limits(limits, par_num, ref zp);
        return(zp);
    }
Exemplo n.º 57
0
 public static DiffWithOrigin Local(Diff diff) =>
     new DiffWithOrigin
     {
         Diff = diff,
         Origin = OriginEnum.Local
     };
Exemplo n.º 58
0
 public void NormalMode()
 {
     difficultyMode = Diff.Norm;
 }
Exemplo n.º 59
0
 public void HardMode()
 {
     difficultyMode = Diff.Hard;
 }
Exemplo n.º 60
0
        private void UpdateSelectedFileViewers()
        {
            var selectedRows = FileChanges.GetSelectedRevisions();

            if (selectedRows.Count == 0)
            {
                return;
            }

            IGitItem revision = selectedRows[0];

            var fileName = revision.Name;

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = FileName;
            }

            Text = string.Format("File History ({0})", fileName);

            if (tabControl1.SelectedTab == Blame)
            {
                blameControl1.LoadBlame(revision.Guid, fileName, FileChanges);
            }
            if (tabControl1.SelectedTab == ViewTab)
            {
                var scrollpos = View.ScrollPos;

                View.ViewGitItemRevision(fileName, revision.Guid);
                View.ScrollPos = scrollpos;
            }

            switch (selectedRows.Count)
            {
            case 1:
            {
                IGitItem revision1 = selectedRows[0];

                if (tabControl1.SelectedTab == DiffTab)
                {
                    Diff.ViewPatch(
                        () =>
                        {
                            Patch diff = Settings.Module.GetSingleDiff(revision1.Guid, revision1.Guid + "^", fileName,
                                                                       Diff.GetExtraDiffArguments());
                            if (diff == null)
                            {
                                return(string.Empty);
                            }
                            return(diff.Text);
                        }
                        );
                }
            }
            break;

            case 2:
            {
                IGitItem revision1 = selectedRows[0];
                IGitItem revision2 = selectedRows[1];

                if (tabControl1.SelectedTab == DiffTab)
                {
                    Diff.ViewPatch(
                        () =>
                        Settings.Module.GetSingleDiff(revision1.Guid, revision2.Guid, fileName,
                                                      Diff.GetExtraDiffArguments()).Text);
                }
            }
            break;

            default:
                Diff.ViewPatch("You need to select 2 files to view diff.");
                break;
            }
        }