public void ResolveDuplicates()
        {
            const string Key = "Reference.To.Resolve.With.MergeTool";
              const string HintPath = @"Reference\To\Resolve\With\MergeTool.dll";

              var baseRerence = new Reference( Key, null, null, HintPath );
              var localRerence = new Reference( Key, false, null, HintPath );
              var incomingRerence1 = new Reference( Key, null, true, HintPath );
              var incomingRerence2 = new Reference( Key, true, null, HintPath );

              var conflict = new Conflict<IEnumerable<Reference>>(
            "TestFilePath",
            Key,
            new[] { baseRerence },
            new[] { localRerence },
            new[] { incomingRerence1, incomingRerence2 } );

              // As the respository will not be in a rebase / merge mode, you need to alter the currentOperation in GitHelper.RunStandardMergetool

              GitMergeToolResolver<Reference> resolver = new GitMergeToolResolver<Reference>( "../../../", conflict );

              var result = resolver.Resolve();

              Assert.That( result, Is.Not.Null );
        }
        private void FillConflictNode(TreeNode node, Conflict conflict)
        {
            node.Tag = conflict;

            NodeConflict nodeConflict = conflict as NodeConflict;
            if (nodeConflict != null)
            {
                if (nodeConflict.AcceptedSubdifferences.Count > 0)
                {
                    TreeNode acceptedNode = node.Nodes.Add("Accepted Differences");
                    foreach (Difference subdifference in nodeConflict.AcceptedSubdifferences)
                    {
                        TreeNode subnode = acceptedNode.Nodes.Add(subdifference.ToString());
                        FillDifferenceNode(subnode, subdifference);
                    }
                }

                TreeNode conflictNode = node.Nodes.Add("Conflicts");
                foreach (Conflict subconflict in nodeConflict.Subconflicts)
                {
                    TreeNode subnode = conflictNode.Nodes.Add(subconflict.ToString());
                    FillConflictNode(subnode, subconflict);
                }
            }
        }
        public MergeSolutionsForm(
                NodeDifference differenceInSourceBranch,
                NodeDifference differenceInDestinationBranch,
                Conflict conflict,
                OperationTypeConflictResolver operationTypeConflictResolver,
                ValueConflictResolver valueConflictResolver)
        {
            InitializeComponent();
            FormPosition.LoadFromRegistry(this);

            m_differencesInSourceBranchControl.Data = differenceInSourceBranch;
            m_differencesInDestinationBranchControl.Data = differenceInDestinationBranch;
            m_conflict = conflict as NodeConflict;
            m_operationTypeConflictResolver = operationTypeConflictResolver;
            m_valueConflictResolver = valueConflictResolver;
            if (m_conflict.Subconflicts.Count == 0)
            {
                m_result = (NodeDifference)m_conflict.Resolve(m_operationTypeConflictResolver, m_valueConflictResolver);
            }
            else
            {
                m_result = null;
            }

            UpdateUI();
        }
 protected virtual void OnConflict(Conflict conflict)
 {
     var handler = this.Conflict;
     if(handler != null)
     {
         handler(this, conflict);
     }
 }
        public void AutoMergesHighestVersionWhenNoOtherChanges()
        {
            PackageConflictResolver resolver = new PackageConflictResolver( new ExceptionResolver<ConfigitPackageReference>() );

              var conflict = new Conflict<ConfigitPackageReference>( "TestFilePath", PackageKey, _packageV0, _packageV1, _packageV2 );

              var result = resolver.Resolve( conflict );

              Assert.That( result.ResolvedItem, Is.EqualTo( _packageV2 ) );
        }
        public void UsesDefaultResolverIfOtherDifferencesExist()
        {
            var defaultResolver = new TestConflictResolver<ConfigitPackageReference>( ConflictItemType.Base );

              PackageConflictResolver resolver = new PackageConflictResolver( defaultResolver );

              var conflict = new Conflict<ConfigitPackageReference>( "TestFilePath", PackageKey, _packageV0, _packageV1, _packageV2UserInstalled );

              var result = resolver.Resolve( conflict );

              Assert.That( defaultResolver.Called, Is.EqualTo( true ) );
              Assert.That( result.ResolvedItem, Is.EqualTo( _packageV0 ) );
        }
Пример #7
0
 /// <summary>
 /// Export the content of the given LR conflict to the specified writer
 /// </summary>
 /// <param name="writer">The writer to export with</param>
 /// <param name="conflict">The LR conflict to export</param>
 private static void ExportLRConflict(TextWriter writer, Conflict conflict)
 {
     writer.WriteLine("\t\tConflict {0} on {1}:", conflict.ErrorType, conflict.ConflictSymbol);
     writer.WriteLine("\t\t\tItems:");
     foreach (Item item in conflict.Items)
     {
         writer.WriteLine("\t\t\t\t" + item);
     }
     writer.WriteLine("\t\t\tExamples:");
     foreach (Phrase example in conflict.Examples)
     {
         writer.WriteLine("\t\t\t\t" + example);
     }
 }
Пример #8
0
        public ConflictSet ConvertGateListToConflict(List <List <Gate> > conflictList)
        {
            ConflictSet conflictSet = new ConflictSet();

            conflictSet.Conflicts = new List <Conflict>();

            foreach (List <Gate> conflictGateList in conflictList)
            {
                Conflict conflict = new Conflict(conflictGateList);
                conflictSet.Conflicts.Add(conflict);
            }

            return(conflictSet);
        }
Пример #9
0
        private ConflictSet BuildConflictSet()
        {
            var conflictSet = new ConflictSet {
                Conflicts = new List <Conflict>()
            };

            for (var index = 0; index < _conflictsSetDataStructure.GetCompSets().Count; index++)
            {
                var gates    = _conflictsSetDataStructure.GetCompSets()[index];
                var conflict = new Conflict(gates);
                conflictSet.Conflicts.Add(conflict);
            }
            return(conflictSet);
        }
Пример #10
0
        public void CanSpecifyConflictFileStrategy(CheckoutFileConflictStrategy conflictStrategy)
        {
            const string conflictFile       = "a.txt";
            const string conflictBranchName = "conflicts";

            string path = SandboxMergeTestRepo();

            using (var repo = new Repository(path))
            {
                Branch branch = repo.Branches[conflictBranchName];
                Assert.NotNull(branch);

                MergeOptions mergeOptions = new MergeOptions()
                {
                    FileConflictStrategy = conflictStrategy,
                };

                MergeResult result = repo.Merge(branch, Constants.Signature, mergeOptions);
                Assert.Equal(MergeStatus.Conflicts, result.Status);

                // Get the information on the conflict.
                Conflict conflict = repo.Index.Conflicts[conflictFile];

                Assert.NotNull(conflict);
                Assert.NotNull(conflict.Theirs);
                Assert.NotNull(conflict.Ours);

                // Get the blob containing the expected content.
                Blob expectedBlob = null;
                switch (conflictStrategy)
                {
                case CheckoutFileConflictStrategy.Theirs:
                    expectedBlob = repo.Lookup <Blob>(conflict.Theirs.Id);
                    break;

                case CheckoutFileConflictStrategy.Ours:
                    expectedBlob = repo.Lookup <Blob>(conflict.Ours.Id);
                    break;

                default:
                    throw new Exception("Unexpected FileConflictStrategy");
                }

                Assert.NotNull(expectedBlob);

                // Check the content of the file on disk matches what is expected.
                string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictFile));
                Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictFile)));
            }
        }
Пример #11
0
        //return the conflict
        private static CompSet conflictMinstComponent(CompSet conflict, Gate gate)
        {
            if (conflict == null || conflictConatinsComponent(conflict, gate) == false)
            {
                return(conflict);
            }
            List <Gate> gates = conflict.getComponents();

            gates = removeGateFromSet(gates, gate);

            Conflict retValConflict = new Conflict(gates);

            return(retValConflict);
        }
Пример #12
0
        private string PrintConflict(Conflict conflict)
        {
            var text = $"Possible conflict with {(conflict.Plugin.userModInstance as IUserMod)?.Name ?? "Unknown mod"} by methods:";

            foreach (var info in conflict.Infos)
            {
                text += $"\n--- {info.Key.DeclaringType.FullName}.{info.Key.Name}";
                foreach (var patch in info.Value)
                {
                    text += $"\n------ [{patch.Type}] {patch.Method.DeclaringType.FullName}.{patch.Method.Name}";
                }
            }
            return(text);
        }
Пример #13
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Conflict = await _context.Conflict.FirstOrDefaultAsync(m => m.Id == id);

            if (Conflict == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Пример #14
0
        public static void RunTest()
        {
            Gate aGate  = new OneInputComponent(1, Gate.Type.and);
            Gate bGate  = new OneInputComponent(2, Gate.Type.and);
            Gate cGate  = new OneInputComponent(3, Gate.Type.and);
            Gate dGate  = new OneInputComponent(4, Gate.Type.and);
            Gate eGate  = new OneInputComponent(5, Gate.Type.and);
            Gate aGate2 = new OneInputComponent(6, Gate.Type.and);
            Gate bGate2 = new OneInputComponent(7, Gate.Type.and);
            Gate cGate2 = new OneInputComponent(8, Gate.Type.and);
            Gate dGate2 = new OneInputComponent(9, Gate.Type.and);
            Gate eGate2 = new OneInputComponent(10, Gate.Type.and);
            Gate aGate3 = new OneInputComponent(11, Gate.Type.and);
            Gate bGate3 = new OneInputComponent(12, Gate.Type.and);
            Gate cGate3 = new OneInputComponent(13, Gate.Type.and);
            Gate dGate3 = new OneInputComponent(14, Gate.Type.and);
            Gate eGate3 = new OneInputComponent(15, Gate.Type.and);

            Conflict con1 = new Conflict(new List <Gate> {
                aGate, bGate, cGate
            });
            Conflict con2 = new Conflict(new List <Gate> {
                dGate, bGate, eGate
            });
            Conflict con3 = new Conflict(new List <Gate> {
                aGate2, bGate2, cGate2
            });
            Conflict con4 = new Conflict(new List <Gate> {
                dGate2, bGate2, eGate2
            });
            Conflict con5 = new Conflict(new List <Gate> {
                aGate3, bGate3, cGate3
            });
            Conflict con6 = new Conflict(new List <Gate> {
                dGate3, bGate3, eGate3
            });
            Conflict con7 = new Conflict(new List <Gate> {
                dGate, bGate2, eGate3
            });

            ConflictSet conflictSet = new ConflictSet();

            conflictSet.Conflicts = new List <Conflict> {
                con1, con2, con3, con4, con5, con6, con7
            };

            HittingSetFinder.FindHittingSets(null, conflictSet);
        }
Пример #15
0
        /// <summary>
        /// Reiter’s HS-Tree Algorithm 2
        /// </summary>
        /// <param name="existingNode"></param>
        /// <param name="c"></param>
        /// <param name="diagnosisSet"></param>
        /// <param name="paths"></param>
        /// <param name="conflicts"></param>
        /// <param name="newNodes"></param>
        private void Expand(HSTreeNode existingNode, Gate c, DiagnosisSet diagnosisSet, List <HSTreePath> paths, ConflictSet conflicts, List <HSTreeNode> newNodes)
        {
            HSTreePath newPathLabel = new HSTreePath(existingNode.PathLabel, c);

            if (!HSHelper.IsSubsetOfPathDoesExitInDiagnosis(newPathLabel, diagnosisSet) &&
                CheckAndAddPath(paths, newPathLabel))
            {
                HSTreeNode node = new HSTreeNode(newPathLabel);

                Conflict S = HSHelper.IsAConflictExistConjWithPathLabelIsEmpty(conflicts, newPathLabel);

                if (S != null)
                {
                    node.Conflict = S;
                }
                else
                {
                    //consistency checker, which tests if the new node is a diagnosis or returns a minimal conflict otherwise.
                    bool IsDiagnosis = ConstraintSystemSolver.Instance.CheckConsistensy(observation, node.PathLabel.Path);

                    //If its not a diagnosis we add it as a conflict
                    if (!IsDiagnosis)
                    {
                        node.Conflict = new Conflict(node.PathLabel.Path);
                    }
                }

                if (node.Conflict != null && node.Conflict.TheConflict.Count > 0)
                {
                    // Add if not exist
                    if (!newNodes.Contains(node))
                    {
                        newNodes.Add(node);
                    }

                    // Add if not exist
                    if (!conflicts.Conflicts.Contains(node.Conflict))
                    {
                        conflicts.Conflicts.Add(node.Conflict);
                    }
                }
                else
                {
                    Diagnosis diagnosis = new Diagnosis(node.PathLabel.Path);
                    diagnosisSet.AddDiagnosis(diagnosis);
                }
            }
        }
Пример #16
0
        void Dump(PipeObject pipeObj, Guid portionId, string tempDir)
        {
            Conflict conflict = new Conflict();

            conflict.PortionID = portionId;
            conflict.Pipe      = pipeObj;

            string conflictDir = Path.Combine(System.Environment.CurrentDirectory, "Conflicts");

            if (!Directory.Exists(conflictDir))
            {
                Directory.CreateDirectory(conflictDir);
            }

            string dumpFilePath = Path.Combine(conflictDir, pipeObj.Id + ".xml");

            if (System.IO.File.Exists(dumpFilePath))
            {
                System.IO.File.Delete(dumpFilePath);
            }

            string attDir = Path.Combine(conflictDir, pipeObj.Id + "_Attachments");

            if (pipeObj.Attachments != null && pipeObj.Attachments.Count > 0)
            {
                if (Directory.Exists(attDir))
                {
                    Directory.Delete(attDir, true);
                }

                Directory.CreateDirectory(attDir);

                foreach (var file in pipeObj.Attachments)
                {
                    string attPathInTemp = Path.Combine(tempDir, "Attachments", file.NewName);
                    string targetPath    = Path.Combine(attDir, file.NewName);

                    System.IO.File.Copy(attPathInTemp, targetPath, true);
                }
            }

            XmlSerializer serializer = new XmlSerializer(typeof(Conflict));

            using (FileStream fs = new FileStream(dumpFilePath, FileMode.Create))
            {
                serializer.Serialize(fs, conflict);
            }
        }
Пример #17
0
        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            // Response
            Error errorResponse;

            switch (exception)
            {
            case UnauthorizedException _:     // 401
                var unauthorizedException = (UnauthorizedException)exception;
                errorResponse = new Unauthorized(nameof(ErrorMessage.Unauthorized), unauthorizedException.Message);
                break;

            case ForbiddenException _:        // 403
                var forbiddenException = (ForbiddenException)exception;
                errorResponse = new Forbidden(nameof(ErrorMessage.Forbidden), forbiddenException.Message);
                break;

            case NotFoundException _:         // 404
                var notFoundException = (NotFoundException)exception;
                errorResponse = new NotFound(nameof(ErrorMessage.NotFound), notFoundException.Message);
                break;

            case ConflictException _:         // 409
                var conflictException = (ConflictException)exception;
                errorResponse = new Conflict(nameof(ErrorMessage.Conflict), conflictException.Message);
                break;

            default:                          // 500
                errorResponse = new InternalServerError(nameof(ErrorMessage.InternalServerError), ErrorMessage.InternalServerError);
                // Log error
                _logger.LogSplunkError(exception);
                break;
            }

            var response = JsonConvert.SerializeObject(errorResponse, Formatting.None,
                                                       new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                Converters        = new List <JsonConverter> {
                    new Newtonsoft.Json.Converters.StringEnumConverter()
                }
            });

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = errorResponse.Status;
            return(context.Response.WriteAsync(response));
        }
Пример #18
0
 public static Conflict UpdateConflict(Conflict conflict)
 {
     using (var repo = new CRUDRepository <Conflict>())
     {
         var cft = repo.GetQuery <Conflict>(c => c.Id == conflict.Id)
                   .FirstOrDefault();
         if (cft != null)
         {
             cft.State               = conflict.State;
             cft.HasArbitralClause   = conflict.HasArbitralClause;
             cft.AskedForArbitration = conflict.AskedForArbitration;
             repo.Update(cft);
         }
         return(cft);
     }
 }
Пример #19
0
        public void TestFindHittingSet()
        {
            Dictionary <int, Gate> idTGates = new Dictionary <int, Gate>();

            Gate gate1 = new MultipleInputComponent(1, Gate.Type.and);

            idTGates.Add(gate1.Id, gate1);
            Gate gate2 = new MultipleInputComponent(2, Gate.Type.or);

            idTGates.Add(gate2.Id, gate2);
            Gate gate3 = new MultipleInputComponent(3, Gate.Type.xor);

            idTGates.Add(gate3.Id, gate3);
            Gate gate4 = new MultipleInputComponent(4, Gate.Type.and);

            idTGates.Add(gate4.Id, gate4);

            List <Gate> gateList1 = new List <Gate>();

            gateList1.Add(gate1);
            gateList1.Add(gate2);
            gateList1.Add(gate3);
            Conflict conflict1 = new Conflict(gateList1);

            List <Gate> gateList2 = new List <Gate>();

            gateList2.Add(gate3);
            gateList2.Add(gate4);
            Conflict conflict2 = new Conflict(gateList2);

            List <Gate> gateList3 = new List <Gate>();

            gateList3.Add(gate2);
            gateList3.Add(gate4);
            Conflict conflict3 = new Conflict(gateList3);

            List <List <Gate> > conflictSet = new List <List <Gate> >();

            conflictSet.Add(conflict1.TheConflict);
            conflictSet.Add(conflict2.TheConflict);
            conflictSet.Add(conflict3.TheConflict);
            List <List <Gate> > hittingSets = SwitchingAlgorithmHittingSetFinder.FindHittingSet(conflictSet, 10, idTGates);

            Assert.AreEqual(hittingSets.Count, 4);

            printSetList(hittingSets);
        }
Пример #20
0
        public override void CreateDiff()
        {
            int curOffset = 0;

            currentConflicts = new List <Conflict> (Conflicts(MainEditor.Document));
            leftConflicts.Clear();
            rightConflicts.Clear();
            editors[0].Document.IsReadOnly = editors[2].Document.IsReadOnly = false;
            editors[0].Document.Text       = "";
            editors[2].Document.Text       = "";

            for (int i = 0; i < currentConflicts.Count; i++)
            {
                Conflict conflict = currentConflicts[i];

                string above = MainEditor.Document.GetTextBetween(curOffset, conflict.StartSegment.Offset);
                editors[0].Insert(editors[0].Document.Length, above);
                int leftA = editors[0].Document.LineCount;
                editors[0].Insert(editors[0].Document.Length, MainEditor.Document.GetTextAt(conflict.MySegment));
                int leftB = editors[0].Document.LineCount;

                editors[2].Insert(editors[2].Document.Length, above);
                int rightA = editors[2].Document.LineCount;
                editors[2].Insert(editors[2].Document.Length, MainEditor.Document.GetTextAt(conflict.TheirSegment));
                int rightB = editors[2].Document.LineCount;

                int middleA = MainEditor.Document.OffsetToLineNumber(conflict.StartSegment.Offset);
                int middleB = MainEditor.Document.OffsetToLineNumber(conflict.EndSegment.EndOffset);

                leftConflicts.Add(conflict.LeftHunk   = new Hunk(leftA, middleA, leftB - leftA, middleB - middleA));
                rightConflicts.Add(conflict.RightHunk = new Hunk(rightA, middleA, rightB - rightA, middleB - middleA));
            }
            int endOffset = 0;

            if (currentConflicts.Count > 0)
            {
                endOffset = currentConflicts.Last().EndSegment.EndOffset;
            }

            string lastPart = MainEditor.Document.GetTextBetween(endOffset, MainEditor.Document.Length);

            editors[0].Insert(editors[0].Document.Length, lastPart);
            editors[2].Insert(editors[2].Document.Length, lastPart);
            editors[0].Document.IsReadOnly = editors[2].Document.IsReadOnly = true;

            UpdateDiff();
        }
Пример #21
0
        private string GetPath(Conflict conflict)
        {
            if (conflict.Ancestor != null)
            {
                return conflict.Ancestor.Path;
            }
            if (conflict.Ours != null)
            {
                return conflict.Ours.Path;
            }
            if (conflict.Theirs != null)
            {
                return conflict.Theirs.Path;
            }

            return null;
        }
Пример #22
0
        public static Stream GenerateIndependencyAndAcceptanceAct(int conflictId)
        {
            Conflict conflict = BLLConflicts.GetConflictForArbitration(conflictId);

            var stream = File.OpenWrite(HttpContext.Current.Server.MapPath("~/Templates/C2. Déclaration d'acceptation et d'indépendance_V1.docx"));

            using (DocX document = DocX.Load(stream))
            {
                document.ReplaceText("[N° du Litige]", conflict.Id.ToString());
                document.ReplaceText("[Demandeur]", conflict.CreatedBy.DisplayName);
                document.ReplaceText("[Défendeur]", conflict.UsersInConflicts.First(c => c.IdUser != conflict.IdCreationUser).User.DisplayName);
                document.ReplaceText("[Arbitre]", conflict.Arbiter.DisplayName);
                document.ReplaceText("[Date]", DateTime.Now.ToShortDateString());
            }

            return(stream);
        }
Пример #23
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Conflict = await _context.Conflict.FindAsync(id);

            if (Conflict != null)
            {
                _context.Conflict.Remove(Conflict);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Пример #24
0
        public void CanRetrieveSingleConflictByPath(string filepath, string ancestorId, string ourId, string theirId)
        {
            using (var repo = new Repository(MergedTestRepoWorkingDirPath))
            {
                Conflict conflict = repo.Index.Conflicts[filepath];
                Assert.NotNull(conflict);

                ObjectId expectedAncestor = ancestorId != null ? new ObjectId(ancestorId) : null;
                ObjectId expectedOurs     = ourId != null ? new ObjectId(ourId) : null;
                ObjectId expectedTheirs   = theirId != null ? new ObjectId(theirId) : null;

                Assert.Null(repo.Index[filepath]);
                Assert.Equal(expectedAncestor, conflict.Ancestor != null ? conflict.Ancestor.Id : null);
                Assert.Equal(expectedOurs, conflict.Ours != null ? conflict.Ours.Id : null);
                Assert.Equal(expectedTheirs, conflict.Theirs != null ? conflict.Theirs.Id : null);
            }
        }
Пример #25
0
        public void CanSpecifyFileConflictStrategy()
        {
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
            var path = Repository.Init(scd.DirectoryPath);

            using (Repository repo = new Repository(path))
            {
                ConstructRebaseTestRepository(repo);

                Commands.Checkout(repo, topicBranch1Name);
                Assert.False(repo.RetrieveStatus().IsDirty);

                Branch branch   = repo.Branches[topicBranch1Name];
                Branch upstream = repo.Branches[conflictBranch1Name];
                Branch onto     = repo.Branches[conflictBranch1Name];

                RebaseOptions options = new RebaseOptions()
                {
                    FileConflictStrategy = CheckoutFileConflictStrategy.Ours,
                };

                RebaseResult rebaseResult = repo.Rebase.Start(branch, upstream, onto, Constants.Identity, options);

                // Verify that we have a conflict.
                Assert.Equal(CurrentOperation.RebaseMerge, repo.Info.CurrentOperation);
                Assert.Equal(RebaseStatus.Conflicts, rebaseResult.Status);
                Assert.True(repo.RetrieveStatus().IsDirty);
                Assert.False(repo.Index.IsFullyMerged);
                Assert.Equal(0, rebaseResult.CompletedStepCount);
                Assert.Equal(3, rebaseResult.TotalStepCount);

                string conflictFile = filePathB;
                // Get the information on the conflict.
                Conflict conflict = repo.Index.Conflicts[conflictFile];

                Assert.NotNull(conflict);
                Assert.NotNull(conflict.Theirs);
                Assert.NotNull(conflict.Ours);

                Blob expectedBlob = repo.Lookup <Blob>(conflict.Ours.Id);

                // Check the content of the file on disk matches what is expected.
                string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictFile));
                Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictFile)));
            }
        }
Пример #26
0
        private string GetPath(Conflict conflict)
        {
            if (conflict.Ancestor != null)
            {
                return(conflict.Ancestor.Path);
            }
            if (conflict.Ours != null)
            {
                return(conflict.Ours.Path);
            }
            if (conflict.Theirs != null)
            {
                return(conflict.Theirs.Path);
            }

            return(null);
        }
Пример #27
0
        /// <summary>
        /// Join the conflicting groups into a single group
        /// </summary>
        /// <param name="conflict">An object that describes the conflict</param>
        /// <returns>The composite group of agents</returns>
        protected override AgentsGroup JoinGroups(Conflict conflict)
        {
            AgentsGroup answer = conflict.group1.Join(conflict.group2);

            // TODO: Currently storing the previous groups - this might lead to a memory problem when there are many agents
            // (if this happens then store only the costs)
            answer.instance.parameters[PARENT_GROUP1_KEY] = conflict.group1;
            answer.instance.parameters[PARENT_GROUP2_KEY] = conflict.group2;

            // Free memory of grandparents
            conflict.group1.instance.parameters.Remove(PARENT_GROUP1_KEY);
            conflict.group1.instance.parameters.Remove(PARENT_GROUP2_KEY);
            conflict.group2.instance.parameters.Remove(PARENT_GROUP1_KEY);
            conflict.group2.instance.parameters.Remove(PARENT_GROUP2_KEY);

            return(answer);
        }
        internal ResolveResult Resolve(Conflict conflict, ResolutionType resolutionType)
        {
            var invoker = new SoapInvoker(this);
            var msg     = invoker.CreateEnvelope("Resolve");

            msg.Add(new XElement(MessageNs + "workspaceName", conflict.Workspace.Name));
            msg.Add(new XElement(MessageNs + "ownerName", conflict.Workspace.OwnerName));
            msg.Add(new XElement(MessageNs + "conflictId", conflict.ConflictId));
            msg.Add(new XElement(MessageNs + "resolution", resolutionType));
            var           response = invoker.InvokeResponse();
            ResolveResult result   = new ResolveResult();

            result.GetOperations     = GetOperationExtractor(invoker.MethodResultExtractor(response));
            result.UndoOperations    = GetOperationExtractor(response.Element(MessageNs + "undoOperations"));
            result.ResolvedConflicts = ConflictExtractor(response.Element(MessageNs + "resolvedConflicts"), conflict.Workspace);
            return(result);
        }
Пример #29
0
        public void ConflictSettingsDeSerializeTest()
        {
            string conflictResponsePayload = @"{
                 id: 'Conflict1',
                 operationType: 'Replace',
                 resourceType: 'trigger'
                }";

            ConflictProperties conflictSettings = SettingsContractTests.CosmosDeserialize <ConflictProperties>(conflictResponsePayload);
            Conflict           conflict         = SettingsContractTests.DirectDeSerialize <Conflict>(conflictResponsePayload);

            Assert.AreEqual(conflict.Id, conflictSettings.Id);
            Assert.AreEqual((int)conflictSettings.OperationKind, (int)conflict.OperationKind);
            Assert.AreEqual(typeof(Trigger), conflict.ResourceType);
            Assert.AreEqual(typeof(TriggerProperties), conflictSettings.ResourceType);

            Assert.AreEqual("Conflict1", conflictSettings.Id);
        }
Пример #30
0
        public static Conflict AddConflict(Conflict c)
        {
            using (var repo = new CRUDRepository <Conflict>())
            {
                if (c.UsersInConflicts == null)
                {
                    c.UsersInConflicts = new List <UsersInConflict>();
                }

                c.UsersInConflicts.Add(new UsersInConflict()
                {
                    IdUser = c.IdCreationUser
                });
                c.CreateDate = DateTime.Now;
                c.State      = (int)ConflictState.Created;
                return(repo.Add(c));
            }
        }
Пример #31
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Conflict = await _context.Conflict
                       .Include(c => c.Journals)
                       .AsNoTracking()
                       .FirstOrDefaultAsync(m => m.Id == id);

            if (Conflict == null)
            {
                return(NotFound());
            }
            return(Page());
        }
        private void CollectConflictsBetween(
            ValidationContext context,
            List <Conflict> conflicts,
            Dictionary <SelectionSet, CachedField> cachedFieldsAndFragmentNames,
            PairSet comparedFragmentPairs,
            bool parentFieldsAreMutuallyExclusive,
            Dictionary <string, List <FieldDefPair> > fieldMap1,
            Dictionary <string, List <FieldDefPair> > fieldMap2)
        {
            // A field map is a keyed collection, where each key represents a response
            // name and the value at that key is a list of all fields which provide that
            // response name. For any response name which appears in both provided field
            // maps, each field from the first field map must be compared to every field
            // in the second field map to find potential conflicts.

            foreach (var responseName in fieldMap1.Keys)
            {
                fieldMap2.TryGetValue(responseName, out List <FieldDefPair> fields2);

                if (fields2 != null && fields2.Count != 0)
                {
                    var fields1 = fieldMap1[responseName];
                    for (var i = 0; i < fields1.Count; i++)
                    {
                        for (var j = 0; j < fields2.Count; j++)
                        {
                            Conflict conflict = FindConflict(
                                context,
                                cachedFieldsAndFragmentNames,
                                comparedFragmentPairs,
                                parentFieldsAreMutuallyExclusive,
                                responseName,
                                fields1[i],
                                fields2[j]);

                            if (conflict != null)
                            {
                                conflicts.Add(conflict);
                            }
                        }
                    }
                }
            }
        }
Пример #33
0
        public Conflict GetConflictByID(int intConflictID)
        {
            Conflict retval = null;

            // define a query
            string        query = "SELECT * FROM \"conflicts\" WHERE \"intConflictID\" = " + intConflictID;
            NpgsqlCommand cmd   = new NpgsqlCommand(query, conn);

            // execute query
            NpgsqlDataReader dr = cmd.ExecuteReader();

            // read all rows and output the first column in each row
            while (dr.Read())
            {
                retval = GetConflictFromDR(dr);
            }

            return(retval);
        }
Пример #34
0
        public void RemovedVsEditedElementConflict_RoundtripThroughXml()
        {
            MergeSituation mergesituation = new MergeSituation("path", "x", "1", "y", "2", MergeOrder.ConflictHandlingModeChoices.TheyWin);
            var            c = new RemovedVsEditedElementConflict("testElement",
                                                                  GetNodeFromString("<a>ours</a>"),
                                                                  GetNodeFromString("<a>theirs</a>"),
                                                                  GetNodeFromString("<a>ancestor</a>"),
                                                                  mergesituation, new ElementStrategy(false), "theWinner");

            c.Context = new ContextDescriptor("testLabel", "testPath");
            string desc = c.GetFullHumanReadableDescription();

            var annotationXml = XmlTestHelper.WriteConflictAnnotation(c);
            var regurgitated  = Conflict.CreateFromChorusNotesAnnotation(annotationXml);

            Assert.AreEqual("path", regurgitated.RelativeFilePath);
            Assert.AreEqual(desc, regurgitated.GetFullHumanReadableDescription());
            Assert.AreEqual(c.Context.PathToUserUnderstandableElement, regurgitated.Context.PathToUserUnderstandableElement);
            Assert.AreEqual(c.Context.DataLabel, regurgitated.Context.DataLabel);
        }
Пример #35
0
        /// <summary>
        /// Is A Conflict Exist Conj With "newPathLabel" Is Empty
        /// </summary>
        /// <param name="conflicts"></param>
        /// <param name="newPathLabel"></param>
        /// <returns> Return the conflict if found. If not found return null </returns>
        public static Conflict IsAConflictExistConjWithPathLabelIsEmpty(ConflictSet conflicts, HSTreePath newPathLabel)
        {
            List <Gate> pathLabelsGates = newPathLabel.Path;

            //Check if in any conflict:
            for (int j = 0; j < conflicts.Conflicts.Count; j++)
            {
                Conflict conflict = conflicts.Conflicts[j];

                List <Gate> conflictGats = conflict.TheConflict;

                //Check if pathLabelsGates Conj (CHITOCH)  conflictGats is empty
                bool intersect = conflictGats.Intersect(pathLabelsGates).Any();
                if (!intersect)
                {
                    return(conflict);
                }
            }

            return(null);
        }
Пример #36
0
        public NodeConflict Validate(out List <string> messages)
        {
            // TODO Finish this.
            messages = new List <string>();

            var projectsByFullName  = new Dictionary <string, Project>(StringComparer.InvariantCultureIgnoreCase);
            var acceptedDifferences = new List <Difference>();
            var conflicts           = new List <Conflict>();

            foreach (var project in this.Projects)
            {
                Project otherProject;
                if (projectsByFullName.TryGetValue(project.ProjectFullName, out otherProject))
                {
                    acceptedDifferences.Add(
                        new NodeDifference(
                            new ElementIdentifier(
                                TagProject + project.ProjectGuid,
                                string.Format("Project \"{0}\" [{1}]", project.ProjectFullName, project.ProjectGuid)),
                            OperationOnParent.Removed,
                            null));

                    var otherProjectIdentifier = new ElementIdentifier(
                        TagProject + otherProject.ProjectGuid,
                        string.Format("Project \"{0}\" [{1}]", otherProject.ProjectFullName, otherProject.ProjectGuid));

                    conflicts.Add(
                        Conflict.Merge(
                            new NodeElement(otherProjectIdentifier, null),
                            otherProject.ToElement(otherProjectIdentifier),
                            project.ToElement(otherProjectIdentifier)));
                }
                else
                {
                    projectsByFullName.Add(project.ProjectFullName, project);
                }
            }

            return(new NodeConflict(new ElementIdentifier("SolutionFile"), OperationOnParent.Modified, acceptedDifferences, conflicts));
        }
Пример #37
0
        public Conflict ConflictCheck(Shift newShift)
        {
            // output
            Conflict output = new Conflict();

            // Check for and get double shift
            Shift conflicter = this.ReturnDoubleShift(newShift);

            // if there is a double shift
            if (conflicter != null)
            {
                // create output
                output._conflict1    = newShift;
                output._conflict2    = conflicter;
                output._conflictType = "Double Shift";

                // return it
                return(output);
            }
            // check if they have an evening shift followed by night shift
            else
            {
                conflicter = ReturnConsecutiveOpenCloseShift(newShift);

                if (conflicter != null)
                {
                    // create output
                    output._conflict1    = newShift;
                    output._conflict2    = conflicter;
                    output._conflictType = "Close/Open Shift";

                    // return it
                    return(output);
                }
            }

            // otherwise, return null
            return(null);
        }
Пример #38
0
 public ConflictHolder(Conflict con, string iFolderPath)
 {
     ifPath = (iFolderPath == null) ? "iFolderPathUnknown" : iFolderPath;
        if(!con.IsNameConflict)
        {
     this.isNameConflict = false;
     localConflict = con;
        }
        else
        {
     this.isNameConflict = true;
     if( (con.LocalName != null) &&
      (con.LocalName.Length > 0) )
     {
      localConflict = con;
     }
     else
     {
      serverConflict = con;
     }
        }
 }
Пример #39
0
        /// <summary>
        /// Finds any slot conflicts that cause unsatisfied dependencies.
        /// </summary>
        /// <returns>an array of conflicted distributions</returns>
        public Conflict[] FindSlotConflicts()
        {
            /* first, find all slot conflicts */
            IDistribution[] conflicts = _sorted
                .Where(d => _sorted.Where(
                    dd => d.Package.FullName == dd.Package.FullName && d.Slot == dd.Slot).Count() > 1)
                .ToArray();

            Dictionary<string, List<IDistribution>> pkgdict = new Dictionary<string, List<IDistribution>>();
            foreach (string pkg in conflicts.Select(c => c.Package.FullName + ":" + c.Slot).Distinct())
                pkgdict.Add(pkg, new List<IDistribution>());

            foreach (IDistribution dist in conflicts)
                pkgdict[dist.Package.FullName + ":" + dist.Slot].Add(dist);

            List<Conflict> results = new List<Conflict>();

            /* scan the conflicts table for packages that satisfy dependency requirements,
             * and add dists that fail the check to the results set */
            foreach (KeyValuePair<string, List<IDistribution>> kvp in pkgdict) {
                bool pass = false;

                foreach (IDistribution d in kvp.Value) {
                    if (!_selected.Contains(d) && this.CheckSatisfies(d.Atom)) {
                        pass = true;
                        break;
                    }
                }

                if (!pass) {
                    IDistribution first = kvp.Value.First();
                    Conflict c = new Conflict() {
                        Package = first.Package,
                        Slot = first.Slot,
                        Distributions = kvp.Value.ToArray(),
                        ReverseMap = new Dictionary<IDistribution, IDistribution[]>()
                    };

                    foreach (IDistribution d in kvp.Value)
                        c.ReverseMap[d] = this.QueryPulledInBy(d);

                    results.Add(c);
                }
            }

            return results.ToArray();
        }
Пример #40
0
 public void CheckoutTheirs(Conflict conflict)
 {
     // Not available in libgit2sharp : https://github.com/libgit2/libgit2sharp/issues/868
     // git checkout --theirs
     system(String.Format ("cd {0} ; git checkout --theirs {1}", repo.Info.Path, conflict.Theirs.Path));
     repo.Stage (conflict.Theirs.Path);
 }
        public bool TryGetAllConflicts(out Conflict[] conflicts, Workspace workspace)
        {
            try
            {
                conflicts = _teamPilgrimTfsService.GetAllConflicts(workspace);
                return true;
            }
            catch (Exception ex)
            {
                this.Logger().DebugException(ex);
                LastException = ex;
            }

            conflicts = null;
            return false;
        }
Пример #42
0
 private static void TryResolve(Workspace workspace, Conflict conflict, MergeOption mergeOption)
 {
     if (mergeOption == MergeOption.KeepTarget)
     {
         conflict.Resolution = Resolution.AcceptYours;
         workspace.ResolveConflict(conflict);
     }
     if (mergeOption == MergeOption.OverwriteTarget)
     {
         conflict.Resolution = Resolution.AcceptTheirs;
         workspace.ResolveConflict(conflict);
     }
 }
Пример #43
0
        private static bool IsTryRestoreUnexpectedFile(Conflict[] conflicts)
        {
            foreach (var conflict in conflicts)
            {
                if (conflict.BaseChangeType.HasFlag(ChangeType.Undelete)
                    && !conflict.TheirChangeType.HasFlag(ChangeType.Undelete))
                {
                    return true;
                }
            }

            return false;
        }
Пример #44
0
 internal void AddConflict(Conflict conflict)
 {
     this._conflicts.Add(conflict);
 }
Пример #45
0
 public void AddNameConflict(Conflict con)
 {
     if(!con.IsNameConflict)
     throw new Exception("Cannot add a FileConflict");
        if( (con.LocalName != null) &&
     (con.LocalName.Length > 0) &&
     (localConflict == null) )
        {
     localConflict = con;
        }
        else if(serverConflict == null)
        {
     serverConflict = con;
        }
        else
     throw new Exception("Can't add additional conflicts");
 }
Пример #46
0
		public static void Play()
		{
			new Key().PubKey.WitHash.GetAddress(Network.SegNet).ToString();

			var node = Node.Connect(Network.SegNet, "qbitninja-server.cloudapp.net");
			node.VersionHandshake();

			uint256 p2wsh = null;
			uint256 p2pwkh = null;
			uint256 p2wshp2sh = null;
			uint256 p2wpkhp2sh = null;
			foreach(var block in node.GetBlocks())
			{
				foreach(var tx in block.Transactions)
				{
					if(p2wsh != null && p2pwkh != null && p2wshp2sh != null && p2wpkhp2sh != null)
						break;
					if(!tx.IsCoinBase && !tx.Witness.IsEmpty)
					{
						foreach(var input in tx.Inputs.AsIndexedInputs())
						{
							if(input.WitScript == WitScript.Empty)
								continue;
							if(input.ScriptSig == Script.Empty)
							{
								if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null)
									p2pwkh = tx.GetHash();
								else
									p2wsh = tx.GetHash();
							}
							else
							{
								if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null)
									p2wpkhp2sh = tx.GetHash();
								else
									p2wshp2sh = tx.GetHash();
							}
							break;
						}
					}
				}
			}

			var secret = new BitcoinSecret("QTrKVpsVwNUD9GayzdbUNz2NNDqiPgjd9RCprwSa4gmBFg3V2oik", Network.SegNet);

			var oo = secret.PubKey.WitHash.GetAddress(Network.SegNet);

			var key = new Key().GetBitcoinSecret(Network.SegNet);
			var aa = key.GetAddress();
			foreach(var n in new[]{Network.Main, Network.SegNet})
			{
				for(int i = 0; i < 2;i++)
				{
					BitcoinAddress addr = i == 0 ? (BitcoinAddress)new Key().PubKey.GetSegwitAddress(n) : new Key().ScriptPubKey.GetWitScriptAddress(n);
					var c = addr.ScriptPubKey.ToString();
				}
			}


			var networks = Network.GetNetworks().ToArray();		
			List<Conflict> conflicts = new List<Conflict>();
			for(int n = 0 ; n < networks.Length ; n++)
			{
				for(int n2 = n+1; n2 < networks.Length ; n2++)
				{
					var a = networks[n];
					var b = networks[n2];
					if(a == Network.RegTest || b == Network.RegTest)
						continue;
					if(a == b)
						throw new Exception();
					for(int i = 0 ; i < a.base58Prefixes.Length ; i++)
					{
						for(int y = i + 1 ; y < a.base58Prefixes.Length ; y++)
						{
							if(a.base58Prefixes[i] != null && b.base58Prefixes[y] != null)
							{
								var ae = Encoders.Hex.EncodeData(a.base58Prefixes[i]);
								var be = Encoders.Hex.EncodeData(b.base58Prefixes[y]);
								if(ae == be)
									continue;
								if(ae.StartsWith(be) || be.StartsWith(ae))
								{
									ConflictPart ca = new ConflictPart();
									ca.Network = a;
									ca.Type = (Base58Type)i;
									ca.Value = a.base58Prefixes[i];

									ConflictPart cb = new ConflictPart();
									cb.Network = b;
									cb.Type = (Base58Type)y;
									cb.Value = b.base58Prefixes[y];

									Conflict cc = new Conflict();
									cc.A = ca;
									cc.B = cb;
									conflicts.Add(cc);
								}
							}
						}
					}
				}
			}

			var rr = String.Join("\r\n", conflicts.OfType<object>().ToArray());
			Console.WriteLine();

			//ConcurrentChain chain = new ConcurrentChain(Network.Main);
			//ChainBehavior chainBehavior = new ChainBehavior(chain);
			//NodeConnectionParameters para = new NodeConnectionParameters();
			//para.TemplateBehaviors.Add(chainBehavior);

			//NodesGroup group = new NodesGroup(Network.Main, para);
			//group.Connect();
			//while(true)
			//{
			//	Thread.Sleep(1000);
			//}



			//Parallel.ForEach(Enumerable.Range(0, 10), _ =>
			//{
			//	ConcurrentChain chain = new ConcurrentChain(Network.Main);
			//	node.SynchronizeChain(chain);
			//});

			//Wallet wallet = new Wallet(new ExtKey(), Network.Main);
			//wallet.Connect(addrman: AddressManager.LoadPeerFile(@"E:\Program Files\Bitcoin\peers.dat", Network.Main));
			//while(true)
			//{
			//	Thread.Sleep(1000);
			//	Console.WriteLine(wallet.ConnectedNodes + " " + wallet.State);

			//}

			//var node = Node.ConnectToLocal(Network.Main);
			//node.VersionHandshake();
			//var chain = node.GetChain();
			//var v3 = chain.Tip
			//	.EnumerateToGenesis()
			//	.Take(1000)
			//	.Aggregate(0, (a, b) => b.Header.Version == 3 ? a+1 : a);

			//var r = (double)v3 / (double)1000;

			Stopwatch watch = new Stopwatch();
			watch.Start();
			System.Net.ServicePointManager.DefaultConnectionLimit = 100;
			System.Net.ServicePointManager.Expect100Continue = false;
			var repo = new QBitNinjaTransactionRepository("http://rapidbase-test.azurewebsites.net/");
			var colored = new OpenAsset.NoSqlColoredTransactionRepository(repo);


			var result = repo
				.Get("c3462373f1a722c66cbb1b93712df94aa7b3731f4142cd8413f10c9e872927de")
				.GetColoredTransaction(colored);
			watch.Stop();
			//for(int i = 0 ; i < 100 ; i++)
			//{
			//	using(var node = Node.ConnectToLocal(Network.Main))
			//	{
			//		node.VersionHandshake();
			//		var chain = new ConcurrentChain(Network.Main);
			//		node.SynchronizeChain(chain);
			//	}
			//}
		}
 internal void Link(Conflict conflict)
 {
     if (this.conflicts == null)
         conflicts = new List<Conflict>();
     conflicts.Add(conflict);
 }
Пример #48
0
		public static void Play()
		{
			Transaction txxxxx = new Transaction("0100000000010213206299feb17742091c3cb2ab45faa3aa87922d3c030cafb3f798850a2722bf0000000000feffffffa12f2424b9599898a1d30f06e1ce55eba7fabfeee82ae9356f07375806632ff3010000006b483045022100fcc8cf3014248e1a0d6dcddf03e80f7e591605ad0dbace27d2c0d87274f8cd66022053fcfff64f35f22a14deb657ac57f110084fb07bb917c3b42e7d033c54c7717b012102b9e4dcc33c9cc9cb5f42b96dddb3b475b067f3e21125f79e10c853e5ca8fba31feffffff02206f9800000000001976a9144841b9874d913c430048c78a7b18baebdbea440588ac8096980000000000160014e4873ef43eac347471dd94bc899c51b395a509a502483045022100dd8250f8b5c2035d8feefae530b10862a63030590a851183cb61b3672eb4f26e022057fe7bc8593f05416c185d829b574290fb8706423451ebd0a0ae50c276b87b43012102179862f40b85fa43487500f1d6b13c864b5eb0a83999738db0f7a6b91b2ec64f00db080000");

			Script scriptCode = new Script("OP_DUP OP_HASH160 e4873ef43eac347471dd94bc899c51b395a509a5 OP_EQUALVERIFY OP_CHECKSIG");
			var rrrr = Script.SignatureHash(scriptCode, txxxxx, 0, SigHash.All, Money.Satoshis(10000000), HashVersion.Witness);

			//Console.WriteLine(total);
			new Key().PubKey.WitHash.GetAddress(Network.SegNet).ToString();

			var node = Node.Connect(Network.SegNet, "qbitninja-server.cloudapp.net");
			node.VersionHandshake();

			uint256 p2wsh = null;
			uint256 p2pwkh = null;
			uint256 p2wshp2sh = null;
			uint256 p2wpkhp2sh = null;
			foreach(var block in node.GetBlocks())
			{
				foreach(var tx in block.Transactions)
				{
					if(p2wsh != null && p2pwkh != null && p2wshp2sh != null && p2wpkhp2sh != null)
						break;
					if(!tx.IsCoinBase && tx.HasWitness)
					{
						foreach(var input in tx.Inputs.AsIndexedInputs())
						{
							if(input.WitScript == WitScript.Empty)
								continue;
							if(input.ScriptSig == Script.Empty)
							{
								if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null)
									p2pwkh = tx.GetHash();
								else
									p2wsh = tx.GetHash();
							}
							else
							{
								if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null)
									p2wpkhp2sh = tx.GetHash();
								else
									p2wshp2sh = tx.GetHash();
							}
							break;
						}
					}
				}
			}

			var secret = new BitcoinSecret("QTrKVpsVwNUD9GayzdbUNz2NNDqiPgjd9RCprwSa4gmBFg3V2oik", Network.SegNet);

			var oo = secret.PubKey.WitHash.GetAddress(Network.SegNet);

			var key = new Key().GetBitcoinSecret(Network.SegNet);
			var aa = key.GetAddress();
			foreach(var n in new[] { Network.Main, Network.SegNet })
			{
				for(int i = 0 ; i < 2 ; i++)
				{
					BitcoinAddress addr = i == 0 ? (BitcoinAddress)new Key().PubKey.GetSegwitAddress(n) : new Key().ScriptPubKey.GetWitScriptAddress(n);
					var c = addr.ScriptPubKey.ToString();
				}
			}


			var networks = Network.GetNetworks().ToArray();
			List<Conflict> conflicts = new List<Conflict>();
			for(int n = 0 ; n < networks.Length ; n++)
			{
				for(int n2 = n + 1 ; n2 < networks.Length ; n2++)
				{
					var a = networks[n];
					var b = networks[n2];
					if(a == Network.RegTest || b == Network.RegTest)
						continue;
					if(a == b)
						throw new Exception();
					for(int i = 0 ; i < a.base58Prefixes.Length ; i++)
					{
						for(int y = i + 1 ; y < a.base58Prefixes.Length ; y++)
						{
							if(a.base58Prefixes[i] != null && b.base58Prefixes[y] != null)
							{
								var ae = Encoders.Hex.EncodeData(a.base58Prefixes[i]);
								var be = Encoders.Hex.EncodeData(b.base58Prefixes[y]);
								if(ae == be)
									continue;
								if(ae.StartsWith(be) || be.StartsWith(ae))
								{
									ConflictPart ca = new ConflictPart();
									ca.Network = a;
									ca.Type = (Base58Type)i;
									ca.Value = a.base58Prefixes[i];

									ConflictPart cb = new ConflictPart();
									cb.Network = b;
									cb.Type = (Base58Type)y;
									cb.Value = b.base58Prefixes[y];

									Conflict cc = new Conflict();
									cc.A = ca;
									cc.B = cb;
									conflicts.Add(cc);
								}
							}
						}
					}
				}
			}

			var rr = String.Join("\r\n", conflicts.OfType<object>().ToArray());
			Console.WriteLine();

			//ConcurrentChain chain = new ConcurrentChain(Network.Main);
			//ChainBehavior chainBehavior = new ChainBehavior(chain);
			//NodeConnectionParameters para = new NodeConnectionParameters();
			//para.TemplateBehaviors.Add(chainBehavior);

			//NodesGroup group = new NodesGroup(Network.Main, para);
			//group.Connect();
			//while(true)
			//{
			//	Thread.Sleep(1000);
			//}



			//Parallel.ForEach(Enumerable.Range(0, 10), _ =>
			//{
			//	ConcurrentChain chain = new ConcurrentChain(Network.Main);
			//	node.SynchronizeChain(chain);
			//});

			//Wallet wallet = new Wallet(new ExtKey(), Network.Main);
			//wallet.Connect(addrman: AddressManager.LoadPeerFile(@"E:\Program Files\Bitcoin\peers.dat", Network.Main));
			//while(true)
			//{
			//	Thread.Sleep(1000);
			//	Console.WriteLine(wallet.ConnectedNodes + " " + wallet.State);

			//}

			//var node = Node.ConnectToLocal(Network.Main);
			//node.VersionHandshake();
			//var chain = node.GetChain();
			//var v3 = chain.Tip
			//	.EnumerateToGenesis()
			//	.Take(1000)
			//	.Aggregate(0, (a, b) => b.Header.Version == 3 ? a+1 : a);

			//var r = (double)v3 / (double)1000;

			Stopwatch watch = new Stopwatch();
			watch.Start();
			System.Net.ServicePointManager.DefaultConnectionLimit = 100;
			System.Net.ServicePointManager.Expect100Continue = false;
			var repo = new QBitNinjaTransactionRepository("http://rapidbase-test.azurewebsites.net/");
			var colored = new OpenAsset.NoSqlColoredTransactionRepository(repo);


			var result = repo
				.Get("c3462373f1a722c66cbb1b93712df94aa7b3731f4142cd8413f10c9e872927de")
				.GetColoredTransaction(colored);
			watch.Stop();
			//for(int i = 0 ; i < 100 ; i++)
			//{
			//	using(var node = Node.ConnectToLocal(Network.Main))
			//	{
			//		node.VersionHandshake();
			//		var chain = new ConcurrentChain(Network.Main);
			//		node.SynchronizeChain(chain);
			//	}
			//}
		}
Пример #49
0
		public static void Play()
		{
			var networks = Network.GetNetworks().ToArray();		
			List<Conflict> conflicts = new List<Conflict>();
			for(int n = 0 ; n < networks.Length ; n++)
			{
				for(int n2 = n+1; n2 < networks.Length ; n2++)
				{
					var a = networks[n];
					var b = networks[n2];
					if(a == Network.RegTest || b == Network.RegTest)
						continue;
					if(a == b)
						throw new Exception();
					for(int i = 0 ; i < a.base58Prefixes.Length ; i++)
					{
						for(int y = i + 1 ; y < a.base58Prefixes.Length ; y++)
						{
							if(a.base58Prefixes[i] != null && b.base58Prefixes[y] != null)
							{
								var ae = Encoders.Hex.EncodeData(a.base58Prefixes[i]);
								var be = Encoders.Hex.EncodeData(b.base58Prefixes[y]);
								if(ae == be)
									continue;
								if(ae.StartsWith(be) || be.StartsWith(ae))
								{
									ConflictPart ca = new ConflictPart();
									ca.Network = a;
									ca.Type = (Base58Type)i;
									ca.Value = a.base58Prefixes[i];

									ConflictPart cb = new ConflictPart();
									cb.Network = b;
									cb.Type = (Base58Type)y;
									cb.Value = b.base58Prefixes[y];

									Conflict cc = new Conflict();
									cc.A = ca;
									cc.B = cb;
									conflicts.Add(cc);
								}
							}
						}
					}
				}
			}

			var rr = String.Join("\r\n", conflicts.OfType<object>().ToArray());
			Console.WriteLine();

			//ConcurrentChain chain = new ConcurrentChain(Network.Main);
			//ChainBehavior chainBehavior = new ChainBehavior(chain);
			//NodeConnectionParameters para = new NodeConnectionParameters();
			//para.TemplateBehaviors.Add(chainBehavior);

			//NodesGroup group = new NodesGroup(Network.Main, para);
			//group.Connect();
			//while(true)
			//{
			//	Thread.Sleep(1000);
			//}



			//Parallel.ForEach(Enumerable.Range(0, 10), _ =>
			//{
			//	ConcurrentChain chain = new ConcurrentChain(Network.Main);
			//	node.SynchronizeChain(chain);
			//});

			//Wallet wallet = new Wallet(new ExtKey(), Network.Main);
			//wallet.Connect(addrman: AddressManager.LoadPeerFile(@"E:\Program Files\Bitcoin\peers.dat", Network.Main));
			//while(true)
			//{
			//	Thread.Sleep(1000);
			//	Console.WriteLine(wallet.ConnectedNodes + " " + wallet.State);

			//}

			//var node = Node.ConnectToLocal(Network.Main);
			//node.VersionHandshake();
			//var chain = node.GetChain();
			//var v3 = chain.Tip
			//	.EnumerateToGenesis()
			//	.Take(1000)
			//	.Aggregate(0, (a, b) => b.Header.Version == 3 ? a+1 : a);

			//var r = (double)v3 / (double)1000;

			Stopwatch watch = new Stopwatch();
			watch.Start();
			System.Net.ServicePointManager.DefaultConnectionLimit = 100;
			System.Net.ServicePointManager.Expect100Continue = false;
			var repo = new QBitNinjaTransactionRepository("http://rapidbase-test.azurewebsites.net/");
			var colored = new OpenAsset.NoSqlColoredTransactionRepository(repo);


			var result = repo
				.Get("c3462373f1a722c66cbb1b93712df94aa7b3731f4142cd8413f10c9e872927de")
				.GetColoredTransaction(colored);
			watch.Stop();
			//for(int i = 0 ; i < 100 ; i++)
			//{
			//	using(var node = Node.ConnectToLocal(Network.Main))
			//	{
			//		node.VersionHandshake();
			//		var chain = new ConcurrentChain(Network.Main);
			//		node.SynchronizeChain(chain);
			//	}
			//}
		}