private void Persist(Encoding generatedEncoding, Encoding persistedEncoding)
        {
            var compilation   = CSharpCompilation.Create(GetUniqueName(), new[] { CSharpSyntaxTree.ParseText(@"class C { }") }, new[] { MscorlibRef });
            var generatedText = @"class __C { }";
            var generator     = new MyGenerator(context => context.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(generatedText, encoding: generatedEncoding)));

            using (var directory = new DisposableDirectory(Temp))
            {
                var path  = directory.Path;
                var trees = compilation.GenerateSource(
                    ImmutableArray.Create <SourceGenerator>(generator),
                    path,
                    writeToDisk: true,
                    cancellationToken: default(CancellationToken));
                Assert.Equal(1, trees.Length);
                var filePath = Path.Combine(path, "__c.cs");
                Assert.Equal(filePath, trees[0].FilePath);
                Assert.True(File.Exists(filePath));
                using (var reader = new StreamReader(filePath, detectEncodingFromByteOrderMarks: true))
                {
                    // Need at least one read to get encoding.
                    var persistedText = reader.ReadToEnd();
                    Assert.Equal(persistedEncoding, reader.CurrentEncoding);
                    Assert.Equal(persistedText, generatedText);
                }
            }
        }
        private List <AppTableView> GetApplicationTables(String connectionString, Application application)
        {
            var myGenerator = new MyGenerator(connectionString, application.Name, "");

            if (myGenerator.DatabaseTables != null)
            {
                var tables      = myGenerator.DatabaseTables.Select(tb => tb.Name).ToList <string>();
                var tablesNames = myGenerator.DatabaseTables.ToList();

                var appTablesView = new List <AppTableView>();
                foreach (var item in tables)
                {
                    AppTableView appTable = new AppTableView();
                    appTable.Name = item;
                    var currentTable = tablesNames.Where(t => t.Name == item).FirstOrDefault();
                    var columns      = currentTable.Properties.ToList();
                    //Read table columns
                    foreach (var column in columns)
                    {
                        appTable.Columns.Add(new TableColumn
                        {
                            Name = column.Name
                        });
                    }
                    appTablesView.Add(appTable);
                }
                return(appTablesView);
            }
            return(null);
        }
        public void Generate_NoArguments_GeneratesTextToken()
        {
            // Arrange
            var generator = new MyGenerator();

            // Act
            var token = generator.Generate(100);

            // Assert
            Assert.Pass(token, Has.Length.EqualTo(100));
        }
Exemple #4
0
        static void Main(string[] args)
        {
            MyGenerator g = new MyGenerator();
            CompilationUnitSyntax cus = g.Ast_CompilationUnit();
            SyntaxTree syntaxTree = SyntaxFactory.SyntaxTree(cus);

            using (var sw = new StreamWriter(File.Open("Generator.cs", FileMode.Create, FileAccess.Write)))
            {
                syntaxTree.GetRoot().NormalizeWhitespace().WriteTo(sw);
                sw.Flush();
            }
        }
        private static SyntaxNode?NewBinaryOperation(
            IBinaryOperation binaryOperation,
            SyntaxNode leftOperand,
            BinaryOperatorKind operationKind,
            SyntaxNode rightOperand,
            CancellationToken cancellationToken)
        {
            MyGenerator generator = new MyGenerator();

            switch (operationKind)
            {
            case BinaryOperatorKind.Equals:
                return(binaryOperation.LeftOperand.Type?.IsValueType == true && binaryOperation.RightOperand.Type?.IsValueType == true
                        ? generator.ValueEqualsExpression(leftOperand, rightOperand)
                        : generator.ReferenceEqualsExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.NotEquals:
                return(binaryOperation.LeftOperand.Type?.IsValueType == true && binaryOperation.RightOperand.Type?.IsValueType == true
                        ? generator.ValueNotEqualsExpression(leftOperand, rightOperand)
                        : generator.ReferenceNotEqualsExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.LessThanOrEqual:
                return(IsSpecialCaseBinaryExpression(binaryOperation, operationKind, cancellationToken)
                        ? generator.ValueEqualsExpression(leftOperand, rightOperand)
                        : generator.LessThanOrEqualExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.GreaterThanOrEqual:
                return(IsSpecialCaseBinaryExpression(binaryOperation, operationKind, cancellationToken)
                        ? generator.ValueEqualsExpression(leftOperand, rightOperand)
                        : generator.GreaterThanOrEqualExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.LessThan:
                return(generator.LessThanExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.GreaterThan:
                return(generator.GreaterThanExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.Or:
                return(generator.BitwiseOrExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.And:
                return(generator.BitwiseAndExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.ConditionalOr:
                return(generator.LogicalOrExpression(leftOperand, rightOperand));

            case BinaryOperatorKind.ConditionalAnd:
                return(generator.LogicalAndExpression(leftOperand, rightOperand));
            }

            return(null);
        }
        //public override void PrePlanRun()
        //{
        //    // This method is called on all TestSteps at the START of TestPlan execution.
        //    // If no setup code is needed, this method can be removed.
        //    base.PrePlanRun();
        //}

        public override void Run()
        {
            // The Run method is where the main execution logic of a TestStep exists.
            // This is a required method.
            try
            {
                // Setup instrument.
                MyGenerator.SetInputData(InputData);

                // Setup DUT.
                MyFilter.WindowSize = WindowSize;

                // Execute logic for DUT and handle data from DUT.
                ReadOnlyOutputData = MyFilter.CalcMovingAverage(InputData);

                // Check to see if limit checking is enabled.  If so, Upgrade the verdict.
                if (LimitCheckEnabled)
                {
                    // The Verdict is used by TAP to convey the general execution result of a Test Step.
                    UpgradeVerdict(ReadOnlyOutputData.Max() >= MaxAmplitude ? Verdict.Fail : Verdict.Pass);
                }
                else
                {
                    // All Test Steps have a standard Log object (inherited from the base class)
                    // that can be used to write messages to the run log and the session log.
                    Log.Debug("Limit checking was not enabled.  This is why the verdict is inconclusive.");
                    UpgradeVerdict(Verdict.Inconclusive);
                }

                // Different log message types can be used based on what is being written.
                Log.Info("The DUT comment is {0}", MyFilter.Comment);

                // All Test Steps also contain a Results object. Results are store by calling Publish or PublishTable.
                Results.PublishTable("Inputs Versus Moving Average", new List <string>()
                {
                    "Input Values", "Output Values"
                },
                                     InputData, ReadOnlyOutputData);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);

                // The verdict can be set more than once in a Test Step.
                // UpgradeVerdict sets the current verdict to the more serious verdict.
                // If the new Verdict is not more severe, the original setting will be kept.
                UpgradeVerdict(Verdict.Error);
            }
        }
Exemple #7
0
 private void UseFunction_Click(object sender, EventArgs e)
 {
     limitNumber = (int)maxOutCount.Value;
     if (limitNumber != 0)
     {
         MyGenerator.GenericAndAnswer(limitNumber, out genNumbers, out summ, out kolNumbers);
         randomNumbers.Text = genNumbers;
         amountNumbers.Text = kolNumbers.ToString();
         summNumbers.Text   = summ.ToString();
     }
     else
     {
         MessageBox.Show("Введите значения.");
     }
 }
Exemple #8
0
        public void RunAnalyzersAfterGeneratingSource()
        {
            string text =
                @"class C
{
}";

            using (var directory = new DisposableDirectory(Temp))
            {
                var file = directory.CreateFile("c.cs");
                file.WriteAllText(text);

                int analyzerCalls = 0;
                ImmutableArray <SyntaxTree> treesToAnalyze;
                var analyzer = new MyAnalyzer(c =>
                {
                    analyzerCalls++;
                    Assert.True(treesToAnalyze.IsDefault);
                    treesToAnalyze = ImmutableArray.CreateRange(c.Compilation.SyntaxTrees);
                });

                int generatorCalls = 0;
                var generator      = new MyGenerator(c =>
                {
                    generatorCalls++;
                    c.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText("class __C { }"));
                });

                var compiler = new MyCompiler(
                    baseDirectory: directory.Path,
                    args: new[] { "/nologo", "/preferreduilang:en", "/t:library", file.Path },
                    analyzers: ImmutableArray.Create <DiagnosticAnalyzer>(analyzer),
                    generators: ImmutableArray.Create <SourceGenerator>(generator));

                var builder = new StringBuilder();
                using (var writer = new StringWriter(builder))
                {
                    compiler.Run(writer);
                }
                var output = builder.ToString();
                // No errors from analyzer.
                Assert.Equal("", output);

                Assert.Equal(1, generatorCalls);
                Assert.Equal(1, analyzerCalls);
                Assert.Equal(2, treesToAnalyze.Length);
            }
        }
        public void CustomToolchain()
        {
            var logger = new OutputLogger(output);

            var generator = new MyGenerator();
            var builder = new MyBuilder();
            var executor = new MyExecutor();
            var myToolchain = new Toolchain("My", generator, builder, executor);
            var job = Job.Default.With(myToolchain).With(Mode.SingleRun).WithLaunchCount(1).WithWarmupCount(1).WithTargetCount(1);

            var config = DefaultConfig.Instance.With(job).With(logger);
            BenchmarkRunner.Run<ToolchainTest>(config);
            Assert.True(generator.Done);
            Assert.True(builder.Done);
            Assert.True(executor.Done);
        }
Exemple #10
0
        public void RunAnalyzersAfterGeneratingSource()
        {
            string text =
@"class C
{
}";
            using (var directory = new DisposableDirectory(Temp))
            {
                var file = directory.CreateFile("c.cs");
                file.WriteAllText(text);

                int analyzerCalls = 0;
                ImmutableArray<SyntaxTree> treesToAnalyze;
                var analyzer = new MyAnalyzer(c =>
                {
                    analyzerCalls++;
                    Assert.True(treesToAnalyze.IsDefault);
                    treesToAnalyze = ImmutableArray.CreateRange(c.Compilation.SyntaxTrees);
                });

                int generatorCalls = 0;
                var generator = new MyGenerator(c =>
                {
                    generatorCalls++;
                    c.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText("class __C { }"));
                });

                var compiler = new MyCompiler(
                    baseDirectory: directory.Path,
                    args: new[] { "/nologo", "/preferreduilang:en", "/t:library", file.Path },
                    analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer),
                    generators: ImmutableArray.Create<SourceGenerator>(generator));

                var builder = new StringBuilder();
                using (var writer = new StringWriter(builder))
                {
                    compiler.Run(writer);
                }
                var output = builder.ToString();
                // No errors from analyzer.
                Assert.Equal("", output);

                Assert.Equal(1, generatorCalls);
                Assert.Equal(1, analyzerCalls);
                Assert.Equal(2, treesToAnalyze.Length);
            }
        }
Exemple #11
0
        public void CustomToolchainsAreSupported()
        {
            var logger = new OutputLogger(Output);

            var generator   = new MyGenerator();
            var builder     = new MyBuilder();
            var executor    = new MyExecutor();
            var myToolchain = new Toolchain("My", generator, builder, executor);
            var job         = Job.Dry.With(myToolchain);
            var config      = CreateSimpleConfig(logger).With(job);

            CanExecute <ToolchainBenchmark>(config, fullValidation: false);

            Assert.True(generator.Done);
            Assert.True(builder.Done);
            Assert.True(executor.Done);
        }
Exemple #12
0
        public void CustomToolchain()
        {
            var logger = new OutputLogger(output);

            var generator   = new MyGenerator();
            var builder     = new MyBuilder();
            var executor    = new MyExecutor();
            var myToolchain = new Toolchain("My", generator, builder, executor);
            var job         = Job.Default.With(myToolchain).With(Mode.SingleRun).WithLaunchCount(1).WithWarmupCount(1).WithTargetCount(1);

            var config = DefaultConfig.Instance.With(job).With(logger);

            BenchmarkRunner.Run <ToolchainTest>(config);
            Assert.True(generator.Done);
            Assert.True(builder.Done);
            Assert.True(executor.Done);
        }
        public void CustomToolchainsAreSupported()
        {
            var logger = new OutputLogger(Output);

            var generator = new MyGenerator();
            var builder = new MyBuilder();
            var executor = new MyExecutor();
            var myToolchain = new Toolchain("My", generator, builder, executor);
            var job = new Job(Job.Dry) { Infrastructure = { Toolchain = myToolchain} };
            var config = CreateSimpleConfig(logger).With(job);

            CanExecute<ToolchainBenchmark>(config, fullValidation: false);

            Assert.True(generator.Done);
            Assert.True(builder.Done);
            Assert.True(executor.Done);
        }
Exemple #14
0
    public override float CulcPoint(Vector3 InPoint)
    {
        if (TurnOffTest)
        {
            return(1);
        }

        float Dist = (MyQuery.GetPoint() - InPoint).magnitude;


        if (Dist < MinDistance)
        {
            return(MinMultiplier);
        }

        if (MaxDistance > MinDistance && Dist > MaxDistance)
        {
            return(MinMultiplier);
        }

        if (MyValueGraphic == 0)
        {
            return(Multiplier);
        }

        float MyMax = MaxDistance > MinDistance ? MaxDistance : MyGenerator.GetMaxDistance();

        switch (MyValueGraphic)
        {
        case ValueGraphic.UpLinear:
        {
            return(MinMultiplier + (Multiplier - MinMultiplier) * (Dist - MinDistance) / (MyMax - MinDistance));
        }

        case ValueGraphic.DownLinear:
        {
            return(MinMultiplier + (Multiplier - MinMultiplier) * (MyMax - Dist) / (MyMax - MinDistance));
        }

        default:
            break;
        }

        return(Multiplier);
    }
        public void CustomToolchain()
        {
            var generator = new MyGenerator();
            var builder = new MyBuilder();
            var executor = new MyExecutor();
            var plugins = BenchmarkPluginBuilder.CreateEmpty().
                AddToolchain(new BenchmarkToolchainBuilder(
                    BenchmarkToolchain.Custom1,
                    (benchmark, logger) => generator,
                    (benchmark, logger) => builder,
                    (benchmark, logger) => executor));
            new BenchmarkRunner(plugins).Run<ToolchainTest>();
            Assert.True(generator.Done);
            Assert.True(builder.Done);
            Assert.True(executor.Done);

            Assert.Throws<NotSupportedException>(() => new BenchmarkRunner(BenchmarkPluginBuilder.CreateEmpty()).Run<ToolchainTest>());
        }
Exemple #16
0
        private static void GenerateRandomValue()
        {
            if (Generator is null)
            {
                Generator = new MyGenerator();
            }

            if (GeneratedValueQueue is null)
            {
                GeneratedValueQueue = new Queue <MyBigInteger>();
            }

            var randomNumber = Generator.GetNextRandomValue();

            Console.WriteLine($"Generated number: {randomNumber}");

            GeneratedValueQueue.Enqueue(randomNumber);
        }
        public void CustomToolchain()
        {
            var generator = new MyGenerator();
            var builder   = new MyBuilder();
            var executor  = new MyExecutor();
            var plugins   = BenchmarkPluginBuilder.CreateEmpty().
                            AddToolchain(new BenchmarkToolchainBuilder(
                                             BenchmarkToolchain.Custom1,
                                             (benchmark, logger) => generator,
                                             (benchmark, logger) => builder,
                                             (benchmark, logger) => executor));

            new BenchmarkRunner(plugins).Run <ToolchainTest>();
            Assert.True(generator.Done);
            Assert.True(builder.Done);
            Assert.True(executor.Done);

            Assert.Throws <NotSupportedException>(() => new BenchmarkRunner(BenchmarkPluginBuilder.CreateEmpty()).Run <ToolchainTest>());
        }
        public void Paths()
        {
            string text =
@"class C
{
}";
            var compilation = CSharpCompilation.Create(GetUniqueName(), new[] { CSharpSyntaxTree.ParseText(text) }, new[] { MscorlibRef });
            var generator = new MyGenerator(context => context.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(@"class __C { }")));
            using (var directory = new DisposableDirectory(Temp))
            {
                // Null path.
                Assert.Throws<ArgumentNullException>(() =>
                    compilation.GenerateSource(ImmutableArray.Create<SourceGenerator>(generator), path: null, writeToDisk: false, cancellationToken: default(CancellationToken)));
                // Relative path.
                var path = Path.GetFileName(directory.Path);
                var trees = compilation.GenerateSource(ImmutableArray.Create<SourceGenerator>(generator), path, writeToDisk: false, cancellationToken: default(CancellationToken));
                Assert.Equal(1, trees.Length);
                var filePath = Path.Combine(path, "__c.cs");
                Assert.Equal(filePath, trees[0].FilePath);
            }
        }
        public void DoNotPersist()
        {
            string text =
@"class C
{
}";
            var compilation = CSharpCompilation.Create(GetUniqueName(), new[] { CSharpSyntaxTree.ParseText(text) }, new[] { MscorlibRef });
            var generator = new MyGenerator(context => context.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(@"class __C { }")));
            using (var directory = new DisposableDirectory(Temp))
            {
                var path = directory.Path;
                var trees = compilation.GenerateSource(
                    ImmutableArray.Create<SourceGenerator>(generator),
                    path,
                    writeToDisk: false,
                    cancellationToken: default(CancellationToken));
                Assert.Equal(1, trees.Length);
                var filePath = Path.Combine(path, "__c.cs");
                Assert.Equal(filePath, trees[0].FilePath);
                Assert.False(File.Exists(filePath));
            }
        }
        public void Paths()
        {
            string text =
                @"class C
{
}";
            var compilation = CSharpCompilation.Create(GetUniqueName(), new[] { CSharpSyntaxTree.ParseText(text) }, new[] { MscorlibRef });
            var generator   = new MyGenerator(context => context.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(@"class __C { }")));

            using (var directory = new DisposableDirectory(Temp))
            {
                // Null path.
                Assert.Throws <ArgumentNullException>(() =>
                                                      compilation.GenerateSource(ImmutableArray.Create <SourceGenerator>(generator), path: null, writeToDisk: false, cancellationToken: default(CancellationToken)));
                // Relative path.
                var path  = Path.GetFileName(directory.Path);
                var trees = compilation.GenerateSource(ImmutableArray.Create <SourceGenerator>(generator), path, writeToDisk: false, cancellationToken: default(CancellationToken));
                Assert.Equal(1, trees.Length);
                var filePath = Path.Combine(path, "__c.cs");
                Assert.Equal(filePath, trees[0].FilePath);
            }
        }
        public void DoNotPersist()
        {
            string text =
                @"class C
{
}";
            var compilation = CSharpCompilation.Create(GetUniqueName(), new[] { CSharpSyntaxTree.ParseText(text) }, new[] { MscorlibRef });
            var generator   = new MyGenerator(context => context.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(@"class __C { }")));

            using (var directory = new DisposableDirectory(Temp))
            {
                var path  = directory.Path;
                var trees = compilation.GenerateSource(
                    ImmutableArray.Create <SourceGenerator>(generator),
                    path,
                    writeToDisk: false,
                    cancellationToken: default(CancellationToken));
                Assert.Equal(1, trees.Length);
                var filePath = Path.Combine(path, "__c.cs");
                Assert.Equal(filePath, trees[0].FilePath);
                Assert.False(File.Exists(filePath));
            }
        }
        private void FindRealPoint(ConcurrentQueue <List <MyPoint> > batches)
        {
            var randomValue = _randomValues.Dequeue();
            var stopwatch   = new Stopwatch();

            stopwatch.Start();
            while (batches.TryDequeue(out List <MyPoint> batch))
            {
                foreach (var point in batch)
                {
                    var generator      = new MyGenerator(point);
                    var generatedValue = generator.GetNextRandomValue(false);

                    if (generatedValue != randomValue)
                    {
                        continue;
                    }

                    Console.WriteLine("Cracked");
                    Console.WriteLine($"{stopwatch.Elapsed}");
                    return;
                }
            }
        }
        public ActionResult Generate(int appId = 0, string[] selectedTables = null, string selectedTheme = "")
        {
            try
            {
                string      userName    = User.Identity.Name;
                Application application = applicationRepository.FindFirst(ap => ap.Member.username == userName && ap.Id == appId);

                if (application != null)
                {
                    bool connectionSuccess = CheckConnection(application);
                    if (connectionSuccess == true)
                    {
                        DeleteExistsFile(application);

                        //Change Application Theme
                        application.theme_id = GetTheme(selectedTheme);
                        applicationRepository.Edit(application);

                        //Create Application Folders
                        string appMainDirectory = CreateAppDirectories(application);
                        if (!string.IsNullOrEmpty(appMainDirectory))
                        {
                            //Generate Database files
                            string connectionString = Globals.GetSQLServerConnectionString(application);
                            string appName          = application.Name;

                            var myGenerator = new MyGenerator(connectionString, appName, appMainDirectory);

                            //App Tables
                            var tablesType = myGenerator.DatabaseTables.Where(tb => selectedTables.Contains(tb.Name)).ToList();

                            //Create application models and mapping
                            myGenerator.GenerateCode();

                            CreateContextAndConfig(myGenerator.DatabaseTables.ToList(), application, appMainDirectory);

                            //Create application controllers
                            var controllerGenerator = new ControllerGenerator(myGenerator, appName, appMainDirectory);
                            controllerGenerator.Generate(tablesType, connectionString);

                            //Create application navigation menu
                            ApplicationUtilities utilities = new ApplicationUtilities(appMainDirectory, application.Name);
                            utilities.CreateAppNav(tablesType);

                            //Create Application project file
                            string[] controllers = tablesType.Select(tp => tp.Name).ToArray <string>();
                            string[] allModels   = myGenerator.DatabaseTables.Select(tp => tp.Name).ToArray <string>();
                            utilities.CreateProjectFile(controllers, allModels, application.Theme.FileName);

                            //Create Home Controller
                            utilities.CreateControllerHome(tablesType);

                            application.generated = true;
                            applicationRepository.Edit(application);

                            //Zip Application Folder
                            string member_public_id = application.Member.public_id;
                            utilities.ZipApplication(application);

                            //Check the application has folders or not
                            //DirectoryUtility.DeleteFolder(Globals.APP_DATA_PATH + "\\" + member_public_id + "\\" + application.Name + "_" + application.Id);

                            return(View("Success", new MessageView()
                            {
                                Message = "Your application has been generated successfully."
                            }));
                        }
                    }
                    else
                    {
                        return(View("Error", new MessageView()
                        {
                            Message = "An error while connecting to your database."
                        }));
                    }
                }
                ViewBag.appId = application.Id;
                return(View());
            }
            catch (Exception ex)
            {
                return(View("Error", new MessageView()
                {
                    Message = "An error occured while generating the application"
                }));
            }
        }
 public static void CreateGeneratorWithGivenProvider()
 {
     using var generator = new MyGenerator();
     using var random    = new SecureRandom(generator);
     Assert.That(random.Generator, Is.Not.Null);
 }
Exemple #25
0
        public void TestSourceGenerators()
        {
            string source0 =
                @"partial class C
{
    D F() { return (D)G; }
}
class P
{
    static void Main()
    {
    }
}";
            string source1 =
                @"partial class C
{
    const object G = null;
}
class D
{
}";
            var generator          = new MyGenerator(c => c.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(source1)));
            var generatorReference = new MyGeneratorReference(ImmutableArray.Create <SourceGenerator>(generator));

            using (var directory = new DisposableDirectory(Temp))
            {
                var outputPath = Path.Combine(directory.Path, "obj", "debug");
                Directory.CreateDirectory(outputPath);

                var projectId   = ProjectId.CreateNewId();
                var docId       = DocumentId.CreateNewId(projectId);
                var workspace   = new AdhocWorkspace();
                var projectInfo = ProjectInfo.Create(
                    projectId,
                    VersionStamp.Default,
                    name: "C",
                    assemblyName: "C.dll",
                    language: LanguageNames.CSharp,
                    outputFilePath: outputPath + Path.DirectorySeparatorChar);
                var solution = workspace.CurrentSolution
                               .AddProject(projectInfo)
                               .AddMetadataReference(projectId, MscorlibRef)
                               .AddDocument(docId, "C.cs", source0)
                               .AddAnalyzerReference(projectId, generatorReference);

                bool ok = workspace.TryApplyChanges(solution);
                Assert.True(ok);

                var actualAnalyzerReferences = solution.GetProject(projectId).AnalyzerReferences;
                Assert.Equal(1, actualAnalyzerReferences.Count);
                Assert.Equal(generatorReference, actualAnalyzerReferences[0]);
                var actualGenerators = actualAnalyzerReferences[0].GetSourceGenerators(LanguageNames.CSharp);
                Assert.Equal(1, actualGenerators.Length);
                Assert.Equal(generator, actualGenerators[0]);

                // Before generating source.
                solution = workspace.CurrentSolution;
                var project = solution.GetProject(projectId);
                Assert.Equal(1, project.DocumentIds.Count);
                var doc   = solution.GetDocument(docId);
                var model = doc.GetSemanticModelAsync().Result;
                Assert.NotNull(model);
                var compilation = model.Compilation;
                var trees       = compilation.SyntaxTrees.ToArray();
                Assert.Equal(1, trees.Length);

                // After generating source.
                workspace.UpdateGeneratedDocumentsIfNecessary(projectId);
                solution = workspace.CurrentSolution;
                project  = solution.GetProject(projectId);
                Assert.Equal(2, project.DocumentIds.Count);
                doc   = solution.GetDocument(docId);
                model = doc.GetSemanticModelAsync().Result;
                Assert.NotNull(model);
                compilation = model.Compilation;
                trees       = compilation.SyntaxTrees.ToArray();
                Assert.Equal(2, trees.Length);
                var tree = trees[1];
                doc = solution.GetDocument(tree);
                Assert.NotNull(doc);
                Assert.True(doc.State.IsGenerated);
                var actualSource = tree.GetText().ToString();
                Assert.Equal(source1, actualSource);
                var filePath = doc.FilePath;
                Assert.NotNull(filePath);
                Assert.Equal(outputPath, Path.GetDirectoryName(filePath));
                // Workspace should not write files to disk.
                Assert.False(File.Exists(filePath));
            }
        }
 private void Persist(Encoding generatedEncoding, Encoding persistedEncoding)
 {
     var compilation = CSharpCompilation.Create(GetUniqueName(), new[] { CSharpSyntaxTree.ParseText(@"class C { }") }, new[] { MscorlibRef });
     var generatedText = @"class __C { }";
     var generator = new MyGenerator(context => context.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(generatedText, encoding: generatedEncoding)));
     using (var directory = new DisposableDirectory(Temp))
     {
         var path = directory.Path;
         var trees = compilation.GenerateSource(
             ImmutableArray.Create<SourceGenerator>(generator),
             path,
             writeToDisk: true,
             cancellationToken: default(CancellationToken));
         Assert.Equal(1, trees.Length);
         var filePath = Path.Combine(path, "__c.cs");
         Assert.Equal(filePath, trees[0].FilePath);
         Assert.True(File.Exists(filePath));
         using (var reader = new StreamReader(filePath, detectEncodingFromByteOrderMarks: true))
         {
             // Need at least one read to get encoding.
             var persistedText = reader.ReadToEnd();
             Assert.Equal(persistedEncoding, reader.CurrentEncoding);
             Assert.Equal(persistedText, generatedText);
         }
     }
 }