コード例 #1
0
        public void Equals_ChangesetAndObject_ReturnsFalse()
        {
            var set = new Changeset();
            var obj = new object();

            Assert.That(set.Equals(obj), Is.False);
        }
            public void Apply(Changeset changeset) {
                if (!_fullPath.StartsWithIgnoreCase(_rootDirectory)) {
                    return;
                }

                var newDirectoryInfo = _fileSystem.GetDirectoryInfo(_fullPath);
                var newRelativePath = PathHelper.MakeRelative(_rootDirectory, _fullPath);
                if (!newDirectoryInfo.Exists || !_fileSystemFilter.IsDirectoryAllowed(newRelativePath, newDirectoryInfo.Attributes)) {
                    return;
                }

                newRelativePath = PathHelper.EnsureTrailingSlash(newRelativePath);
                var oldRelativePath = PathHelper.EnsureTrailingSlash(PathHelper.MakeRelative(_rootDirectory, _oldFullPath));

                // If directory with the oldRelativePath was previously added, remove it from the AddedDirectories, add newRelativePath and change all its content paths:
                if (changeset.AddedDirectories.Contains(oldRelativePath)) {
                    UpdatePrefix(changeset.AddedDirectories, oldRelativePath, newRelativePath);
                    UpdatePrefix(changeset.AddedFiles, oldRelativePath, newRelativePath);
                    return;
                }

                // if directory with the newRelativePath was previously deleted, keep both changes (delete and rename),
                // cause the content of the directory to be deleted is different from the content of renamed directory

                // if there is a directory that was renamed into oldRelativePath, rename it to newRelativePath instead
                // or remove from RenamedDirectories if previouslyRenamedRelativePath equal to newRelativePath
                var previouslyRenamedRelativePath = changeset.RenamedDirectories.GetFirstKeyByValueIgnoreCase(oldRelativePath);
                if (string.IsNullOrEmpty(previouslyRenamedRelativePath)) {
                    changeset.RenamedDirectories[oldRelativePath] = newRelativePath;
                } else if (previouslyRenamedRelativePath.EqualsIgnoreCase(newRelativePath)) {
                    changeset.RenamedDirectories.Remove(previouslyRenamedRelativePath);
                } else {
                    changeset.RenamedDirectories[previouslyRenamedRelativePath] = newRelativePath;
                }
            }
            public void Apply(Changeset changeset) {
                if (!_fullPath.StartsWithIgnoreCase(_rootDirectory)) {
                    return;
                }

                var relativePath = PathHelper.EnsureTrailingSlash(PathHelper.MakeRelative(_rootDirectory, _fullPath));

                // Remove all the files and directories that start with relativePath
                changeset.AddedDirectories.RemoveWhere(d => d.StartsWithIgnoreCase(relativePath));
                changeset.AddedFiles.RemoveWhere(f => f.StartsWithIgnoreCase(relativePath));

                // If directory was previously added to AddedDirectories, we need to remove all its content as well
                if (changeset.AddedDirectories.Remove(relativePath)) {
                    return;
                }

                // If directory was renamed into relativePath, put the oldRelativePath into RemovedFiles instead.
                var oldRelativePath = changeset.RenamedDirectories.GetFirstKeyByValueIgnoreCase(relativePath);
                if (oldRelativePath != null) {
                    changeset.RenamedDirectories.Remove(oldRelativePath);
                    changeset.RemovedDirectories.Add(oldRelativePath);
                    return;
                }

                changeset.RemovedDirectories.Add(relativePath);
            }
コード例 #4
0
 public TFSRevision(Repository repo, string itemPath, Changeset changeset) : 
     this(repo, changeset.ChangesetId, itemPath)
 {
     this.Author = changeset.Committer;
     this.Message = changeset.Comment;
     this.Time = changeset.CreationDate;
 }
コード例 #5
0
        public Changeset GetParentCommit(Changeset commit)
        {
            var command = new LogCommand().WithRevision(new RevSpec("{0}^".Fmt(commit.Hash))).WithIncludePathActions();
            var changesets = _repository.Log(command);
			var changeset = changesets.FirstOrDefault();
            return changeset;
        }
コード例 #6
0
 /// <summary>
 /// Merges the specified changesets.
 /// </summary>
 /// <param name="changeset1">The changeset1.</param>
 /// <param name="changeset2">The changeset2.</param>
 /// <param name="source">The source.</param>
 /// <returns></returns>
 public Changeset<IChange> Merge(MergableChangeset changeset1, MergableChangeset changeset2,
                                 IReadOnlyList<string> source)
 {
     var result = new Changeset<IChange>();
     IEnumerable<IChange> changes = CollectChanges(changeset1, changeset2, source);
     foreach (IChange change in changes)
     {
         result.Add(change.Start, change);
     }
     return result;
 }
コード例 #7
0
        public void ParseSingleChangesetSpec()
        {
            string plasticChangesetEnvironVar =
                "cs:19@br:/main/test2/@rep:codice@repserver:skull.mydomain.com:9095";

            Changeset expectedChangeset = new Changeset(
                19,
                "/main/test2/",
                "codice",
                "skull.mydomain.com:9095");

            List <Changeset> changesets =
                Changeset.ParsePlasticChangesetEnvironVar(plasticChangesetEnvironVar);

            Assert.AreEqual(1, changesets.Count);

            AssertChangesetEquals(expectedChangeset, changesets[0]);
        }
コード例 #8
0
ファイル: AggregateTests.cs プロジェクト: heynickc/NStore
        public void changes_must_be_applied_in_strict_order()
        {
            var ticket    = TicketTestFactory.ForTest();
            var persister = (IEventSourcedAggregate)ticket;

            var first = new Changeset(1, new TicketSold());
            var third = new Changeset(3, new TicketSold());

            persister.ApplyChanges(first);

            var ex = Assert.Throws <AggregateRestoreException>(() =>
            {
                persister.ApplyChanges(third);
            });

            Assert.Equal(2, ex.ExpectedVersion);
            Assert.Equal(3, ex.RestoreVersion);
        }
コード例 #9
0
        static void RunAfterCheckin(
            List <string> filteredRepos,
            List <string> dstServers,
            List <RepoMapping> mappings,
            string csetSpecs,
            ErrorEmailSender emailSender)
        {
            Logger.LogInfo("Running as after-checkin trigger...");

            List <Changeset> csets =
                Changeset.ParsePlasticChangesetEnvironVar(csetSpecs);

            List <Replica> pendingReplicas = new List <Replica>();

            foreach (Changeset cset in csets)
            {
                pendingReplicas.AddRange(
                    Replica.BuildPendingReplicas(
                        cset.BranchName,
                        cset.RepositoryName,
                        cset.ServerName,
                        filteredRepos,
                        dstServers,
                        mappings));
            }

            Logger.LogInfo(
                $"Found {pendingReplicas.Count} destinations to replicate to.");

            List <Replica> failedReplicas = new List <Replica>();

            foreach (Replica pendingReplica in pendingReplicas)
            {
                if (!Replicate(pendingReplica))
                {
                    failedReplicas.Add(pendingReplica);
                }
            }

            NotifyFailedReplicas(
                "after-checkin",
                failedReplicas,
                emailSender);
        }
コード例 #10
0
        private void ProcessFileChange(Changeset changeset, Change change)
        {
            // Undelete file (really just an add)
            if ((change.ChangeType & ChangeType.Undelete) == ChangeType.Undelete)
            {
                UndeleteFile(changeset, change);
            }

            // Rename file.
            else if ((change.ChangeType & ChangeType.Rename) == ChangeType.Rename)
            {
                RenameFile(changeset, change);

                //"Edit, Rename" is possible and should be handled
                if ((change.ChangeType & ChangeType.Edit) == ChangeType.Edit)
                {
                    EditFile(changeset, change);
                }
            }

            // Branch file.
            else if ((change.ChangeType & ChangeType.Branch) == ChangeType.Branch)
            {
                BranchFile(changeset, change);
            }

            // Add file.
            else if ((change.ChangeType & ChangeType.Add) == ChangeType.Add)
            {
                AddFile(changeset, change);
            }

            // Delete file.
            else if ((change.ChangeType & ChangeType.Delete) == ChangeType.Delete)
            {
                DeleteFile(changeset, change);
            }

            // Edit file.
            else if ((change.ChangeType & ChangeType.Edit) == ChangeType.Edit)
            {
                EditFile(changeset, change);
            }
        }
コード例 #11
0
        /// <summary>
        ///   Convert the passed changeset to an array of modifcations.
        /// </summary>
        private Modification[] toModifcations(Changeset changeset)
        {
            List <Modification> modifications = new List <Modification>();

            string userName     = changeset.Committer;
            string comment      = changeset.Comment;
            int    changeNumber = changeset.ChangesetId;
            // In VSTS, the version of the file is the same as the changeset number it was checked in with.
            string version = Convert.ToString(changeNumber);

            DateTime modifedTime = this.TFS.TimeZone.ToLocalTime(changeset.CreationDate);

            foreach (Change change in changeset.Changes)
            {
                Modification modification = new Modification();
                modification.UserName     = userName;
                modification.Comment      = comment;
                modification.ChangeNumber = changeNumber;
                modification.ModifiedTime = modifedTime;
                modification.Version      = version;
                modification.Type         = PendingChange.GetLocalizedStringForChangeType(change.ChangeType);

                // Populate fields from change item
                Item item = change.Item;
                if (item.ItemType == ItemType.File)
                {
                    // split into foldername and filename
                    int lastSlash = item.ServerItem.LastIndexOf('/');
                    modification.FileName = item.ServerItem.Substring(lastSlash + 1);
                    // patch to the following line submitted by Ralf Kretzschmar.
                    modification.FolderName = item.ServerItem.Substring(0, lastSlash);
                }
                else
                {
                    // TODO - what should filename be if dir??  Empty string or null?
                    modification.FileName   = string.Empty;
                    modification.FolderName = item.ServerItem;
                }
                Log.Debug(modification.ToString());
                modifications.Add(modification);
            }

            return(modifications.ToArray());
        }
コード例 #12
0
        private static void SetLastWorkItem(ITeamExplorer teamExplorer, Changeset changeset)
        {
            var workItemId = GetAssociatedWorkItemId(changeset);

            if (workItemId == 0)
            {
                return;
            }

            var pendingChangesPage = (TeamExplorerPageBase)teamExplorer.NavigateToPage(new Guid(TeamExplorerPageIds.PendingChanges), null);
            var model = (IPendingCheckin)pendingChangesPage.Model;

            var modelType = model.GetType();
            var method    = modelType.GetMethod("AddWorkItemsByIdAsync",
                                                BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            var workItemsIdsArray = new[] { workItemId };

            method.Invoke(model, new object[] { workItemsIdsArray, 1 /* Add */ });
        }
コード例 #13
0
        static void Main(string[] args)
        {
            string tfsurl = "http://tfscollectionurl";
            TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(tfsurl));
            VersionControlServer     vcs  = ttpc.GetService <VersionControlServer>();

            string[]   path      = { "$/Path/To/Item.cs" };
            ItemSpec[] itemSpecs = ItemSpec.FromStrings(path, RecursionType.Full);
            ItemSpec   itemSpec  = itemSpecs.Cast <ItemSpec>().First();
            IEnumerable <Changeset> changesets = vcs.QueryHistory(itemSpec);
            Changeset latestchangeset          = changesets.Cast <Changeset>().First();

            Console.WriteLine(latestchangeset.Committer);
            Console.WriteLine(latestchangeset.CommitterDisplayName);
            Console.WriteLine(latestchangeset.Owner);
            Console.WriteLine(latestchangeset.OwnerDisplayName);
            Console.WriteLine(latestchangeset.CreationDate);
            Console.ReadLine();
        }
コード例 #14
0
        public void persister_should_create_changeset_only_with_new_events()
        {
            var ticket    = TicketTestFactory.ForTest();
            var persister = (IEventSourcedAggregate)ticket;

            var changeSet = new Changeset(1, new TicketSold());

            persister.ApplyChanges(changeSet);

            ticket.Refund();

            changeSet = persister.GetChangeSet();

            Assert.NotNull(changeSet);
            Assert.False(changeSet.IsEmpty());
            Assert.Equal(2, changeSet.AggregateVersion);
            Assert.True(1 == changeSet.Events.Length);
            Assert.IsType <TicketRefunded>(changeSet.Events[0]);
        }
コード例 #15
0
        protected async Task <Changeset> ProcessEvents(
            DomainEvent[] evts,
            Func <Int64, IIdentity> generateId = null)
        {
            Int64 commitId = ++_lastCommit;

            generateId = generateId ?? (p => new SampleAggregateId(p));
            foreach (var evt in evts)
            {
                evt.SetPropertyValue(d => d.AggregateId, generateId(_aggregateIdSeed));
                evt.SetPropertyValue(d => d.CheckpointToken, commitId);
            }

            Changeset cs    = new Changeset(_aggregateVersion++, evts);
            var       chunk = await _persistence.AppendAsync(evts[0].AggregateId, cs).ConfigureAwait(false);

            lastUsedPosition = chunk.Position;
            return(cs);
        }
コード例 #16
0
        /// <summary>
        /// Poll readmodel until the readmodel does not satisfy condition or timeout is reached.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="changeset"></param>
        /// <param name="conditionToAssert"></param>
        private void AssertForReadmodelCondition <T>(Changeset changeset, Func <T, Boolean> conditionToAssert)
            where T : class, IAtomicReadModel
        {
            var      firstEvent = changeset.Events[0] as DomainEvent;
            DateTime startWait  = DateTime.UtcNow;
            var      collection = GetCollection <T>();

            while (DateTime.UtcNow.Subtract(startWait).TotalSeconds < 5)
            {
                var record = collection.FindOneById(firstEvent.AggregateId.AsString());
                if (record != null && conditionToAssert(record))
                {
                    return; //Assertion is correct
                }

                Thread.Sleep(100);
            }
            Assert.Fail("Condition not met in the allotted timespan");
        }
コード例 #17
0
        private Func <IBuildDetail, bool> GetFilter()
        {
            if (UserContext != null)
            {
                return(detail => detail.RequestedFor == UserContext.UserName);
            }

            Changeset changeset = GetChangesetFromCurrentPage();

            if (changeset != null)
            {
                return(detail =>
                {
                    var chString = detail.SourceGetVersion.Replace("C", "");
                    return (changeset.ChangesetId.ToString() == chString) || (InformationNodeConverters.GetAssociatedChangesets(detail).Any(summary => summary.ChangesetId == changeset.ChangesetId));
                });
            }
            return(detail => true);
        }
コード例 #18
0
        private void ProcessLogEntry(Repository repo, Changeset commit)
        {
            var logEntryDto = new LogEntryDto
                {
                    Revision = commit.RevisionNumber.ToString(),
                    Author = commit.AuthorName,
                    CommittedDate = commit.Timestamp,
                    Message = "("+commit.Branch + ") " +  commit.CommitMessage,
                    ChangedFiles = new List<ChangedFileDto>()
                };

            foreach (ChangesetPathAction change in commit.PathActions)
            {
                var changeFileDto = new ChangedFileDto
                    {
                        FileName = change.Path,
                        ChangeType = MercurialChangeStatusToChangeType(change.Action)
                    };

                switch (changeFileDto.ChangeType)
                {
                    case ChangeType.Added:
                        changeFileDto.OldVersion = new byte[0];
                        changeFileDto.NewVersion = GetFile(repo, commit.RevisionNumber, change.Path);
                        break;
                    case ChangeType.Deleted:
                        changeFileDto.OldVersion = GetFile(repo, commit.LeftParentRevision, change.Path);
                        changeFileDto.NewVersion = new byte[0];
                        break;
                    default:
                        changeFileDto.OldVersion = GetFile(repo, commit.LeftParentRevision, change.Path);
                        changeFileDto.NewVersion = GetFile(repo, commit.RevisionNumber, change.Path);
                        break;
                }

                logEntryDto.ChangedFiles.Add(changeFileDto);
            }

            var args = new NewLogEntryEventArgs { LogEntry = logEntryDto };
            OnNewLogEntry(args);
            MaxDateTimeRetrieved = logEntryDto.CommittedDate;
        }
コード例 #19
0
        /// <summary>
        /// this function acts as a proxy for the function below it.
        /// </summary>
        public IList <QueryRec> queryMerge(Changeset cs, string targetPath, int distance)
        {
            saastdlib.Timer t = new saastdlib.Timer();
            t.start();

            /* pull down the item type.
             * i need this to determine params for the querymergedetails call.
             */
            Item itm = _getItem(targetPath, cs.ChangesetId, 0, false);

            IList <QueryRec> queries = queryMerge(cs, itm, distance);

            t.stop();
            Logger.logger.DebugFormat("qm[{0} queries took {1}]", this.QueryCount, this.QueryTime);
            Logger.logger.DebugFormat("qm[{0} get items took {1}]", this.GetItemCount, this.GetItemTime);
            Logger.logger.DebugFormat("qm[{0} get changesets took {1}]", this.GetChangesetCount, this.GetChangesetTime);
            Logger.logger.DebugFormat("qm[total time {1}]", t.Total);

            return(queries);
        }
        public async Task Verify_basic_fix_for_readmodel()
        {
            //Arrange: Generate some commit and project them
            Changeset changeset = await GenerateSomeEvents().ConfigureAwait(false);

            var engine = await CreateSutAndStartProjectionEngineAsync().ConfigureAwait(false);

            GetTrackerAndWaitForChangesetToBeProjected("SimpleTestAtomicReadModel");
            await engine.StopAsync().ConfigureAwait(false);

            //Act, start the fixer and change signature
            SimpleTestAtomicReadModel.FakeSignature = 2;
            var sut = GenerateSut();

            sut.AddReadmodelToFix(typeof(SimpleTestAtomicReadModel));
            sut.StartFixing();

            //ok I'm expecting the fix to correct the readmodel
            AssertForReadmodelCondition <SimpleTestAtomicReadModel>(changeset, rm => rm.ReadModelVersion == 2 && rm.TouchCount == 4);
        }
コード例 #21
0
 public static RevisionInfo ToRevisionInfo(this Changeset changeset)
 {
     return(new RevisionInfo
     {
         Author = changeset.AuthorName,
         Comment = changeset.CommitMessage,
         Id = new RevisionId()
         {
             Time = changeset.Timestamp, Value = changeset.Hash
         },
         Time = changeset.Timestamp,
         Entries = changeset.PathActions
                   .Select(pa => new RevisionEntryInfo()
         {
             Path = pa.Path, Action = pa.Action.ToFileAction()
         }).ToArray(),
         Email = changeset.AuthorEmailAddress,
         TimeCreated = changeset.Timestamp
     });
 }
コード例 #22
0
        /// <summary>
        /// Merges the specified changesets.
        /// </summary>
        /// <param name="changeset1">The changeset1.</param>
        /// <param name="changeset2">The changeset2.</param>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public Changeset <IChange> Merge(MergableChangeset changeset1, MergableChangeset changeset2,
                                         IReadOnlyList <string> source)
        {
            if ((changeset1 == null) || (changeset2 == null) || (source == null))
            {
                throw new ArgumentNullException();
            }

            changeset1.Verify(source.Count);
            changeset2.Verify(source.Count);

            var result = new Changeset <IChange>();

            foreach (int key in changeset1.Keys)
            {
                result.Add(key, changeset1[key]);
            }

            return(result);
        }
コード例 #23
0
        private List <Changeset> ExtractDifferentialChanges(TId id, IOrderedEnumerable <HistoricalEvent> events, HistoricalEvent sourceEvent, TEntity sourceObject)
        {
            var differentialChangeset = new List <Changeset>();

            var currentEvent  = sourceEvent;
            var currentObject = sourceObject;
            var currentDto    = _mapper.Map <TDto>(currentObject);

            for (int i = 1; i < events.Count(); i++)
            {
                var nextEvent       = events.ToArray()[i];
                var nextEventObject = JsonConvert.DeserializeObject <TEntity>(currentEvent.Changeset.ObjectDelta);
                var nextEventDto    = _mapper.Map <TDto>(nextEventObject);
                var changeset       = new Changeset();
                changeset.EventDate   = currentEvent.CreatedDate.Value;
                changeset.UserId      = currentEvent.CreatedBy;
                changeset.ChangesetId = currentEvent.Changeset.Id;
                changeset.EventName   = currentEvent.Action;
                changeset.Changes     = _historicalCrudReadService.ExtractChanges(currentDto, nextEventDto);
                differentialChangeset.Add(changeset);

                currentObject = nextEventObject;
                currentDto    = _mapper.Map <TDto>(currentObject);
                currentEvent  = nextEvent;
            }
            // add last event to current object
            var lastChangeset = new Changeset();
            var lastEvent     = events.Last();

            lastChangeset.EventDate   = lastEvent.CreatedDate.Value;
            lastChangeset.UserId      = lastEvent.CreatedBy;
            lastChangeset.ChangesetId = lastEvent.Changeset.Id;
            lastChangeset.Changes     = lastEvent.Action != HistoricalActions.Delete.ToString() ? _historicalCrudReadService.ExtractChanges(
                _mapper.Map <TDto>(currentObject),
                _mapper.Map <TDto>(_repository.GetById <TId, TEntity>(id))) : null;
            lastChangeset.EventName = lastEvent.Action;

            differentialChangeset.Add(lastChangeset);

            return(differentialChangeset);
        }
コード例 #24
0
        private static void FeedVersionControlData(ICollection <VersionControlItem> versionControlItemCollection, TfsTeamProjectCollection tpc, string projectName)
        {
            VersionControlServer vcs = tpc.GetService <VersionControlServer>();
            ItemSet items            = vcs.GetItems("$/" + projectName + "/*", RecursionType.None);

            foreach (Item item in items.Items)
            {
                int         itemChangeSetId      = item.ChangesetId;
                DateTime    lastInnerCheckInDate = DateTime.MinValue;
                int         lastInnerChangeSetId = 0;
                IEnumerable history = vcs.QueryHistory(item.ServerItem, VersionSpec.Latest,
                                                       item.DeletionId,
                                                       RecursionType.Full,
                                                       null,
                                                       new ChangesetVersionSpec(itemChangeSetId),
                                                       VersionSpec.Latest,
                                                       Int32.MaxValue,
                                                       false,
                                                       false);
                IEnumerator enumerator = history.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    Changeset lastChangeSet = enumerator.Current as Changeset;
                    if (lastChangeSet != null)
                    {
                        lastInnerCheckInDate = lastChangeSet.CreationDate;
                        lastInnerChangeSetId = lastChangeSet.ChangesetId;
                    }
                }

                VersionControlItem vci = new VersionControlItem()
                {
                    DisplayName      = item.ServerItem,
                    ItemChangeSetId  = itemChangeSetId,
                    ItemLastCheckIn  = item.CheckinDate,
                    InnerChangeSetId = lastInnerChangeSetId,
                    InnerLastCheckIn = lastInnerCheckInDate
                };
                versionControlItemCollection.Add(vci);
            }
        }
コード例 #25
0
        private void _queueOrVisit(QueryProcessor qp,
                                   Changeset cs, int distance, string branch)
        {
            Revision rev = _results.getRevision(cs.ChangesetId);

            if (rev == null)
            {
                /* ok, ok, we really don't have it...
                 * didn't find it, so do the first level query.
                 */
                if (!_handleVisit(qp, cs, distance))
                {
                    /* manufacture a visit since this changeset
                     * has no merge actions to get branches from
                     */
                    if (branch == null)
                    {
                        /* determine a branch from the changesets's changes
                         * we're not queuing it, so we look for _all_ branches.
                         * (eg, 2nd level :[ )
                         */
                        List <string> branches =
                            tfsinterface.Utils.FindChangesetBranches(cs, (cng) => true);

                        foreach (string b in branches)
                        {
                            _results.construct(b, cs);
                        }
                    }
                    else
                    {
                        Logger.logger.DebugFormat("building {0}", cs.ChangesetId);
                        _results.construct(branch, cs);
                    }
                }
            }
            else
            {
                /* woo, got nothing left to do! */
            }
        }
コード例 #26
0
        protected virtual bool HasWorkItems(Changeset changeset)
        {
            // This method wraps changeset.WorkItems, because
            // changeset.WorkItems might result to ConnectionException: TF26175: Team Foundation Core Services attribute 'AttachmentServerUrl' not found.
            // in this case assume that it is initialized to null
            // NB: in VS2011 a new property appeared (AssociatedWorkItems), which works correctly
            WorkItem[] result = null;
            try
            {
                result = changeset.WorkItems;
            }
            catch (ConnectionException exception)
            {
                if (!exception.Message.StartsWith("TF26175:"))
                {
                    throw;
                }
            }

            return(result != null && result.Length > 0);
        }
コード例 #27
0
        private ITfsChangeset BuildTfsChangeset(Changeset changeset, GitTfsRemote remote)
        {
            var tfsChangeset = _container.With <ITfsHelper>(this).With <IChangeset>(_bridge.Wrap <WrapperForChangeset, Changeset>(changeset)).GetInstance <TfsChangeset>();

            tfsChangeset.Summary = new TfsChangesetInfo {
                ChangesetId = changeset.ChangesetId, Remote = remote
            };

            if (changeset.WorkItems != null)
            {
                tfsChangeset.Summary.Workitems = changeset.WorkItems.Select(wi => new TfsWorkitem
                {
                    Id          = wi.Id,
                    Title       = wi.Title,
                    Description = wi.Description,
                    Url         = Linking.GetArtifactUrl(wi.Uri.AbsoluteUri)
                });
            }

            return(tfsChangeset);
        }
コード例 #28
0
ファイル: utils.cs プロジェクト: cptnalf/megahist_stuff
        /// <summary>
        /// is the changeset passed in a merge changeset?
        /// it looks at the changes contained in the changeset to make that determiniation
        /// </summary>
        /// <param name="cs"></param>
        /// <returns></returns>
        public static bool IsMergeChangeset(Changeset cs)
        {
            bool isMerge      = false;
            int  changesCount = cs.Changes.Length;

            for (int i = 0; i < changesCount; ++i)
            {
                Change cng = cs.Changes[i];

                isMerge =
                    ((cng.ChangeType & ChangeType.Branch) == ChangeType.Branch
                     ||
                     (cng.ChangeType & ChangeType.Merge) == ChangeType.Merge);
                if (isMerge)
                {
                    break;
                }
            }

            return(isMerge);
        }
コード例 #29
0
        /// <summary>
        /// Helper method that request the agrsso code with a given changeset id
        /// </summary>
        /// <param name="changesetId"></param>
        /// <returns></returns>
        public async Task <string> GetAgressoCode(int?changesetId)
        {
            if (!changesetId.HasValue)
            {
                return(string.Empty);
            }

            string cacheKey = string.Format("GetAgressoCode{0}", changesetId.Value);

            return(await _cacheManager.Resolve(cacheKey, async() =>
            {
                Changeset changeset = await _changesets.GetChangeset(changesetId.ToString());
                if (changeset?.WitList != null && changeset.WitList.Count > 0)
                {
                    WorkItem wit = await _wit.GetWorkItem(changeset.WitList?.First()?.Id.ToString());
                    string codeProject = wit?.WitFields?.ProjectCodeAgresso ?? wit?.WitFields?.MantisProject;
                    return codeProject;
                }
                return "no project name";
            }));
        }
コード例 #30
0
ファイル: DataChangeset.cs プロジェクト: Cyrinehl/Portail
        public static void InsertData(Changeset Changeset, MySqlConnection myConnection)
        {
            try
            {
                string query = "INSERT IGNORE INTO changeset (ChangesetId, Comment, CreatedDate, DevelopperId)";
                query += " VALUES (@ChangesetId, @Comment, @CreatedDate, @DevelopperId)";

                MySqlCommand myCommand = new MySqlCommand(query, myConnection);
                myCommand.Parameters.AddWithValue("@ChangesetId", Changeset.ChangesetId);
                myCommand.Parameters.AddWithValue("@Comment", Changeset.Comment);
                myCommand.Parameters.AddWithValue("@CreatedDate", Changeset.CreatedDate);
                myCommand.Parameters.AddWithValue("@DevelopperId", Changeset.DevelopperId);


                int row = myCommand.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                string error = "Exception Occre while Inserting in table changeset:" + e.Message + "\t" + e.GetType();
            }
        }
コード例 #31
0
        public Changeset ExtractOneDifferentialChangeset <T2>(HistoricalEvent currentEvent, HistoricalEvent nextEvent) where T2 : class, IEntity <T1>, new()
        {
            var currentObject = JsonConvert.DeserializeObject <T2>(currentEvent.Changeset.ObjectDelta);
            var nextObject    =
                nextEvent.Action == HistoricalActions.Delete.ToString()
                    ? JsonConvert.DeserializeObject <T2>(nextEvent.Changeset?.ObjectData)
                    : JsonConvert.DeserializeObject <T2>(nextEvent.Changeset?.ObjectDelta);

            var changeset = new Changeset();

            changeset.EventDate   = nextEvent.CreatedDate.Value;
            changeset.UserId      = nextEvent.CreatedBy;
            changeset.ChangesetId = nextEvent.Changeset.Id;
            changeset.EventName   = nextEvent.Action;
            changeset.Changes     =
                currentEvent.Action != HistoricalActions.Delete.ToString() ?
                ExtractChanges(currentObject, nextObject) :
                null;

            return(changeset);
        }
コード例 #32
0
        static void GetVersionByChangeset(Uri tfsUri, string serverPath, int changesetId)
        {
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(tfsUri);
            VersionControlServer     vcs = tpc.GetService <VersionControlServer>();
            Changeset changeset          = vcs.GetChangeset(changesetId);

            WorkingFolder workfolder = new WorkingFolder(serverPath, @"C:\tsf_" + changesetId);
            Workspace     workspace  = vcs.CreateWorkspace(changesetId.ToString());

            workspace.CreateMapping(workfolder);
            GetStatus status = workspace.Get(VersionSpec.ParseSingleSpec(
                                                 String.Format("C{0}", changesetId), null)
                                             , GetOptions.GetAll);

            workspace.Delete();
            StreamWriter fileWriter = new StreamWriter(@"C:\tsf_" + changesetId + @"\Database_snapshot.txt", false);

            fileWriter.WriteLine(changeset.Comment);
            fileWriter.Close();
            fileWriter.Dispose();
        }
コード例 #33
0
            public void Apply(Changeset changeset) {
                string relativePath;
                if (!IsFileAllowed(_rootDirectory, _fullPath, _fileSystem, _fileSystemFilter, out relativePath)) {
                    return;
                }

                // If file with the same name was removed, just remove it from the RemovedFiles set
                if (changeset.RemovedFiles.Remove(relativePath)) {
                    return;
                }

                // If file had this name before renaming, remove it from RenamedFiles and add to AddedFiles instead
                string renamedFile;
                if (changeset.RenamedFiles.TryGetValue(relativePath, out renamedFile)) {
                    changeset.RenamedFiles.Remove(relativePath);
                    changeset.AddedFiles.Add(renamedFile);
                    return;
                }

                changeset.AddedFiles.Add(relativePath);
            }
コード例 #34
0
        static void Main(string[] args)
        {
            string projecturi             = "https://xxx:8080/tfs/";
            int    changesetid            = xxx;
            TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(projecturi));
            VersionControlServer     vcs  = ttpc.GetService <VersionControlServer>();
            Changeset cset = vcs.GetChangeset(changesetid);
            TeamFoundationDiscussionService tfds = new TeamFoundationDiscussionService();

            tfds.Initialize(ttpc);
            IDiscussionManager idm = tfds.CreateDiscussionManager();
            IAsyncResult       iar = idm.BeginQueryByVersion(cset.ArtifactUri, QueryStoreOptions.ServerOnly, new AsyncCallback(Callback), null);
            var threads            = idm.EndQueryByVersion(iar);

            foreach (DiscussionThread dt in threads)
            {
                Console.WriteLine(dt.RootComment.Content);
                Console.WriteLine(dt.RootComment.Author.DisplayName);
                Console.ReadLine();
            }
        }
コード例 #35
0
        /**
         *  @param srcPath    item path
         *  @param srcVersion version
         *  @param maxChanges maximum number of changes to query for.
         */
        public virtual bool visit(string srcPath, VersionSpec srcVersion, int maxChanges)
        {
            bool result = true;

            _tree = megahistory.SCMUtils.GetBranches(_vcs, srcPath, srcVersion);

            System.Collections.IEnumerable foo =
                _vcs.QueryHistory(srcPath, srcVersion, 0, RecursionType.Full,
                                  null, null, null,                                                                       /* user, from ver, to ver */
                                  maxChanges,
                                  true, false, false);

            /* inc changes, slot mode, inc download info. */
            foreach (object o in foo)
            {
                Changeset cs      = o as Changeset;
                bool      isMerge = false;

                result &= true;
                isMerge = megahistorylib.Utils.IsMergeChangeset(cs);

                if (isMerge)
                {
                    visit(0, srcPath, cs.ChangesetId);
                }
                else
                {
                    _visitor.visit(0, cs);
                }

                _visitor.reset();
            }

            /* dump some stats out to the log file. */
            MH.logger.DebugFormat("{0} queries took {1}", _queries, _queryTimer.Total);
            MH.logger.DebugFormat("{0} findchangesetbranchcalls for {1} changesets.",
                                  megahistorylib.Utils.FindChangesetBranchesCalls, _visitor.visitedCount());

            return(result);
        }
コード例 #36
0
            public void Apply(Changeset changeset) {
                if (!_fullPath.StartsWithIgnoreCase(_rootDirectory)) {
                    return;
                }

                var relativePath = PathHelper.MakeRelative(_rootDirectory, _fullPath);

                // If the file with the same name was previously added, just remove it from the AddedFiles set
                if (changeset.AddedFiles.Remove(relativePath)) {
                    return;
                }

                // if the file was renamed into relativePath, put the oldRelativePath into RemovedFiles instead.
                var oldRelativePath = changeset.RenamedFiles.GetFirstKeyByValueIgnoreCase(relativePath);
                if (oldRelativePath != null) {
                    changeset.RenamedFiles.Remove(oldRelativePath);
                    changeset.RemovedFiles.Add(oldRelativePath);
                    return;
                }

                changeset.RemovedFiles.Add(relativePath);
            }
コード例 #37
0
        public static void Tag(Changeset changeset, Change change, string fileName)
        {
            var sr       = new StreamReader(fileName);
            var tempFile = sr.ReadToEnd();

            sr.Close();
            var sw = new StreamWriter(fileName);

            sw.WriteLine("----------------------------------------------------");
            sw.WriteLine("-- ChangesetId: {0}{1}-- ServerItem: {2}", changeset.ChangesetId, Environment.NewLine, change.Item.ServerItem);

            sw.WriteLine("-- Changeset Creation Date: {0}, Owner: {1}, Committer: {2}", changeset.CreationDate, changeset.Owner, changeset.Committer);

            foreach (var workItem in changeset.WorkItems)
            {
                sw.WriteLine("-- WorkItem: " + workItem.Id);
            }

            sw.WriteLine("----------------------------------------------------" + Environment.NewLine);
            sw.Write(tempFile);
            sw.Close();
        }
コード例 #38
0
        /// <summary>
        /// Returns the changeset type.
        /// </summary>
        private ChangesetType GetChangeType(Changeset chg)
        {
            if (chg.RevertedChangesetId != null)
            {
                return(ChangesetType.Restored);
            }

            var wasNull = string.IsNullOrEmpty(chg.OriginalState);
            var isNull  = string.IsNullOrEmpty(chg.UpdatedState);

            if (wasNull)
            {
                return(ChangesetType.Created);
            }

            if (isNull)
            {
                return(ChangesetType.Removed);
            }

            return(ChangesetType.Updated);
        }
コード例 #39
0
        public static Changeset[] GetUsersChangesets(long userId)
        {
            var changes    = new List <Changeset>();
            var oneDay     = TimeSpan.FromDays(1);
            var newChanges = new Changeset[0];

            do
            {
                var before = newChanges.DefaultIfEmpty(new Changeset()
                {
                    CreatedAt = DateTime.UtcNow
                }).Min(c => c.CreatedAt.Value);
                newChanges = OsmApiClient.QueryChangesets(null, userId, null, DateTime.MinValue, null, false, false, null).Result;
                Thread.Sleep(10000);
                if (newChanges != null)
                {
                    changes.AddRange(newChanges);
                }
            } while (newChanges?.Length == 100);

            return(changes.ToArray());
        }
コード例 #40
0
            public void Apply(Changeset changeset) {
                string newRelativePath;
                if (!IsFileAllowed(_rootDirectory, _fullPath, _fileSystem, _fileSystemFilter, out newRelativePath)) {
                    return;
                }

                var oldRelativePath = PathHelper.MakeRelative(_rootDirectory, _oldFullPath);
                var isRename = true;

                // If file with the oldRelativePath was previously added, remove it from the AddedFiles and add newRelativePath
                if (changeset.AddedFiles.Remove(oldRelativePath)) {
                    changeset.AddedFiles.Add(newRelativePath);
                    isRename = false;
                }

                // if file with the newRelativePath was previously deleted, remove it from the RemovedFiles and add oldRelativePath
                if (changeset.RemovedFiles.Remove(newRelativePath)) {
                    changeset.RemovedFiles.Add(oldRelativePath);
                    isRename = false;
                }

                if (!isRename) {
                    return;
                }

                // if there is a file that was renamed into oldRelativePath, rename it to newRelativePath instead
                // or remove from RenamedFiles if previouslyRenamedRelativePath equal to newRelativePath
                var previouslyRenamedRelativePath = changeset.RenamedFiles.GetFirstKeyByValueIgnoreCase(oldRelativePath);
                if (string.IsNullOrEmpty(previouslyRenamedRelativePath)) {
                    changeset.RenamedFiles[oldRelativePath] = newRelativePath;
                } else if (previouslyRenamedRelativePath.EqualsIgnoreCase(newRelativePath)) {
                    changeset.RenamedFiles.Remove(previouslyRenamedRelativePath);
                } else {
                    changeset.RenamedFiles[previouslyRenamedRelativePath] = newRelativePath;
                }
            }
コード例 #41
0
 private string GetTextFileContentSafe(Changeset commit, string path)
 {
     try
     {
         return GetFileContent(commit, path);
     }
     catch
     {
         return string.Empty;
     }
 }
コード例 #42
0
 private string GetFileContent(Changeset commit, string path)
 {
     return _mercurial.GetFileContent(commit, path);
 }
コード例 #43
0
        private DiffResult GetDiff(string path, Changeset prevCommmit, Changeset commit)
        {
            var fileContent = GetTextFileContentSafe(commit, path);
            var previousRevisionFileContent = GetTextFileContentSafe(prevCommmit, path);
            var diff = _diffProcessor.GetDiff(previousRevisionFileContent, fileContent);

            diff.LeftPanRevisionId = prevCommmit.RevisionNumber.ToString();
            diff.RightPanRevisionId = commit.RevisionNumber.ToString();

            return diff;
        }
コード例 #44
0
        private void UndeleteFolder(Changeset changeset, Change change)
        {
            string itemPath = GetItemPath(change.Item);
            Directory.CreateDirectory(itemPath);

            if (this.FolderUndeleted != null)
                this.FolderUndeleted(changeset.ChangesetId, itemPath, changeset.Committer, changeset.Comment, changeset.CreationDate);
        }
コード例 #45
0
        public string GetFileContent(Changeset commit, string path)
		{
            var command = new CatCommand().WithFile(path);
			if (commit != null)
			{
				command = command.WithAdditionalArgument(string.Format("-r {0}", commit.RevisionNumber));
			}
            _repository.Execute(command);
            return command.RawStandardOutput;
		}
 public void Apply(Changeset changeset) { }
コード例 #47
0
 public Changeset GetParentCommit(Changeset commit)
 {
     var command = new LogCommand().WithIncludePathActions();
     var changeset = _repository.Log(command)
         .FirstOrDefault(ch => ch.RevisionNumber == (commit.RevisionNumber > 0 ? commit.RevisionNumber - 1 : commit.RevisionNumber));
     return changeset;
 }
コード例 #48
0
ファイル: Changeset.cs プロジェクト: wullemsb/TFS-Monitor
 public static Changeset CreateChangeset(int ID, global::System.DateTime creationDate)
 {
     Changeset changeset = new Changeset();
     changeset.Id = ID;
     changeset.CreationDate = creationDate;
     return changeset;
 }
コード例 #49
0
        /// <summary>
        /// Parse the given XML lazily and return a collection of <see cref="Changeset"/>
        /// objects for the information contained in it, in the order the changesets
        /// appear in the xml.
        /// </summary>
        /// <param name="xml">
        /// The XML to parse.
        /// </param>
        /// <returns>
        /// A collection of <see cref="Changeset"/> objects.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// <para>An unknown path action character was detected in the log output.</para>
        /// <para>- or -</para>
        /// <para>The XML content was not legal according to the expected format.</para>
        /// </exception>
        public static IEnumerable<Changeset> LazyParse(string xml)
        {
            if (StringEx.IsNullOrWhiteSpace(xml))
                yield break;

            var serializer = new XmlSerializer(typeof(LogEntryNode));
            foreach (string entryXml in LazyExtractChangesetXmlPieces(xml))
            {
                var entry = (LogEntryNode)serializer.Deserialize(new StringReader(entryXml));
                var changeset = new Changeset
                {
                    Timestamp = entry.Timestamp,
                    AuthorName = (entry.Author ?? new LogEntryAuthorNode()).Name,
                    AuthorEmailAddress = (entry.Author ?? new LogEntryAuthorNode()).Email,
                    CommitMessage = entry.CommitMessage ?? string.Empty,
                    Branch = entry.Branch ?? "default",
                    Hash = entry.Hash,
                    RevisionNumber = entry.Revision,
                    Revision = RevSpec.Single(entry.Hash),
                    Tags = entry.Tags.Select(t => t.Name).ToArray(),
                };

                switch (entry.Parents.Count)
                {
                    case 2:
                        changeset.RightParentHash = entry.Parents[1].Hash;
                        changeset.RightParentRevision = entry.Parents[1].Revision;
                        goto case 1;

                    case 1:
                        changeset.LeftParentHash = entry.Parents[0].Hash;
                        changeset.LeftParentRevision = entry.Parents[0].Revision;
                        break;

                    case 0:
                        changeset.LeftParentRevision = changeset.RevisionNumber - 1;
                        break;
                }

                foreach (LogEntryPathNode action in entry.PathActions)
                {
                    var pathAction = new ChangesetPathAction
                    {
                        Path = action.Path,
                    };
                    switch (action.Action)
                    {
                        case "M":
                            pathAction.Action = ChangesetPathActionType.Modify;
                            break;

                        case "A":
                            pathAction.Action = ChangesetPathActionType.Add;
                            LogEntryCopyNode copySource = entry.Copies.Where(c => c.Destination == action.Path).FirstOrDefault();
                            if (copySource != null)
                                pathAction.Source = copySource.Source;
                            break;

                        case "R":
                            pathAction.Action = ChangesetPathActionType.Remove;
                            break;

                        default:
                            throw new InvalidOperationException("Unknown path action: " + action.Action);
                    }
                    changeset.PathActions.Add(pathAction);
                }

                yield return changeset;
            }
        }
コード例 #50
0
        /// <summary>
        /// Updates the issue tracker from the change set.
        /// </summary>
        /// <param name="repository"> </param>
        /// <param name="changeset"> </param>
        /// <param name="service"> </param>
        public static void UpdateBugNetForChangeset(string repository, Changeset changeset, WebServices.BugNetServices service)
        {
            var issuesAffectedList = new List<int>();
            var regEx = new Regex(AppSettings.IssueIdRegEx, RegexOptions.IgnoreCase);

            var commitMessage = changeset.CommitMessage.Trim();
            var matchResults = regEx.Match(commitMessage);

            if (!matchResults.Success) // none in the commit message
            {
                Log.Info("MercurialChangeGroupHook: Found no Issue Ids in change set");
                return;
            }

            // capture the issues ids in the commit message
            // validate if the issue id is 
            // change the commit message for each issue id (may be more to the commit)
            while (matchResults.Success)
            {
                var value = matchResults.Groups[1].Value.Trim();
                var issueIdParts = value.Split(new[] { '-' });

                if (issueIdParts.Length.Equals(2))
                {
                    var idString = issueIdParts[1];

                    int issueId;
                    if (int.TryParse(idString, out issueId))
                    {
                        if(service.ValidIssue(issueId)) // check the issue to make sure it exists
                        {
                            commitMessage = Regex.Replace(commitMessage, AppSettings.IssueIdRegEx, "<a href=\"IssueDetail.aspx?id=$2#top\"><b>$1</b></a>");
                            issuesAffectedList.Add(issueId);   
                        }
                    }
                }

                matchResults = matchResults.NextMatch();
            }

            if (issuesAffectedList.Count <= 0) return;

            var revisionNumber = changeset.RevisionNumber;
            var revision = changeset.Hash.Trim();
            var author = changeset.AuthorName.Trim();
            var dateTime = changeset.Timestamp.ToString();
            var branch = changeset.Branch.Trim();

            foreach (var id in issuesAffectedList)
            {
                try
                {
                    Log.Info("MercurialChangeGroupHook: Creating new issue revision");

                    var success = service.CreateNewIssueRevision(
                        revisionNumber,
                        id,
                        repository,
                        author,
                        dateTime,
                        commitMessage,
                        revision,
                        branch);

                    if (success)
                        Log.Info("MercurialChangeGroupHook: Successfully added new issue revision");
                    else
                        Log.Warn("MercurialChangeGroupHook: Adding new issue revision failed");
                }
                catch (Exception ex)
                {
                    Log.ErrorFormat("MercurialChangeGroupHook: An error occurred adding a new issue revision to BugNET: {0} \n\n {1}", ex.Message, ex.StackTrace);
                }
            }
        }
コード例 #51
0
 private void Consume(Changeset changeset) {
     IFileSystemChange change;
     while (_queue.TryDequeue(out change)) {
         try {
             _log.WatcherApplyChange(change.ToString());
             change.Apply(changeset);
         } catch (Exception e) {
             _log.WatcherApplyChangeFailed(change.ToString(), e);
             Debug.Fail($"Failed to apply change {change}:\n{e}");
             throw;
         }
     }
 }
コード例 #52
0
ファイル: HgRepository.cs プロジェクト: RaleighHokie/kudu
 private ChangeSet CreateChangeSet(Changeset changeSet)
 {
     return new ChangeSet(changeSet.Hash, changeSet.AuthorName, changeSet.AuthorEmailAddress, changeSet.CommitMessage, new DateTimeOffset(changeSet.Timestamp));
 }
コード例 #53
0
ファイル: BatchWebRequest.cs プロジェクト: larsenjo/odata.net
        private void ParseBatchContent(Stream contentStream, string contentType, bool isResponse, bool matchToExisting)
        {
            int partIndex = 0;
            int changesetIndex = 0;

            if (!matchToExisting)
            {
                this.changesets = new List<Changeset>();
                this.parts = new List<InMemoryWebRequest>();
            }

            MemoryStream memoryStream = new MemoryStream(); // Create a copy since StreamReader will Close the stream, which might not be what we want
            TestUtil.CopyStream(contentStream, memoryStream);
            memoryStream.Position = 0;
            using (TextReader reader = new StreamReader(memoryStream))
            {
                Assert.IsTrue(contentType.StartsWith("multipart/mixed; "), "Response is not a batch response. Expecting 'multipart.mixed', got '" + contentType + "'.");
                string boundary = "--" + contentType.Substring(contentType.IndexOf("; boundary=") + 11).Trim();
                string endboundary = boundary + "--";

                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line == boundary) break;
                    if (line == endboundary)
                    {
                        Assert.IsTrue(partIndex == this.parts.Count, "The response didn't contain enough parts.");
                        return;
                    }
                }

                while (true)
                {
                    line = reader.ReadLine(); // Content-Type
                    Assert.IsTrue(line.StartsWith("Content-Type:"), "The batch part doesn't specify its content type.");
                    contentType = line.Substring("Content-Type:".Length).Trim();
                    if (contentType.StartsWith("multipart/mixed; "))
                    {
                        string changesetBoundary = "--" + contentType.Substring(contentType.IndexOf("; boundary=") + 11).Trim();
                        string changesetEndBoundary = changesetBoundary + "--";
                        int cpartIndex = 0;

                        Changeset changeset;
                        if (matchToExisting)
                        {
                            Assert.IsTrue(this.changesets.Count > changesetIndex, "The batch response contains more changesets than the number of changesets sent.");
                            changeset = this.changesets[changesetIndex];
                        }
                        else
                        {
                            changeset = new Changeset();
                            this.changesets.Add(changeset);
                        }
                        changesetIndex++;

                        while ((line = reader.ReadLine()) != null)
                        {
                            if (line.Trim().Length == 0) break;
                        }

                        while ((line = reader.ReadLine()) != null)
                        {
                            if (line == changesetBoundary) break;
                            if (line == changesetEndBoundary)
                            {
                                goto ChangesetEnd;
                            }
                        }

                        while (true)
                        {
                            reader.ReadLine(); // Content-Type
                            reader.ReadLine(); // Content-Transfer-Encoding

                            InMemoryWebRequest part;
                            if (matchToExisting)
                            {
                                Assert.IsTrue(changeset.Parts.Count > cpartIndex, "The batch response contains more parts than the number of request parts sent.");
                                part = changeset.Parts[cpartIndex];
                            }
                            else
                            {
                                part = new InMemoryWebRequest();
                                changeset.Parts.Add(part);
                            }

                            line = reader.ReadLine();
                            if (!string.IsNullOrEmpty(line))
                            {
                                part.RequestHeaders["Content-ID"] = line.Split(' ')[1];
                                reader.ReadLine();
                            }

                            cpartIndex++;

                            if (ParseBatchPart(isResponse, reader, part, changesetBoundary, changesetEndBoundary))
                            {
                                break;
                            }
                        }
                    ChangesetEnd:
                        if (cpartIndex < changeset.Parts.Count)
                        {
                            int lastStatusCode = changeset.Parts[cpartIndex - 1].ResponseStatusCode;
                            if (!UnitTestsUtil.IsSuccessStatusCode(lastStatusCode))
                            {
                                for (; cpartIndex < changeset.Parts.Count; cpartIndex++)
                                {
                                    changeset.Parts[cpartIndex].SetResponseStatusCode(lastStatusCode);
                                }
                            }
                        }
                        Assert.IsTrue(cpartIndex == changeset.Parts.Count, "The response didn't contain enough parts.");
                        ;

                        while (true)
                        {
                            line = reader.ReadLine();
                            if (line == boundary) break;

                            // We can hit another exception after the changeset.  For example if the changeset fails
                            // and after the server serializes out the error for the changeset, writes the endboundary
                            // for the changeset, and call IUpdatable.ClearChanges(), ClearChanges() can throw.
                            // When that happens we will see the second error but there won't be any boundary after it.
                            // We need to goto End when we either see the end boundary or reached the end of stream.
                            if (line == null || line == endboundary)
                            {
                                goto End;
                            }
                        }
                    }
                    else
                    {
                        Assert.IsTrue(contentType.StartsWith("application/http"), "Batch part is neither changeset nor HTTP.");
                        reader.ReadLine(); // Content-Transfer-Encoding
                        reader.ReadLine(); //

                        InMemoryWebRequest part;
                        if (matchToExisting)
                        {
                            Assert.IsTrue(this.parts.Count > partIndex, "The batch response contains more parts than the number of request parts sent.");
                            part = this.parts[partIndex];
                            partIndex++;
                        }
                        else
                        {
                            part = new InMemoryWebRequest();
                            this.parts.Add(part);
                            partIndex++;
                        }

                        if (ParseBatchPart(isResponse, reader, part, boundary, endboundary))
                        {
                            goto End;
                        }
                    }
                }
            End:
                Assert.IsTrue(partIndex == this.parts.Count, "The response didn't contain enough parts.");
                Assert.IsTrue(changesetIndex == this.changesets.Count, "The response didn't contain enough parts.");
            }
        }
コード例 #54
0
        private async Task ConsumeWaitPublish() {
            _log.WatcherConsumeChangesStarted();

            try {
                var changeset = new Changeset();
                while (!_queue.IsEmpty) {
                    Consume(changeset);
                    await Task.Delay(_delayMilliseconds);
                }

                if (!changeset.IsEmpty()) {
                    _broadcastBlock.Post(changeset);
                    _log.WatcherChangesetSent(changeset);
                }
            } finally {
                _consumerIsWorking = 0;
                _log.WatcherConsumeChangesFinished();
                if (!_queue.IsEmpty) {
                    StartConsumer();
                }
            }
        }
コード例 #55
0
ファイル: Reference.cs プロジェクト: wullemsb/TFS-Monitor
 public void AddToChangesets(Changeset changeset)
 {
     base.AddObject("Changesets", changeset);
 }
コード例 #56
0
        private void UndeleteFile(Changeset changeset, Change change)
        {
            string itemPath = GetItemPath(change.Item);
            DownloadItemFile(change, itemPath);

            if (this.FileUndeleted != null)
                this.FileUndeleted(changeset.ChangesetId, itemPath, changeset.Committer, changeset.Comment, changeset.CreationDate);
        }
コード例 #57
0
        private void RenameFolder(Changeset changeset, Change change)
        {
            string oldPath = GetItemPath(GetPreviousItem(change.Item));
            string newPath = GetItemPath(change.Item);

            if (this.FolderRenamed != null)
                this.FolderRenamed(changeset.ChangesetId, oldPath, newPath, changeset.Committer, changeset.Comment, changeset.CreationDate);
        }
コード例 #58
0
ファイル: Result.cs プロジェクト: Vadim-Borovikov/Automerger
 /// <summary>
 /// Initializes a new instance of the <see cref="Result"/> struct.
 /// </summary>
 /// <param name="changeset">The changeset.</param>
 /// <param name="text">The text.</param>
 internal Result(Changeset<IChange> changeset, IEnumerable<string> text)
 {
     Changeset = changeset;
     Text = text;
 }
コード例 #59
0
        private void ProcessFolderChange(Changeset changeset, Change change)
        {
            // Undelete folder.
            if ((change.ChangeType & ChangeType.Undelete) == ChangeType.Undelete)
                UndeleteFolder(changeset, change);

            // Rename folder.
            else if ((change.ChangeType & ChangeType.Rename) == ChangeType.Rename)
                RenameFolder(changeset, change);

            // Branch folder.
            else if ((change.ChangeType & ChangeType.Branch) == ChangeType.Branch)
                BranchFolder(changeset, change);

            // Add folder.
            else if ((change.ChangeType & ChangeType.Add) == ChangeType.Add)
                AddFolder(changeset, change);

            // Delete folder.
            else if ((change.ChangeType & ChangeType.Delete) == ChangeType.Delete)
                DeleteFolder(changeset, change);
        }
コード例 #60
0
        /// <summary>
        /// Retrieves the latest changeset ID associated with a path
        /// </summary>
        /// <param name="localPath">A path on the local filesystem</param>
        /// <param name="credentials">Credentials used to authenticate against the serer</param>
        /// <returns></returns>
        public int GetLatestChangesetId(string localPath, ICredentials credentials)
        {
            int latestChangesetId = 0;
            string server;

            Workstation workstation = new Workstation(versionControlClientAssembly);
            WorkspaceInfo workspaceInfo = workstation.GetLocalWorkspaceInfo(localPath);
            server = workspaceInfo.ServerUri.ToString();
            VersionControlServer sourceControl = new VersionControlServer(clientAssembly, versionControlClientAssembly, server, credentials);

            Workspace workspace = sourceControl.GetWorkspace(localPath);
            WorkspaceVersionSpec workspaceVersionSpec = new WorkspaceVersionSpec(versionControlClientAssembly, workspace);

            VersionSpec versionSpec = new VersionSpec(versionControlClientAssembly);
            RecursionType recursionType = new RecursionType(versionControlClientAssembly);

            IEnumerable history = sourceControl.QueryHistory(localPath, versionSpec.Latest, recursionType.Full, workspaceVersionSpec);

            IEnumerator historyEnumerator = history.GetEnumerator();
            Changeset latestChangeset = new Changeset(versionControlClientAssembly);
            if (historyEnumerator.MoveNext())
            {
                latestChangeset = new Changeset(versionControlClientAssembly, historyEnumerator.Current);
            }

            if (latestChangeset.Instance != null)
            {
                latestChangesetId = latestChangeset.ChangesetId;
            }
            return latestChangesetId;
        }