public void CSharpCodeGenerator_YieldBreak()
        {
            var statement = new YieldBreakStatement();
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"yield break;
", result);
        }
        public void CSharpCodeGenerator_Throw()
        {
            var expr      = new ThrowStatement(new NewObjectExpression(typeof(Exception)));
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expr);

            Assert.That.StringEquals(@"throw new System.Exception();
", result);
        }
        public void CSharpCodeGenerator_Return()
        {
            var statement = new ReturnStatement();
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"return;
", result);
        }
        public void CSharpCodeGenerator_YieldReturnExpression()
        {
            var statement = new YieldReturnStatement(10);
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"yield return 10;
", result);
        }
        public void CSharpCodeGenerator_CodeExitLoop()
        {
            var statement = new ExitLoopStatement();
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"break;
", result);
        }
        public void CSharpCodeGenerator_NextLoopIteration()
        {
            var statement = new GotoNextLoopIterationStatement();
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"continue;
", result);
        }
Ejemplo n.º 7
0
        public void CreateInvokeMethodExpression_VariableDeclaration_WithMemberName()
        {
            var v      = new VariableDeclarationStatement(typeof(string), "a");
            var member = v.CreateInvokeMethodExpression("Test", "Name");

            var csharp = new CSharpCodeGenerator().Write(member);

            Assert.Equal("a.Test(\"Name\")", csharp);
        }
Ejemplo n.º 8
0
        public void CreateInvokeMethodExpression_VariableDeclaration()
        {
            var v      = new VariableDeclarationStatement(typeof(string), "a");
            var member = v.CreateInvokeMethodExpression(LiteralExpression.Null());

            var csharp = new CSharpCodeGenerator().Write(member);

            Assert.Equal("a(null)", csharp);
        }
Ejemplo n.º 9
0
 private void GenerateCSharp()
 {
     if (GeneratorParameters.Generate)
     {
         Console.Out.WriteLine("***** Génération du modèle *****");
         AbstractCodeGenerator generator = new CSharpCodeGenerator(GeneratorParameters.OutputDirectory);
         generator.Generate(_modelList);
     }
 }
        public void CSharpCodeGenerator_CodeExpressionFromEnum_UndefinedValue()
        {
            Expression expression = (SampleEnum)10;

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals("((Meziantou.Framework.CodeDom.Tests.CSharpCodeGeneratorTests.SampleEnum)10)", result);
        }
        public void CSharpCodeGenerator_CodeExpressionFromEnum_DefinedCombinaison()
        {
            Expression expression = SampleEnum.All;

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals("Meziantou.Framework.CodeDom.Tests.CSharpCodeGeneratorTests.SampleEnum.All", result);
        }
        public void CSharpCodeGenerator_CommentNull()
        {
            var statement = new CommentStatement();
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"//
", result);
        }
        public void CSharpCodeGenerator_TypeReference_Generic()
        {
            var expression = new TypeReference(typeof(Sample <int>));

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals("Meziantou.Framework.CodeDom.Tests.CSharpCodeGeneratorTests.Sample<int>", result);
        }
        public void CSharpCodeGenerator_TypeReference()
        {
            var expression = new TypeReference(typeof(Console));

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals("System.Console", result);
        }
        public void CSharpCodeGenerator_UsingDirective()
        {
            var directive = new UsingDirective("System");

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(directive);

            Assert.That.StringEquals("using System;", result);
        }
        public void CSharpCodeGenerator_ExpressionCommentAfter()
        {
            var expression = new SnippetExpression("code");

            expression.CommentsAfter.Add("comment2");
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals("code /* comment2 */", result);
        }
        public void CSharpCodeGenerator_ExpressionCommentBefore()
        {
            var expression = new SnippetExpression("code");

            expression.CommentsBefore.Add("comment1");
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals("/* comment1 */ code", result);
        }
        public void CSharpCodeGenerator_ArrayIndexer_Multiple()
        {
            var        array      = new VariableReference("array");
            Expression expression = new ArrayIndexerExpression(array, 10, "test");

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals(@"array[10, ""test""]", result);
        }
        public void CSharpCodeGenerator_Assign()
        {
            var statement = new AssignStatement(new VariableReference("a"), 10);

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"a = 10;
", result);
        }
Ejemplo n.º 20
0
        public override string Generate()
        {
            var builder = CSharpCodeGeneratorBuilder.Instance;

            return(CSharpCodeGenerator
                   .AddFromGenerators(this, builder.TopLevelGenerators)
                   .AppendLine("}")
                   .AppendLine()
                   .ToString());
        }
        public void CSharpCodeGenerator_ExpressionStatement()
        {
            var statement = new ExpressionStatement(new NewObjectExpression(new TypeReference("Disposable")));

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"new Disposable();
", result);
        }
        public override async Task <KeyActions> InsertCompletionText(CompletionListWindow window, KeyActions ka, KeyDescriptor descriptor)
        {
            var  editor     = ext.Editor;
            bool isExplicit = false;
            //			if (member.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
            //				foreach (var m in type.Members) {
            //					if (m.Name == member.Name && !m.ReturnType.Equals (member.ReturnType)) {
            //						isExplicit = true;
            //						break;
            //					}
            //				}
            //			}
            //			var resolvedType = type.Resolve (ext.Project).GetDefinition ();
            //			if (ext.Project != null)
            //				generator.PolicyParent = ext.Project.Policies;

            var    result    = CSharpCodeGenerator.CreatePartialMemberImplementation(ext.DocumentContext, ext.Editor, currentType, currentType.Locations.First(), Symbol, isExplicit, factory.SemanticModel);
            string sb        = result.Code.TrimStart();
            int    trimStart = result.Code.Length - sb.Length;

            sb = sb.TrimEnd();

            var lastRegion = result.BodyRegions.LastOrDefault();
            var region     = lastRegion == null? null
                                : new CodeGeneratorBodyRegion(lastRegion.StartOffset - trimStart, lastRegion.EndOffset - trimStart);

            int targetCaretPosition;
            int selectionEndPosition = -1;

            if (region != null && region.IsValid)
            {
                targetCaretPosition = declarationBegin + region.EndOffset;
            }
            else
            {
                targetCaretPosition = declarationBegin + sb.Length;
            }

            editor.ReplaceText(declarationBegin, editor.CaretOffset - declarationBegin, sb);
            if (selectionEndPosition > 0)
            {
                editor.CaretOffset = selectionEndPosition;
                editor.SetSelection(targetCaretPosition, selectionEndPosition);
            }
            else
            {
                editor.CaretOffset = targetCaretPosition;
            }

            await OnTheFlyFormatter.Format(editor, ext.DocumentContext, declarationBegin, declarationBegin + sb.Length);

            editor.CaretLine--;
            return(ka);
        }
        public void CSharpCodeGenerator_Iteration_Empty()
        {
            var statement = new IterationStatement();
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"for (; ; )
{
}
", result);
        }
        public void CSharpCodeGenerator_ExpressionCommentBeforeWithInlineCommentEnd()
        {
            var expression = new SnippetExpression("code");

            expression.CommentsBefore.Add("comment with */ in the middle");
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(expression);

            Assert.That.StringEquals(@"// comment with */ in the middle
code", result);
        }
        public void CSharpCodeGenerator_CommentMultiLine()
        {
            var statement = new CommentStatement("test1" + Environment.NewLine + Environment.NewLine + "test2");
            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"// test1
//
// test2
", result);
        }
Ejemplo n.º 26
0
        public void SetUp()
        {
            var codeNamespace = new CodeNamespace(_sampleNamespace);
            var configuration = new CodeGeneratorParameters(_outputDirectory);
            // Todo: Mock this.
            var testBuilders = MemberBuilderFactory.Default;
            var buildSystem  = new FakeBuildSystem();

            _cSharpCodeGenerator =
                new CSharpCodeGenerator(buildSystem, codeNamespace, testBuilders, configuration);
        }
        public void CSharpCodeGenerator_InterfaceDeclaration()
        {
            var type = new InterfaceDeclaration("Sample");

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(type);

            Assert.That.StringEquals(@"interface Sample
{
}
", result);
        }
        public void CSharpCodeGenerator_RemoveEventHandler()
        {
            var statement = new RemoveEventHandlerStatement(
                new MemberReferenceExpression(new ThisExpression(), "A"),
                new MemberReferenceExpression(new ThisExpression(), "Handler"));

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"this.A -= this.Handler;
", result);
        }
Ejemplo n.º 29
0
        public void ApexTestAnnotationsConvertedToNUnitAttributes()
        {
            var annotation = new AnnotationSyntax {
                Identifier = ApexKeywords.IsTest
            };
            var attribute = CSharpCodeGenerator.ConvertUnitTestAnnotation(annotation, new ClassDeclarationSyntax());

            Assert.AreEqual("TestFixture", attribute.Identifier);

            attribute = CSharpCodeGenerator.ConvertUnitTestAnnotation(annotation, new MethodDeclarationSyntax());
            Assert.AreEqual("Test", attribute.Identifier);
        }
        public void CSharpCodeGenerator_Method_Abstract()
        {
            var method = new MethodDeclaration("Sample");

            method.Modifiers = Modifiers.Protected | Modifiers.Abstract;

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(method);

            Assert.That.StringEquals(@"protected abstract void Sample();
", result);
        }
Ejemplo n.º 31
0
        internal static MemoryFileSystem GenerateCodeInto(this string inputFile, MemoryFileSystem fileSystem )
        {
            fileSystem.Copy(Path.Combine("Resource", inputFile));

            var settings = new Settings
            {
                Modeler = "Swagger",
                CodeGenerator = "CSharp",
                FileSystem = fileSystem,
                OutputDirectory = "GeneratedCode",
                Input = inputFile,
            };

            var codeGenerator = new CSharpCodeGenerator(settings);
            Modeler modeler = ExtensionsLoader.GetModeler(settings);
            var sc = modeler.Build();
            codeGenerator.NormalizeClientModel(sc);
            codeGenerator.Generate(sc).GetAwaiter().GetResult();

            return fileSystem;
        }
Ejemplo n.º 32
0
        internal static MemoryFileSystem GenerateCodeInto(this string inputFile, MemoryFileSystem fileSystem, Settings settings)
        {
            string fileName = Path.GetFileName(inputFile);

            // If inputFile does not contain a path use the local Resource folder
            if (inputFile == fileName)
            {
                fileSystem.Copy(Path.Combine("Resource", inputFile));
            }
            else
            {
                fileSystem.Copy(inputFile);
            }

            settings.Input = fileName;

            var codeGenerator = new CSharpCodeGenerator(settings);
            var modeler = ExtensionsLoader.GetModeler(settings);
            var sc = modeler.Build();
            codeGenerator.NormalizeClientModel(sc);
            codeGenerator.Generate(sc).GetAwaiter().GetResult();

            return fileSystem;
        }
Ejemplo n.º 33
0
 public void SetUp()
 {
     var codeNamespace = new CodeNamespace(_sampleNamespace);
     var configuration = new CodeGeneratorParameters(_outputDirectory);
     // Todo: Mock this.
     var testBuilders = MemberBuilderFactory.Default;
     var buildSystem = new FakeBuildSystem();
     _cSharpCodeGenerator =
         new CSharpCodeGenerator(buildSystem, codeNamespace, testBuilders, configuration);
 }
Ejemplo n.º 34
0
        public void DecorateCodeGenerator_DesignTimeRazorPathNormalizer_NormalizesChunkInheritanceUtilityPaths(
            string rootPrefix)
        {
            // Arrange
            var rootedAppPath = $"{rootPrefix}SomeComputer/Location/Project/";
            var rootedFilePath = $"{rootPrefix}SomeComputer/Location/Project/src/file.cshtml";
            var chunkTreeCache = new DefaultChunkTreeCache(new TestFileProvider());
            using (var host = new MvcRazorHost(
                chunkTreeCache,
                pathNormalizer: new DesignTimeRazorPathNormalizer(rootedAppPath)))
            {
                var chunkInheritanceUtility = new PathValidatingChunkInheritanceUtility(host, chunkTreeCache);
                var codeGeneratorContext = new CodeGeneratorContext(
                    new ChunkGeneratorContext(
                        host,
                        host.DefaultClassName,
                        host.DefaultNamespace,
                        rootedFilePath,
                        shouldGenerateLinePragmas: true),
                    new ErrorSink());
                var codeGenerator = new CSharpCodeGenerator(codeGeneratorContext);
                host.ChunkInheritanceUtility = chunkInheritanceUtility;

                // Act
                host.DecorateCodeGenerator(codeGenerator, codeGeneratorContext);

                // Assert
                Assert.Equal("src/file.cshtml", chunkInheritanceUtility.InheritedChunkTreePagePath, StringComparer.Ordinal);
            }
        }
        public void SequenceWithRenamedComplexType()
        {
            var serviceClient = new ServiceClient();
            serviceClient.Name = "azure always rocks!";

            var complexType = new CompositeType();
            complexType.Name = "Greetings";

            serviceClient.Methods.Add(new Method
            {
                Name = "List",
                ReturnType = new SequenceType {ElementType = complexType }
            });

            serviceClient.Methods.Add(new Method
            {
                Name = "List2",
                ReturnType = new DictionaryType { ValueType = complexType }
            });

            serviceClient.ModelTypes.Add(complexType);

            var codeGenerator = new CSharpCodeGenerator(new Settings { Namespace = "Polar.Greetings" });
            codeGenerator.NormalizeClientModel(serviceClient);

            Assert.Equal("GreetingsModel", complexType.Name);
            Assert.Equal("IList<GreetingsModel>", serviceClient.Methods[0].ReturnType.Name);
            Assert.Equal("IDictionary<string, GreetingsModel>", serviceClient.Methods[1].ReturnType.Name);
        }
		static string GenerateMethodDeclaration (RefactoringOptions options, ExtractMethodParameters param)
		{
			StringBuilder methodText = new StringBuilder ();
			string indent = options.GetIndent (param.DeclaringMember);
			if (param.InsertionPoint != null) {
				switch (param.InsertionPoint.LineBefore) {
				case NewLineInsertion.Eol:
					methodText.AppendLine ();
					break;
				case NewLineInsertion.BlankLine:
					methodText.Append (indent);
					methodText.AppendLine ();
					break;
				}
			} else {
				methodText.AppendLine ();
				methodText.Append (indent);
				methodText.AppendLine ();
			}
			var codeGenerator = new CSharpCodeGenerator () {
				UseSpaceIndent = options.Document.Editor.Options.TabsToSpaces,
				EolMarker = options.Document.Editor.EolMarker,
				TabSize = options.Document.Editor.Options.TabSize
			};
			
			var newMethod = GenerateMethodStub (options, param);
			IType callingType = null;
			var cu = options.Document.CompilationUnit;
			if (cu != null)
				callingType = newMethod.DeclaringType = options.Document.CompilationUnit.GetTypeAt (options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column);
				
			var createdMethod = codeGenerator.CreateMemberImplementation (callingType, newMethod, false);

			if (param.GenerateComment && DocGenerator.Instance != null)
				methodText.AppendLine (DocGenerator.Instance.GenerateDocumentation (newMethod, indent + "/// "));
			string code = createdMethod.Code;
			int idx1 = code.LastIndexOf ("throw");
			int idx2 = code.LastIndexOf (";");
			methodText.Append (code.Substring (0, idx1));

			if (param.Nodes != null && (param.Nodes.Count == 1 && param.Nodes[0].NodeType == NodeType.Expression)) {
				methodText.Append ("return ");
				methodText.Append (param.Text.Trim ());
				methodText.Append (";");
			} else {
				StringBuilder text = new StringBuilder ();
				if (param.OneChangedVariable) {
					var par = param.Variables.First (p => p.IsDefinedInsideCutRegion && p.UsedAfterCutRegion);
					if (!par.UsedInCutRegion) {
						
						text.Append (new CSharpAmbience ().GetString (par.ReturnType, OutputFlags.ClassBrowserEntries));
						text.Append (" ");
						text.Append (par.Name);
						text.AppendLine (";");
					}
				}
				text.Append (param.Text);
				if (param.OneChangedVariable) {
					text.AppendLine ();
					text.Append ("return ");
					text.Append (param.Variables.First (p => p.IsDefinedInsideCutRegion && p.UsedAfterCutRegion).Name);
					text.Append (";");
				}
				methodText.Append (AddIndent (text.ToString (), indent + "\t"));
			}

			methodText.Append (code.Substring (idx2 + 1));
			if (param.InsertionPoint != null) {
				switch (param.InsertionPoint.LineAfter) {
				case NewLineInsertion.Eol:
					methodText.AppendLine ();
					break;
				case NewLineInsertion.BlankLine:
					methodText.AppendLine ();
					methodText.Append (indent);
					methodText.AppendLine ();
					break;
				case NewLineInsertion.None:
					methodText.AppendLine ();
					break;
				}
			} else {
				methodText.AppendLine ();
				methodText.Append (indent);
				methodText.AppendLine ();
			}
			return methodText.ToString ();
		}
Ejemplo n.º 37
0
 public void SetUp()
 {
     CodeNamespace codeNamespace = new CodeNamespace(_sampleNamespace);
     _cSharpCodeGenerator =
         new CSharpCodeGenerator(codeNamespace, _outputDirectory);
 }
Ejemplo n.º 38
0
        public void CreateCodeGenerator_PassesChunkGeneratorThroughDecorateMethodOnHost()
        {
            // Arrange
            var mockHost = new Mock<RazorEngineHost>(new CSharpRazorCodeLanguage()) { CallBase = true };
            var codeGeneratorContext = new CodeGeneratorContext(
                mockHost.Object,
                "different-class",
                "different-ns",
                string.Empty,
                shouldGenerateLinePragmas: true,
                errorSink: new ErrorSink());

            var expected = new CSharpCodeGenerator(codeGeneratorContext);

            mockHost
                .Setup(h => h.DecorateCodeGenerator(It.IsAny<CSharpCodeGenerator>(), codeGeneratorContext))
                .Returns(expected);
            var engine = new RazorTemplateEngine(mockHost.Object);

            // Act
            var actual = engine.CreateCodeGenerator(codeGeneratorContext);

            // Assert
            Assert.Equal(expected, actual);
        }