public List <ServiceInstance> CreateGenerator()
        {
            var serviceInstances = new List <ServiceInstance>();

            var metadataInfo = mMetadataLoader.GetMetadata();

            var serviceContractGenerator = new ServiceContractGenerator
            {
                Options = ServiceContractGenerationOptions.ClientClass
            };

            foreach (var contract in metadataInfo.Contracts)
            {
                serviceContractGenerator.GenerateServiceContractType(contract);
            }

            if (serviceContractGenerator.Errors.Count != 0)
            {
                throw new Exception("ServiceContractGenerator: " + serviceContractGenerator.Errors.ToString());
            }

            var codeDom          = CodeDomProvider.CreateProvider("C#");
            var generatorOptions = new CodeGeneratorOptions
            {
                BracingStyle = "C"
            };

            var codeDomProvider    = CodeDomProvider.CreateProvider("C#");
            var compilerParameters = new CompilerParameters(
                new string[]
            {
                "System.dll",
                "System.ServiceModel.dll",
                "System.Runtime.Serialization.dll"
            }
                );

            var results = codeDomProvider.CompileAssemblyFromDom(compilerParameters,
                                                                 serviceContractGenerator.TargetCompileUnit);

            var contractAssembly = Assembly.LoadFile(results.PathToAssembly);
            var list             = new List <object>();

            foreach (var contract in metadataInfo.Contracts)
            {
                var endpoint         = GetEndpoint(metadataInfo, contract);
                var serviceInterface = GetServiceInterface(contractAssembly, contract);
                var serviceInstance  = new ServiceInstance
                {
                    ServiceName      = serviceInterface.Name,
                    ServiceOprations = new List <Operation>()
                };

                var proxyInstance = CreateProxyInstance(contractAssembly, serviceInterface);

                var inst = results.CompiledAssembly.CreateInstance(proxyInstance.Name, false,
                                                                   BindingFlags.CreateInstance, null,
                                                                   new object[] { endpoint.Binding, endpoint.Address },
                                                                   CultureInfo.CurrentCulture, null);

                serviceInstance.Instance = inst;
                //Generate operation
                foreach (var operationName in contract.Operations.Select(x => x.Name).ToArray())
                {
                    serviceInstance.ServiceOprations.Add(ReflectionDetails.GenerateOperation(inst, operationName));
                }
                serviceInstances.Add(serviceInstance);
            }
            return(serviceInstances);
        }
Example #2
0
        /// <summary>
        /// データベースからテーブルを自動生成します。
        /// </summary>
        public void GenerateCode(string projectName)
        {
            CodeCompileUnit compileUnit         = new CodeCompileUnit();
            CodeNamespace   importCodeNamespace = new CodeNamespace();

            importCodeNamespace.Imports.Add(new CodeNamespaceImport("ObjectDatabase"));
            compileUnit.Namespaces.Add(importCodeNamespace);
            CodeNamespace codeNamespace = new CodeNamespace($"{projectName}.DataModels");

            compileUnit.Namespaces.Add(codeNamespace);

            var tables = _connection.GetSchema("Tables");

            foreach (DataRow row in tables.Rows)
            {
                var name = row["TABLE_NAME"].ToString();
                CodeTypeDeclaration typeDeclaration = new CodeTypeDeclaration(name);
                typeDeclaration.BaseTypes.Add(new CodeTypeReference(typeof(DataModel)));
                var columns = _connection.GetSchema("Columns").Select($"TABLE_NAME='{name}'");
                foreach (var column in columns)
                {
                    string    colName = column["COLUMN_NAME"].ToString();
                    OleDbType type    = (OleDbType)column["DATA_TYPE"];
                    var       rows    = _connection.GetSchema("Indexes")
                                        .Select($"TABLE_NAME='{name}' AND COLUMN_NAME='{colName}'");
                    bool               isKey    = rows.Length > 0 && bool.Parse(rows[0]["UNIQUE"].ToString());
                    CodeMemberField    field    = new CodeMemberField(type.CreateType(), colName.ToLower());
                    CodeMemberProperty property = new CodeMemberProperty
                    {
                        Type       = new CodeTypeReference(type.CreateType()),
                        Name       = colName,
                        HasGet     = true,
                        HasSet     = true,
                        Attributes = MemberAttributes.Public | MemberAttributes.Final
                    };
                    property.CustomAttributes.Add(new CodeAttributeDeclaration(
                                                      new CodeTypeReference(typeof(SerializePropertyAttribute)),
                                                      new CodeAttributeArgument(new CodePrimitiveExpression(colName)),
                                                      new CodeAttributeArgument("IsKey", new CodePrimitiveExpression(isKey)),
                                                      new CodeAttributeArgument("RelationKey", new CodePrimitiveExpression(isKey))));
                    property.GetStatements.Add(
                        new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, colName.ToLower())));
                    property.SetStatements.Add(
                        new CodeAssignStatement(new CodeFieldReferenceExpression(null, colName.ToLower()),
                                                new CodePropertySetValueReferenceExpression()));
                    typeDeclaration.Members.Add(field);
                    typeDeclaration.Members.Add(property);
                }

                codeNamespace.Types.Add(typeDeclaration);
            }

            CodeDomProvider provider = CodeDomProvider.CreateProvider("CS");
            StringWriter    writer   = new StringWriter();

            provider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions
            {
                IndentString = "    "
            });

            Directory.CreateDirectory("GeneratedCode");
            File.WriteAllText("GeneratedCode/DatabaseGenerationCode.cs", writer.ToString());
        }
Example #3
0
        /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
        private void GoodB2G2()
        {
            string data;

            if (IO.staticFive == 5)
            {
                data = ""; /* Initialize data */
                {
                    try
                    {
                        /* read string from file into data */
                        using (StreamReader sr = new StreamReader("data.txt"))
                        {
                            /* POTENTIAL FLAW: Read data from a file */

                            /* This will be reading the first "line" of the file, which
                             * could be very long if there are little or no newlines in the file */
                            data = sr.ReadLine();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (IO.staticFive == 5)
            {
                int?parsedNum = null;
                /* FIX: Validate user input prior to compiling */
                try
                {
                    parsedNum = int.Parse(data);
                }
                catch (FormatException exceptNumberFormat)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number.");
                }
                if (parsedNum != null)
                {
                    StringBuilder sourceCode = new StringBuilder("");
                    sourceCode.Append("public class Calculator \n{\n");
                    sourceCode.Append("\tpublic int Sum()\n\t{\n");
                    sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n");
                    sourceCode.Append("\t}\n");
                    sourceCode.Append("}\n");
                    CodeDomProvider    provider   = CodeDomProvider.CreateProvider("CSharp");
                    CompilerParameters cp         = new CompilerParameters();
                    CompilerResults    cr         = provider.CompileAssemblyFromSource(cp, sourceCode.ToString());
                    Assembly           a          = cr.CompiledAssembly;
                    object             calculator = a.CreateInstance("Calculator");
                    Type       calculatorType     = calculator.GetType();
                    MethodInfo mi = calculatorType.GetMethod("Sum");
                    int        s  = (int)mi.Invoke(calculator, new object[] {});
                    IO.WriteLine("Result: " + s.ToString());
                }
            }
        }
        public static bool CompileExecutable(string sourceName)
        {
            FileInfo        sourceFile = new FileInfo(sourceName);
            CodeDomProvider provider   = null;
            bool            compileOk  = false;

            // Select the code provider based on the input file extension.
            if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS")
            {
                provider = CodeDomProvider.CreateProvider("CSharp");
            }
            else
            {
                Console.WriteLine("Source file must have a .cs extension");
            }

            if (provider != null)
            {
                // Format the executable file name.
                // Build the output assembly path using the current directory
                // and <source>_cs.exe or <source>_vb.exe.

                string exeName = string.Format(@"{0}\{1}.exe",
                                               System.Environment.CurrentDirectory,
                                               sourceFile.Name.Replace(".", "_"));

                CompilerParameters cp = new CompilerParameters();

                // Generate an executable instead of
                // a class library.
                cp.GenerateExecutable = true;

                // Specify the assembly file name to generate.
                cp.OutputAssembly = exeName;

                // Save the assembly as a physical file.
                cp.GenerateInMemory = true;

                // Set whether to treat all warnings as errors.
                cp.TreatWarningsAsErrors = false;

                // Invoke compilation of the source file.
                var cr = provider.CompileAssemblyFromFile(cp, sourceName);

                if (cr.Errors.Count > 0)
                {
                    // Display compilation errors.
                    Console.WriteLine("Errors building {0} into {1}",
                                      sourceName, cr.PathToAssembly);
                    foreach (CompilerError ce in cr.Errors)
                    {
                        Console.WriteLine("  {0}", ce.ToString());
                        Console.WriteLine();
                    }
                }
                else
                {
                    // Display a successful compilation message.
                    Console.WriteLine("Source {0} built into {1} successfully.",
                                      sourceName, cr.PathToAssembly);
                }

                // Return the results of the compilation.
                if (cr.Errors.Count > 0)
                {
                    compileOk = false;
                }
                else
                {
                    compileOk = true;
                }
            }
            return(compileOk);
        }