public StandardTextDocument(
                DocumentProvider documentProvider,
                IVisualStudioHostProject project,
                DocumentKey documentKey,
                IReadOnlyList<string> folderNames,
                SourceCodeKind sourceCodeKind,
                ITextUndoHistoryRegistry textUndoHistoryRegistry,
                IVsFileChangeEx fileChangeService,
                ITextBuffer openTextBuffer,
                DocumentId id,
                EventHandler updatedOnDiskHandler,
                EventHandler<bool> openedHandler,
                EventHandler<bool> closingHandler)
            {
                Contract.ThrowIfNull(documentProvider);

                this.Project = project;
                this.Id = id ?? DocumentId.CreateNewId(project.Id, documentKey.Moniker);
                this.Folders = folderNames;

                _documentProvider = documentProvider;

                this.Key = documentKey;
                this.SourceCodeKind = sourceCodeKind;
                _itemMoniker = documentKey.Moniker;
                _textUndoHistoryRegistry = textUndoHistoryRegistry;
                _fileChangeTracker = new FileChangeTracker(fileChangeService, this.FilePath);
                _fileChangeTracker.UpdatedOnDisk += OnUpdatedOnDisk;

                _openTextBuffer = openTextBuffer;
                _snapshotTracker = new ReiteratedVersionSnapshotTracker(openTextBuffer);

                // The project system does not tell us the CodePage specified in the proj file, so
                // we use null to auto-detect.
                _doNotAccessDirectlyLoader = new FileTextLoader(documentKey.Moniker, defaultEncoding: null);

                // If we aren't already open in the editor, then we should create a file change notification
                if (openTextBuffer == null)
                {
                    _fileChangeTracker.StartFileChangeListeningAsync();
                }

                if (updatedOnDiskHandler != null)
                {
                    UpdatedOnDisk += updatedOnDiskHandler;
                }

                if (openedHandler != null)
                {
                    Opened += openedHandler;
                }

                if (closingHandler != null)
                {
                    Closing += closingHandler;
                }
            }
            public StandardTextDocument(
                DocumentProvider documentProvider,
                IVisualStudioHostProject project,
                DocumentKey documentKey,
                uint itemId,
                SourceCodeKind sourceCodeKind,
                ITextBufferFactoryService textBufferFactoryService,
                ITextUndoHistoryRegistry textUndoHistoryRegistry,
                IVsFileChangeEx fileChangeService,
                ITextBuffer openTextBuffer,
                DocumentId id)
            {
                Contract.ThrowIfNull(documentProvider);
                Contract.ThrowIfNull(textBufferFactoryService);

                this.Project = project;
                this.Id = id ?? DocumentId.CreateNewId(project.Id, documentKey.Moniker);
                this.Folders = project.GetFolderNames(itemId);

                // TODO: 
                // this one doesn't work for asynchronous project load situation where shared projects is loaded after one uses shared file. 
                // we need to figure out what to do on those case. but this works for project k case.
                // opened an issue to track this issue - https://github.com/dotnet/roslyn/issues/1859
                this.SharedHierarchy = project.Hierarchy == null ? null : LinkedFileUtilities.GetSharedHierarchyForItem(project.Hierarchy, itemId);
                _documentProvider = documentProvider;

                this.Key = documentKey;
                this.SourceCodeKind = sourceCodeKind;
                _itemMoniker = documentKey.Moniker;
                _textBufferFactoryService = textBufferFactoryService;
                _textUndoHistoryRegistry = textUndoHistoryRegistry;
                _fileChangeTracker = new FileChangeTracker(fileChangeService, this.FilePath);
                _fileChangeTracker.UpdatedOnDisk += OnUpdatedOnDisk;

                _openTextBuffer = openTextBuffer;
                _snapshotTracker = new ReiteratedVersionSnapshotTracker(openTextBuffer);

                // The project system does not tell us the CodePage specified in the proj file, so
                // we use null to auto-detect.
                _doNotAccessDirectlyLoader = new FileTextLoader(documentKey.Moniker, defaultEncoding: null);

                // If we aren't already open in the editor, then we should create a file change notification
                if (openTextBuffer == null)
                {
                    _fileChangeTracker.StartFileChangeListeningAsync();
                }
            }
Exemple #3
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            string filePath;
            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemId, out filePath))
                {
                    Environment.FailFast("Failed to get document moniker for a contained document");
                }
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
 public Task <Stream?> ReadStreamAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken)
 => SpecializedTasks.Null <Stream>();
        ///// <summary>
        ///// Implement this method for verifying tempory owener ship change in case of multiple state transfer
        ///// </summary>
        ///// <param name="bkId"></param>
        ///// <param name="p"></param>
        ///// <returns></returns>
        // private Boolean VerifyFinalOwnership(int bkId, NodeIdentity finalShard)
        // {
        //     if (finalShard!=null)
        //     {
        //         IStateTransferOperation operation = null;
        //         try
        //         {
        //             operation = CreateStateTransferOperation(StateTransferOpCode.VerifyFinalOwnerShip);
        //             operation.Params.SetParamValue(ParamName.BucketFinalShard, finalShard);
        //             operation.Params.SetParamValue(ParamName.BucketID, bkId);
        //             return (Boolean)_dispatcher.DispatchOperation<Object>(operation);
        //         }
        //         catch (Exception e)
        //         {
        //             if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsErrorEnabled)
        //                 LoggerManager.Instance.StateXferLogger.Error(loggingModule + ".VerifyFinalOwnership", e.ToString());
        //             try
        //             {
        //                 return (Boolean)Context.ConfigurationSession.StateTransferOperation(Context.ClusterName, operation);
        //             }
        //             catch (Exception ex)
        //             {
        //                 if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsErrorEnabled)
        //                     LoggerManager.Instance.StateXferLogger.Error(loggingModule + ".VerifyFinalOwnership", ex.ToString());
        //             }
        //         }
        //     }

        //     return false;
        // }

        private StateTxfrInfo GetData(int bucketId)
        {
            HashVector result     = new HashVector();
            long       sizeToSend = 0;
            bool       lastChunk  = true;

            if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsDebugEnabled)
            {
                LoggerManager.Instance.StateXferLogger.Debug(loggingModule + ".GetData(2)", "state txfr request for :" + bucketId + " _lastTxfrId :" + _lastTxfrId);
            }

            if (_currentBucketkeys != null && _currentBucketkeys.Count > 0 && _sentKeysCount < _currentBucketkeys.Count)
            {
                if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsDebugEnabled)
                {
                    LoggerManager.Instance.StateXferLogger.Debug(loggingModule + ".GetData(2)", "bucket size :"); // + _keyList.Count);
                }
                //do{
                for (/*_sentKeysCount = 0*/; _sentKeysCount < _currentBucketkeys.Count; _sentKeysCount++)
                {
                    //DocumentKey docKey = _currentBucketkeys.Current as DocumentKey;

                    DocumentKey docKey = _currentBucketkeys[_sentKeysCount] as DocumentKey;
                    if (docKey == null)
                    {
                        continue;
                    }

                    JSONDocument jdoc = new JSONDocument();
                    jdoc.Key = docKey.Value as string;

                    System.Collections.Generic.List <IJSONDocument> documents = new System.Collections.Generic.List <IJSONDocument>();
                    documents.Add(jdoc);

                    IGetOperation operation = new LocalGetOperation();
                    operation.Database    = corresponderIdentity.DBName;
                    operation.Collection  = corresponderIdentity.ColName;
                    operation.DocumentIds = documents;
                    IGetResponse response = null;
                    if (_databasesManager != null)
                    {
                        response = _databasesManager.GetDocuments(operation);
                    }
                    if (response != null)
                    {
                        IJSONDocument doc = (response.DataChunk != null && response.DataChunk.Documents != null)?response.DataChunk.Documents[0]:null;

                        if (doc != null)
                        {
                            long size = GetDocumentSize(doc as ISize);

                            result[docKey] = doc;
                            sizeToSend    += size;
                            if (sizeToSend > _threshold)
                            {
                                lastChunk = false;
                                break;
                            }
                        }
                    }
                }
                //} while (_currentBucketkeys.MoveNext());

                if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsDebugEnabled)
                {
                    LoggerManager.Instance.StateXferLogger.Debug(loggingModule + ".GetData()", "bucketid: " + bucketId + " items sent: " + result.Count);
                }

                if (_isBalanceDataLoad)
                {
                    if (StatsManager.Instance.GetStatsCollector(_statsIdentity) != null)
                    {
                        StatsManager.Instance.GetStatsCollector(_statsIdentity).IncrementStatsValue(StatisticsType.DataBalancePerSec, result.Count);
                    }
                    else
                    if (StatsManager.Instance.GetStatsCollector(_statsIdentity) != null)
                    {
                        StatsManager.Instance.GetStatsCollector(_statsIdentity).IncrementStatsValue(StatisticsType.StateTransferPerSec, result.Count);
                    }
                }

                return(new StateTxfrInfo(result, false, sizeToSend));//, this.stream);
            }
            else if (corresponderIdentity.Type == StateTransferType.INTER_SHARD)
            {
                SetBucketStatus(corresponderIdentity.NodeInfo, new ArrayList()
                {
                    _currentBucket
                });

                StopLoggingOnSource(_currentBucket);

                //We need to transfer the logs.
                if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsDebugEnabled)
                {
                    LoggerManager.Instance.StateXferLogger.Debug(loggingModule + ".GetData(2)", "sending log data for bucket: " + bucketId);
                }

                return(GetLoggedData(_currentBucket));
            }
            else
            {
                //As transfer mode is not MOVE_DATA, therefore no logs are maintained
                //and hence are not transferred.
                return(new StateTxfrInfo(null, true, 0));//, null);
            }
        }
        private void NewBufferOpened(uint docCookie, ITextBuffer textBuffer, DocumentKey documentKey, bool isCurrentContext)
        {
            AssertIsForeground();

            lock (_gate)
            {
                NewBufferOpened_NoLock(docCookie, textBuffer, documentKey, isCurrentContext);
            }
        }
 private TextBufferDataEventsSink(DocumentProvider documentProvider, IVsTextBuffer textBuffer, DocumentKey documentKey)
 {
     _documentProvider = documentProvider;
     _textBuffer = textBuffer;
     _documentKey = documentKey;
 }
 protected override Task <Checksum> ReadChecksumAsync(DocumentKey documentKey, Document?bulkLoadSnapshot, string name, CancellationToken cancellationToken)
 => _documentAccessor.ReadChecksumAsync((documentKey, bulkLoadSnapshot, name), cancellationToken);
 public DocumentItem(DocumentKey key, IDocumentDb backingStore, Dictionary<Type, Dictionary<string, string>> persistentValues)
 {
     _backingStore = backingStore;
     _persistentValues = persistentValues;
     Key = key;
 }
Exemple #10
0
 public abstract Task <Stream?> ReadStreamAsync(
     DocumentKey documentKey,
     string name,
     Checksum?checksum,
     CancellationToken cancellationToken
     );
Exemple #11
0
 public abstract Task <bool> ChecksumMatchesAsync(
     DocumentKey documentKey,
     string name,
     Checksum checksum,
     CancellationToken cancellationToken
     );
Exemple #12
0
 public Task <ImmutableArray <ClassifiedSpan> > GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken)
 => SpecializedTasks.Default <ImmutableArray <ClassifiedSpan> >();
Exemple #13
0
 public static Task <TopLevelSyntaxTreeIndex?> LoadAsync(
     IChecksummedPersistentStorageService storageService, DocumentKey documentKey, Checksum?checksum, StringTable stringTable, CancellationToken cancellationToken)
 {
     return(LoadAsync(storageService, documentKey, checksum, stringTable, ReadIndex, cancellationToken));
 }
 public Document(DocumentKey key)
 {
     Key = key;
 }
Exemple #15
0
        private void NewBufferOpened(uint docCookie, ITextBuffer textBuffer, DocumentKey documentKey, bool isCurrentContext)
        {
            StandardTextDocument document;

            if (_documentMap.TryGetValue(documentKey, out document))
            {
                document.ProcessOpen(textBuffer, isCurrentContext);
                AddCookieOpenDocumentPair(docCookie, documentKey);
            }
        }
Exemple #16
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));

            IVsHierarchy sharedHierarchy;
            uint itemIdInSharedHierarchy;
            var isSharedHierarchy = LinkedFileUtilities.TryGetSharedHierarchyAndItemId(hierarchy, itemId, out sharedHierarchy, out itemIdInSharedHierarchy);

            var filePath = isSharedHierarchy
                ? rdt.GetMonikerForHierarchyAndItemId(sharedHierarchy, itemIdInSharedHierarchy)
                : rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);

            // we couldn't look up the document moniker in RDT for a hierarchy/item pair
            // Since we only use this moniker as a key, we could fall back to something else, like the document name.
            if (filePath == null)
            {
                Debug.Assert(false, "Could not get the document moniker for an item in its hierarchy.");
                filePath = hierarchy.GetDocumentNameForHierarchyAndItemId(itemId);
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
Exemple #17
0
 public abstract EditorDocument GetOrCreateDocument(
     DocumentKey key,
     EventHandler changedOnDisk,
     EventHandler changedInEditor,
     EventHandler opened,
     EventHandler closed);
Exemple #18
0
 public abstract bool TryGetDocument(DocumentKey key, out EditorDocument document);
Exemple #19
0
 public override void Deserialize(Common.Serialization.IO.CompactReader reader)
 {
     base.Deserialize(reader);
     _key = (DocumentKey)reader.ReadObject();
 }
Exemple #20
0
 private void AddCookieOpenDocumentPair_NoLock(uint foundCookie, DocumentKey documentKey)
 {
     if (_docCookiesToOpenDocumentKeys.TryGetValue(foundCookie, out var documentKeys))
     {
         if (!documentKeys.Contains(documentKey))
         {
             documentKeys.Add(documentKey);
         }
     }
     else
     {
         _docCookiesToOpenDocumentKeys.Add(foundCookie, new List<DocumentKey> { documentKey });
     }
 }
Exemple #21
0
 protected abstract Task <Stream?> ReadStreamAsync(DocumentKey documentKey, Document?document, string name, Checksum?checksum, CancellationToken cancellationToken);
Exemple #22
0
        private void OnDocumentLoadCompleted(IVsTextBuffer shimTextBuffer, DocumentKey documentKeyOpt, string moniker)
        {
            AssertIsForeground();
            // This is called when IVsTextBufferDataEvents.OnLoadComplete() has been triggered for a
            // newly-created buffer.
            if (!_runningDocumentTable.TryGetCookieForInitializedDocument(moniker, out var docCookie))
            {
                return;
            }

            var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);
            if (textBuffer == null)
            {
                throw new InvalidOperationException("The IVsTextBuffer has been populated but the underlying ITextBuffer does not exist!");
            }

            if (documentKeyOpt == null)
            {
                // Non-Roslyn document.
                OnNonRoslynBufferOpened_NoLock(textBuffer, docCookie);
            }
            else
            {
                NewBufferOpened(docCookie, textBuffer, documentKeyOpt, IsCurrentContext(docCookie, documentKeyOpt));
            }
        }
Exemple #23
0
        public async Task TestOpenWithSolutionKeyReadWithDocumentKeyAndDocument1_WriteWithSolutionKey()
        {
            var solution = CreateOrOpenSolution();
            var document = solution.Projects.Single().Documents.Single();

            var streamName1 = "stream";

            await using (var storage = await GetStorageFromKeyAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution)))
            {
                await storage.WriteStreamAsync(document, streamName1, EncodeString(GetData1(Size.Small)), checksum : s_checksum1);
            }

            await using (var storage = await GetStorageFromKeyAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution)))
            {
                Assert.True(await storage.ChecksumMatchesAsync(DocumentKey.ToDocumentKey(document), streamName1, s_checksum1));
                Assert.Equal(GetData1(Size.Small), ReadStringToEnd(await storage.ReadStreamAsync(DocumentKey.ToDocumentKey(document), streamName1)));

                Assert.True(await storage.ChecksumMatchesAsync(document, streamName1, s_checksum1));
                Assert.Equal(GetData1(Size.Small), ReadStringToEnd(await storage.ReadStreamAsync(document, streamName1)));
            }
        }
 public Task <bool> WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum?checksum, CancellationToken cancellationToken)
 => WriteStreamAsync(documentKey, bulkLoadSnapshot: null, name, stream, checksum, cancellationToken);
Exemple #25
0
 public static void AddKeys(this DocumentMeta meta, DocumentKey documentKey)
 {
     meta.Keys.Add(documentKey);
 }
 public Task <bool> ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken)
 => SpecializedTasks.False;
Exemple #27
0
 protected override Task <bool> ChecksumMatchesAsync(DocumentKey documentKey, Document?bulkLoadSnapshot, string name, Checksum checksum, CancellationToken cancellationToken)
 => _documentAccessor.ChecksumMatchesAsync((documentKey, bulkLoadSnapshot, name), checksum, cancellationToken);
 public Task <bool> WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken)
 => SpecializedTasks.False;
 protected abstract Task <Checksum> ReadChecksumAsync(DocumentKey documentKey, Document?bulkLoadSnapshot, string name, CancellationToken cancellationToken);
Exemple #30
0
        public TDocument GetDocument(DocumentKey documentKey)
        {
            var metadata = DocumentMetadataRepository.GetDocumentMetadata(documentKey);

            return(GetDocument(metadata));
        }
 public Task <Checksum> ReadChecksumAsync(DocumentKey documentKey, string name, CancellationToken cancellationToken)
 => ReadChecksumAsync(documentKey, bulkLoadSnapshot: null, name, cancellationToken);
Exemple #32
0
        private void DocumentLoadCompleted(IVsTextBuffer shimTextBuffer, DocumentKey documentKey)
        {
            // This is called when IVsTextBufferDataEvents.OnLoadComplete() has been triggered for a
            // newly-created buffer.

            uint docCookie;
            if (!RunningDocumentTable.TryGetCookieForInitializedDocument(documentKey.Moniker, out docCookie))
            {
                return;
            }

            var textBuffer = EditorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);
            if (textBuffer == null)
            {
                throw new InvalidOperationException("The IVsTextBuffer has been populated but the underlying ITextBuffer does not exist!");
            }

            NewBufferOpened(docCookie, textBuffer, documentKey, IsCurrentContext(docCookie, documentKey));
        }
 protected abstract Task <bool> ChecksumMatchesAsync(DocumentKey documentKey, Document?bulkLoadSnapshot, string name, Checksum checksum, CancellationToken cancellationToken);
        public async Task DocumentChanged_ReparsesRelatedFiles()
        {
            // Arrange
            var projectManager = new TestProjectSnapshotManager(Dispatcher, Workspace)
            {
                AllowNotifyListeners = true,
            };
            var documents = new[]
            {
                TestProjectData.SomeProjectComponentFile1,
                TestProjectData.SomeProjectImportFile
            };

            projectManager.ProjectAdded(HostProject1);
            for (var i = 0; i < documents.Length; i++)
            {
                projectManager.DocumentAdded(HostProject1, documents[i], null);
            }

            var queue = new BackgroundDocumentGenerator(Dispatcher, DynamicFileInfoProvider)
            {
                Delay = TimeSpan.FromMilliseconds(1),
                BlockBackgroundWorkStart         = new ManualResetEventSlim(initialState: false),
                NotifyBackgroundWorkStarting     = new ManualResetEventSlim(initialState: false),
                NotifyBackgroundCapturedWorkload = new ManualResetEventSlim(initialState: false),
                BlockBackgroundWorkCompleting    = new ManualResetEventSlim(initialState: false),
                NotifyBackgroundWorkCompleted    = new ManualResetEventSlim(initialState: false),
            };

            var changedSourceText = SourceText.From("@inject DateTime Time");

            queue.Initialize(projectManager);

            // Act & Assert
            projectManager.DocumentChanged(HostProject1.FilePath, TestProjectData.SomeProjectImportFile.FilePath, changedSourceText);

            Assert.True(queue.IsScheduledOrRunning, "Queue should be scheduled during Enqueue");
            Assert.True(queue.HasPendingNotifications, "Queue should have a notification created during Enqueue");

            for (var i = 0; i < documents.Length; i++)
            {
                var key = new DocumentKey(HostProject1.FilePath, documents[i].FilePath);
                Assert.True(queue.Work.ContainsKey(key));
            }

            // Allow the background work to start.
            queue.BlockBackgroundWorkStart.Set();

            await Task.Run(() => queue.NotifyBackgroundWorkStarting.Wait(TimeSpan.FromSeconds(1)));

            Assert.True(queue.IsScheduledOrRunning, "Worker should be processing now");

            await Task.Run(() => queue.NotifyBackgroundCapturedWorkload.Wait(TimeSpan.FromSeconds(1)));

            Assert.False(queue.HasPendingNotifications, "Worker should have taken all notifications");

            // Allow work to complete
            queue.BlockBackgroundWorkCompleting.Set();

            await Task.Run(() => queue.NotifyBackgroundWorkCompleted.Wait(TimeSpan.FromSeconds(3)));

            Assert.False(queue.HasPendingNotifications, "Queue should have processed all notifications");
            Assert.False(queue.IsScheduledOrRunning, "Queue should not have restarted");
        }
 protected abstract Task <bool> WriteStreamAsync(DocumentKey documentKey, Document?bulkLoadSnapshot, string name, Stream stream, Checksum?checksum, CancellationToken cancellationToken);
Exemple #36
0
        public async Task TestOpenWithSolutionReadWithDocumentKeyAndDocument2_WriteWithSolutionKey(Size size, [CombinatorialRange(0, Iterations)] int iteration)
        {
            _ = iteration;
            var solution = CreateOrOpenSolution();
            var document = solution.Projects.Single().Documents.Single();

            var streamName1 = "stream";

            await using (var storage = await GetStorageFromKeyAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution)))
            {
                await storage.WriteStreamAsync(document, streamName1, EncodeString(GetData1(size)), checksum : s_checksum1);
            }

            await using (var storage = await GetStorageAsync(solution))
            {
                Assert.True(await storage.ChecksumMatchesAsync(document, streamName1, s_checksum1));
                Assert.Equal(GetData1(size), ReadStringToEnd(await storage.ReadStreamAsync(document, streamName1)));

                Assert.True(await storage.ChecksumMatchesAsync(DocumentKey.ToDocumentKey(document), streamName1, s_checksum1));
                Assert.Equal(GetData1(size), ReadStringToEnd(await storage.ReadStreamAsync(DocumentKey.ToDocumentKey(document), streamName1)));
            }
        }
 public Task <bool> ChecksumMatchesAsync(DocumentKey documentKey, string name, Checksum checksum, CancellationToken cancellationToken)
 => ChecksumMatchesAsync(documentKey, bulkLoadSnapshot: null, name, checksum, cancellationToken);
            /// <summary>
            /// Helper method for creating and hooking up a <c>TextBufferDataEventsSink</c>.
            /// </summary>
            public static void HookupHandler(DocumentProvider documentProvider, IVsTextBuffer textBuffer, DocumentKey documentKey)
            {
                var eventHandler = new TextBufferDataEventsSink(documentProvider, textBuffer, documentKey);

                eventHandler._sink = ComEventSink.Advise<IVsTextBufferDataEvents>(textBuffer, eventHandler);
            }
 public Task <bool> ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken)
 => ChecksumMatchesAsync(DocumentKey.ToDocumentKey(document), document, name, checksum, cancellationToken);
Exemple #40
0
        /// <summary>
        /// Gets the <see cref="IVisualStudioHostDocument"/> for the file at the given filePath.
        /// If we are on the foreground thread and this document is already open in the editor,
        /// then we also attempt to associate the text buffer with it.
        /// Otherwise, if we are on a background thread, then this text buffer association will happen on a scheduled task
        /// whenever <see cref="NotifyDocumentRegisteredToProjectAndStartToRaiseEvents"/> is invoked for the returned document.
        /// </summary>
        public IVisualStudioHostDocument TryGetDocumentForFile(
            IVisualStudioHostProject hostProject,
            string filePath,
            SourceCodeKind sourceCodeKind,
            Func<ITextBuffer, bool> canUseTextBuffer,
            Func<uint, IReadOnlyList<string>> getFolderNames,
            EventHandler updatedOnDiskHandler = null,
            EventHandler<bool> openedHandler = null,
            EventHandler<bool> closingHandler = null)
        {
            var documentKey = new DocumentKey(hostProject, filePath);
            StandardTextDocument document;

            lock (_gate)
            {
                if (_documentMap.TryGetValue(documentKey, out document))
                {
                    return document;
                }
            }

            ITextBuffer openTextBuffer = null;
            uint foundCookie = VSConstants.VSCOOKIE_NIL;

            if (IsForeground())
            {
                // If we are on the foreground thread and this document is already open in the editor we want to associate the text buffer with it.
                // Otherwise, we are on a background thread, and this text buffer association will happen on a scheduled task
                // whenever NotifyDocumentRegisteredToProjectAndStartToRaiseEvents is invoked for the returned document.
                // However, determining if a document is already open is a bit complicated. With the introduction
                // of the lazy tabs feature in Dev12, a document may be open (i.e. it has a tab in the shell) but not
                // actually initialized (no data has been loaded for it because its contents have not actually been
                // viewed or used). We only care about documents that are open AND initialized.
                // That means we can't call IVsRunningDocumentTable::FindAndLockDocument to find the document; if the
                // document is open but not initialized, the call will force initialization. This is bad for two
                // reasons:
                //   1.) It circumvents lazy tabs for any document that is part of a VB or C# project.
                //   2.) Initialization may cause a whole host of other code to run synchronously, such as taggers.
                // Instead, we check if the document is already initialized, and avoid asking for the doc data and
                // hierarchy if it is not.
                if (_runningDocumentTable.TryGetCookieForInitializedDocument(documentKey.Moniker, out foundCookie))
                {
                    object foundDocData = _runningDocumentTable.GetDocumentData(foundCookie);
                    openTextBuffer = TryGetTextBufferFromDocData(foundDocData);
                    if (openTextBuffer == null)
                    {
                        // We're open but not open as a normal text buffer. This can happen if the
                        // project system (say in ASP.NET cases) is telling us to add a file which
                        // actually isn't a normal text file at all.
                        return null;
                    }

                    if (!canUseTextBuffer(openTextBuffer))
                    {
                        return null;
                    }
                }
            }

            lock (_gate)
            {
                // If this is being added through a public call to Workspace.AddDocument (say, ApplyChanges) then we might
                // already have a document ID that we should be using here.
                _documentIdHints.TryGetValue(filePath, out var id);

                document = new StandardTextDocument(
                    this,
                    hostProject,
                    documentKey,
                    getFolderNames,
                    sourceCodeKind,
                    _textUndoHistoryRegistry,
                    _fileChangeService,
                    openTextBuffer,
                    id,
                    updatedOnDiskHandler,
                    openedHandler,
                    closingHandler);

                // Add this to our document map
                _documentMap.Add(documentKey, document);

                if (openTextBuffer != null)
                {
                    AddCookieOpenDocumentPair_NoLock(foundCookie, documentKey);
                }
            }

            return document;
        }
 public Task <Stream?> ReadStreamAsync(DocumentKey documentKey, string name, Checksum?checksum, CancellationToken cancellationToken)
 => ReadStreamAsync(documentKey, bulkLoadSnapshot: null, name, checksum, cancellationToken);
Exemple #42
0
        private bool IsCurrentContext(uint docCookie, DocumentKey documentKey)
        {
            AssertIsForeground();
            _runningDocumentTable.GetDocumentHierarchyItem(docCookie, out var hierarchy, out var itemid);

            // If it belongs to a Shared Code or ASP.NET 5 project, then find the correct host project
            var hostProject = LinkedFileUtilities.GetContextHostProject(hierarchy, _projectContainer);

            return documentKey.HostProject == hostProject;
        }
 public Task <Stream?> ReadStreamAsync(Document document, string name, Checksum?checksum, CancellationToken cancellationToken)
 => ReadStreamAsync(DocumentKey.ToDocumentKey(document), document, name, checksum, cancellationToken);
Exemple #44
0
 private void NewBufferOpened_NoLock(uint docCookie, ITextBuffer textBuffer, DocumentKey documentKey, bool isCurrentContext)
 {
     if (_documentMap.TryGetValue(documentKey, out var document))
     {
         document.ProcessOpen(textBuffer, isCurrentContext);
         AddCookieOpenDocumentPair_NoLock(docCookie, documentKey);
     }
 }
 public Task <bool> WriteStreamAsync(Document document, string name, Stream stream, Checksum?checksum, CancellationToken cancellationToken)
 => WriteStreamAsync(DocumentKey.ToDocumentKey(document), document, name, stream, checksum, cancellationToken);
Exemple #46
0
        private void TryProcessOpenForDocCookie_NoLock(uint docCookie)
        {
            string moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
            _runningDocumentTable.GetDocumentHierarchyItem(docCookie, out var hierarchy, out var itemid);

            var shimTextBuffer = _runningDocumentTable.GetDocumentData(docCookie) as IVsTextBuffer;

            if (shimTextBuffer != null)
            {
                var hasAssociatedRoslynDocument = false;
                foreach (var project in _projectContainer.GetProjects())
                {
                    var documentKey = new DocumentKey(project, moniker);

                    if (_documentMap.ContainsKey(documentKey))
                    {
                        hasAssociatedRoslynDocument = true;
                        var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);

                        // If we already have an ITextBuffer for this document, then we can open it now.
                        // Otherwise, setup an event handler that will do it when the buffer loads.
                        if (textBuffer != null)
                        {
                            // We might already have this docCookie marked as open an older document. This can happen
                            // if we're in the middle of a rename but this class hasn't gotten the notification yet but
                            // another listener for RDT events got it
                            if (_docCookiesToOpenDocumentKeys.ContainsKey(docCookie))
                            {
                                CloseDocuments_NoLock(docCookie, monikerToKeep: moniker);
                            }

                            if (hierarchy == project.Hierarchy)
                            {
                                // This is the current context
                                NewBufferOpened_NoLock(docCookie, textBuffer, documentKey, isCurrentContext: true);
                            }
                            else
                            {
                                // This is a non-current linked context
                                NewBufferOpened_NoLock(docCookie, textBuffer, documentKey, isCurrentContext: false);
                            }
                        }
                        else
                        {
                            TextBufferDataEventsSink.HookupHandler(shimTextBuffer, onDocumentLoadCompleted: () => OnDocumentLoadCompleted(shimTextBuffer, documentKey, moniker));
                        }
                    }
                }

                if (!hasAssociatedRoslynDocument && this._documentTrackingServiceOpt != null && !_docCookiesToNonRoslynDocumentBuffers.ContainsKey(docCookie))
                {
                    // Non-Roslyn document opened.
                    var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);
                    if (textBuffer != null)
                    {
                        OnNonRoslynBufferOpened_NoLock(textBuffer, docCookie);
                    }
                    else
                    {
                        TextBufferDataEventsSink.HookupHandler(shimTextBuffer, onDocumentLoadCompleted: () => OnDocumentLoadCompleted(shimTextBuffer, documentKeyOpt: null, moniker: moniker));
                    }
                }
            }
            else
            {
                // This is opening some other designer or property page. If it's tied to our IVsHierarchy, we should
                // let the workspace know
                foreach (var project in _projectContainer.GetProjects())
                {
                    if (hierarchy == project.Hierarchy)
                    {
                        _projectContainer.NotifyNonDocumentOpenedForProject(project);
                    }
                }
            }
        }
        private void TryProcessOpenForDocCookie(uint docCookie)
        {
            string moniker = RunningDocumentTable.GetDocumentMoniker(docCookie);

            IVsHierarchy hierarchy;
            uint itemid;
            RunningDocumentTable.GetDocumentHierarchyItem(docCookie, out hierarchy, out itemid);

            foreach (var project in _projectContainer.GetProjects())
            {
                var documentKey = new DocumentKey(project, moniker);

                if (_documentMap.ContainsKey(documentKey))
                {
                    var shimTextBuffer = RunningDocumentTable.GetDocumentData(docCookie) as IVsTextBuffer;

                    if (shimTextBuffer != null)
                    {
                        var textBuffer = EditorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);

                        // If we already have an ITextBuffer for this document, then we can open it now.
                        // Otherwise, setup an event handler that will do it when the buffer loads.
                        if (textBuffer != null)
                        {
                            // We might already have this docCookie marked as open an older document. This can happen
                            // if we're in the middle of a rename but this class hasn't gotten the notification yet but
                            // another listener for RDT events got it
                            if (_docCookiesToOpenDocumentKeys.ContainsKey(docCookie))
                            {
                                CloseDocuments(docCookie, monikerToKeep: moniker);
                            }

                            if (hierarchy == project.Hierarchy)
                            {
                                // This is the current context
                                NewBufferOpened(docCookie, textBuffer, documentKey, isCurrentContext: true);
                            }
                            else
                            {
                                // This is a non-current linked context
                                NewBufferOpened(docCookie, textBuffer, documentKey, isCurrentContext: false);
                            }
                        }
                        else
                        {
                            TextBufferDataEventsSink.HookupHandler(this, shimTextBuffer, documentKey);
                        }
                    }
                }
            }
        }