The DocumentProvider object is used to provide event reader implementations for DOM. Wrapping the mechanics of the DOM framework within a Provider ensures that it can be plugged in without any dependencies. This allows other parsers to be swapped in should there be such a requirement.
Inheritance: Provider
Exemplo n.º 1
0
        public int Execute(Options o)
        {
            var documents = DocumentProvider.GetDocuments(o);

            Logger.LogInformation($"{documents.Count()} document(s) found");
            return(0);
        }
Exemplo n.º 2
0
        public async Task RewritesDefaultConstructor(string filePath)
        {
            // Arrange
            var filePathClassUnderTest = "files.ClassUnderTest.txt";
            var filePaths = new[] { filePath, filePathClassUnderTest };
            var documents = DocumentProvider.CreateCompilationAndReturnDocuments(filePaths);

            var documentWithTestClass = documents[filePath];
            var root = await documentWithTestClass.GetSyntaxRootAsync();

            var testClass = root.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().First();

            var documentWithClassUnderTest = documents[filePathClassUnderTest];
            var classUnderTest             = SyntaxNodeProvider.GetSyntaxNodeFromDocument <ClassDeclarationSyntax>(documentWithClassUnderTest, "ClassUnderTest");
            var semanticModel = await documentWithClassUnderTest.GetSemanticModelAsync();

            _classUnderTestFinder.Setup(_ => _.GetAsync(It.IsAny <Solution>(), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(new ClassUnderTest(classUnderTest, semanticModel));

            // Act
            var actual = await _target.RegenerateSetup(documentWithTestClass, testClass, new CancellationToken());

            // Assert
            var actualText = await actual.GetTextAsync();

            _testOutput.WriteLine(actualText.ToString().Replace(";", ";\n"));

            var expected = await DocumentProvider.CreateDocumentFromFile("files.TestClass_WithFinalSetupConstructor.txt").GetTextAsync();

            Assert.Equal(expected.ToString().RemoveWhitespace(), actualText.ToString().RemoveWhitespace());
        }
Exemplo n.º 3
0
        private async Task <Model> ComputeModelInBackgroundAsync(
            int position,
            ITextSnapshot snapshot,
            IQuickInfoProviderCoordinator providerCoordinator,
            bool trackMouse,
            CancellationToken cancellationToken)
        {
            try
            {
                AssertIsBackground();

                //using (Logger.LogBlock(FunctionId.QuickInfo_ModelComputation_ComputeModelInBackground, cancellationToken))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var document = await DocumentProvider.GetDocumentAsync(snapshot, cancellationToken).ConfigureAwait(false);

                    if (document == null)
                    {
                        return(null);
                    }

                    var(item, provider) = await providerCoordinator.GetItemAsync(document, position, cancellationToken).ConfigureAwait(false);

                    return(new Model(snapshot.Version, item, provider, trackMouse));
                }
            }
            catch (Exception e) when(FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
Exemplo n.º 4
0
 public PostgreWriter(string typeOf, DocumentProvider provider, DocumentOption option, IDocumentLogger logger)
 {
     TypeOf   = typeOf;
     Provider = provider;
     Option   = option;
     Logger   = logger;
 }
Exemplo n.º 5
0
        public async Task <JsonResult> GetID(int id)
        {
            DocumentProvider documentProvider = new DocumentProvider();
            Document         document         = await documentProvider.GetByIDAsync(id);

            return(Json(document, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 6
0
 public void Append <T>(DocumentProvider <T> provider)
 {
     // This might cause Marten to re-check the database storage, but double dipping
     // seems smarter than trying to be too clever and miss doing the check
     _storage = _storage.Remove(typeof(T));
     _inner.Append(provider);
 }
Exemplo n.º 7
0
 public PostgreReader(DocumentProvider provider, DocumentOption option, DocumentQuery query, IDocumentLogger logger)
 {
     Provider = provider;
     Option   = option;
     Query    = query;
     Logger   = logger;
 }
Exemplo n.º 8
0
        public async Task ReplacesSetupMethodInClass()
        {
            var document  = DocumentProvider.CreateDocumentFromFile(TestClassWithEmptyConstructor);
            var root      = document.GetSyntaxRootAsync().Result;
            var testClass = root.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().First();

            _target = new DocumentBuilder(_memberFinder.Object, _fieldFinder.Object, document, testClass);

            var newSetupMethod =
                SyntaxNodeProvider.GetSyntaxNodeFromFile <ConstructorDeclarationSyntax>(Constructor, "ClassUnderTestTests");

            var existingSetupMethod = root.DescendantNodes().OfType <ConstructorDeclarationSyntax>().First();

            _memberFinder.Setup(_ =>
                                _.FindSimilarNode(It.IsAny <SyntaxList <MemberDeclarationSyntax> >(),
                                                  It.Is <SyntaxNode>(s => s == newSetupMethod)))
            .Returns(existingSetupMethod);

            var actual = await _target.WithSetupMethod(newSetupMethod)
                         .BuildAsync(new CancellationToken());

            var actualRoot = await actual.GetSyntaxRootAsync();

            var actualMethods = actualRoot.DescendantNodes().OfType <ConstructorDeclarationSyntax>().ToList();

            Assert.Single((IEnumerable)actualMethods);
            Assert.Equal(newSetupMethod.GetText().ToString(), actualMethods.First().GetText().ToString());
        }
        public async Task SetsFields(string testClassFilePath)
        {
            // Arrange
            var document  = DocumentProvider.CreateDocumentFromFile(testClassFilePath);
            var root      = document.GetSyntaxRootAsync().Result;
            var testClass = root.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().First();

            _target = new DocumentBuilder(_memberFinder.Object, _fieldFinder, document, testClass);

            var newFieldDeclarations =
                SyntaxNodeProvider.GetAllSyntaxNodesFromFile <FieldDeclarationSyntax>(FieldDeclarations).ToList();

            var expectedFieldDeclarations =
                SyntaxNodeProvider.GetAllSyntaxNodesFromFile <FieldDeclarationSyntax>(TestClassWithAllFields).ToList();
            var expected = GetCollectionTextAsString(expectedFieldDeclarations);

            // Act
            var actual = await _target.WithFields(newFieldDeclarations)
                         .BuildAsync(new CancellationToken());

            // Assert
            var actualRoot = await actual.GetSyntaxRootAsync();

            var actualFields = GetCollectionTextAsString(actualRoot.DescendantNodes().OfType <FieldDeclarationSyntax>());

            _testOutput.WriteLine(actualFields);

            Assert.Equal(expected, actualFields);
        }
Exemplo n.º 10
0
        public DocumentProvider <T> StorageFor <T>() where T : notnull
        {
            var documentType = typeof(T);

            if (_storage.TryFind(documentType, out var stored))
            {
                return(stored.As <DocumentProvider <T> >());
            }

            if (documentType == typeof(IEvent))
            {
                var slot = EventDocumentStorageGenerator.BuildProvider(_options);

                _storage = _storage.AddOrUpdate(documentType, slot);

                return(slot.As <DocumentProvider <T> >());
            }

            var mapping = _options.Storage.FindMapping(documentType);

            switch (mapping)
            {
            case DocumentMapping m:
            {
                var builder = new DocumentPersistenceBuilder(m, _options);
                var slot    = builder.Generate <T>();

                _storage = _storage.AddOrUpdate(documentType, slot);

                return(slot);
            }

            case SubClassMapping s:
            {
                var loader =
                    typeof(SubClassLoader <, ,>).CloseAndBuildAs <ISubClassLoader <T> >(mapping.Root.DocumentType, documentType,
                                                                                        mapping.IdType);

                var slot = loader.BuildPersistence(this, s);
                _storage = _storage.AddOrUpdate(documentType, slot);

                return(slot);
            }

            case EventMapping em:
            {
                var storage = (IDocumentStorage <T>)em;
                var slot    = new DocumentProvider <T> {
                    Lightweight = storage, IdentityMap = storage, DirtyTracking = storage, QueryOnly = storage
                };
                _storage = _storage.AddOrUpdate(documentType, slot);

                return(slot);
            }

            default:
                throw new NotSupportedException("Unable to build document persistence handlers for " + mapping.DocumentType.FullNameInCode());
            }
        }
Exemplo n.º 11
0
        public async Task ProviderTest()
        {
            PhysicalFileProvider fileProvider = new PhysicalFileProvider("D:\\Docs\\ComBoost");
            DocumentProvider     docProvider  = new DocumentProvider(fileProvider, "");
            await docProvider.LoadAsync();

            Assert.AreEqual(4, docProvider.Pages.Count);
        }
Exemplo n.º 12
0
        public void FindsClassUnderTest(string filePath, string projectName, string classUnderTestName)
        {
            var source   = TextFileReader.ReadFile(filePath);
            var document = DocumentProvider.CreateDocument(source);

            var actual = _target.GetAsync(document.Project.Solution, projectName, classUnderTestName);

            Assert.NotNull(actual);
        }
Exemplo n.º 13
0
        public async Task <JsonResult> VB_Delete(int id)
        {
            DocumentProvider documentProvider = new DocumentProvider();
            var result = await documentProvider.DeleteAsync(id);

            return(Json(new AccessEntityResult {
                Status = result, Data = id, Message = ""
            }));
        }
Exemplo n.º 14
0
 public PostgreReader(string typeOf, DocumentProvider provider, DocumentOption option, IDocumentLogger logger)
 {
     TypeOf      = typeOf;
     Provider    = provider;
     Option      = option;
     Logger      = logger;
     Limit       = option.SqlProviderDataReaderPageSize;
     Skip        = 0;
     CurrentPage = 1;
 }
        public int Execute(Options o)
        {
            var documents = DocumentProvider.GetDocuments(o);

            var success        = IndexService.AddOrUpdateDocuments(o, documents);
            var successMessage = success ? "updated" : "failed";

            Logger.LogInformation($"{documents.Count()} document(s) {successMessage} to {o.IndexName}");
            return(success ? 0 : 1);
        }
        public async Task NoActionTest(string test, string source)
        {
            var document   = DocumentProvider.GetDocument(source);
            var diagnostic = await GetDiagnosticAsync(document);

            var actions = new List <CodeAction>();
            var context = new CodeFixContext(document, diagnostic, (a, d) => actions.Add(a), CancellationToken.None);
            await codeFixProvider.RegisterCodeFixesAsync(context);

            Assert.Empty(actions);
        }
        public async Task Adds_Usings_For_All_Parameters(string filePath, string parameterName, string expectedNamespaces)
        {
            var source   = TextFileReader.ReadFile(filePath);
            var document = DocumentProvider.CreateDocument(source);

            var parameterSyntax = SyntaxNodeProvider.GetSyntaxNodeFromDocument <ParameterSyntax>(document, parameterName);
            var syntaxGenerator = new SyntaxGeneratorProvider().GetSyntaxGenerator();

            var semanticModel = await document.GetSemanticModelAsync();

            var usingDirectives = _target.UsingDirectives(semanticModel.Compilation, new[] { parameterSyntax }, new List <string>(), syntaxGenerator);

            Assert.Equal(expectedNamespaces, usingDirectives.First().Name.ToString());
        }
Exemplo n.º 18
0
        public async Task DoesNotReplaceSetupMethod_When_WithSetupMethodIsNotCalled()
        {
            var document  = DocumentProvider.CreateDocumentFromFile(EmptyTestClass);
            var root      = document.GetSyntaxRootAsync().Result;
            var testClass = root.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().First();

            _target = new DocumentBuilder(_memberFinder.Object, _fieldFinder.Object, document, testClass);

            var actual = await _target
                         .BuildAsync(new CancellationToken());

            var actualRoot = await actual.GetSyntaxRootAsync();

            Assert.Equal(root.GetText().ToString(), actualRoot.GetText().ToString());
        }
Exemplo n.º 19
0
        public static CodeRefactoringContext Build(string[] sources, ICodeActionAcceptor acceptor, IEnumerable <MetadataReference> additionalReferences)
        {
            var normalizedSources = new[] { NormalizeSource(sources[0]) }.Concat(sources.Skip(1)).ToArray();
            var documents = DocumentProvider.GetDocuments(normalizedSources);

            var document = documents[0];

            if (additionalReferences != null && additionalReferences.Any())
            {
                var solution = document.Project.Solution.AddMetadataReferences(document.Project.Id, additionalReferences);
                document = solution.GetDocument(document.Id);
            }

            return(new CodeRefactoringContext(document, GetTextSpan(sources[0]), acceptor.Accept, CancellationToken.None));
        }
        public async Task CodeFixTest(string test, string source, string expected)
        {
            var document   = DocumentProvider.GetDocument(source);
            var diagnostic = await GetDiagnosticAsync(document);

            var actions = new List <CodeAction>();
            var context = new CodeFixContext(document, diagnostic, (a, d) => actions.Add(a), CancellationToken.None);
            await codeFixProvider.RegisterCodeFixesAsync(context);

            Assert.Single(actions);

            document = await CodeFixVerifier.ApplyFixAsync(document, actions[0]);

            var actual = await CodeFixVerifier.GetStringFromDocumentAsync(document);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 21
0
        public async Task <JsonResult> VB_Update(int id, Document model)
        {
            if (ModelState.IsValid)
            {
                model.UserUpdate = SessionApp.UserID;
                model.UpdateTime = DateTime.Now;
                DocumentProvider documentProvider = new DocumentProvider();
                var result = await documentProvider.EditAsync(id, model);

                return(Json(result));
            }
            else
            {
                return(Json(new AccessEntityResult {
                    Status = AccessEntityStatusCode.ModelFailed, Message = "Thông tin văn bản nhập vào không chính xác"
                }));
            }
        }
        public bool AttachTypesSynchronously(GenerationRules rules, Assembly assembly, IServiceProvider services,
                                             string containingNamespace)
        {
            var storageType = assembly.FindPreGeneratedType(@containingNamespace,
                                                            EventDocumentStorageGenerator.EventDocumentStorageTypeName);

            if (storageType == null)
            {
                Provider = null;
            }
            else
            {
                var storage = (EventDocumentStorage)Activator.CreateInstance(storageType, Options);
                Provider = new DocumentProvider <IEvent>(null, storage, storage, storage, storage);
            }

            return(Provider != null);
        }
Exemplo n.º 23
0
        public async Task <JsonResult> VB_Insert(Document model)
        {
            model.CategoryID    = (int)DocumentType.VanBan;
            model.Status        = 0;
            model.UserIDCreated = SessionApp.UserID;
            if (ModelState.IsValid)
            {
                DocumentProvider documentProvider = new DocumentProvider();
                var result = await documentProvider.AddAsync(model);

                return(Json(result));
            }
            else
            {
                return(Json(new AccessEntityResult {
                    Status = AccessEntityStatusCode.ModelFailed, Message = "Thông tin văn bản nhập vào không chính xác"
                }));
            }
        }
Exemplo n.º 24
0
        private async Task <Model> ComputeModelInBackgroundAsync(
            int position,
            ITextSnapshot snapshot,
            IList <IQuickInfoProvider> providers,
            bool trackMouse,
            CancellationToken cancellationToken)
        {
            try
            {
                AssertIsBackground();

                using (Logger.LogBlock(FunctionId.QuickInfo_ModelComputation_ComputeModelInBackground, cancellationToken))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var document = await DocumentProvider.GetDocumentAsync(snapshot, cancellationToken).ConfigureAwait(false);

                    if (document == null)
                    {
                        return(null);
                    }

                    foreach (var provider in providers)
                    {
                        // TODO(cyrusn): We're calling into extensions, we need to make ourselves resilient
                        // to the extension crashing.
                        var item = await provider.GetItemAsync(document, position, cancellationToken).ConfigureAwait(false);

                        if (item != null)
                        {
                            return(new Model(snapshot.Version, item, provider, trackMouse));
                        }
                    }

                    return(null);
                }
            }
            catch (Exception e) when(FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
Exemplo n.º 25
0
        public async Task InvalidDocumentNameForTypeNameTest()
        {
            var source = @"
namespace HelloWorld
{
    class TestService
    {
    }
}";

            var document            = DocumentProvider.GetDocument(source, @"c:\temp\Test.Part.cs");
            var analyzerDiagnostics = await DiagnosticRunner.GetSortedDiagnosticsFromDocumentsAsync(Analyzer, new[] { document });

            Assert.NotEmpty(analyzerDiagnostics);

            var actions = new List <CodeAction>();
            var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
            await CodeFixProvider.RegisterCodeFixesAsync(context);

            Assert.Single(actions);
            Assert.Equal("Rename 'Test.Part.cs' to 'TestService.cs'", actions[0].Title);
        }
Exemplo n.º 26
0
        public async Task SetsConstructorAndFields(string testClassFilePath)
        {
            // Arrange
            var document  = DocumentProvider.CreateDocumentFromFile(testClassFilePath);
            var root      = document.GetSyntaxRootAsync().Result;
            var testClass = root.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().First();

            _target = new DocumentBuilder(_memberFinder, _fieldFinder, document, testClass);

            var newFieldDeclarations =
                SyntaxNodeProvider.GetAllSyntaxNodesFromFile <FieldDeclarationSyntax>(FieldDeclarations).ToList();

            var expectedFieldDeclarations =
                SyntaxNodeProvider.GetAllSyntaxNodesFromFile <FieldDeclarationSyntax>(TestClassWithConstructorAndFields)
                .ToList();
            var expectedFields = GetCollectionTextAsString(expectedFieldDeclarations);

            var newSetupMethod =
                SyntaxNodeProvider.GetSyntaxNodeFromFile <ConstructorDeclarationSyntax>(Constructor, "ClassUnderTestTests");

            // Act
            var actual = await _target.WithSetupMethod(newSetupMethod)
                         .WithFields(newFieldDeclarations)
                         .BuildAsync(new CancellationToken());

            // Assert
            var actualRoot = await actual.GetSyntaxRootAsync();

            _testOutput.WriteLine(actualRoot.GetText().ToString());

            var actualFields = GetCollectionTextAsString(actualRoot.DescendantNodes().OfType <FieldDeclarationSyntax>());

            Assert.Equal(expectedFields, actualFields);

            var actualMethods = actualRoot.DescendantNodes().OfType <ConstructorDeclarationSyntax>().ToList();

            Assert.Single((IEnumerable)actualMethods);
            Assert.Equal(newSetupMethod.GetText().ToString(), actualMethods.First().GetText().ToString());
        }
Exemplo n.º 27
0
        public void TestReader()
        {
            Provider     provider = new DocumentProvider();
            StringReader source   = new StringReader(SOURCE);
            EventReader  reader   = provider.provide(source);

            AssertEquals(reader.peek().getName(), "root");
            AssertEquals(reader.next().getName(), "root");
            assertTrue(reader.peek().isText());
            assertTrue(reader.next().isText());
            while (reader.peek().isText())
            {
                assertTrue(reader.next().isText()); // remove text from the document
            }
            AssertEquals(reader.peek().getName(), "child");
            AssertEquals(reader.next().getName(), "child");
            assertTrue(reader.peek().isText());
            assertTrue(reader.next().isText());
            while (reader.peek().isText())
            {
                assertTrue(reader.next().isText()); // remove text from the document
            }
            AssertEquals(reader.peek().getName(), "leaf");
            AssertEquals(reader.next().getName(), "leaf");
            assertTrue(reader.peek().isText());
            AssertEquals(reader.peek().getValue(), "leaf node");
            AssertEquals(reader.next().getValue(), "leaf node");
            assertTrue(reader.next().isEnd());
            while (reader.peek().isText())
            {
                assertTrue(reader.next().isText()); // remove text from the document
            }
            assertTrue(reader.next().isEnd());
            while (reader.peek().isText())
            {
                assertTrue(reader.next().isText()); // remove text from the document
            }
        }
Exemplo n.º 28
0
        string SimulateSelectionOfFile(DocumentProvider dp, WdDocument wdDocument, string filters)
        {
            var module = dp.module;
            //user selects file           
            Mock.Get(module.Resolve<IOpenFileDialog>()).Setup(a => a.ShowDialog()).Returns(true);
            Mock.Get(module.Resolve<IOpenFileDialog>()).Setup(a => a.SelectedFile).Returns(wdDocument);
            string selected;
            dp.SelectDocumentEx(123, filters, string.Empty, out selected).Assert_Is_S_OK();
            Assert.That(selected, Is.EqualTo(WsDocumentID.Create(wdDocument)));

            //professional asks about selected document
            tagWSDOCUMENT doc1;
            dp.GetDocument(selected, (int)wsGetDocFlags.DF_INFO_ONLY, out doc1).Assert_Is_S_OK();
            Assert.That(doc1.bstrDocumentID, Is.EqualTo(selected));
            Assert.That(doc1.bstrExtension, Is.EqualTo(wdDocument.Ext));
            Assert.That(doc1.bstrDescription, Is.EqualTo(wdDocument.FIleName));
            Assert.IsNotNullOrEmpty(doc1.bstrType);
            Assert.That(doc1.bstrLocalFile, (Is.EqualTo(string.Empty) | Is.Null));

            dp.CloseDocument(ref doc1, 0).Assert_Is_S_OK();

            return doc1.bstrDocumentID;
        }
Exemplo n.º 29
0
        tagWSDOCUMENT[] SimulateComparison(DocumentProvider dp, WdDocument wdDoc1, WdDocument wdDoc2)
        {
            var res = new List<tagWSDOCUMENT>();
            foreach (var wdDoc in new[] { wdDoc1, wdDoc2 })
            {
                tagWSDOCUMENT doc;
                dp.GetDocument(WsDocumentID.Create(wdDoc), 0, out doc).Assert_Is_S_OK();
                Assert.That(doc.bstrDocumentID, Is.EqualTo(WsDocumentID.Create(wdDoc)));
                Assert.That(doc.bstrExtension, Is.EqualTo(wdDoc.Ext));
                Assert.That(doc.bstrDescription, Is.EqualTo(wdDoc.FIleName));
                Assert.IsNotNullOrEmpty(doc.bstrType);
                Assert.IsNotNullOrEmpty(doc.bstrLocalFile);

                string descr;
                dp.GetDocIDDescription(WsDocumentID.Create(wdDoc), out descr).Assert_Is_S_OK();

                Assert.That(descr, Is.EqualTo(wdDoc.FIleName));

                res.Add(doc);
            }


            return res.ToArray();
        }
Exemplo n.º 30
0
        public void CanOpenPdfAfterSaveItToDMS_ForNonIndexedFile()
        {
            var newWdDocument = MockUtils.GetDefaultDoc("a.pdf");

            var dp = new DocumentProvider(GetTestModule());

            var wsDocumentToConvert = new tagWSDOCUMENT();
            wsDocumentToConvert.bstrLocalFile = Path.GetTempFileName();
            dp.Resolve(ref wsDocumentToConvert).Assert_Is_S_FALSE();
            Assert.IsNullOrEmpty(wsDocumentToConvert.bstrDocumentID);

            var mockRepo = Mock.Get(dp.module.Resolve<IWdDocumentRepository>());
            mockRepo.Setup_GetByPath(newWdDocument);

            var wsDoc = SimulateSaving(dp, newWdDocument, "Pdf|*.pdf", 1);

            //PdfCreator opens document is another AppDomain
            var dp1 = new DocumentProvider(GetTestModule());
            var mockRepo1 = Mock.Get(dp1.module.Resolve<IWdDocumentRepository>());
            mockRepo1.Setup_GetByPath(newWdDocument);
            dp1.OpenDocument(ref wsDoc).Assert_Is_S_OK();
        }
Exemplo n.º 31
0
        tagWSDOCUMENT SimulateSaving(DocumentProvider dp, WdDocument newWdDocument,string filters, int filterIndex)
        {
            Mock.Get(dp.module.Resolve<ISaveFileDialog>()).Setup(p => p.ShowDialog()).Returns(true);
            Mock.Get(dp.module.Resolve<ISaveFileDialog>()).Setup(p => p.FilePath).Returns(newWdDocument.LocalFilePath);
            Mock.Get(dp.module.Resolve<ISaveFileDialog>()).Setup(p => p.FormatIndex).Returns(filterIndex);

            int index = 0;
            var wsDoc = new tagWSDOCUMENT();
            int ret;
            dp.GetSaveInfoEx(123, filters, 0, 0, ref index, ref wsDoc, out ret).Assert_Is_S_OK();
            wsDoc.bstrLocalFile = Path.GetTempFileName();
            dp.SaveDocument(ref wsDoc, 0).Assert_Is_S_OK();

            return wsDoc;
        }
Exemplo n.º 32
0
        public void CanCompareAndManageChanges()
        {
            var module = GetTestModule();
            var wdOriginal = MockUtils.GetDefaultDoc("a.docx");
            var wdModified = MockUtils.GetDefaultDoc("a.doc");
            
            try
            {
                File.WriteAllText(wdOriginal.LocalFilePath, @"Workshare Placeholder");
                File.WriteAllText(wdModified.LocalFilePath, @"Workshare Placeholder");
                var mockRepo = Mock.Get(module.Resolve<IWdDocumentRepository>());
                mockRepo.Setup_GetByPath(wdOriginal);
                mockRepo.Setup_GetByPath(wdModified);

                //DeltaView
                var dp = new DocumentProvider(module);
                var wsId1 = SimulateSelectionOfFile(dp, wdOriginal, "Word 2003|*.doc|Word 2010|*.docx");
                var wsId2 = SimulateSelectionOfFile(dp, wdModified, "Word 2003|*.doc|Word 2010|*.docx");

                var wsDocs = SimulateComparison(dp, wdOriginal, wdModified);

                dp.CloseDocument(ref wsDocs[0], 0).Assert_Is_S_OK();
                dp.CloseDocument(ref wsDocs[1], 0).Assert_Is_S_OK();

                //W3Launcher
                var dp2 = new DocumentProvider(GetTestModule());
                var mockRepo2 = Mock.Get(dp2.module.Resolve<IWdDocumentRepository>());
                mockRepo2.Setup_GetByPath(wdOriginal);
                mockRepo2.Setup(
                    p =>
                        p.GetVersions(It.IsAny<int>(),
                            It.Is<string>(
                                a => string.Equals(a, wdOriginal.DocId, StringComparison.InvariantCultureIgnoreCase))))
                    .Returns(() => new List<WdDocument> {wdOriginal});

                SimulateOpeningOfLastVersion(dp2, wdOriginal);

                //word
                var dp3 = new DocumentProvider(GetTestModule());
                var mockRepo3 = Mock.Get(dp3.module.Resolve<IWdDocumentRepository>());
                mockRepo3.Setup_GetByPath(wdOriginal);
                mockRepo3.Setup(
                    p =>
                        p.GetVersions(It.IsAny<int>(),
                            It.Is<string>(
                                a => string.Equals(a, wdOriginal.DocId, StringComparison.InvariantCultureIgnoreCase))))
                    .Returns(() => new List<WdDocument> {wdOriginal});

                var doc3 = new tagWSDOCUMENT
                {
                    bstrLocalFile = wdOriginal.LocalFilePath
                };
                dp3.Resolve(ref doc3).Assert_Is_S_OK();
                Assert.That(doc3.bstrDocumentID, Is.EqualTo(WsDocumentID.Create(wdOriginal)).IgnoreCase);
            }
            finally
            {
                File.Delete(wdOriginal.LocalFilePath);
                File.Delete(wdModified.LocalFilePath);
            }
        }
Exemplo n.º 33
0
 protected override IDocumentStorage <T> selectStorage <T>(DocumentProvider <T> provider)
 {
     return(provider.DirtyTracking);
 }
Exemplo n.º 34
0
		public VoteCountLocator( DocumentProvider provider )
		{
			this.provider = provider;
		}
 protected internal override IDocumentStorage <T> selectStorage <T>(DocumentProvider <T> provider)
 {
     return(provider.Lightweight);
 }
Exemplo n.º 36
0
        tagWSDOCUMENT SimulateOpeningOfLastVersion(DocumentProvider dp, WdDocument wdDoc)
        {
            var res = new List<tagWSDOCUMENT>();

            IntPtr ptr=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
            try
            {
                int size;
                dp.GetVersions(WsDocumentID.Create(wdDoc), out size, ptr).Assert_Is_S_OK();

                var collectionPtr=MarshallingHelper.GetCollectionFromPtr<IntPtr>(ptr,1).First();
                try
                {
                    var versions = MarshallingHelper.GetCollectionFromPtr<tagWSDOCUMENTVERSION>(collectionPtr, size);

                    var lastVersionDoc = versions.OrderByDescending(p => p.szVersionLabel).First().wsdDocumentDetails;

                    dp.OpenDocument(ref lastVersionDoc).Assert_Is_S_OK();

                    Mock.Get(dp.module.Resolve<IProcessLauncher>()).Verify(a => a.Launch(wdDoc.LocalFilePath));

                    return lastVersionDoc;
                }
                finally
                {
                    Marshal.FreeHGlobal(collectionPtr);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }
        }
Exemplo n.º 37
0
 protected virtual IDocumentStorage <T> selectStorage <T>(DocumentProvider <T> provider)
 {
     return(provider.QueryOnly);
 }
Exemplo n.º 38
0
        public void CanCompareDocuments1()
        {
            var module = GetTestModule();
            var wdDoc1 = MockUtils.GetDefaultDoc("a.docx");
            var wdDoc2 = MockUtils.GetDefaultDoc("a.doc");

            try
            {
                File.WriteAllText(wdDoc1.LocalFilePath, @"Workshare Placeholder");
                File.WriteAllText(wdDoc2.LocalFilePath, @"Workshare Placeholder");
                
                Mock.Get(module.Resolve<IWdDocumentRepository>()).Setup_GetByPath(wdDoc1);
                Mock.Get(module.Resolve<IWdDocumentRepository>()).Setup_GetByPath(wdDoc2);

                var dp = new DocumentProvider(module);
                var wsId1 = SimulateSelectionOfFile(dp, wdDoc1, "Word 2003|*.doc|Word 2010|*.docx");
                var wsId2 = SimulateSelectionOfFile(dp, wdDoc2, "Word 2003|*.doc|Word 2010|*.docx");

                var wsDocs = SimulateComparison(dp, wdDoc1, wdDoc2);

                dp.CloseDocument(ref wsDocs[0], 0).Assert_Is_S_OK();
                dp.CloseDocument(ref wsDocs[1], 0).Assert_Is_S_OK();
            }
            finally
            {
                File.Delete(wdDoc1.LocalFilePath);
                File.Delete(wdDoc2.LocalFilePath);
            } 
        }