コード例 #1
0
ファイル: _01_QueryIndex.cs プロジェクト: dirten/lezen
        public void Test()
        {
            using (var temp = new TempDirectory(System.IO.Directory.GetCurrentDirectory()))
                using (var directory = FSDirectory.Open(temp.Path))
                {
                    var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);

                    IndexWriter.MaxFieldLength length = new IndexWriter.MaxFieldLength(IndexWriter.DEFAULT_MAX_FIELD_LENGTH);
                    var writer = new IndexWriter(directory, analyzer, length);

                    var documentFactory = new DocumentFactory();
                    var searchItem1     = new SearchItem {
                        EntityID = 1, Abstract = "abstract1", Keywords = new string[0], Text = "text1"
                    };
                    var searchItem2 = new SearchItem {
                        EntityID = 2, Abstract = "abstract2", Keywords = new string[0], Text = "text2"
                    };
                    var searchItem3 = new SearchItem {
                        EntityID = 3, Abstract = "abstract3", Keywords = new string[0], Text = "text3"
                    };

                    writer.AddDocument(documentFactory.Create(searchItem1));
                    writer.AddDocument(documentFactory.Create(searchItem2));
                    writer.AddDocument(documentFactory.Create(searchItem3));

                    writer.Commit();

                    writer.NumDocs().Should().Be(3);
                    writer.Dispose();
                }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: stephanscheidl/SharpDocx
        private static void Main()
        {
            var viewPath     = $"{BasePath}/Views/Inheritance.cs.docx";
            var documentPath = $"{BasePath}/Documents/Inheritance.docx";

#if DEBUG
            Ide.Start(viewPath, documentPath, null, typeof(MyDocument), f => ((MyDocument)f).MyProperty = "The code");
#else
            var myDocument = DocumentFactory.Create <MyDocument>(viewPath);
            myDocument.MyProperty = "The Code";

            // It's possible to generate a file or a stream.

            // 1. Generate a file
            // myDocument.Generate(documentPath);

            //2. Generate an output stream.
            using (var outputStream = myDocument.Generate())
            {
                using (var outputFile = File.Open(documentPath, FileMode.Create))
                {
                    outputFile.Write(outputStream.GetBuffer(), 0, (int)outputStream.Length);
                }
            }
#endif
        }
コード例 #3
0
        public void AllowsLongChainOfReadOnlyFields()
        {
            var source        = @"
class Test {
  private static readonly C c = new C();

  public void Run() {
    var v = Test.c.Value.Value.Value;
  }
}

class A {
  public readonly int Value;
}

class B {
  public readonly A Value;
}

class C {
  public readonly B Value;
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(source);
            var method        = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <MethodDeclarationSyntax>()
                                .Single();


            var code     = CodeFactory.Create(method.Body, semanticModel);
            var expected = @"
DECL v
v = \literal";

            Assert.AreEqual(expected.Trim(), CodeStringifier.Generate(code));
        }
コード例 #4
0
        public void CreateIndexer()
        {
            TestUtils.InitializeDefaultExtensionPoints();

            _indexerPath = Path.GetTempPath() + "luceneindexer";
            Directory.CreateDirectory(_indexerPath);
            _solutionKey = new SolutionKey(Guid.NewGuid(), "C:/SolutionPath");
            ServiceLocator.RegisterInstance(_solutionKey);
            ServiceLocator.RegisterInstance <Analyzer>(new SimpleAnalyzer());
            _indexer = new DocumentIndexer(TimeSpan.FromSeconds(1));
            ServiceLocator.RegisterInstance(_indexer);

            ClassElement classElement = SampleProgramElementFactory.GetSampleClassElement(
                accessLevel: AccessLevel.Public,
                definitionLineNumber: 11,
                extendedClasses: "SimpleClassBase",
                fullFilePath: "C:/Projects/SimpleClass.cs",
                implementedInterfaces: "IDisposable",
                name: "SimpleName",
                namespaceName: "Sanod.Indexer.UnitTests"
                );
            SandoDocument sandoDocument = DocumentFactory.Create(classElement);

            _indexer.AddDocument(sandoDocument);
            MethodElement methodElement = SampleProgramElementFactory.GetSampleMethodElement(
                accessLevel: AccessLevel.Protected,
                name: "SimpleName",
                returnType: "Void",
                fullFilePath: "C:/stuff"
                );

            sandoDocument = DocumentFactory.Create(methodElement);
            _indexer.AddDocument(sandoDocument);
        }
コード例 #5
0
ファイル: DocumentFactoryTest.cs プロジェクト: dirten/lezen
        public void DocumentShouldHaveCorrectFieldNames()
        {
            var searchItem = new SearchItem
            {
                EntityID = 1,
                Abstract = "--abstract--",
                Keywords = new[] { "keyword1", "keyword2", "keyword3" },
                Text     = "--text--",
            };

            var testSubject = new DocumentFactory();
            var document    = testSubject.Create(searchItem);

            var fields = document.GetFields();
            var names  = String.Join(",", fields.Select(x => x.Name).ToArray());

            //names.Should().Be("donkey");

            fields.Any(x => x.Name == "Abstract").Should().BeTrue();
            fields.Any(x => x.Name == "Text").Should().BeTrue();
            fields.Count(x => x.Name == "Keyword").Should().Be(3);

            document.Get("Abstract").Should().Be("--abstract--");
            document.Get("Text").Should().Be("--text--");
            document.GetValues("Keyword").Should().HaveCount(3);
            document.GetValues("Keyword").Should().Contain("keyword1", "keyword2", "keyword3");
        }
コード例 #6
0
ファイル: DocumentFactoryTest.cs プロジェクト: dirten/lezen
        public void KeywordShouldBeAnalyzedField()
        {
            var searchItem = new SearchItem
            {
                EntityID = 1,
                Abstract = "--abstract--",
                Keywords = new[] { "keyword1", "keyword2", "keyword3" },
                Text     = "--text--",
            };

            var testSubject = new DocumentFactory();
            var document    = testSubject.Create(searchItem);

            var abstractField = document.GetField("Keyword");

            abstractField.IsBinary.Should().BeFalse();
            abstractField.IsIndexed.Should().BeTrue();
            abstractField.IsLazy.Should().BeFalse();
            abstractField.IsStored.Should().BeFalse();
            abstractField.IsStoreOffsetWithTermVector.Should().BeFalse();
            abstractField.IsStorePositionWithTermVector.Should().BeFalse();
            abstractField.IsTermVectorStored.Should().BeFalse();
            abstractField.IsTokenized.Should().BeTrue();
            abstractField.OmitNorms.Should().BeFalse();
            abstractField.OmitTermFreqAndPositions.Should().BeFalse();
        }
コード例 #7
0
        public void ProhibitsRetrievalOfArrayWithinMemberChain()
        {
            var source        = @"
class Test {
  private static readonly C c = new C();

  public void Run() {
    var v = Test.c.Value.Value.Values;
  }
}

class A {
  public readonly int[] Values;
}

class B {
  public readonly A Value;
}

class C {
  public readonly B Value;
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(source);
            var method        = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <MethodDeclarationSyntax>()
                                .Single();


            CodeFactory.Create(method.Body, semanticModel);
        }
コード例 #8
0
        private static void Main()
        {
            var viewPath     = $"{BasePath}/Views/Inheritance.cs.docx";
            var documentPath = $"{BasePath}/Documents/Inheritance.docx";

#if DEBUG
            string documentViewer = null; // NET35 and NET45 will automatically search for a Docx viewer.
            //var documentViewer = @"C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE"; // NETCOREAPP3_1 and NET6_0 won't.

            Ide.Start(viewPath, documentPath, null, typeof(MyDocument), f => ((MyDocument)f).MyProperty = "The code", documentViewer);
#else
            var myDocument = DocumentFactory.Create <MyDocument>(viewPath);
            myDocument.MyProperty = "The Code";

            // It's possible to generate a file or a stream.

            // 1. Generate a file
            // myDocument.Generate(documentPath);

            //2. Generate an output stream.
            using (var outputStream = myDocument.Generate())
            {
                using (var outputFile = File.Open(documentPath, FileMode.Create))
                {
                    outputFile.Write(outputStream.GetBuffer(), 0, (int)outputStream.Length);
                }
            }
#endif
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: stephanscheidl/SharpDocx
        private static void ExecuteTemplates(out WeakReference loadContextRef)
        {
            var loadCtx = new TestAssemblyLoadContext(Path.GetDirectoryName(typeof(Program).Assembly.Location));

            DocumentFactory.LoadContext = loadCtx;

            var viewPath       = $"{BasePath}/Views/Tutorial.cs.docx";
            var documentPath   = $"{BasePath}/Documents/Tutorial.docx";
            var imageDirectory = $"{BasePath}/Images";

#if DEBUG
            Ide.Start(viewPath, documentPath, null, null, f => f.ImageDirectory = imageDirectory);
#else
            DocumentBase document = DocumentFactory.Create(viewPath);
            document.ImageDirectory = imageDirectory;
            document.Generate(documentPath);
#endif
            loadContextRef = new WeakReference(loadCtx);

            Console.WriteLine("---------------------Assemblies Loaded In the Default Context-------------------------------");
            var assemblyNames = AssemblyLoadContext.Default.Assemblies.Select(s => s.FullName).ToArray();
            Console.WriteLine(string.Join(Environment.NewLine, assemblyNames));

            Console.WriteLine("---------------------Assemblies Loaded In Context-------------------------------");
            assemblyNames = loadCtx.Assemblies.Select(s => s.FullName).ToArray();
            Console.WriteLine(string.Join(Environment.NewLine, assemblyNames));

            loadCtx.Unload();
            DocumentFactory.LoadContext = null;
        }
コード例 #10
0
        public void BodyWithSingleInvocation()
        {
            var invokerSource = @"var a = 10; Method(a);";
            var invokerCfg    = CreateControlFlowGraph(invokerSource);

            var methodSource  = @"
class Test {
  private void Method(int x) {
  }
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(methodSource);
            var methodCode    = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <MethodDeclarationSyntax>()
                                .Select(declaration => CodeFactory.CreateMethod(declaration, semanticModel))
                                .Single();
            var methodCfg     = ControlFlowGraphFactory.Create(methodCode, "Method", true);
            var procedureCfgs = new Dictionary <string, ControlFlowGraph> {
                { "Method", methodCfg }
            };
            var callGraph = CallGraphFactory.Create(invokerCfg, procedureCfgs);

            Assert.AreEqual(4, callGraph.Edges.Count);
            Assert.IsTrue(callGraph.Edges.Any(edge => edge.From is FlowInvocation && _IsExpectedTransfer(edge.To, "<root>", "Method", true, false)));
            Assert.IsTrue(callGraph.Edges.Any(edge => _IsExpectedTransfer(edge.From, "<root>", "Method", true, false) && _IsExpectedBoundary(edge.To, "Method", FlowKind.Start)));

            Assert.IsTrue(callGraph.Edges.Any(edge => _IsExpectedBoundary(edge.From, "Method", FlowKind.End) && _IsExpectedTransfer(edge.To, "Method", "<root>", false, true)));
            Assert.IsTrue(callGraph.Edges.Any(edge => _IsExpectedTransfer(edge.From, "Method", "<root>", false, true) && edge.To is FlowInvocation));

            Debug.WriteLine(new[] { invokerCfg }.Concat(procedureCfgs.Values).ToDot(callGraph));
        }
コード例 #11
0
        public void EqualityOperatorOverloadedCustomType()
        {
            var code          = @"
class Test {
  public void Run() {
    if(new Integer() == new Integer()) {}
  }
}

class Integer {
  public static bool operator ==(Integer lhv, Integer b) {
    return false;
  }

  public static bool operator !=(Integer lhv, Integer b) {
    return false;
  }
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var binary        = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <BinaryExpressionSyntax>()
                                .Single();

            Assert.IsTrue(binary.IsOverloadedBinaryOperator(semanticModel));
        }
コード例 #12
0
        public ImmutableArray <Diagnostic> Analyze(string source)
        {
            var factory = DocumentFactory.Create();

            factory.CreateFromSource(source);
            return(factory.Project.GetCompilationAsync().Result
                   .WithAnalyzers(ImmutableArray.Create <DiagnosticAnalyzer>(new TAnalyzer()))
                   .GetAnalyzerDiagnosticsAsync().Result);
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: egonl/SharpDocx
        private static void GenerateDocument(int i)
        {
            var viewPath     = $"{BasePath}\\Views\\Model.cs.docx";
            var documentPath = $"{BasePath}\\Documents\\Model {i}.docx";
            var model        = CreateViewModel();

            var document = DocumentFactory.Create(viewPath, model);

            document.Generate(documentPath);
        }
コード例 #14
0
        public static Document GetLuceneDocument()
        {
            ClassElement element  = SampleProgramElementFactory.GetSampleClassElement();
            Document     document = DocumentFactory.Create(element).GetDocument();

            document.Add(new Field("Bam", "Zaow", Field.Store.YES, Field.Index.ANALYZED));
            document.RemoveField(ProgramElement.CustomTypeTag);
            document.Add(new Field(ProgramElement.CustomTypeTag, typeof(MyCustomClassForTesting).AssemblyQualifiedName, Field.Store.YES, Field.Index.NO));
            return(document);
        }
コード例 #15
0
        private Code CreateCode(string methodDeclaration, string methodName)
        {
            var code          = $"class Test {{ {methodDeclaration} }}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var method        = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <MethodDeclarationSyntax>()
                                .Where(declaration => declaration.Identifier.Text.Equals(methodName))
                                .Single();

            return(CodeFactory.CreateMethod(method, semanticModel));
        }
コード例 #16
0
        public IDocument Create(IFormFile file)
        {
            var type = GetDocType(file);

            using (var stream = file.OpenReadStream())
            {
                var document = DocumentFactory.Create(type, stream);
                return(document);
                // return _documentRepository.Save(document);
            }
        }
コード例 #17
0
        /// <summary>
        /// Creates a code from the given source syntax.
        /// </summary>
        /// <returns></returns>
        public static Code CreateCode(string body)
        {
            var methodName    = "Method";
            var code          = $"class Test {{ void {methodName}() {{ {body} }} }}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var method        = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <MethodDeclarationSyntax>()
                                .Single();

            return(CodeFactory.Create(method.Body));
        }
コード例 #18
0
        public ControlFlowGraph CreateControlFlowGraph(string methodDeclaration)
        {
            var code          = $"class Test {{ {methodDeclaration} }}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var method        = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <MethodDeclarationSyntax>()
                                .Single();


            return(ControlFlowGraphFactory.Create(CodeFactory.CreateMethod(method, semanticModel), true));
        }
コード例 #19
0
 public void DocumentFactory_CreateThrowsContractExceptionIfUnsportedProgramElementSubclassObjectPassed()
 {
     try
     {
         SandoDocument sandoDocument = DocumentFactory.Create(new TestElement("name", 12, -1000, "full path", "snippet"));
     }
     catch
     {
         //contract exception catched here
     }
     Assert.True(contractFailed, "Contract should fail!");
 }
コード例 #20
0
 public void DocumentFactory_CreateThrowsContractExceptionIfProgramElementIsNull()
 {
     try
     {
         SandoDocument sandoDocument = DocumentFactory.Create(null);
     }
     catch
     {
         //contract exception catched here
     }
     Assert.True(contractFailed, "Contract should fail!");
 }
コード例 #21
0
        /// <summary>
        /// Creates an expression from the given source syntax.
        /// </summary>
        /// <returns></returns>
        public static Expression CreateExpression(string body)
        {
            var methodName    = "Method";
            var code          = $"class Test {{ void {methodName}() {{ var variable = {body}; }} }}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var expression    = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <VariableDeclaratorSyntax>()
                                .Select(declarator => declarator.Initializer.Value)
                                .Single();

            return(new ExpressionFactory(null, false).Create(expression));
        }
コード例 #22
0
        public void VirtualInstanceMethodIsVirtual()
        {
            var code          = @"
class Test { 
  public virtual void Run() {}
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var method        = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <MethodDeclarationSyntax>()
                                .Single();

            Assert.IsTrue(method.IsVirtual());
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: xiaoxiongnpu/SharpDocx
        private static void Main()
        {
            var viewPath     = $"{BasePath}/Views/Inheritance.cs.docx";
            var documentPath = $"{BasePath}/Documents/Inheritance.docx";

#if DEBUG
            Ide.Start(viewPath, documentPath, null, typeof(MyDocument), f => ((MyDocument)f).MyProperty = "The code");
#else
            var myDocument = DocumentFactory.Create <MyDocument>(viewPath);
            myDocument.MyProperty = "The Code";
            myDocument.Generate(documentPath);
#endif
        }
コード例 #24
0
        private static void Main()
        {
            var viewPath       = $"{BasePath}/Views/Tutorial.cs.docx";
            var documentPath   = $"{BasePath}/Documents/Tutorial.docx";
            var imageDirectory = $"{BasePath}/Images";

#if DEBUG
            Ide.Start(viewPath, documentPath, null, null, f => f.ImageDirectory = imageDirectory);
#else
            DocumentBase document = DocumentFactory.Create(viewPath);
            document.ImageDirectory = imageDirectory;
            document.Generate(documentPath);
#endif
        }
コード例 #25
0
        public void ObjectIsNoPrimitiveType()
        {
            var code          = @"
class Test { 
  private readonly object value = new object();
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var field         = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <VariableDeclaratorSyntax>()
                                .Select(declarator => (IFieldSymbol)semanticModel.GetDeclaredSymbol(declarator))
                                .Single();

            Assert.IsFalse(field.Type.IsPrimitiveType());
        }
コード例 #26
0
        public void DefinitionWithConditionAccessingLocalVariable()
        {
            var source        = @"
class Test {
  public void Run() {
    var local = 10;
    for(var i = 0; i < local; i++) {}
  }
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(source);
            var forStatement  = _GetForStatement(semanticModel);

            Assert.IsTrue(LoopDeclarationVerifier.IsNormalized(forStatement, semanticModel));
        }
コード例 #27
0
 public void DocumentFactory_CreateReturnsMethodDocumentForValidMethodElement()
 {
     try
     {
         ProgramElement programElement = SampleProgramElementFactory.GetSampleMethodElement();
         SandoDocument  sandoDocument  = DocumentFactory.Create(programElement);
         Assert.True(sandoDocument != null, "Null returned from DocumentFactory!");
         Assert.True(sandoDocument is MethodDocument, "MethodDocument must be returned for MethodElement object!");
     }
     catch (Exception ex)
     {
         Assert.Fail(ex.Message + ". " + ex.StackTrace);
     }
 }
コード例 #28
0
        public void AutoPropertyHasNoSideEffects()
        {
            var code          = @"
class Test { 
  public int Value { get; set; }
}";
            var semanticModel = DocumentFactory.Create().CreateSemanticModel(code);
            var property      = semanticModel.SyntaxTree.GetRoot().DescendantNodes()
                                .OfType <PropertyDeclarationSyntax>()
                                .Select(declaration => semanticModel.GetDeclaredSymbol(declaration))
                                .Single();

            Assert.IsTrue(property.IsLocalAutoProperty(semanticModel));
        }
コード例 #29
0
        public static LEADDocument CreateVirtualDocument()
        {
            LEADDocument virtualDocument = DocumentFactory.Create(new CreateDocumentOptions()
            {
                UseCache = true, Cache = CacheObject
            });

            virtualDocument.AutoDisposeDocuments = true;
            virtualDocument.AutoSaveToCache      = true;
            virtualDocument.AutoDeleteFromCache  = false;
            virtualDocument.IsReadOnly           = false;

            return(virtualDocument);
        }
コード例 #30
0
ファイル: SearchTester.cs プロジェクト: abb-iss/Sando
        private void IndexFilesInDirectory(string solutionPath)
        {
            var files = Directory.GetFiles(solutionPath);

            foreach (var file in files)
            {
                string fullPath = Path.GetFullPath(file);
                var    srcMl    = _parser.Parse(fullPath);
                foreach (var programElement in srcMl)
                {
                    _indexer.AddDocument(DocumentFactory.Create(programElement));
                }
            }
        }