/// <summary>
        /// Writes the code to string in the specific language
        /// and returns the string
        /// </summary>
        public static string Create(Language language, string expression, RegexOptions options)
        {
            CodeCompileUnit unit = Create(expression, options);

            System.Text.StringBuilder builder = new System.Text.StringBuilder();

            using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(builder))
            {
                System.CodeDom.Compiler.ICodeGenerator generator;

                switch (language)
                {
                    case Language.CSharp:
                        System.CodeDom.Compiler.CodeGeneratorOptions genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions();
                        genOptions.BracingStyle = "C";
                        generator = new Microsoft.CSharp.CSharpCodeProvider().CreateGenerator();
                        generator.GenerateCodeFromCompileUnit(unit, stringWriter, genOptions);
                        break;
                    case Language.VisualBasic:
                        generator = new Microsoft.VisualBasic.VBCodeProvider().CreateGenerator();
                        generator.GenerateCodeFromCompileUnit(unit, stringWriter, null);
                        break;
                }

                return builder.ToString();
            }
        }
        public void Generate(IEnumerable <string> files)
        {
            var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f, new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Ignore
            }), (s, e) =>
            {
                Trace.TraceError(e.Message);
            }));

            foreach (var s in schemas)
            {
                Set.Add(s.TargetNamespace, s.SourceUri);
            }

            Set.Compile();

            BuildModel();

            var namespaces = GenerateCode();

            var provider = new Microsoft.CSharp.CSharpCodeProvider();

            var outputFolder = this.OutputFolder ?? ".";

            foreach (var ns in namespaces)
            {
                var compileUnit = new CodeCompileUnit();
                compileUnit.Namespaces.Add(ns);

                var title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
                                                                                  typeof(AssemblyTitleAttribute))).Title;
                var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

                ns.Comments.Add(new CodeCommentStatement(string.Format("This code was generated by {0} version {1}.", title, version)));

                using (StringWriter sw = new StringWriter())
                {
                    provider.GenerateCodeFromCompileUnit(compileUnit, sw, new CodeGeneratorOptions {
                        VerbatimOrder = true, BracingStyle = "C"
                    });
                    var s    = sw.ToString().Replace("};", "}"); // remove ';' at end of automatic properties
                    var path = Path.Combine(outputFolder, ns.Name + ".cs");
                    Log?.Invoke(path); File.WriteAllText(path, s);
                }
            }
        }
Beispiel #3
0
        public void Execute(
            CodeGenSettings config,
            List <EntityMetadata> entitMetadatas,
            Dictionary <string, PicklistAttributeMetadata> picklists,
            Dictionary <string, string> referencedEntities
            )
        {
            var provider             = new Microsoft.CSharp.CSharpCodeProvider();
            var codeGeneratorOptions = new CodeGeneratorOptions();

            var ns = CreateNameSpace(config.Namespace);

            foreach (var entitMetadata in entitMetadatas.OrderBy(p => p.SchemaName))
            {
                MakeEntity(entitMetadata, ns, picklists, referencedEntities);
            }

            var generatedOptionsets = new List <string>();

            foreach (var picklist in picklists.Values.OrderBy(p => p.LogicalName))
            {
                if (generatedOptionsets.Contains(picklist.OptionSet.Name))
                {
                    continue;
                }
                generatedOptionsets.Add(picklist.OptionSet.Name);
                MakOptionSet(picklist, ns);
            }

            var cu = new CodeCompileUnit();

            cu.Namespaces.Add(ns);

            codeGeneratorOptions.BlankLinesBetweenMembers = false;
            codeGeneratorOptions.BracingStyle             = "C";
            codeGeneratorOptions.IndentString             = "   ";

            var code         = new StringBuilder();
            var stringWriter = new StringWriter(code);

            provider.GenerateCodeFromCompileUnit(cu, stringWriter, codeGeneratorOptions);

            var result = code.ToString().Replace("PowerAppsWebApiUtils.Entities.", "");

            System.IO.File.WriteAllText(config.FileName, result);
        }
Beispiel #4
0
        static void ImportSchemas(XmlSchemaSet schemas)
        {
            Console.WriteLine("Now doing schema import.");
            // The following code demonstrates schema import with
            // a surrogate. The surrogate is used to indicate that
            // the Person class already exists and that there is no
            // need to generate a new class when importing the
            // PersonSurrogated data contract. If the surrogate
            // was not used, schema import would generate a
            // PersonSurrogated class, and the person field
            // of Employee would be imported as
            // PersonSurrogated and not Person.
            XsdDataContractImporter xsdimp = new XsdDataContractImporter();

            xsdimp.Options = new ImportOptions();
            xsdimp.Options.DataContractSurrogate = new LegacyPersonTypeSurrogate();
            xsdimp.Import(schemas);

            // Write out the imported schema to a C-Sharp file.
            // The code contains data contract types.
            FileStream fs4 = new FileStream("sample.cs", FileMode.Create);

            try
            {
                StreamWriter tw = new StreamWriter(fs4);
                Microsoft.CSharp.CSharpCodeProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();
                cdp.GenerateCodeFromCompileUnit(xsdimp.CodeCompileUnit, tw, null);
                tw.Flush();
            }
            finally
            {
                fs4.Dispose();
            }


            Console.WriteLine("\t  To see the results of schema export and import,");
            Console.WriteLine(" see SAMPLE.XSD and SAMPLE.CS.");

            Console.WriteLine(" Press ENTER to terminate the sample.");
            Console.ReadLine();
        }
Beispiel #5
0
        public void SaveAssembly(Diagram diagram, String path)
        {
            myassembly = new CodeCompileUnit();
            myassembly.Namespaces.Add(mynamespace);
            Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();

            String sourceFile;

            if (ccp.FileExtension[0] == '.')
            {
                sourceFile = diagram.className.Name + ccp.FileExtension;
            }
            else
            {
                sourceFile = diagram.className.Name + "." + ccp.FileExtension;
            }
            var tw1 = new IndentedTextWriter(new StreamWriter(Path.Combine(path, sourceFile), false), "    ");

            ccp.GenerateCodeFromCompileUnit(myassembly, tw1, new CodeGeneratorOptions());
            tw1.Close();
        }
        CodeCompileUnit ParseForm()
        {
            ParseInformation parseInfo = ParserService.ParseFile(this.Generator.ViewContent.DesignerCodeFile.FileName, this.Generator.ViewContent.DesignerCodeFileContent, false);
            Module           module    = ParseFormAsModule();

                        #if DEBUG
            Console.WriteLine(module.ToCodeString());
                        #endif

            CodeDomVisitor visitor = new CodeDomVisitor(parseInfo.MostRecentCompilationUnit.ProjectContent);
            module.Accept(visitor);

                        #if DEBUG
            // output generated CodeDOM to the console :
            ICSharpCode.NRefactory.Visitors.CodeDomVerboseOutputGenerator outputGenerator = new ICSharpCode.NRefactory.Visitors.CodeDomVerboseOutputGenerator();
            outputGenerator.GenerateCodeFromMember(visitor.OutputCompileUnit.Namespaces[0].Types[0], Console.Out, null);
            CodeDomProvider cSharpProvider = new Microsoft.CSharp.CSharpCodeProvider();
            cSharpProvider.GenerateCodeFromCompileUnit(visitor.OutputCompileUnit, Console.Out, null);
                        #endif

            return(visitor.OutputCompileUnit);
        }
		CodeCompileUnit ParseForm()
		{
			ParseInformation parseInfo = ParserService.ParseFile(this.Generator.ViewContent.DesignerCodeFile.FileName, this.Generator.ViewContent.DesignerCodeFileContent, false);
			Module module = ParseFormAsModule();
			
			#if DEBUG
			Console.WriteLine(module.ToCodeString());
			#endif
			
			CodeDomVisitor visitor = new CodeDomVisitor(parseInfo.MostRecentCompilationUnit.ProjectContent);
			module.Accept(visitor);
			
			#if DEBUG
			// output generated CodeDOM to the console :
			ICSharpCode.NRefactory.Visitors.CodeDomVerboseOutputGenerator outputGenerator = new ICSharpCode.NRefactory.Visitors.CodeDomVerboseOutputGenerator();
			outputGenerator.GenerateCodeFromMember(visitor.OutputCompileUnit.Namespaces[0].Types[0], Console.Out, null);
			CodeDomProvider cSharpProvider = new Microsoft.CSharp.CSharpCodeProvider();
			cSharpProvider.GenerateCodeFromCompileUnit(visitor.OutputCompileUnit, Console.Out, null);
			#endif
			
			return visitor.OutputCompileUnit;
		}
Beispiel #8
0
        /// <summary>
        /// Generates a C# designer class.
        /// </summary>
        /// <param name="resXFile">The source resx file.</param>
        /// <param name="className">The base class name.</param>
        /// <param name="namespaceName">The namespace for the generated code.</param>
        /// <param name="internalClass">Specifies if the class has internal or public access level.</param>
        /// <returns>false if generation of at least one property failed.</returns>
        public static bool GenerateDesignerFile(string resXFile, string className, string namespaceName, bool internalClass)
        {
            if (!File.Exists(resXFile))
            {
                throw new FileNotFoundException($"The file '{resXFile}' could not be found");
            }

            if (string.IsNullOrEmpty(className))
            {
                throw new ArgumentException($"The class name must not be empty or null");
            }

            if (string.IsNullOrEmpty(namespaceName))
            {
                throw new ArgumentException($"The namespace name must not be empty or null");
            }

            string[] unmatchedElements;
            var      codeProvider = new Microsoft.CSharp.CSharpCodeProvider();

            System.CodeDom.CodeCompileUnit code =
                System.Resources.Tools.StronglyTypedResourceBuilder.Create(
                    resXFile,
                    className,
                    namespaceName,
                    codeProvider,
                    internalClass,
                    out unmatchedElements);

            var designerFileName = Path.Combine(Path.GetDirectoryName(resXFile), $"{className}.Designer.cs");

            using (StreamWriter writer = new StreamWriter(designerFileName, false, System.Text.Encoding.UTF8))
            {
                codeProvider.GenerateCodeFromCompileUnit(code, writer, new System.CodeDom.Compiler.CodeGeneratorOptions());
            }

            return(unmatchedElements.Length == 0);
        }
		public static byte[] GenerateAssembly(string namespaceName, string className, params CodeMemberMethod[] methods)
		{
			CodeCompileUnit unit = new CodeCompileUnit();
			CodeNamespace space = new CodeNamespace(namespaceName);
			CodeTypeDeclaration type = new CodeTypeDeclaration(className);

			type.Attributes = MemberAttributes.Static | MemberAttributes.Public;
			type.TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed;

			type.Members.AddRange(methods);
			space.Types.Add(type);
			unit.Namespaces.Add(space);

			Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

			System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
			options.IncludeDebugInformation = false;
			options.GenerateExecutable = false;

			options.ReferencedAssemblies.Add(typeof(int).Assembly.Location);
			options.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location);

			System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromDom(options,unit);

			System.CodeDom.Compiler.CodeGeneratorOptions ops = new System.CodeDom.Compiler.CodeGeneratorOptions();
			ops.IndentString = "\t";
			ops.VerbatimOrder = true;
			ops.BracingStyle = "C";

			StringWriter text = new StringWriter();
			provider.GenerateCodeFromCompileUnit(unit, text, ops);
			string code = text.ToString();

			if (results.Errors.HasErrors)
			{
				string errors = "";
				foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
				{
					errors += error.ToString() + Environment.NewLine;
				}
				throw new InvalidOperationException(errors);
			}
			
			byte[] data = File.ReadAllBytes(results.PathToAssembly);
			File.Delete(results.PathToAssembly);
			return data;
		}
        public void Generate(string filepath, CompiledShaderReader reader)
        {
            string classname = Path.GetFileNameWithoutExtension(filepath);
            string outputfilename = Path.ChangeExtension(filepath, ".cs");

            CodeCompileUnit targetUnit = new CodeCompileUnit();

            CodeNamespace targetNamespace = new CodeNamespace("ShaderClasses");
            SetCommonImports(targetNamespace);

            CodeTypeDeclaration targetClass = new CodeTypeDeclaration(Path.GetFileNameWithoutExtension(filepath));
            targetClass.IsClass = true;
            targetClass.TypeAttributes = TypeAttributes.Public;

            CodeMemberMethod disposeMethod = ClassHelper.MakeDisposable(targetClass);

            if (reader.IsVertexShader)
            {

                //create a class to store vertex  information
                CodeTypeDeclaration vertexClass = new CodeTypeDeclaration(targetClass.Name + "_Vertex");
                vertexClass.IsStruct = true;

                //a list to store the codemembers that are vectors so we can write the serialization code
                List<CodeTypeMember> Vectors = new List<CodeTypeMember>(); // vectors are not serializable
                List<CodeTypeMember> OtherMembers = new List<CodeTypeMember>();

                //get the input parameters to build our Vertex type
                ShaderParameterDescription[] paramdesciptions = reader.GetParameterDescription();

                int sizeInBytes = 0;

                //test for SV_VertexID only
                if (paramdesciptions.All(a => a.SemanticName == "SV_VertexID"))
                {
                    //no buffer needed
                }
                else
                {
                    //add a the input layout field
                    CodeMemberField inputLayoutMemberField = new CodeMemberField("InputLayout", "inputLayout");
                    targetClass.Members.Add(inputLayoutMemberField);
                    ClassHelper.AddDisposalOfMember(disposeMethod, inputLayoutMemberField.Name);

                    //read the vertex input parameters
                    foreach (ShaderParameterDescription paramdesc in paramdesciptions)
                    {
                        string propertyname = new string(paramdesc.SemanticName.Take(1).ToArray()) + new string(paramdesc.SemanticName.ToLower().Skip(1).ToArray()) + paramdesc.SemanticIndex.ToString();//this may change if I find a better way to generate unique names that make sense
                        string fieldName = "_" + propertyname;

                        //NOTE: this contains the constructor code for all the fields as well

                        //Usage Mask was not set-up correctly in SharpDX so we need to mask it to get the expected results
                        //https://github.com/sharpdx/SharpDX/issues/565

                        int UsageMask = ((int)paramdesc.UsageMask) & (int)RegisterComponentMaskFlags.All;

                        CodeMemberField iFX = new CodeMemberField(typeof(float), fieldName + "_X");
                        iFX.UserData.Add("Type", "float");
                        iFX.UserData.Add("Name", fieldName + "_X");
                        CodeMemberProperty iFXProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_X",
                            Type = new CodeTypeReference(typeof(float)),
                            HasSet = false,
                            HasGet = true,

                        };
                        iFXProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iFX.Name)));
                        iFXProp.UserData.Add("Type", "int");
                        iFXProp.UserData.Add("Name", fieldName + "_X");

                        CodeMemberField iSX = new CodeMemberField(typeof(int), fieldName + "_X");
                        iSX.UserData.Add("Type", "int");
                        iSX.UserData.Add("Name", fieldName + "_X");
                        CodeMemberProperty iSXProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_X",
                            Type = new CodeTypeReference(typeof(int)),
                            HasSet = false,
                            HasGet = true
                        };
                        iSXProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iSX.Name)));
                        iSXProp.UserData.Add("Type", "int");
                        iSXProp.UserData.Add("Name", fieldName + "_X");

                        CodeMemberField iSY = new CodeMemberField(typeof(int), fieldName + "_Y");
                        iSY.UserData.Add("Type", "int");
                        iSY.UserData.Add("Name", fieldName + "_Y");
                        CodeMemberProperty iSYProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_Y",
                            Type = new CodeTypeReference(typeof(int)),
                            HasSet = false,
                            HasGet = true
                        };
                        iSYProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iSY.Name)));
                        iSYProp.UserData.Add("Type", "int");
                        iSYProp.UserData.Add("Name", fieldName + "_Y");

                        CodeMemberField iSZ = new CodeMemberField(typeof(int), fieldName + "_Z");
                        iSZ.UserData.Add("Type", "int");
                        iSZ.UserData.Add("Name", fieldName + "_Z");
                        CodeMemberProperty iSZProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_Z",
                            Type = new CodeTypeReference(typeof(int)),
                            HasSet = false,
                            HasGet = true
                        };
                        iSZProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iSZ.Name)));
                        iSZProp.UserData.Add("Type", "int");
                        iSZProp.UserData.Add("Name", fieldName + "_Z");

                        CodeMemberField iSW = new CodeMemberField(typeof(int), fieldName + "_W");
                        iSW.UserData.Add("Type", "int");
                        iSW.UserData.Add("Name", fieldName + "_W");
                        CodeMemberProperty iSWProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_W",
                            Type = new CodeTypeReference(typeof(int)),
                            HasSet = false,
                            HasGet = true
                        };
                        iSWProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iSW.Name)));
                        iSWProp.UserData.Add("Type", "int");
                        iSWProp.UserData.Add("Name", fieldName + "_W");

                        CodeMemberField iUX = new CodeMemberField(typeof(uint), fieldName + "_X");
                        iUX.UserData.Add("Type", "uint");
                        iUX.UserData.Add("Name", fieldName + "_X");
                        CodeMemberProperty iUXProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_X",
                            Type = new CodeTypeReference(typeof(uint)),
                            HasSet = false,
                            HasGet = true
                        };
                        iUXProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iUX.Name)));
                        iUXProp.UserData.Add("Type", "uint");
                        iUXProp.UserData.Add("Name", fieldName + "_X");

                        CodeMemberField iUY = new CodeMemberField(typeof(uint), fieldName + "_Y");
                        iUY.UserData.Add("Type", "uint");
                        iUY.UserData.Add("Name", fieldName + "_Y");
                        CodeMemberProperty iUYProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_Y",
                            Type = new CodeTypeReference(typeof(uint)),
                            HasSet = false,
                            HasGet = true
                        };
                        iUYProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iUY.Name)));
                        iUYProp.UserData.Add("Type", "uint");
                        iUYProp.UserData.Add("Name", fieldName + "_Y");

                        CodeMemberField iUZ = new CodeMemberField(typeof(uint), fieldName + "_Z");
                        iUZ.UserData.Add("Type", "uint");
                        iUZ.UserData.Add("Name", fieldName + "_Z");
                        CodeMemberProperty iUZProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_Z",
                            Type = new CodeTypeReference(typeof(uint)),
                            HasSet = false,
                            HasGet = true
                        };
                        iUZProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iUZ.Name)));
                        iUZProp.UserData.Add("Type", "uint");
                        iUZProp.UserData.Add("Name", fieldName + "_Z");

                        CodeMemberField iUW = new CodeMemberField(typeof(uint), fieldName + "_W");
                        iUW.UserData.Add("Type", "uint");
                        iUW.UserData.Add("Name", fieldName + "_W");
                        CodeMemberProperty iUWProp = new CodeMemberProperty()
                        {
                            Attributes = MemberAttributes.Public | MemberAttributes.Final,//final removes the virtual attribute
                            Name = propertyname + "_W",
                            Type = new CodeTypeReference(typeof(uint)),
                            HasSet = false,
                            HasGet = true
                        };
                        iUWProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, iUW.Name)));
                        iUWProp.UserData.Add("Type", "uint");
                        iUWProp.UserData.Add("Name", fieldName + "_W");

                        switch (UsageMask)
                        {
                            case (int)RegisterComponentMaskFlags.ComponentX:

                                switch (paramdesc.ComponentType)
                                {
                                    case RegisterComponentType.Float32:
                                        vertexClass.Members.Add(iFX);
                                        vertexClass.Members.Add(iFXProp);
                                        sizeInBytes += 4;

                                        OtherMembers.Add(iFX);
                                        break;
                                    case RegisterComponentType.SInt32:
                                        vertexClass.Members.Add(iSX);
                                        vertexClass.Members.Add(iSXProp);
                                        sizeInBytes += 4;
                                        OtherMembers.Add(iSX);
                                        break;
                                    case RegisterComponentType.UInt32:
                                        vertexClass.Members.Add(iUX);
                                        vertexClass.Members.Add(iUXProp);
                                        sizeInBytes += 4;
                                        OtherMembers.Add(iUX);
                                        break;
                                    case RegisterComponentType.Unknown:
                                    default:
                                        break;
                                }
                                break;
                            case (int)(RegisterComponentMaskFlags.ComponentX | RegisterComponentMaskFlags.ComponentY):

                                switch (paramdesc.ComponentType)
                                {
                                    case RegisterComponentType.Float32:
                                        CodeMemberField vector = new CodeMemberField("Vector2", fieldName);
                                        vector.UserData.Add("Type", "Vector2");
                                        vector.UserData.Add("Name", fieldName);

                                        CodeMemberProperty vectorProp = new CodeMemberProperty()
                                        {
                                            Attributes = MemberAttributes.Public | MemberAttributes.Final,
                                            Name = propertyname,
                                            Type = new CodeTypeReference(typeof(Vector2)),
                                            HasGet = true,
                                            HasSet = false,

                                        };
                                        vectorProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, fieldName)));
                                        vectorProp.UserData.Add("Type", "Vector2");
                                        vectorProp.UserData.Add("Name", fieldName);

                                        vertexClass.Members.Add(vector);
                                        vertexClass.Members.Add(vectorProp);
                                        sizeInBytes += 8;

                                        Vectors.Add(vector);

                                        break;
                                    case RegisterComponentType.SInt32:
                                        vertexClass.Members.Add(iSX);
                                        vertexClass.Members.Add(iSXProp);

                                        vertexClass.Members.Add(iSY);
                                        vertexClass.Members.Add(iSYProp);
                                        sizeInBytes += 8;

                                        OtherMembers.Add(iSX);
                                        OtherMembers.Add(iSY);

                                        break;
                                    case RegisterComponentType.UInt32:
                                        vertexClass.Members.Add(iUX);
                                        vertexClass.Members.Add(iUXProp);

                                        vertexClass.Members.Add(iUY);
                                        vertexClass.Members.Add(iUYProp);
                                        sizeInBytes += 8;

                                        OtherMembers.Add(iUX);
                                        OtherMembers.Add(iUY);

                                        break;
                                    case RegisterComponentType.Unknown:
                                    default:
                                        break;
                                }
                                break;
                            case (int)(RegisterComponentMaskFlags.ComponentX | RegisterComponentMaskFlags.ComponentY | RegisterComponentMaskFlags.ComponentZ):
                                switch (paramdesc.ComponentType)
                                {
                                    case RegisterComponentType.Float32:
                                        CodeMemberField vector = new CodeMemberField("Vector3", fieldName);
                                        vector.UserData.Add("Type", "Vector3");
                                        vector.UserData.Add("Name", fieldName);

                                        CodeMemberProperty vectorProp = new CodeMemberProperty()
                                        {
                                            Attributes = MemberAttributes.Public | MemberAttributes.Final,
                                            Name = propertyname,
                                            Type = new CodeTypeReference(typeof(Vector3)),
                                            HasGet = true,
                                            HasSet = false,

                                        };
                                        vectorProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, fieldName)));
                                        vectorProp.UserData.Add("Type", "Vector3");
                                        vectorProp.UserData.Add("Name", fieldName);

                                        vertexClass.Members.Add(vector);
                                        vertexClass.Members.Add(vectorProp);
                                        sizeInBytes += 12;

                                        Vectors.Add(vector);
                                        break;
                                    case RegisterComponentType.SInt32:
                                        vertexClass.Members.Add(iSX);
                                        vertexClass.Members.Add(iSY);
                                        vertexClass.Members.Add(iSZ);

                                        vertexClass.Members.Add(iSXProp);
                                        vertexClass.Members.Add(iSYProp);
                                        vertexClass.Members.Add(iSZProp);

                                        sizeInBytes += 12;

                                        OtherMembers.Add(iSX);
                                        OtherMembers.Add(iSY);
                                        OtherMembers.Add(iSZ);
                                        break;
                                    case RegisterComponentType.UInt32:
                                        vertexClass.Members.Add(iUX);
                                        vertexClass.Members.Add(iUY);
                                        vertexClass.Members.Add(iUZ);

                                        vertexClass.Members.Add(iUXProp);
                                        vertexClass.Members.Add(iUYProp);
                                        vertexClass.Members.Add(iUZProp);

                                        sizeInBytes += 12;

                                        OtherMembers.Add(iUX);
                                        OtherMembers.Add(iUY);
                                        OtherMembers.Add(iUZ);
                                        break;
                                    case RegisterComponentType.Unknown:
                                    default:
                                        break;
                                }
                                break;
                            case (int)RegisterComponentMaskFlags.All:
                                switch (paramdesc.ComponentType)
                                {
                                    case RegisterComponentType.Float32:
                                        CodeMemberField vector = new CodeMemberField("Vector4", fieldName);
                                        vector.UserData.Add("Type", "Vector4");
                                        vector.UserData.Add("Name", fieldName);

                                        CodeMemberProperty vectorProp = new CodeMemberProperty()
                                        {
                                            Attributes = MemberAttributes.Public | MemberAttributes.Final,
                                            Name = propertyname,
                                            Type = new CodeTypeReference(typeof(Vector4)),
                                            HasGet = true,
                                            HasSet = false,

                                        };
                                        vectorProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, fieldName)));
                                        vectorProp.UserData.Add("Type", "Vector4");
                                        vectorProp.UserData.Add("Name", fieldName);

                                        vertexClass.Members.Add(vector);
                                        vertexClass.Members.Add(vectorProp);
                                        sizeInBytes += 16;

                                        Vectors.Add(vector);
                                        break;
                                    case RegisterComponentType.SInt32:
                                        vertexClass.Members.Add(iSX);
                                        vertexClass.Members.Add(iSY);
                                        vertexClass.Members.Add(iSZ);
                                        vertexClass.Members.Add(iSW);

                                        vertexClass.Members.Add(iSXProp);
                                        vertexClass.Members.Add(iSYProp);
                                        vertexClass.Members.Add(iSZProp);
                                        vertexClass.Members.Add(iSWProp);

                                        sizeInBytes += 16;

                                        OtherMembers.Add(iSX);
                                        OtherMembers.Add(iSY);
                                        OtherMembers.Add(iSZ);
                                        OtherMembers.Add(iSW);
                                        break;
                                    case RegisterComponentType.UInt32:
                                        vertexClass.Members.Add(iUX);
                                        vertexClass.Members.Add(iUY);
                                        vertexClass.Members.Add(iUZ);
                                        vertexClass.Members.Add(iUW);

                                        vertexClass.Members.Add(iUXProp);
                                        vertexClass.Members.Add(iUYProp);
                                        vertexClass.Members.Add(iUZProp);
                                        vertexClass.Members.Add(iUWProp);

                                        sizeInBytes += 16;

                                        OtherMembers.Add(iUX);
                                        OtherMembers.Add(iUY);
                                        OtherMembers.Add(iUZ);
                                        OtherMembers.Add(iUW);
                                        break;
                                    case RegisterComponentType.Unknown:
                                    default://not sure what to do here
                                        break;
                                }
                                break;
                            case (int)RegisterComponentMaskFlags.None:
                            default://not sure what to do here
                                break;
                        }

                    }

                    //calculate size of input struct and add attributes
                    vertexClass.CustomAttributes = new CodeAttributeDeclarationCollection(
                        new CodeAttributeDeclaration[]
                    {
                        new CodeAttributeDeclaration("Serializable"),
                        new CodeAttributeDeclaration("StructLayout",new CodeAttributeArgument[]
                        {
                            new CodeAttributeArgument(new CodeSnippetExpression("LayoutKind.Sequential")),
                            new CodeAttributeArgument("Size",new CodeSnippetExpression(sizeInBytes.ToString()))//this will need normalized to a multiple of 16(BYTE)
                        }),
                    });

                    //build serialization method
                    if (Vectors.Count > 0)
                    {

                        ClassHelper.MakeSerilizable(vertexClass);

                    }

                    //generate Equality code
                    ClassHelper.GenerateEqualityCode(vertexClass);

                    //add input type to namespace
                    targetNamespace.Types.Add(vertexClass);
                }

            }

            //add constant buffer classes

            CodeTypeDeclaration[] cBufferClasses = ClassHelper.GenerateConstantBufferClasses(reader.GetConsttantBuffers());
            targetNamespace.Types.AddRange(cBufferClasses);

            //add samplers to the shaderclass

            //add directX objects

            //add the correct Shader class

            string shaderName = "NULL";
            switch (reader.TypePrefix)
            {
                case "vs":
                    {
                        shaderName = "vertexShader";
                        targetClass.Members.Add(new CodeMemberField(vertexShaderRef, shaderName));

                        break;
                    }
                case "ps":
                    {
                        shaderName = "pixelShader";
                        targetClass.Members.Add(new CodeMemberField(pixelShaderRef, shaderName));

                        break;
                    }
                case "ds":
                    {
                        shaderName = "domainShader";
                        targetClass.Members.Add(new CodeMemberField(domainShaderRef, shaderName));

                        break;
                    }
                case "hs":
                    {
                        shaderName = "hullShader";
                        targetClass.Members.Add(new CodeMemberField(hullShaderRef, shaderName));

                        break;
                    }
                case "gs":
                    {
                        shaderName = "geometryShader";
                        targetClass.Members.Add(new CodeMemberField(geometryShaderRef, shaderName));
                        break;
                    }

            }

            if (shaderName != "NULL")
            {
                ClassHelper.AddDisposalOfMember(disposeMethod, shaderName);
            }
            else throw new Exception("unrecognized Shader prefix. check the shader profile in the reader code");

            foreach (CodeTypeDeclaration cbuffer in cBufferClasses)
            {
                string bufferName = cbuffer.Name.ToLower() + "Buffer";

                targetClass.Members.Add(new CodeMemberField(bufferRef, bufferName));

                ClassHelper.AddDisposalOfMember(disposeMethod, bufferName);
            }

            //add buffer assignment methods

            //add others

            //add dispose method
            targetClass.Members.Add(disposeMethod);

            //wrap up /////////////////////////////////////////////////////////////////////////////////////////////////////
            targetNamespace.Types.Add(targetClass);

            targetUnit.Namespaces.Add(targetNamespace);

            using (Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BracingStyle = "C";

                using (StreamWriter sourceWriter = new StreamWriter(outputfilename))
                {
                    codeProvider.GenerateCodeFromCompileUnit(
                        targetUnit, sourceWriter, options);
                }
            }
        }
Beispiel #11
0
        private static void GenerateCode(Options options)
        {
            var packageTransform = new NMF.Models.Meta.Meta2ClassesTransformation();
            var stopWatch = new Stopwatch();

            packageTransform.ForceGeneration = options.Force;
            packageTransform.CreateOperations = options.Operations;
            packageTransform.DefaultNamespace = options.OverallNamespace;

            Dictionary<Uri, string> mappings = null;
            if (options.NamespaceMappings != null && options.NamespaceMappings.Count > 0)
            {
                mappings = new Dictionary<Uri, string>();
                foreach (var mapping in options.NamespaceMappings)
                {
                    if (string.IsNullOrEmpty(mapping)) continue;
                    var lastIdx = mapping.LastIndexOf('=');
                    if (lastIdx == -1)
                    {
                        Console.WriteLine("Namespace mapping {0} is missing required separator =", mapping);
                        continue;
                    }
                    Uri uri;
                    if (!Uri.TryCreate(mapping.Substring(0, lastIdx), UriKind.Absolute, out uri))
                    {
                        uri = new Uri(mapping.Substring(0, lastIdx), UriKind.Relative);
                    }
                    mappings.Add(uri, mapping.Substring(lastIdx + 1));
                }
            }

            var metaPackage = LoadPackageFromFiles(options.InputFiles, options.OverallNamespace, mappings);
            if (options.Uri != null)
            {
                Uri uri;
                if (Uri.TryCreate(options.Uri, UriKind.Absolute, out uri))
                {
                    metaPackage.Uri = uri;
                }
                else
                {
                    Console.Error.WriteLine("The provided string {0} could not be parsed as an absolute URI.", options.Uri);
                }
            }
            if (metaPackage.Uri == null)
            {
                Console.Error.WriteLine("Warning: There is no base Uri for the provided metamodels. Some features of the generated code will be disabled.");
            }

            var model = metaPackage.Model;
            if (model == null)
            {
                model = new Model();
                model.RootElements.Add(metaPackage);
            }
            model.ModelUri = metaPackage.Uri;
            if (options.NMeta != null)
            {
                using (var fs = File.Create(options.NMeta))
                {
                    MetaRepository.Instance.Serializer.Serialize(model, fs);
                }
            }

            stopWatch.Start();
            var compileUnit = TransformationEngine.Transform<INamespace, CodeCompileUnit>(metaPackage,
                options.Parallel
                   ? (ITransformationEngineContext)new ParallelTransformationContext(packageTransform)
                   : new TransformationContext(packageTransform));
            stopWatch.Stop();

            Console.WriteLine("Operation took {0}ms", stopWatch.Elapsed.TotalMilliseconds);

            CodeDomProvider generator = null;

            switch (options.Language)
            {
                case SupportedLanguage.CS:
                    generator = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
                case SupportedLanguage.VB:
                    generator = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                case SupportedLanguage.CPP:
                    generator = new Microsoft.VisualC.CppCodeProvider();
                    break;
                case SupportedLanguage.JS:
                    generator = new Microsoft.JScript.JScriptCodeProvider();
                    break;
                default:
                    Console.WriteLine("Unknown language detected. Falling back to default C#");
                    generator = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
            }

            var genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions()
                {
                    BlankLinesBetweenMembers = true,
                    VerbatimOrder = false,
                    ElseOnClosing = false,
                    BracingStyle = "C",
                    IndentString = "    "
                };
            if (options.UseFolders)
            {
                foreach (var file in MetaFacade.SplitCompileUnit(compileUnit))
                {
                    var fileInfo = new FileInfo(Path.Combine(options.OutputFile, file.Key) + "." + generator.FileExtension);
                    CheckDirectoryExists(fileInfo.Directory);
                    using (var fs = fileInfo.Create())
                    {
                        using (var sw = new StreamWriter(fs))
                        {
                            generator.GenerateCodeFromCompileUnit(file.Value, sw, genOptions);
                        }
                    }
                }
            }
            else
            {
                using (var sw = new StreamWriter(options.OutputFile))
                {
                    generator.GenerateCodeFromCompileUnit(compileUnit, sw, genOptions);
                }
            }

            Console.WriteLine("Code generated successfully!");
        }
Beispiel #12
0
        public void WriteCode(string mainFileName, string stubFileName)
        {
            Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Writing code to {0} and {1}", mainFileName, stubFileName));
            string mainTempFile = Path.GetTempFileName();
            string stubTempFile = Path.GetTempFileName();

            try
            {
                using (CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
                {
                    StreamWriter mainFileWriter = null;
                    try
                    {
                        mainFileWriter = new StreamWriter(mainTempFile);
                        using (IndentedTextWriter mainFileTextWriter = new IndentedTextWriter(mainFileWriter, "    "))
                        {
                            mainFileWriter = null;
                            CodeGeneratorOptions cgo = new CodeGeneratorOptions();
                            cgo.BracingStyle = "C";
                            cgo.IndentString = IndentString;
                            try
                            {
                                provider.GenerateCodeFromCompileUnit(this.mainCcu, mainFileTextWriter, cgo);
                            }
                            catch (ArgumentException ae)
                            {
                                Regex r = new Regex(@"Invalid Primitive Type: (?<DataType>\S+). Consider using CodeObjectCreateExpression.");
                                Match m = r.Match(ae.Message);
                                if (m.Success)
                                {
                                    throw new UserException(string.Format(CultureInfo.CurrentCulture, Messages.UTGenerator_TypeNotSupported, m.Result("${DataType}")));
                                }
                                else
                                {
                                    throw;
                                }
                            }

                            mainFileTextWriter.Close();
                        }
                    }
                    finally
                    {
                        if (mainFileWriter != null)
                        {
                            mainFileWriter.Dispose();
                        }
                    }

                    // Any namespaces in the main class to be copied across to the stub as they will be needed there too.
                    foreach (CodeNamespaceImport n in this.mainTestNamespace.Imports)
                    {
                        this.stubTestNamespace.Imports.Add(n);
                    }

                    StreamWriter stubFileWriter = null;
                    try
                    {
                        stubFileWriter = new StreamWriter(stubTempFile);
                        using (IndentedTextWriter stubTextFileWriter = new IndentedTextWriter(stubFileWriter, "    "))
                        {
                            stubFileWriter = null;
                            CodeGeneratorOptions cgo = new CodeGeneratorOptions();
                            cgo.BracingStyle = "C";
                            provider.GenerateCodeFromCompileUnit(this.stubCcu, stubTextFileWriter, cgo);
                            stubTextFileWriter.Close();
                        }
                    }
                    finally
                    {
                        if (stubFileWriter != null)
                        {
                            stubFileWriter.Dispose();
                        }
                    }

                    File.Copy(mainTempFile, mainFileName, true);
                    File.Copy(stubTempFile, stubFileName, true);
                }
            }
            finally
            {
                File.Delete(mainTempFile);
                File.Delete(stubTempFile);
            }

            Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Completed writing code to {0} and {1}", mainFileName, stubFileName));
        }
Beispiel #13
0
        static void Main3()
        {
            CodeMemberMethod Calc = new CodeMemberMethod()
            {
                Name = "Calc",
                Attributes = MemberAttributes.Public | MemberAttributes.Static
            };

            Calc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "x"));

            Calc.Statements.Add(
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeArgumentReferenceExpression("x"), CodeBinaryOperatorType.LessThanOrEqual,
                        new CodeSnippetExpression("1")
                    ),
                    new CodeMethodReturnStatement(new CodeSnippetExpression("1"))
                )
            );

            Calc.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeMethodInvokeExpression(null, "Calc",
                            new CodeBinaryOperatorExpression(
                                new CodeArgumentReferenceExpression("x"), CodeBinaryOperatorType.Subtract,
                                new CodeSnippetExpression("1")
                            )
                        ), CodeBinaryOperatorType.Add,
                        new CodeMethodInvokeExpression(null, "Calc",
                            new CodeBinaryOperatorExpression(
                                new CodeArgumentReferenceExpression("x"), CodeBinaryOperatorType.Subtract,
                                new CodeSnippetExpression("2")
                            )
                        )
                    )
                )
            );

            CodeTypeDeclaration Fibonacci = new CodeTypeDeclaration();
            Fibonacci.Members.Add(Calc);

            CodeNamespace ns = new CodeNamespace("TestNS");
            ns.Types.Add(Fibonacci);

            CodeCompileUnit unit = new CodeCompileUnit();
            unit.Namespaces.Add(ns);

            using (TextWriter tw = new IndentedTextWriter(Console.Out))
            {
                using (CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider())
                {
                    codeProvider.GenerateCodeFromCompileUnit(unit, tw, new CodeGeneratorOptions());
                }
            }
        }
Beispiel #14
0
        private static void writeSource(string outputFile, CodeCompileUnit cu)
        {
            Microsoft.CSharp.CSharpCodeProvider csp = new Microsoft.CSharp.CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            options.BlankLinesBetweenMembers = false;

            using (StreamWriter writer = new StreamWriter(outputFile, false))
            {
                csp.GenerateCodeFromCompileUnit(cu, writer, options);
            }
        }
Beispiel #15
0
        // Emit byte code for the expression tree owned by this root.
        // Accepts the compiler parameters that were given to PieCodeProvider
        // since it will be needed for the CSharpCodeProvider.
        public CompilerResults Emit(CompilerParameters compilerParams, Root root)
        {
            // Emit the code compile unit, the top of the codedom tree.
            // This method will cal emit method for all child expressions
            // until all expressions have had byte code emitted.
            var codeCompileUnit = RootEmitter.Emit(root);

            // Create the C# compiler.
            var csProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";

            // Compile the codedom tree into an assembly
            var sw = new StringWriter();
            csProvider.GenerateCodeFromCompileUnit(codeCompileUnit, sw, options);

            // Display the C# code for debugging purposes.
            string ccode = sw.GetStringBuilder().ToString();
            Console.WriteLine(ccode);

            // Get the results of the compilation: the assembly and error list
            CompilerResults results = csProvider.CompileAssemblyFromSource(compilerParams, ccode);

            // Store all C# compiler errors, so that they can be included with Pie compiler errors..
            foreach (CompilerError e in root.CompilerErrors)
                results.Errors.Add(e);
            root.CompilerErrors.Clear();

            return results;
        }
Beispiel #16
0
        private void generateResourceMenuItem_Click(object sender, EventArgs e)
        {
            Point origStart = GetOriginalXY(selStartMousePos);
            Point origEnd   = GetOriginalXY(selEndMousePos);

            if (selStartMousePos.X != 0 || selStartMousePos.Y != 0)
            {
                int       top    = origStart.Y < origEnd.Y ? origStart.Y : origEnd.Y;
                int       left   = origStart.X < origEnd.X ? origStart.X : origEnd.X;
                int       width  = Math.Abs(origEnd.X - origStart.X);
                int       height = Math.Abs(origEnd.Y - origStart.Y);
                Rectangle box    = new Rectangle(left, top, width, height);
                Bitmap    bitmap = ((Bitmap)image).Clone(box, ((Bitmap)image).PixelFormat);

                if (Statics.DTE.Solution.IsOpen)
                {
                    foreach (EnvDTE.Project proj in Statics.DTE.Solution.Projects)
                    {
                        if (proj.Name.Contains("Test"))
                        {
                            try
                            {
                                ImageInputForm inputForm = new ImageInputForm();
                                inputForm.ShowDialog();

                                Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                                string resFile       = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.resx";
                                string resDesginFile = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.Designer.cs";
                                System.Resources.ResXResourceReader reader = new System.Resources.ResXResourceReader(resFile);
                                using (System.Resources.ResXResourceWriter writer = new System.Resources.ResXResourceWriter(resFile + ".new"))
                                {
                                    System.Collections.IDictionaryEnumerator iterator = reader.GetEnumerator();
                                    while (iterator.MoveNext())
                                    {
                                        writer.AddResource(iterator.Key.ToString(), iterator.Value);
                                    }
                                    writer.AddResource(inputForm.Input, bitmap);
                                    writer.Generate();
                                }
                                File.Copy(resFile + ".new", resFile, true);
                                File.Delete(resFile + ".new");
                                string[] unMatched;
                                System.CodeDom.CodeCompileUnit unit = System.Resources.Tools.StronglyTypedResourceBuilder.Create(resFile, "Resources",
                                                                                                                                 proj.Properties.Item("DefaultNamespace").Value + ".Properties",
                                                                                                                                 codeProvider,
                                                                                                                                 true, out unMatched);
                                using (StreamWriter designWriter = new StreamWriter(resDesginFile))
                                {
                                    codeProvider.GenerateCodeFromCompileUnit(unit, designWriter,
                                                                             new System.CodeDom.Compiler.CodeGeneratorOptions());
                                }
                                MessageBox.Show("Image generation succeeded", "Resources Updated");
                                return;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Image generation failed\n" + ex.Message, "Resources Did Not Update");
                            }
                        }
                    }
                    MessageBox.Show("You need to have a project open, named *Test*", "Resources Did Not Update");
                    return;
                }
                MessageBox.Show("You need to have a solution open with a project named *Test*", "Resources Did Not Update");
                return;
            }
        }
        private void SaveAssembly(string Path)
        {
            //Create a new object of the global CodeCompileUnit class.
            myassembly = new CodeCompileUnit();
            //Add the namespace to the assembly.
            myassembly.Namespaces.Add(mynamespace);
            //Add the following compiler parameters. (The references to the //standard .net dll(s) and framework library).
            CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll" });
            comparam.ReferencedAssemblies.Add("System.dll");
            comparam.ReferencedAssemblies.Add("System.Core.dll");
            comparam.ReferencedAssemblies.Add("System.Data.dll");
            comparam.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
            comparam.ReferencedAssemblies.Add("System.Xml.dll");
            comparam.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            comparam.ReferencedAssemblies.Add("System.Core.dll");
            //comparam.ReferencedAssemblies.Add("System.Collections.Generic.dll");
            comparam.ReferencedAssemblies.Add("Driver.dll");
            comparam.ReferencedAssemblies.Add("SupportLibrary.dll");
            comparam.ReferencedAssemblies.Add("log4net.dll");
            //Indicates Whether the compiler has to generate the output in //memory
            comparam.GenerateInMemory = false;
            //Indicates whether the output is an executable.
            comparam.GenerateExecutable = true;
            //provide the name of the class which contains the Main Entry //point method
            comparam.MainClass = "mynamespace.myclass";
            //provide the path where the generated assembly would be placed
            comparam.OutputAssembly = @Path;
            //Create an instance of the c# compiler and pass the assembly to //compile
            Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();

            //Build to cs file

            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            using (StreamWriter sourceWriter = new StreamWriter( @"release.cs"))
            {
                ccp.GenerateCodeFromCompileUnit(
                myassembly, sourceWriter, options);
            }

            ICodeCompiler icc = ccp.CreateCompiler();
            ////The CompileAssemblyFromDom would either return the list of
            ////compile time errors (if any), or would create the
            ////assembly in the respective path in case of successful //compilation
            CompilerResults compres = icc.CompileAssemblyFromDom(comparam, myassembly);
            if (compres == null || compres.Errors.Count > 0)
            {
                for (int i = 0; i < compres.Errors.Count; i++)
                {
                    //Console.WriteLine(compres.Errors[i]);
                    MessageShow.Writelog("CCodeGenerator.cs::", compres.Errors[i].ToString());
                }
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage:\n\t{0} <idl file>", Path.GetFileName(Environment.GetCommandLineArgs()[0]));
                return;
            }

            string in_filename = args[0];
            if (!File.Exists(in_filename))
            {
                Console.WriteLine("{0} not exists.", in_filename);
                return;
            }
            string out_filename = Path.ChangeExtension(in_filename, ".cs");

            try
            {
                string idl = File.ReadAllText(in_filename);
                if (idl == null || idl.Length == 0)
                {
                    Console.WriteLine("Fail reading input file.");
                    return;
                }

                MatchCollection r;

                #region Process include
                //while (ProcessInclude(ref idl)) { }
                #endregion
                #region Prepare mapping hash table
                Dictionary<string, string> type_def_table = new Dictionary<string, string>();
                Dictionary<string, string> type_mapping_table = new Dictionary<string, string>();
                type_mapping_table.Add("int", "int");
                type_mapping_table.Add("short", "short");
                type_mapping_table.Add("long", "int");
                type_mapping_table.Add("double", "double");
                type_mapping_table.Add("LONGLONG", "Int64");
                type_mapping_table.Add("unsigned long", "uint");
                type_mapping_table.Add("unsigned char", "byte");
                type_mapping_table.Add("void", "IntPtr");
                type_mapping_table.Add("HRESULT", "int");
                type_mapping_table.Add("BOOL", "bool");
                type_mapping_table.Add("bool", "bool");
                type_mapping_table.Add("BSTR", "string");
                type_mapping_table.Add("interface", "interface");
                type_mapping_table.Add("enum", "enum");
                #endregion

                StreamWriter w = new StreamWriter(out_filename, false);
                w.WriteLine("// Auto generated by idl2cs /(c) toki, 2009/ @ {0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                w.WriteLine("using System;");
                w.WriteLine("using System.Collections.Generic;");
                w.WriteLine("using System.Text;");
                w.WriteLine("using System.Runtime.InteropServices;");
                w.WriteLine("");
                w.WriteLine("namespace {0}\n{{", Path.GetFileNameWithoutExtension(in_filename));

            #if USE_DOM
                StreamWriter code_writer = new StreamWriter(Path.ChangeExtension(out_filename, ".code.cs"), false);
                CodeCompileUnit code_root = new CodeCompileUnit();
                CodeNamespace code_imports = new CodeNamespace();
                code_root.Namespaces.Add(code_imports);
                code_imports.Comments.Add(new CodeCommentStatement(String.Format("Auto generated by idl2cs /(c) toki, 2009/ @ {0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"))));
                code_imports.Imports.Add(new CodeNamespaceImport("System"));
                code_imports.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
                code_imports.Imports.Add(new CodeNamespaceImport("System.Text"));
                code_imports.Imports.Add(new CodeNamespaceImport("System.Runtime.InteropServices"));
                CodeNamespace code = new CodeNamespace(Path.GetFileNameWithoutExtension(in_filename));
                code_root.Namespaces.Add(code);

                CodeTypeDeclaration test_enum = new CodeTypeDeclaration("BMDTestEnum");
                test_enum.IsEnum = true;
                CodeMemberField mt = new CodeMemberField("", "TEST03");
                mt.InitExpression = new CodePrimitiveExpression(0xFFFF);
                test_enum.Members.Add(new CodeMemberField("", "TEST01"));
                test_enum.Members.Add(new CodeMemberField("", "TEST02"));
                test_enum.Members.Add(mt);

                code.Types.Add(test_enum);
            #endif
                r = null;

                #region typedef
                Console.WriteLine("Process typedef ...");
                r = find_typedef.Matches(idl);

                foreach (Match m in r)
                {
                    try
                    {
                        string key = m.Groups["key"].Value;
                        string value = m.Groups["value"].Value;
                        //Console.WriteLine("Adding: {0} => {1}", key, value);

                        if (type_def_table.ContainsKey(key))
                        {
                            if (value.StartsWith("enum "))
                            {
                                type_def_table.Remove(key);
                                type_def_table.Add(key, "enum");
                                type_def_table.Add(value.Substring(5).Trim(), key);
                            }
                        }
                        else
                        {
                            type_def_table.Add(m.Groups["key"].Value, m.Groups["value"].Value);
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Error when add: {0} => {1}", m.Groups["key"].Value, m.Groups["value"].Value);
                    }
                }

                foreach (KeyValuePair<string, string> p in type_def_table)
                {
                    Console.WriteLine("\t{0} => {1}", p.Key, p.Value);
                }
                Console.WriteLine("Total {0} typedef processed.", r.Count);
                #endregion

                #region enum
                Console.WriteLine("Process enum ...");
                r = find_enum.Matches(idl);

                w.Write("#region enum");
                foreach (Match m in r)
                {
                    string enum_name = m.Groups["name2"].Value.Trim() == String.Empty ? m.Groups["name1"].Value.Trim() : m.Groups["name2"].Value.Trim();
                    string def_name;
                    type_def_table.TryGetValue(enum_name, out def_name);

                    if (!String.IsNullOrEmpty(def_name))
                        enum_name = def_name;

                    Console.WriteLine("\t{0}", enum_name);

                    w.WriteLine();
                    if (enum_name.EndsWith("s"))
                    {
                        w.WriteLine("// idl2cs warning: possible flag enum\n[Flags]");
                    }
                    w.WriteLine("public enum {0}\n{{{1}}}", enum_name, m.Groups["body"].Value);
                    if (!type_def_table.ContainsKey(enum_name))
                        type_def_table.Add(enum_name, "enum");
                }
                w.WriteLine("#endregion");
                Console.WriteLine("Total {0} enum processed.", r.Count);
                #endregion

                #region coclass
                Console.WriteLine("Process coclass ...");
            //                r = find_coclass.Matches(idl);
                w.Write("\n#region coclass");

                   while (true)
                    {
                        Match m = find_coclass.Match(idl);

                        if (!m.Success)
                            break;

                        w.WriteLine();
                        string cc_name = m.Groups["name"].Value.Trim();
                        string cc_attr = m.Groups["attr"].Value.Trim();
                        string cc_declear = m.Groups["declear"].Value.Trim();
                        string cc_uuid = string.Empty;

                        Console.WriteLine("\tProcess coclass {0}", cc_name);

                        Match mm = null;
                        mm = find_helpstring.Match(cc_attr);
                        if (mm.Success)
                            w.WriteLine("/// <summary>\n/// {0}\n/// </summary>", mm.Groups["value"].Value);

                        mm = null;
                        mm = find_uuid.Match(cc_attr);
                        if (mm.Success)
                        {
                            cc_uuid = mm.Groups["value"].Value;
                            w.WriteLine(@"[ComImport, Guid(""{0}"")]", cc_uuid);
                        }

                        w.WriteLine("public class {0}\n{{\n/*\nidl2cs warning: edit this block for helper\n{1}\n*/\n}}", cc_name, cc_declear);

                        idl = idl.Remove(m.Captures[0].Index, m.Captures[0].Length);
                    }

                //foreach (Match m in r)
                //{
                //    w.WriteLine();
                //    string cc_name = m.Groups["name"].Value.Trim();
                //    string cc_attr = m.Groups["attr"].Value.Trim();
                //    string cc_declear = m.Groups["declear"].Value.Trim();
                //    string cc_uuid = string.Empty;

                //    Console.WriteLine("\tProcess coclass {0}", cc_name);

                //    Match mm = null;
                //    mm = find_helpstring.Match(cc_attr);
                //    if (mm.Success)
                //        w.WriteLine("/// <summary>\n/// {0}\n/// </summary>", mm.Groups["value"].Value);

                //    mm = null;
                //    mm = find_uuid.Match(cc_attr);
                //    if (mm.Success)
                //    {
                //        cc_uuid = mm.Groups["value"].Value;
                //        w.WriteLine(@"[ComImport, Guid(""{0}"")]", cc_uuid);
                //    }

                //    w.WriteLine("public class {0}\n{{\n/*\nidl2cs warning: edit this block for helper\n{1}\n*/\n}}", cc_name, cc_declear);

                //    idl = idl.Remove(m.Captures[0].Index, m.Captures[0].Length);
                //}

                w.WriteLine("#endregion");
                Console.WriteLine("Total {0} coclass processed.", r.Count);
                #endregion

                #region pre-scan interrface
                Console.WriteLine("Pre-scan interface ...");
                r = find_interface.Matches(idl);
                foreach (Match m in r)
                {
                    string interface_name = m.Groups["name"].Value.Trim();

                    if (!type_def_table.ContainsKey(interface_name))
                    {
                        type_def_table.Add(interface_name, "interface");
                        Console.WriteLine("\tAdd {0} to def hash table.", interface_name);
                    }
                }
                Console.WriteLine("Total {0} interface scanned.", r.Count);
                #endregion

                #region interface
                Console.WriteLine("Process interface ...");
                r = find_interface.Matches(idl);

                w.Write("\n#region interface");
                foreach (Match m in r)
                {
                    string interface_name = m.Groups["name"].Value.Trim();
                    string interface_type = m.Groups["type"].Value.Trim();
                    string interface_comtype = interface_type == "IDispatch" ? "InterfaceIsIDispatch" : "InterfaceIsIUnknown";
                    string interface_attr = m.Groups["attr"].Value.Trim();
                    Console.WriteLine("\tProcess interface: {0} => type: {1}", interface_name, interface_type);

                    Match uuid;
                    uuid = find_uuid.Match(interface_attr);
                    Match helpstring;
                    helpstring = find_helpstring.Match(interface_attr);

                    w.WriteLine();
                    w.WriteLine("/// <summary>\n/// {0}\n/// </summary>", helpstring.Groups["value"].Value);
                    w.WriteLine(@"[ComImport, Guid(""{0}""), InterfaceType(ComInterfaceType.{1})]", uuid.Groups["value"].Value, interface_comtype);
                    if (interface_type == "IUnknown" || interface_type == "IDispatch")
                        w.WriteLine("public interface {0}\n{{", interface_name);
                    else
                        w.WriteLine("public interface {0} : {1}\n{{", interface_name, interface_type);

                    if (!type_def_table.ContainsKey(interface_name))
                        type_def_table.Add(interface_name, "interface");

                    MatchCollection rr = find_function.Matches(m.Groups["function"].Value);
                    foreach (Match mm in rr)
                    {
                        string func_type = mm.Groups["func_type"].Value.Trim();
                        string func_name = mm.Groups["func_name"].Value.Trim();
                        //Console.WriteLine("\t{0} {1}", func_type, func_name);

                        string func_native_type = string.Empty;
                        if (!type_mapping_table.TryGetValue(func_type, out func_native_type))
                            if (!type_def_table.TryGetValue(func_type, out func_native_type))
                            {
                                Console.WriteLine("[warning] unable to mapping {0} to c# native type.", func_type);
                                w.WriteLine("// idl2cs warning: unmapped type: {0}", func_type);
                            }

                        if (!type_mapping_table.ContainsValue(func_native_type))
                        {
                            if (!type_mapping_table.TryGetValue(func_native_type, out func_native_type))
                            {
                                Console.WriteLine("[warning] unable to mapping {0} to c# native type.", func_native_type);
                                w.WriteLine("// idl2cs warning: unmapped type: {0}", func_native_type);
                            }
                        }

                        if (!string.IsNullOrEmpty(func_native_type) && func_native_type != "enum")
                            func_type = func_native_type;

                        string func_paras = string.Empty;

                        if (mm.Groups["func_para"].Value.Trim() != "void")
                        {
                            string[] paras = mm.Groups["func_para"].Value.Split(new char[] { ',' });

                            for (int i = 0; i < paras.Length; i++)
                            {
                                string pa = paras[i].Trim();
                                string para_attr;

                                //Console.WriteLine(pa);

                                Match ma = find_func_attr.Match(pa.Trim());
                                string[] pa_split = null;
                                if (ma.Success)
                                {
                                    para_attr = ma.Groups["attr"].Value;
                                    pa_split = ma.Groups["para"].Value.Trim().Split();
                                }
                                else
                                {
                                    para_attr = string.Empty;
                                    pa_split = pa.Split();
                                }

                                if (pa_split.Length < 2)
                                    continue;

                                int j = pa_split.Length - 1;

                                string para_type = string.Empty;
                                string para_native_type = string.Empty;
                                string para_name = pa_split[j];
                                int para_ptr_count = 0;

                                foreach (char c in para_name)
                                {
                                    if (c == '*')
                                        para_ptr_count++;
                                    else
                                        break;
                                }

                                j--;
                                para_type = pa_split[j];

                                if (para_ptr_count != 0)
                                {
                                    para_name = para_name.Substring(para_ptr_count);
                                }
                                else
                                {
                                    for (int ii = para_type.Length - 1; ii != 0; ii--)
                                    {
                                        if (para_type[ii] == '*')
                                            para_ptr_count++;
                                        else
                                            break;
                                    }

                                    if (para_ptr_count != 0)
                                    {
                                        para_type = para_type.Substring(0, para_type.Length - para_ptr_count);
                                    }
                                }

                                j--;
                                while (j >= 0)
                                {
                                    para_type = pa_split[j] + " " + para_type;
                                    j--;
                                }

                                if (!type_mapping_table.TryGetValue(para_type, out para_native_type))
                                    if (!type_def_table.TryGetValue(para_type, out para_native_type))
                                    {
                                        Console.WriteLine("[warning] unable to mapping {0} to c# natvie type.", para_type);
                                        w.WriteLine("// idl2cs warning: unmapped type: {0}", para_type);
                                    }

                                if (!type_mapping_table.ContainsValue(para_native_type))
                                {
                                    if (!type_mapping_table.TryGetValue(para_native_type, out para_native_type))
                                    {
                                        Console.WriteLine("[warning] unable to mapping {0} to c# native type.", para_native_type);
                                        w.WriteLine("// idl2cs warning: unmapped type: {0}", para_native_type);
                                    }
                                }

                                string final_para = string.Empty;
                                bool is_out = false;
                                switch (para_attr)
                                {
                                    case "in":
                                        final_para += "[In";
                                        break;
                                    case "out":
                                        final_para += "[Out";
                                        is_out = true;
                                        break;
                                    default:
                                        break;
                                }

                                if (final_para != string.Empty)
                                {
                                    if (para_type == "BSTR")
                                        final_para += ", MarshalAs(UnmanagedType.BStr)";

                                    final_para += "] ";
                                }

                                switch (para_ptr_count)
                                {
                                    case 0:
                                        goto normal_final_para_type;
                                    case 1:
                                        if (!is_out)
                                        {
                                            if (para_native_type == "interface")
                                                final_para += para_type + " ";
                                            else if (para_type == "void")
                                                final_para += para_native_type + " ";
                                            else
                                                Console.WriteLine("[warning] {0}/{1}* with [In] attr in {2}:{3}",
                                                              para_type, para_native_type,
                                                              interface_name, func_name);

                                            goto after_normal_final_para_type;
                                        }
                                        else
                                        {
                                            final_para += "out ";
                                            goto normal_final_para_type;
                                        }
                                    case 2:
                                        if (is_out)
                                        {
                                            if (para_native_type == "interface")
                                            {
                                                final_para += string.Format("out {0} ", para_type);
                                                goto after_normal_final_para_type;
                                            }
                                            else if (para_type == "void")
                                            {
                                                final_para += string.Format("out {0} ", para_native_type);
                                                goto after_normal_final_para_type;
                                            }
                                        }
                                        Console.WriteLine("[warning] {0}/{1}** in {2}:{3}",
                                                      para_type, para_native_type,
                                                      interface_name, func_name);
                                        goto after_normal_final_para_type;
                                    default:
                                        break;
                                }

                            normal_final_para_type:
                                if (para_native_type == "interface" || para_native_type == "enum")
                                    final_para += para_type + " ";
                                else
                                    final_para += para_native_type + " ";

                            after_normal_final_para_type:
                                final_para += para_name;
                                //Console.WriteLine(final_para);

                                func_paras += final_para + ", ";
                            }
                        }

                        if (!string.IsNullOrEmpty(func_paras))
                            func_paras = func_paras.Substring(0, func_paras.Length - 2);

                        w.WriteLine("\t[PreserveSig]\n\t{0} {1} ({2});", func_type, func_name, func_paras);
                    }
                    w.WriteLine("}}", interface_name);
                }
                w.WriteLine("#endregion");
                Console.WriteLine("Total {0} interface processed.", r.Count);
                #endregion

                w.WriteLine("}");
                w.Close();

            #if USE_DOM
                Microsoft.CSharp.CSharpCodeProvider code_provider = new Microsoft.CSharp.CSharpCodeProvider();
                CodeGeneratorOptions code_opts = new CodeGeneratorOptions();
                code_opts.BlankLinesBetweenMembers = false;
                code_opts.VerbatimOrder = true;
                code_opts.BracingStyle = "C";
                code_provider.GenerateCodeFromCompileUnit(code_root, code_writer, code_opts);
                code_writer.Close();
            #endif
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return;
            }

            #if AUTO_DUMP_OUTPUT
            Console.WriteLine("\nDumping output file: {0}\n", out_filename);
            StreamReader o = new StreamReader(out_filename);
            while (!o.EndOfStream)
            {
                Console.WriteLine(o.ReadLine());
            }
            o.Close();
            #endif
        }
        private static void OutputGeneratedCode(CodeCompileUnit compileUnit)
        {
            Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();

            using (MemoryStream stream = new MemoryStream())
            using (TextWriter textWriter = new StreamWriter(stream))
            {
                codeProvider.GenerateCodeFromCompileUnit(compileUnit, textWriter, new System.CodeDom.Compiler.CodeGeneratorOptions());

                textWriter.Flush();

                stream.Seek(0, SeekOrigin.Begin);

                using (StreamReader reader = new StreamReader(stream))
                {
                    string output = reader.ReadToEnd();

                    //Trace.WriteLine(output);
                }
            }
        }
Beispiel #20
0
        private void OutputGeneratedCode(CodeCompileUnit compileUnit)
        {
            CodeDomProvider generator = null;

            switch (options.Language)
            {
            case SupportedLanguage.CS:
                generator = new Microsoft.CSharp.CSharpCodeProvider();
                break;

            case SupportedLanguage.VB:
                generator = new Microsoft.VisualBasic.VBCodeProvider();
                break;

            case SupportedLanguage.CPP:
                generator = new Microsoft.VisualC.CppCodeProvider();
                break;

            case SupportedLanguage.JS:
                generator = new Microsoft.JScript.JScriptCodeProvider();
                break;

            case SupportedLanguage.PY:
                generator = new PythonProvider();
                break;

            default:
                Console.WriteLine("Unknown language detected. Falling back to default C#");
                generator = new Microsoft.CSharp.CSharpCodeProvider();
                break;
            }

            var genOptions = new CodeGeneratorOptions()
            {
                BlankLinesBetweenMembers = true,
                VerbatimOrder            = false,
                ElseOnClosing            = false,
                BracingStyle             = "C",
                IndentString             = "    "
            };

            if (options.UseFolders)
            {
                foreach (var file in MetaFacade.SplitCompileUnit(compileUnit))
                {
                    var fileInfo = new FileInfo(Path.Combine(options.OutputFile, file.Key) + "." + generator.FileExtension);
                    CheckDirectoryExists(fileInfo.Directory);
                    using (var sw = new StreamWriter(fileInfo.Create()))
                    {
                        generator.GenerateCodeFromCompileUnit(file.Value, sw, genOptions);
                    }
                }
            }
            else
            {
                using (var sw = new StreamWriter(options.OutputFile))
                {
                    generator.GenerateCodeFromCompileUnit(compileUnit, sw, genOptions);
                }
            }
        }
Beispiel #21
0
        static void Main()
        {
            Inventory store1 = new Inventory();

            store1.pencils = 5;
            store1.pens    = 10;
            store1.paper   = 15;
            DataContractSerializer surrogateDcs =
                new DataContractSerializer(typeof(Inventory), null, int.MaxValue, false, false, new InventoryTypeSurrogate());

            // Plug in the surrogate in order to use the serializer.
            Console.WriteLine("Plug in a surrogate for the Inventory class\n");
            StringWriter sw2 = new StringWriter();
            XmlWriter    xw2 = XmlWriter.Create(sw2);

            try
            {
                surrogateDcs.WriteObject(xw2, store1);
            }
            catch (InvalidDataContractException)
            {
                Console.WriteLine(" We should never get here");
            }
            xw2.Flush();
            sw2.Flush();
            Console.Write(sw2.ToString());
            Console.WriteLine("\n\n Serialization succeeded. Now doing deserialization...\n");

            StringReader tr       = new StringReader(sw2.ToString());
            XmlReader    xr       = XmlReader.Create(tr);
            Inventory    newstore = (Inventory)surrogateDcs.ReadObject(xr);

            Console.Write("Deserialized Inventory data: \nPens:" + newstore.pens + "\nPencils: " + newstore.pencils + "\nPaper: " + newstore.paper);

            Console.WriteLine("\n\n Deserialization succeeded. Now doing schema export/import...\n");

            //The following code demonstrates schema export with a surrogate.
            //The surrogate indicates how to export the non-DataContract Inventory type.
            //Without the surrogate, schema export would fail.
            XsdDataContractExporter xsdexp = new XsdDataContractExporter();

            xsdexp.Options = new ExportOptions();
            xsdexp.Options.DataContractSurrogate = new InventoryTypeSurrogate();
            try
            {
                xsdexp.Export(typeof(Inventory));
            }
            catch (Exception) { }

            //Write out exported schema to a file
            using (FileStream fs = new FileStream("sample.xsd", FileMode.Create))
            {
                foreach (XmlSchema sch in xsdexp.Schemas.Schemas())
                {
                    sch.Write(fs);
                }
            }

            //The following code demonstrates schema import with a surrogate.
            //The surrogate is used to indicate that the Inventory class already exists
            //and that there is no need to generate a new class when importing the
            //"InventorySurrogated" data contract.

            XsdDataContractImporter xsdimp = new XsdDataContractImporter();

            xsdimp.Options = new ImportOptions();
            xsdimp.Options.DataContractSurrogate = new InventoryTypeSurrogate();
            xsdimp.Import(xsdexp.Schemas);

            //Write out the imported schema to a C-Sharp file
            using (FileStream fs = new FileStream("sample.cs", FileMode.Create))
            {
                TextWriter      tw  = new StreamWriter(fs);
                CodeDomProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();
                cdp.GenerateCodeFromCompileUnit(xsdimp.CodeCompileUnit, tw, null);
                tw.Flush();
            }

            Console.WriteLine("\n\n To see the results of schema export and import,");
            Console.WriteLine(" see SAMPLE.XSD and SAMPLE.CS.\n");

            Console.WriteLine(" Press ENTER to terminate the sample.\n");
            Console.ReadLine();
        }
        public void Generate(IEnumerable<string> files)
        {
            var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore }), (s, e) =>
            {
                Trace.TraceError(e.Message);
            }));

            foreach (var s in schemas)
            {
                Set.Add(s);
            }

            Set.Compile();

            BuildModel();

            var namespaces = GenerateCode();

            var provider = new Microsoft.CSharp.CSharpCodeProvider();

            foreach (var ns in namespaces)
            {
                var compileUnit = new CodeCompileUnit();
                compileUnit.Namespaces.Add(ns);

                var title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
                    typeof(AssemblyTitleAttribute))).Title;
                var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

                ns.Comments.Add(new CodeCommentStatement(string.Format("This code was generated by {0} version {1}.", title, version)));

                using (StringWriter sw = new StringWriter())
                {
                    provider.GenerateCodeFromCompileUnit(compileUnit, sw, new CodeGeneratorOptions { VerbatimOrder = true, BracingStyle = "C" });
                    var s = sw.ToString().Replace("};", "}"); // remove ';' at end of automatic properties
                    var path = Path.Combine(OutputFolder, ns.Name + ".cs");
                    if (Log != null) Log(path);
                    File.WriteAllText(path, s);
                }
            }
        }
Beispiel #23
0
        private static void GenerateCode(Options options)
        {
            var packageTransform = new NMF.Models.Meta.Meta2ClassesTransformation();
            var stopWatch        = new Stopwatch();

            packageTransform.ForceGeneration  = options.Force;
            packageTransform.CreateOperations = options.Operations;
            packageTransform.DefaultNamespace = options.OverallNamespace;

            Dictionary <Uri, string> mappings = null;

            if (options.NamespaceMappings != null && options.NamespaceMappings.Count > 0)
            {
                mappings = new Dictionary <Uri, string>();
                foreach (var mapping in options.NamespaceMappings)
                {
                    if (string.IsNullOrEmpty(mapping))
                    {
                        continue;
                    }
                    var lastIdx = mapping.LastIndexOf('=');
                    if (lastIdx == -1)
                    {
                        Console.WriteLine("Namespace mapping {0} is missing required separator =", mapping);
                        continue;
                    }
                    Uri uri;
                    if (!Uri.TryCreate(mapping.Substring(0, lastIdx), UriKind.Absolute, out uri))
                    {
                        uri = new Uri(mapping.Substring(0, lastIdx), UriKind.Relative);
                    }
                    mappings.Add(uri, mapping.Substring(lastIdx + 1));
                }
            }

            var metaPackage = LoadPackageFromFiles(options.InputFiles, options.OverallNamespace, mappings);

            if (options.Uri != null)
            {
                Uri uri;
                if (Uri.TryCreate(options.Uri, UriKind.Absolute, out uri))
                {
                    metaPackage.Uri = uri;
                }
                else
                {
                    Console.Error.WriteLine("The provided string {0} could not be parsed as an absolute URI.", options.Uri);
                }
            }
            if (metaPackage.Uri == null)
            {
                Console.Error.WriteLine("Warning: There is no base Uri for the provided metamodels. Some features of the generated code will be disabled.");
            }

            var model = metaPackage.Model;

            if (model == null)
            {
                model = new Model();
                model.RootElements.Add(metaPackage);
            }
            model.ModelUri = metaPackage.Uri;
            if (options.NMeta != null)
            {
                using (var fs = File.Create(options.NMeta))
                {
                    MetaRepository.Instance.Serializer.Serialize(model, fs);
                }
            }

            stopWatch.Start();
            var compileUnit = TransformationEngine.Transform <INamespace, CodeCompileUnit>(metaPackage,
                                                                                           options.Parallel
                   ? (ITransformationEngineContext) new ParallelTransformationContext(packageTransform)
                   : new TransformationContext(packageTransform));

            stopWatch.Stop();

            Console.WriteLine("Operation took {0}ms", stopWatch.Elapsed.TotalMilliseconds);

            CodeDomProvider generator = null;

            switch (options.Language)
            {
            case SupportedLanguage.CS:
                generator = new Microsoft.CSharp.CSharpCodeProvider();
                break;

            case SupportedLanguage.VB:
                generator = new Microsoft.VisualBasic.VBCodeProvider();
                break;

            case SupportedLanguage.CPP:
                generator = new Microsoft.VisualC.CppCodeProvider();
                break;

            case SupportedLanguage.JS:
                generator = new Microsoft.JScript.JScriptCodeProvider();
                break;

            default:
                Console.WriteLine("Unknown language detected. Falling back to default C#");
                generator = new Microsoft.CSharp.CSharpCodeProvider();
                break;
            }

            var genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions()
            {
                BlankLinesBetweenMembers = true,
                VerbatimOrder            = false,
                ElseOnClosing            = false,
                BracingStyle             = "C",
                IndentString             = "    "
            };

            if (options.UseFolders)
            {
                foreach (var file in MetaFacade.SplitCompileUnit(compileUnit))
                {
                    var fileInfo = new FileInfo(Path.Combine(options.OutputFile, file.Key) + "." + generator.FileExtension);
                    CheckDirectoryExists(fileInfo.Directory);
                    using (var fs = fileInfo.Create())
                    {
                        using (var sw = new StreamWriter(fs))
                        {
                            generator.GenerateCodeFromCompileUnit(file.Value, sw, genOptions);
                        }
                    }
                }
            }
            else
            {
                using (var sw = new StreamWriter(options.OutputFile))
                {
                    generator.GenerateCodeFromCompileUnit(compileUnit, sw, genOptions);
                }
            }

            Console.WriteLine("Code generated successfully!");
        }
        public void Generate(IEnumerable <string> names, string targetDirectory)
        {
            CodeNamespaceImportCollection imports = new CodeNamespaceImportCollection();

            // Generate the ILibiMobileDevice interface
            CodeTypeDeclaration interfaceType = new CodeTypeDeclaration();

            interfaceType.Name        = "ILibiMobileDevice";
            interfaceType.IsInterface = true;

            foreach (var name in names)
            {
                interfaceType.Members.Add(
                    new CodeMemberProperty()
                {
                    Name   = name,
                    Type   = new CodeTypeReference($"I{name}Api"),
                    HasGet = true
                });

                imports.Add(new CodeNamespaceImport($"iMobileDevice.{name}"));
            }

            // Generate the interface implementation
            CodeTypeDeclaration classType = new CodeTypeDeclaration();

            classType.Name = "LibiMobileDevice";
            classType.BaseTypes.Add("ILibiMobileDevice");

            var constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            classType.Members.Add(constructor);

            var instanceField = new CodeMemberField();

            instanceField.Attributes     = MemberAttributes.Static;
            instanceField.Name           = "instance";
            instanceField.Type           = new CodeTypeReference("ILibiMobileDevice");
            instanceField.InitExpression =
                new CodeObjectCreateExpression(
                    new CodeTypeReference("LibiMobileDevice"));
            classType.Members.Add(instanceField);

            var instanceProperty = new CodeMemberProperty();

            instanceProperty.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            instanceProperty.Name       = "Instance";
            instanceProperty.HasGet     = true;
            instanceProperty.Type       = new CodeTypeReference("ILibiMobileDevice");

            instanceProperty.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeTypeReferenceExpression("LibiMobileDevice"),
                        "instance")));

            instanceProperty.SetStatements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(
                        new CodeTypeReferenceExpression("LibiMobileDevice"),
                        "instance"),
                    new CodeArgumentReferenceExpression("value")));

            classType.Members.Add(instanceProperty);

            foreach (var name in names)
            {
                string camelCased = null;

                if (name[0] != 'i')
                {
                    camelCased = char.ToLower(name[0]) + name.Substring(1);
                }
                else
                {
                    camelCased = "i" + char.ToLower(name[1]) + name.Substring(2);
                }

                // Add the backing field
                classType.Members.Add(
                    new CodeMemberField()
                {
                    Name = camelCased,
                    Type = new CodeTypeReference($"I{name}Api")
                });

                // Add the property + getter
                var property =
                    new CodeMemberProperty()
                {
                    Name       = name,
                    Type       = new CodeTypeReference($"I{name}Api"),
                    HasGet     = true,
                    HasSet     = true,
                    Attributes = MemberAttributes.Public
                };
                property.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            camelCased)));
                property.SetStatements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            camelCased),
                        new CodeArgumentReferenceExpression("value")));
                classType.Members.Add(property);

                constructor.Statements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            camelCased),
                        new CodeObjectCreateExpression(
                            new CodeTypeReference($"{name}Api"),
                            new CodeThisReferenceExpression())));
            }

            // Add the LibraryFound property
            var libraryFoundInterfaceProperty = new CodeMemberProperty();

            libraryFoundInterfaceProperty.Name   = "LibraryFound";
            libraryFoundInterfaceProperty.Type   = new CodeTypeReference(typeof(bool));
            libraryFoundInterfaceProperty.HasGet = true;
            interfaceType.Members.Add(libraryFoundInterfaceProperty);

            var libraryFoundClassProperty = new CodeMemberProperty();

            libraryFoundClassProperty.Name       = "LibraryFound";
            libraryFoundClassProperty.Attributes = MemberAttributes.Public;
            libraryFoundClassProperty.Type       = new CodeTypeReference(typeof(bool));
            libraryFoundClassProperty.HasGet     = true;
            libraryFoundClassProperty.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodePropertyReferenceExpression(
                        new CodeTypeReferenceExpression("NativeLibraries"),
                        "LibraryFound")));
            classType.Members.Add(libraryFoundClassProperty);

            foreach (var type in new CodeTypeDeclaration[] { interfaceType, classType })
            {
                // Generate the container unit
                CodeCompileUnit program = new CodeCompileUnit();

                // Generate the namespace
                CodeNamespace ns = new CodeNamespace($"iMobileDevice");
                ns.Imports.AddRange(imports.OfType <CodeNamespaceImport>().ToArray());
                ns.Types.Add(type);
                program.Namespaces.Add(ns);

                string path = Path.Combine(targetDirectory, $"{type.Name}.cs");

                using (var outFile = File.Open(path, FileMode.Create))
                    using (var fileWriter = new StreamWriter(outFile))
                        using (var indentedTextWriter = new IndentedTextWriter(fileWriter, "    "))
                        {
                            // Generate source code using the code provider.
                            var provider = new Microsoft.CSharp.CSharpCodeProvider();
                            provider.GenerateCodeFromCompileUnit(
                                program,
                                indentedTextWriter,
                                new CodeGeneratorOptions()
                            {
                                BracingStyle = "C"
                            });
                        }
            }
        }
Beispiel #25
0
        private static void GenerateCode(Options options)
        {
            var packageTransform = new NMF.Models.Meta.Meta2ClassesTransformation();
            var stopWatch = new Stopwatch();

            packageTransform.ForceGeneration = options.Force;
            packageTransform.CreateOperations = options.Operations;
            packageTransform.DefaultNamespace = options.OverallNamespace;

            var metaPackage = LoadPackageFromFiles(options.InputFiles, options.OverallNamespace);

            var model = metaPackage.Model;
            if (model == null)
            {
                model = new Model();
                model.RootElements.Add(metaPackage);
            }
            model.ModelUri = metaPackage.Uri;
            if (options.NMeta != null)
            {
                using (var fs = File.OpenWrite(options.NMeta))
                {
                    MetaRepository.Instance.Serializer.Serialize(model, fs);
                }
            }

            stopWatch.Start();
            var compileUnit = TransformationEngine.Transform<INamespace, CodeCompileUnit>(metaPackage, 
                options.Parallel
                   ? (ITransformationEngineContext)new ParallelTransformationContext(packageTransform)
                   : new TransformationContext(packageTransform));
            stopWatch.Stop();

            Console.WriteLine("Operation took {0}ms", stopWatch.Elapsed.TotalMilliseconds);

            CodeDomProvider generator = null;

            switch (options.Language)
            {
                case SupportedLanguage.CS:
                    generator = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
                case SupportedLanguage.VB:
                    generator = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                case SupportedLanguage.FS:
                    generator = new Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider();
                    break;
                case SupportedLanguage.CPP:
                    generator = new Microsoft.VisualC.CppCodeProvider();
                    break;
                case SupportedLanguage.JS:
                    generator = new Microsoft.JScript.JScriptCodeProvider();
                    break;
                default:
                    Console.WriteLine("Unknown language detected. Falling back to default C#");
                    generator = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
            }

            var genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions()
                {
                    BlankLinesBetweenMembers = true,
                    VerbatimOrder = false,
                    ElseOnClosing = false,
                    BracingStyle = "C",
                    IndentString = "    "
                };
            if (options.UseFolders)
            {
                foreach (var file in MetaFacade.SplitCompileUnit(compileUnit))
                {
                    var fileInfo = new FileInfo(Path.Combine(options.OutputFile, file.Key) + "." + generator.FileExtension);
                    CheckDirectoryExists(fileInfo.Directory);
                    using (var fs = fileInfo.Create())
                    {
                        using (var sw = new StreamWriter(fs))
                        {
                            generator.GenerateCodeFromCompileUnit(file.Value, sw, genOptions);
                        }
                    }
                }
            }
            else
            {
                using (var sw = new StreamWriter(options.OutputFile))
                {
                    generator.GenerateCodeFromCompileUnit(compileUnit, sw, genOptions);
                }
            }

            Console.WriteLine("Code generated successfully!");
        }
Beispiel #26
0
        public static void Generate(
            string output_path,
            List <CodeTypeDelegate> delegates,
            List <CodeMemberMethod> functions,
            List <CodeMemberField> constants
            )
        {
            string filename = Path.Combine(output_path, Properties.Bind.Default.OutputClass + ".cs");

            if (!Directory.Exists(Properties.Bind.Default.OutputPath))
            {
                Directory.CreateDirectory(Properties.Bind.Default.OutputPath);
            }

            CodeNamespace ns = new CodeNamespace(Properties.Bind.Default.OutputNamespace);

            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Runtime.InteropServices"));
            ns.Imports.Add(new CodeNamespaceImport("System.Text"));

            foreach (string key in SpecTranslator.CSTypes.Keys)
            {
                ns.Imports.Add(new CodeNamespaceImport(key + " = System." + SpecTranslator.CSTypes[key].BaseType));
            }

            constants.Sort(new CodeTypeNameComparer <CodeMemberField>());
            functions.Sort(new CodeTypeNameComparer <CodeMemberMethod>());
            delegates.Sort(new CodeTypeNameComparer <CodeTypeDelegate>());

            ns.Types.Add(GenerateGlClass(functions, constants));
            ns.Types.Add(GenerateDelegatesClass(delegates));
            ns.Types.Add(GenerateImportsClass(delegates));

            CodeCompileUnit cu = new CodeCompileUnit();

            /*
             * cu.AssemblyCustomAttributes.Add(
             *  new CodeAttributeDeclaration(
             *      "System.CLSCompliant",
             *      new CodeAttributeArgument[] {
             *          new CodeAttributeArgument(
             *              new CodeSnippetExpression("true")
             *          )
             *      }
             *  )
             * );
             */
            cu.StartDirectives.Add(new CodeDirective());
            cu.Namespaces.Add(ns);

            using (StreamWriter sw = new StreamWriter(filename, false))
            {
                Console.WriteLine("Writing Tao.OpenGl.Gl class to {0}", filename);

                Microsoft.CSharp.CSharpCodeProvider          cs      = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions();
                options.BracingStyle             = "C";
                options.BlankLinesBetweenMembers = false;
                options.VerbatimOrder            = true;

                cs.GenerateCodeFromCompileUnit(cu, sw, options);

                sw.Flush();
            }
        }