public static System.Reflection.Assembly GenerateCode(ITextTemplatingEngineHost host, ParsedTemplate pt, TemplateSettings settings, CodeCompileUnit ccu) { CompilerParameters pars = new CompilerParameters (); pars.GenerateExecutable = false; if (settings.Debug) { pars.GenerateInMemory = false; pars.IncludeDebugInformation = true; pars.TempFiles.KeepFiles = true; } else { pars.GenerateInMemory = true; pars.IncludeDebugInformation = false; } //resolve and add assembly references HashSet<string> assemblies = new HashSet<string> (); assemblies.UnionWith (settings.Assemblies); assemblies.UnionWith (host.StandardAssemblyReferences); foreach (string assem in assemblies) { string resolvedAssem = host.ResolveAssemblyReference (assem); if (!String.IsNullOrEmpty (resolvedAssem)) { pars.ReferencedAssemblies.Add (resolvedAssem); } else { pt.LogError ("Could not resolve assembly reference '" + assem + "'"); return null; } } CompilerResults results = settings.Provider.CompileAssemblyFromDom (pars, ccu); pt.Errors.AddRange (results.Errors); if (pt.Errors.HasErrors) return null; return results.CompiledAssembly; }
public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceProxy.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public System.CodeDom.CodeTypeDeclaration ProcessImportedType( System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit ) { Console.WriteLine("ProcessImportedType called for {0}.", typeDeclaration.Name); object typeCustomData = typeDeclaration.UserData[typeof(IDataContractSurrogate)]; if (typeDeclaration.Comments.Count == 0) { typeDeclaration.Comments.AddRange(Formatter.FormatComments(typeCustomData.ToString())); } foreach (CodeTypeMember member in typeDeclaration.Members) { object memberCustomData = member.UserData[typeof(IDataContractSurrogate)]; if (memberCustomData != null && memberCustomData is string && member.Comments.Count == 0) { member.Comments.AddRange( Formatter.FormatComments(memberCustomData.ToString()) ); } } return(typeDeclaration); }
public override void ProcessGeneratedCode( CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod) { ExampleDependencyInjectionLogic(buildMethod); base.ProcessGeneratedCode(codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod); }
public SoapCodeExporter (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit) { this.codeCompileUnit = codeCompileUnit; this.codeNamespace = codeNamespace; codeGenerator = new SoapMapCodeGenerator (codeNamespace, codeCompileUnit); }
public static string GenTableAdapters(System.IO.Stream xmlStream, TypedDataSetGenerator.GenerateOption genOption, string customToolNamespace) { try { EnsureCustomDbProviders(); var designSource = Activator.CreateInstance(assm.GetType("System.Data.Design.DesignDataSource")); designSource.Invoke("ReadXmlSchema", xmlStream, string.Empty ); var dataSourceGeneratorType = assm.GetType("System.Data.Design.TypedDataSourceCodeGenerator"); //get the specific constructor var constructor = dataSourceGeneratorType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, CallingConventions.Any, new Type[0], new ParameterModifier[0]); var dataSourceGenerator = constructor.Invoke(null); var codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); dataSourceGenerator.SetInternalPropertyValue("CodeProvider", codeProvider); var codeCompileUnit = new CodeCompileUnit(); var codeNamespace = new CodeNamespace(customToolNamespace); codeCompileUnit.Namespaces.Add(codeNamespace); dataSourceGenerator.InvokeInternal("GenerateDataSource", designSource, codeCompileUnit, codeNamespace, customToolNamespace, genOption ); var writer = new StringWriter(); var adapterNameSpace = codeCompileUnit.Namespaces[1]; codeProvider.GenerateCodeFromNamespace(adapterNameSpace, writer, new CodeGeneratorOptions()); //codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, options); var res = writer.ToString(); return (string)res; } catch (Exception e) { return e.ToString(); } }
public override bool Execute () { var provider = CodeDomProvider.CreateProvider (Language); if (provider == null) { Log.LogError ("Could not create CodeDOM provider for language '{0}'", Language); return false; } var ccu = new CodeCompileUnit (); foreach (var addin in AddinReferences) { //assembly:Mono.Addins.AddinDependency ("::%(Identity)", MonoDevelop.BuildInfo.Version)] ccu.AssemblyCustomAttributes.Add ( new CodeAttributeDeclaration ( new CodeTypeReference ("Mono.Addins.AddinDependencyAttribute"), new [] { new CodeAttributeArgument (new CodePrimitiveExpression ("::" + addin.ItemSpec)), new CodeAttributeArgument (new CodePrimitiveExpression (addin.GetMetadata ("Version"))) } ) ); } Directory.CreateDirectory (Path.GetDirectoryName (Filename)); using (var sw = new StreamWriter (Filename)) { provider.GenerateCodeFromCompileUnit (ccu, sw, new CodeGeneratorOptions ()); } return true; }
public XsdDataContractImporter (CodeCompileUnit codeCompileUnit) { // null argument is ok. CodeCompileUnit = codeCompileUnit ?? new CodeCompileUnit (); // Options is null by default }
static void Main(string[] args) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1); CSharpCodeProvider provider = new CSharpCodeProvider(); using(StreamWriter sw = new StreamWriter("HelloWorld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } Console.WriteLine("HelloWorld.cs generated in .../bin/Debug or .../bin/Release project folders."); Console.Write("Press a key to exit"); Console.ReadKey(); }
public CodeCompileUnit Generate(ClassData classData) { if (classData == null) { throw FxTrace.Exception.ArgumentNull("classData"); } CodeCompileUnit result = new CodeCompileUnit(); // Add global namespace CodeNamespace globalNamespace = new CodeNamespace(); result.Namespaces.Add(globalNamespace); CodeTypeDeclaration classDeclaration = GenerateClass(classData); if (!String.IsNullOrEmpty(classData.Namespace)) { // Add namespace the class is defined in CodeNamespace classNamespace = new CodeNamespace(classData.Namespace); result.Namespaces.Add(classNamespace); classNamespace.Types.Add(classDeclaration); } else { // Add class to global namespace globalNamespace.Types.Add(classDeclaration); } return result; }
internal BuildResultCodeCompileUnit(Type codeDomProviderType, System.CodeDom.CodeCompileUnit codeCompileUnit, System.CodeDom.Compiler.CompilerParameters compilerParameters, IDictionary linePragmasTable) { this._codeDomProviderType = codeDomProviderType; this._codeCompileUnit = codeCompileUnit; this._compilerParameters = compilerParameters; this._linePragmasTable = linePragmasTable; }
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace, CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod) { base.ProcessGeneratedCode(codeCompileUnit, generatedNamespace, generatedClass, executeMethod); // Create the Href wrapper CodeTypeMember hrefMethod = new CodeSnippetTypeMember(@" // Resolve package relative syntax // Also, if it comes from a static embedded resource, change the path accordingly public override string Href(string virtualPath, params object[] pathParts) { virtualPath = ApplicationPart.ProcessVirtualPath(GetType().Assembly, VirtualPath, virtualPath); return base.Href(virtualPath, pathParts); }"); generatedClass.Members.Add(hrefMethod); Debug.Assert(generatedClass.Name.Length > 0); if (!(Char.IsLetter(generatedClass.Name[0]) || generatedClass.Name[0] == '_')) { generatedClass.Name = '_' + generatedClass.Name; } // If the generatedClass starts with an underscore, add a ClsCompliant(false) attribute. if (generatedClass.Name[0] == '_') { generatedClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(CLSCompliantAttribute).FullName, new CodeAttributeArgument(new CodePrimitiveExpression(false)))); } }
/// <summary> /// Initializes a new instance of the <see cref="CodeGeneratorContext"/> class. /// </summary> /// <param name="metadataSet">The metadata set.</param> /// <param name="codeGeneratorOptions">The code generator options.</param> public CodeGeneratorContext(MetadataSet metadataSet, CodeGeneratorOptions codeGeneratorOptions) { MetadataSet = metadataSet; CodeDomProvider = CodeDomProvider.CreateProvider(codeGeneratorOptions.CodeLanguage.ToString()); CodeCompileUnit = new CodeCompileUnit(); CodeGeneratorOptions = codeGeneratorOptions; }
public override void ProcessGeneratedCode(DomainServiceDescription domainServiceDescription, CodeCompileUnit codeCompileUnit, IDictionary<Type, CodeTypeDeclaration> typeMapping) { // Get a reference to the entity class CodeTypeDeclaration codeGenEntity = typeMapping[typeof(TestEntity)]; AppDomain appDomain = AppDomain.CurrentDomain; AppDomainSetup setup = appDomain.SetupInformation; string baseDir = appDomain.BaseDirectory; codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] BaseDirectory:" + baseDir)); Configuration cfg = WebConfigurationManager.OpenWebConfiguration(null); AuthenticationSection authSection = (AuthenticationSection)cfg.GetSection("system.web/authentication"); FormsAuthenticationConfiguration formsAuth = authSection.Forms; if (formsAuth != null) { codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] Authentication:forms")); } ConnectionStringsSection connSect = cfg.ConnectionStrings; if (connSect != null) { ConnectionStringSettingsCollection connColl = connSect.ConnectionStrings; foreach (ConnectionStringSettings connSetting in connColl) { codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] ConnectionString:" + connSetting.ConnectionString)); } } }
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod) { if (!String.IsNullOrWhiteSpace(Inherits)) { derivedType.BaseTypes[0] = new CodeTypeReference(Inherits); } }
public CodeObject CreateCodeObject() { var conditions = _types .Select(CreateNumberSetValueCondition) .Concat(_types .Concat(_arrayTypes) .Select(CreateArraySetValueCondition)); var firstCondition = conditions.First(); var currentCondition = firstCondition; foreach (var condition in conditions.Skip(1)) { currentCondition.FalseStatements.Add(condition); currentCondition = condition; } currentCondition.FalseStatements.Add(CodeHelper.Return(CodeHelper.False())); var type = new CodeTypeDeclaration("AphidObject") { IsPartial = true }; type.Members.Add(TrySetProperty(firstCondition)); var ns = new CodeNamespace(); ns.Imports.Add(new CodeNamespaceImport("System.Linq")); ns.Name = "Components.Aphid.Interpreter"; ns.Types.Add(type); var unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); return unit; }
public string CreateSpecs(out int specCount) { var files = FindSpecFiles().ToArray(); specCount = files.Length; if (specCount < 1) return string.Empty; var compile = new CodeCompileUnit(); var globalns = new CodeNamespace(); globalns.Imports.Add(new CodeNamespaceImport("NUnit.Framework")); globalns.Imports.Add(new CodeNamespaceImport(config.MyNamespace)); compile.Namespaces.Add(globalns); var specNamespace = new CodeNamespace(config.TargetNamespace + ".ChutzpahSpecs"); compile.Namespaces.Add(specNamespace); foreach (var fileInfo in files) { AddSpec(specNamespace, fileInfo); } //specNamespace.Types.AddRange(files.Select(CreateSpec).ToArray()); var provider = CreateProvider(); var options = new CodeGeneratorOptions { BracingStyle = "C", BlankLinesBetweenMembers = false }; var stringBuilder = new StringBuilder(); using (var writer = new StringWriter(stringBuilder)) { provider.GenerateCodeFromCompileUnit(compile, writer, options); writer.Flush(); writer.Close(); } var result = stringBuilder.ToString(); return result; }
public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services) { NamingService = new NamingService((INamingService)services.GetService(typeof(INamingService))); Services = services; InitializeMappings(); var types = codeUnit.Namespaces[0].Types; foreach (CodeTypeDeclaration type in types) { if (!type.IsClass || type.IsContextType()) { continue; } var logicalName = type.GetFieldInitalizedValue("EntityLogicalName"); var propertiesToAdd = new List<CodeMemberProperty>(); foreach (var member in type.Members) { var property = member as CodeMemberProperty; if (SkipProperty(property, type)) { continue; } propertiesToAdd.Add(GetOptionSetEnumType(property, logicalName)); } foreach (var enumProp in propertiesToAdd.Where(p => p != null)) { type.Members.Add(enumProp); } } AddEntityOptionSetEnumDeclaration(types); }
internal static void WriteGeneratedCode(string sourceFile, CodeCompileUnit codeCompileUnit) { if (!OutputDebuggingEnabled) { return; } RunTask(() => { string extension = Path.GetExtension(sourceFile); RazorCodeLanguage language = RazorCodeLanguage.GetLanguageByExtension(extension); CodeDomProvider provider = CodeDomProvider.CreateProvider(language.LanguageName); using (var writer = new StringWriter()) { // Trim the html part of cshtml or vbhtml string outputExtension = extension.Substring(0, 3); string outputFileName = Normalize(sourceFile) + "_generated" + outputExtension; string outputPath = Path.Combine(Path.GetDirectoryName(sourceFile), outputFileName); // REVIEW: Do these options need to be tweaked? provider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, new CodeGeneratorOptions()); File.WriteAllText(outputPath, writer.ToString()); } }); }
public override string ImportSchemaType(XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (type == null) { return null; } if (importedTypes[type] != null) { mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataSet).Namespace)); compileUnit.ReferencedAssemblies.Add("System.Data.dll"); return (string)importedTypes[type]; } if (!(context is XmlSchemaElement)) return null; if (type is XmlSchemaComplexType) { XmlSchemaComplexType ct = (XmlSchemaComplexType)type; if (ct.Particle is XmlSchemaSequence) { XmlSchemaObjectCollection items = ((XmlSchemaSequence)ct.Particle).Items; if (items.Count == 2 && items[0] is XmlSchemaAny && items[1] is XmlSchemaAny) { XmlSchemaAny any0 = (XmlSchemaAny)items[0]; XmlSchemaAny any1 = (XmlSchemaAny)items[1]; if (any0.Namespace == XmlSchema.Namespace && any1.Namespace == "urn:schemas-microsoft-com:xml-diffgram-v1") { string typeName = typeof(DataTable).FullName; importedTypes.Add(type, typeName); mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataTable).Namespace)); compileUnit.ReferencedAssemblies.Add("System.Data.dll"); return typeName; } } } } return null; }
public static String GenerateCSharpCode(CodeCompileUnit compileunit) { // Generate the code with the C# code provider. CSharpCodeProvider provider = new CSharpCodeProvider(); // Build the output file name. String sourceFile; if (provider.FileExtension[0] == '.') { sourceFile = "HelloWorld" + provider.FileExtension; } else { sourceFile = "HelloWorld." + provider.FileExtension; } // Create a TextWriter to a StreamWriter to the output file. IndentedTextWriter tw = new IndentedTextWriter( new StreamWriter(sourceFile, false), " "); // Generate source code using the code provider. provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions()); // Close the output file. tw.Close(); return sourceFile; }
public void CodeSnippetBlankLines () { var opt = new CodeGeneratorOptions () { BlankLinesBetweenMembers = false, VerbatimOrder = false }; var ccu = new CodeCompileUnit (); var ns = new CodeNamespace ("Foo"); ccu.Namespaces.Add (ns); var t = new CodeTypeDeclaration ("Bar"); ns.Types.Add (t); t.Members.Add (new CodeSnippetTypeMember ("#line hidden")); t.Members.Add (new CodeSnippetTypeMember ("#line hidden2")); t.Members.Add (new CodeMemberMethod () { Name = "Foo" }); using (var sw = new StringWriter ()) { new CSharpCodeProvider ().GenerateCodeFromCompileUnit (ccu, sw, opt); var str = sw.ToString (); Assert.IsFalse (str.Contains ("hidden2private"), "#0"); Assert.IsTrue (str.Contains( "#line hidden#line hidden2"), "#1"); } }
public CodeDomEntity(JToken structualType, string targetNamespace) { this.targetNamespace = targetNamespace; outputFileName = string.Format("{0}.cs", structualType["shortName"].Value<string>()); this.structualType = structualType; targetUnit = new CodeCompileUnit(); CodeNamespace breezeEntities = new CodeNamespace(targetNamespace); breezeEntities.Imports.Add(new CodeNamespaceImport("System")); breezeEntities.Imports.Add(new CodeNamespaceImport("Breeze.Sharp")); breezeEntities.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); targetClass = new CodeTypeDeclaration(structualType["shortName"].Value<string>()); if (structualType["baseTypeName"] != null) { //use base class from the base type (it will still be BaseEntity) string baseType = structualType["baseTypeName"].Value<string>(); targetClass.BaseTypes.Add(new CodeTypeReference(baseType.Substring(0, baseType.IndexOf(':')))); } else { //this entity type has no base class so use BaseEntity targetClass.BaseTypes.Add(new CodeTypeReference("BaseEntity")); } targetClass.IsClass = true; targetClass.TypeAttributes = TypeAttributes.Public; breezeEntities.Types.Add(targetClass); targetUnit.Namespaces.Add(breezeEntities); }
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() { const string expectedPropertyCode = @" protected Foo.Bar ApplicationInstance { get { return ((Foo.Bar)(Context.ApplicationInstance)); } } "; // Arrange CodeCompileUnit generatedCode = new CodeCompileUnit(); CodeNamespace generatedNamespace = new CodeNamespace(); CodeTypeDeclaration generatedClass = new CodeTypeDeclaration(); CodeMemberMethod executeMethod = new CodeMemberMethod(); WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") { GlobalAsaxTypeName = "Foo.Bar" }; // Act host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod); // Assert CodeMemberProperty property = generatedClass.Members[0] as CodeMemberProperty; Assert.IsNotNull(property); CSharpCodeProvider provider = new CSharpCodeProvider(); StringBuilder builder = new StringBuilder(); using(StringWriter writer = new StringWriter(builder)) { provider.GenerateCodeFromMember(property, writer, new CodeDom.Compiler.CodeGeneratorOptions()); } Assert.AreEqual(expectedPropertyCode, builder.ToString()); }
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace, CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod) { if (!String.IsNullOrEmpty(_suffix)) { generatedClass.Name += _suffix; } }
public GeneratorResults(Block document, IList<RazorError> parserErrors, CodeCompileUnit generatedCode, IDictionary<int, GeneratedCodeMapping> designTimeLineMappings) : this(parserErrors.Count == 0, document, parserErrors, generatedCode, designTimeLineMappings) { }
private object CompileAndCreateTest(string fileName, Feature feature) { string className = Path.GetFileNameWithoutExtension(fileName); const string targetNamespace = "Target.Namespace"; // the row test generation has to be set to false, because our verifications support the old style test generation only SpecFlowUnitTestConverter converter = new SpecFlowUnitTestConverter(CreateUnitTestGeneratorProvider(), new CodeDomHelper(CodeDomProviderLanguage.CSharp), new GeneratorConfiguration { AllowRowTests = false, AllowDebugGeneratedFiles = true }); var codeNamespace = converter.GenerateUnitTestFixture(feature, className, targetNamespace); var compileUnit = new CodeCompileUnit(); compileUnit.Namespaces.Add(codeNamespace); Dictionary<string, string> providerOptions = new Dictionary<string, string>(); providerOptions["CompilerVersion"] = "v3.5"; CSharpCodeProvider codeProvider = new CSharpCodeProvider(providerOptions); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateInMemory = true; compilerParameters.TempFiles.KeepFiles = true; compilerParameters.ReferencedAssemblies.Add( TestFileHelper.GetAssemblyPath(typeof (GeneratedCodeAttribute))); //System compilerParameters.ReferencedAssemblies.Add( TestFileHelper.GetAssemblyPath(typeof (TestAttribute))); //NUnit compilerParameters.ReferencedAssemblies.Add( TestFileHelper.GetAssemblyPath(typeof (ITestRunner))); //TechTalk.SpecFlow var results = codeProvider.CompileAssemblyFromDom(compilerParameters, compileUnit); if (results.NativeCompilerReturnValue != 0) throw new InvalidOperationException("Test cannot be compiled: " + string.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select(ce => ce.ToString()).ToArray())); Type testType = results.CompiledAssembly.GetType(targetNamespace + "." + className, true); return Activator.CreateInstance(testType); }
private static Assembly Compile(CodeCompileUnit codeCompileUnit) { var compilerParameters = new CompilerParameters(); compilerParameters.GenerateInMemory = true; compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8)); var codeProvider = new CSharpCodeProvider(); var result = codeProvider.CompileAssemblyFromDom(compilerParameters, codeCompileUnit); if (result.Errors.HasErrors) { foreach (var error in result.Errors) { Console.WriteLine(error); } return null; } return result.CompiledAssembly; }
public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services) { var types = codeUnit.Namespaces[0].Types; var attributes = new HashSet<string>(); foreach (var type in types.Cast<CodeTypeDeclaration>(). Where(type => type.IsClass && !type.IsContextType())) { attributes.Clear(); var @struct = new CodeTypeDeclaration { Name = AttributeConstsStructName, IsStruct = true, TypeAttributes = TypeAttributes.Public }; foreach (var member in from CodeTypeMember member in type.Members let prop = member as CodeMemberProperty where prop != null select prop) { CreateAttributeConstForProperty(@struct, member, attributes); } if (attributes.Any()) { type.Members.Insert(0, GenerateTypeWithoutEmptyLines(@struct)); } } }
/// <summary> /// Creates a function to be evaluated. /// </summary> /// <param name="_input"></param> /// <returns></returns> public static FunctionBaseCore CreateFunction(string _input) { Microsoft.VisualBasic.VBCodeProvider codecompiler = new Microsoft.VisualBasic.VBCodeProvider(); CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); CodeNamespace dom_namespace = pGetNameSpace(); CodeTypeDeclaration dom_class = pGetClass(); CodeMemberMethod dom_func = pGetFunc(_input); dom_class.Members.Add(dom_func); dom_namespace.Types.Add(dom_class); ccu.Namespaces.Add(dom_namespace); CompilerParameters paras = pGetPara(); CompilerResults output = codecompiler.CompileAssemblyFromDom(paras, ccu); foreach (CompilerError CE in output.Errors) { } //pGetCompileCode(codecompiler, ccu); Assembly codebase = output.CompiledAssembly; object classbase = codebase.CreateInstance("DOMSpace.DOMClass"); Type func_class = codebase.GetModules()[0].GetType("DOMSpace.DOMClass"); Type[] temp = codebase.GetModules()[0].GetTypes(); MethodInfo invoker = func_class.GetMethod("DOMfunc"); pGetCompileCode(codecompiler, ccu); return new FunctionBaseCore(classbase, invoker); }
public override string ImportSchemaType( string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { if (ns != "http://www.w3.org/2001/XMLSchema") return null; switch (name) { case "anyURI": return "System.Uri"; case "gDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDay"; case "gMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth"; case "gMonthDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonthDay"; case "gYear": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYear"; case "gYearMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYearMonth"; case "duration": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDuration"; default: return null; } }
public Assembly CreateAssembly(string codeNamespace, IDictionary <string, Dictionary <string, object> > typePropsDictionary) { var csc = new Microsoft.CSharp.CSharpCodeProvider(); var parameters = new CompilerParameters(new[] { "System.dll", "System.Core.dll" }); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; var compileUnit = new System.CodeDom.CodeCompileUnit(); var ns = new CodeNamespace(codeNamespace); compileUnit.Namespaces.Add(ns); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); foreach (var typeProps in typePropsDictionary) { var classType = new CodeTypeDeclaration(typeProps.Key); classType.Attributes = MemberAttributes.Public; ns.Types.Add(classType); foreach (var prop in typeProps.Value) { if (prop.Value is Type type) { var fieldName = "_" + prop.Key; var field = new CodeMemberField(type, fieldName); classType.Members.Add(field); var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Type = new CodeTypeReference(type); property.Name = prop.Key; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName))); property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodePropertySetValueReferenceExpression())); classType.Members.Add(property); } else if (prop.Value is CodeTypeReference codeType) { var fieldName = "_" + prop.Key; var field = new CodeMemberField(codeType, fieldName); classType.Members.Add(field); var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Type = codeType; property.Name = prop.Key; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName))); property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodePropertySetValueReferenceExpression())); classType.Members.Add(property); } } } var results = csc.CompileAssemblyFromDom(parameters, compileUnit); return(results.CompiledAssembly); }
/// <summary> 根据参数执行WebService </summary> public static object InvokeWebService(string url, string classname, string methodname, object[] args) { try { string _namespace = "WebService"; if (string.IsNullOrEmpty(classname)) { classname = GetClassName(url); } //获取服务描述语言(WSDL) Net.WebClient wc = new Net.WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); //【1】 Web.Services.Description.ServiceDescription sd = Web.Services.Description.ServiceDescription.Read(stream); //【2】 Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】 sdi.AddServiceDescription(sd, "", ""); CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace); //【4】 //生成客户端代理类代码 CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit(); //【5】 ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】 CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); //ICodeCompiler icc = csc.CreateCompiler();//【7】 //设定编译器的参数 CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】 cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(_namespace + "." + classname, true, true); object bj = Activator.CreateInstance(t); //【10】 System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】 return(mi.Invoke(bj, args)); } catch (System.Exception ex) { Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace); //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test"); return(null); } }
private System.CodeDom.CodeCompileUnit GetCodeCompileUnit() { if (this.codeCompileUnit == null) { this.codeCompileUnit = new System.CodeDom.CodeCompileUnit(); } return(this.codeCompileUnit); }
public static object WebserviceInvoke(string p_strUrl, string p_strNameSpace, string p_strClassName, string p_strMethodName, object[] p_objArgs) { object oReturnValue = null; try { if (p_strNameSpace == "") { p_strNameSpace = "EnterpriseServerBase.WebService.DynamicWebCalling"; } if (p_strClassName == "") { p_strClassName = WebServiceHelper.GetWsClassName(p_strUrl); } System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(p_strUrl + "?wsdl"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(p_strNameSpace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(p_strNameSpace + "." + p_strClassName, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(p_strMethodName); oReturnValue = mi.Invoke(obj, p_objArgs); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } return(oReturnValue); }
public ServiceDescriptionImportWarnings Import(CodeNamespace codeNamespace, System.CodeDom.CodeCompileUnit codeCompileUnit) { if (codeCompileUnit != null) { codeCompileUnit.ReferencedAssemblies.Add("System.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll"); } return(this.Import(codeNamespace, new System.Xml.Serialization.ImportContext(new CodeIdentifiers(), false), new Hashtable(), new StringCollection())); }
//</snippet4> public System.CodeDom.CodeTypeDeclaration ProcessImportedType( System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit) { // Console.WriteLine("ProcessImportedType invoked") // Not used in this sample. // You could use this method to construct an entirely new CLR // type when a certain type is imported, or modify a // generated type in some way. return(typeDeclaration); }
/// <summary> /// Bootstrap method - loads a blank Form /// </summary> /// <returns></returns> protected override CodeCompileUnit Parse() { CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ReloadAssemblys(ccu); ccu = Fichier.WINDOWS; codeCompileUnit = ccu; return(ccu); }
private static string GenerateCSharpCode(System.CodeDom.CodeCompileUnit compileunit) { var provider = new CSharpCodeProvider(); var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) using (var tw = new IndentedTextWriter(sw, " ")) provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions()); return(sb.ToString()); }
/// <summary> /// 通过反射完成WS调用 /// </summary> /// <param name="url">WSUrl</param> /// <param name="namespace">WS命名空间</param> /// <param name="classname">WS类名</class> /// <param name="methodname">WS方法名</class> /// <param name="args">传递给WS方法的参数</param> /// 示例:url="http://win01:86";serviceUrl = "/Api/SiteGroupFunc.asmx"; /// object s = InvokeWebSer(url + serviceUrl, "SiteGroup", "SiteGroupFunc", "GetSiteName", new object[] { }); /// <returns>执行结果</returns> public object InvokeWS(string url, string @namespace, string classname, string methodname, object[] args) { System.Net.WebClient wc = new System.Net.WebClient(); string URL = string.Empty; if ((url.Substring(url.Length - 5, 5) != null) && ((url.Substring(url.Length - 5, 5).ToLower() != "?wsdl"))) { URL = url + "?WSDL"; } else { URL = url; } System.IO.Stream stream = wc.OpenRead(URL); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return(mi.Invoke(obj, args)); }
internal override void GetPreservedAttributes(PreservationFileReader pfr) { base.GetPreservedAttributes(pfr); string attribute = pfr.GetAttribute("CCUpreservationFileName"); using (FileStream stream = File.Open(Path.Combine(HttpRuntime.CodegenDirInternal, attribute), FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); this._codeCompileUnit = formatter.Deserialize(stream) as System.CodeDom.CodeCompileUnit; this._codeDomProviderType = (Type)formatter.Deserialize(stream); this._compilerParameters = (System.CodeDom.Compiler.CompilerParameters)formatter.Deserialize(stream); this._linePragmasTable = formatter.Deserialize(stream) as IDictionary; } }
public static System.CodeDom.CodeCompileUnit BuildGraph(System.Xml.XmlDocument xmlMetaData, string tableName) { System.Xml.XmlNodeList nodeList; System.CodeDom.CodeCompileUnit compileUnit = new System.CodeDom.CodeCompileUnit(); System.CodeDom.CodeNamespace nSpace; System.CodeDom.CodeTypeDeclaration clsTable; nodeList = xmlMetaData.SelectNodes("/DataSet/Table[@Name='" + tableName + "']/Column"); nSpace = new System.CodeDom.CodeNamespace("ClassViaCodeDOM"); compileUnit.Namespaces.Add(nSpace); nSpace.Imports.Add(new System.CodeDom.CodeNamespaceImport("System")); clsTable = new System.CodeDom.CodeTypeDeclaration(tableName); nSpace.Types.Add(clsTable); System.CodeDom.CodeMemberField field; foreach (System.Xml.XmlNode node in nodeList) { field = new System.CodeDom.CodeMemberField(); field.Name = "m_" + node.Attributes["Name"].Value; field.Attributes = System.CodeDom.MemberAttributes.Private; field.Type = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value); clsTable.Members.Add(field); } System.CodeDom.CodeMemberProperty prop; string name; foreach (System.Xml.XmlNode node in nodeList) { prop = new System.CodeDom.CodeMemberProperty(); name = node.Attributes["Name"].Value; prop.Name = name; prop.Attributes = System.CodeDom.MemberAttributes.Public; prop.Type = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value); prop.GetStatements.Add(new System.CodeDom.CodeMethodReturnStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name))); prop.SetStatements.Add(new System.CodeDom.CodeAssignStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name), new System.CodeDom.CodePropertySetValueReferenceExpression())); clsTable.Members.Add(prop); } return(compileUnit); }
public static void GenerateCode(string fileName, System.CodeDom.Compiler.CodeDomProvider provider, System.CodeDom.CodeCompileUnit compileUnit) { System.CodeDom.Compiler.ICodeGenerator gen = provider.CreateGenerator(); System.CodeDom.Compiler.IndentedTextWriter tw = null; try { tw = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(fileName, false), " "); gen.GenerateCodeFromCompileUnit(compileUnit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); } finally { if (tw != null) { tw.Flush(); tw.Close(); } } }
public static System.CodeDom.CodeCompileUnit BuildGraph() { System.CodeDom.CodeCompileUnit CompileUnit = new System.CodeDom.CodeCompileUnit(); System.CodeDom.CodeNamespace nSpace = new System.CodeDom.CodeNamespace("HelloWorldViaCodeDOM"); CompileUnit.Namespaces.Add(nSpace); nSpace.Imports.Add(new System.CodeDom.CodeNamespaceImport("System")); System.CodeDom.CodeTypeDeclaration clsStartup = new System.CodeDom.CodeTypeDeclaration("Startup"); nSpace.Types.Add(clsStartup); System.CodeDom.CodeEntryPointMethod main = new System.CodeDom.CodeEntryPointMethod(); System.CodeDom.CodePrimitiveExpression exp = new System.CodeDom.CodePrimitiveExpression("Hello World!"); System.CodeDom.CodeTypeReferenceExpression refExp = new System.CodeDom.CodeTypeReferenceExpression("System.Console"); System.CodeDom.CodeMethodInvokeExpression invoke = new System.CodeDom.CodeMethodInvokeExpression(refExp, "WriteLine", exp); main.Statements.Add(new System.CodeDom.CodeExpressionStatement(invoke)); clsStartup.Members.Add(main); return(CompileUnit); }
internal CodeExporter(System.CodeDom.CodeNamespace codeNamespace, System.CodeDom.CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable exportedMappings) { if (codeNamespace != null) { CodeGenerator.ValidateIdentifiers(codeNamespace); } this.codeNamespace = codeNamespace; if (codeCompileUnit != null) { if (!codeCompileUnit.ReferencedAssemblies.Contains("System.dll")) { codeCompileUnit.ReferencedAssemblies.Add("System.dll"); } if (!codeCompileUnit.ReferencedAssemblies.Contains("System.Xml.dll")) { codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); } } this.codeCompileUnit = codeCompileUnit; this.options = options; this.exportedMappings = exportedMappings; this.codeProvider = codeProvider; }
internal ObjectFactoryCodeDomTreeGenerator(string outputAssemblyName) { CodeConstructor constructor; this._codeCompileUnit = new System.CodeDom.CodeCompileUnit(); CodeNamespace namespace2 = new CodeNamespace("__ASP"); this._codeCompileUnit.Namespaces.Add(namespace2); string name = "FastObjectFactory_" + Util.MakeValidTypeNameFromString(outputAssemblyName).ToLower(CultureInfo.InvariantCulture); this._factoryClass = new CodeTypeDeclaration(name); this._factoryClass.TypeAttributes &= ~TypeAttributes.Public; CodeSnippetTypeMember member = new CodeSnippetTypeMember(string.Empty) { LinePragma = new CodeLinePragma(@"c:\\dummy.txt", 1) }; this._factoryClass.Members.Add(member); constructor = new CodeConstructor { Attributes = constructor.Attributes | MemberAttributes.Private }; this._factoryClass.Members.Add(constructor); namespace2.Types.Add(this._factoryClass); }
// Create a CodeDOM graph. static void CreateGraph(CodeCompileUnit cu) { //<Snippet2> cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region")); //</Snippet2> //<Snippet3> cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); //</Snippet3> //<Snippet4> CodeChecksumPragma pragma1 = new CodeChecksumPragma(); //</Snippet4> //<Snippet5> pragma1.FileName = "c:\\temp\\test\\OuterLinePragma.txt"; //</Snippet5> //<Snippet6> pragma1.ChecksumAlgorithmId = HashMD5; //</Snippet6> //<Snippet7> pragma1.ChecksumData = new byte[] { 0xAA, 0xAA }; //</Snippet7> cu.StartDirectives.Add(pragma1); //<Snippet8> CodeChecksumPragma pragma2 = new CodeChecksumPragma("test.txt", HashSHA1, new byte[] { 0xBB, 0xBB, 0xBB }); //</Snippet8> cu.StartDirectives.Add(pragma2); CodeNamespace ns = new CodeNamespace("Namespace1"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.IO")); cu.Namespaces.Add(ns); ns.Comments.Add(new CodeCommentStatement("Namespace Comment")); CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1"); ns.Types.Add(cd); cd.Comments.Add(new CodeCommentStatement("Outer Type Comment")); cd.LinePragma = new CodeLinePragma("c:\\temp\\test\\OuterLinePragma.txt", 300); CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "Method1"; method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeMemberMethod method2 = new CodeMemberMethod(); method2.Name = "Method2"; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method2.Comments.Add(new CodeCommentStatement("Method 2 Comment")); cd.Members.Add(method1); cd.Members.Add(method2); cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region")); cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeMemberField field1 = new CodeMemberField(typeof(String), "field1"); cd.Members.Add(field1); field1.Comments.Add(new CodeCommentStatement("Field 1 Comment")); //<Snippet9> CodeRegionDirective codeRegionDirective1 = new CodeRegionDirective(CodeRegionMode.Start, "Field Region"); //</Snippet9> //<Snippet10> field1.StartDirectives.Add(codeRegionDirective1); //</Snippet10> CodeRegionDirective codeRegionDirective2 = new CodeRegionDirective(CodeRegionMode.End, ""); //<Snippet11> codeRegionDirective2.RegionMode = CodeRegionMode.End; //</Snippet11> //<Snippet12> codeRegionDirective2.RegionText = string.Empty; //</Snippet12> //<Snippet13> field1.EndDirectives.Add(codeRegionDirective2); //</Snippet13> //<Snippet16> CodeSnippetStatement snippet1 = new CodeSnippetStatement(); snippet1.Value = " Console.WriteLine(field1);"; CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, ""); regionStart.RegionText = "Snippet Region"; regionStart.RegionMode = CodeRegionMode.Start; snippet1.StartDirectives.Add(regionStart); snippet1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); //</Snippet16> // CodeStatement example CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeStatement codeAssignStatement1 = new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field1"), new CodePrimitiveExpression("value1")); //<Snippet14> codeAssignStatement1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region")); //</Snippet14> cd.Members.Add(constructor1); //<Snippet15> codeAssignStatement1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); //</Snippet15> method2.Statements.Add(codeAssignStatement1); method2.Statements.Add(snippet1); }
public static int GetWebServiceDataWSDL(string url, string funcName, string className, Object[] parameters, ref Object retItem) { try { string @namespace = "KFBIO.Webservice.WSDL"; System.Net.WebClient client = new System.Net.WebClient(); //String classname; //String url = System.Configuration.ConfigurationManager.ConnectionStrings["serviceAddress"].ConnectionString;//这个地址可以写在Config文件里面,这里取出来就行了.在原地址后面加上: ?WSDL //String url = "http://192.168.4.4:8090/yfy-client/services/Msg_Service"; //String param = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><NOTICEMSG><MSGCONTENT><APPLICATION><INP_ID></INP_ID><INP_VISIT_TYPE_CD>1</INP_VISIT_TYPE_CD><NAME></NAME><GENDER_CD>2</GENDER_CD><BIRTHDATE> </BIRTHDATE><ID_NO></ID_NO><PATI_PHONE> </PATI_PHONE><PROVINCE_NAME> </PROVINCE_NAME><CITY_NAME> </CITY_NAME><AREA_NAME> </AREA_NAME><STREET_ID> </STREET_ID><VILLAGE_NAME> </VILLAGE_NAME><HOUSE_NO> </HOUSE_NO><APPLY_REASON>2</APPLY_REASON><CONSULT_AIM>远程诊断</CONSULT_AIM><ILLNESS_DIAG> </ILLNESS_DIAG><CONSULT_ORG_CODE> </CONSULT_ORG_CODE><CONSULT_ORG_NAME> </CONSULT_ORG_NAME></APPLICATION><EXAMSET><REPORT_NO> </REPORT_NO><REPORT_DATE> </REPORT_DATE><TEST_DEPT_NAME>病理科</TEST_DEPT_NAME><REPORT_DOC_NAME>牛爱芳</REPORT_DOC_NAME><ITEM_CD>00213564</ITEM_CD><ITEM_NAME>病理诊断</ITEM_NAME><CLINICDESC>送检目的</CLINICDESC><EXAMFINDING>检查所见</EXAMFINDING><EXAMCONCLUSION>检查结论</EXAMCONCLUSION><FTP_USER>FTP</FTP_USER><FTP_PASSWORD>1234</FTP_PASSWORD><FTP_FILEPATH> FTP文件完整路径</FTP_FILEPATH></EXAMSET></MSGCONTENT><CREATETIME>产生日期时间</CREATETIME></NOTICEMSG>"; //classname = "Msg_Service"; url = url + "?wsdl"; Stream stream = client.OpenRead(url); ServiceDescription description = ServiceDescription.Read(stream); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //创建客户端代理代理类。 importer.ProtocolName = "Soap"; //指定访问协议。 importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理。 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //添加WSDL文档。 CodeNamespace nmspace = new CodeNamespace(); //命名空间 nmspace.Name = @namespace; System.CodeDom.CodeCompileUnit unit = new System.CodeDom.CodeCompileUnit(); unit.Namespaces.Add(nmspace); System.Web.Services.Description.ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); System.CodeDom.Compiler.CodeDomProvider provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); System.CodeDom.Compiler.CompilerParameters parameter = new System.CodeDom.Compiler.CompilerParameters(); parameter.GenerateExecutable = false; if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("Temp"))) { Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("Temp")); } parameter.OutputAssembly = System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll"; //"D:/TempClass.dll";//输出程序集的名称 parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { // 显示编译错误信息 //临时模板编译错误,内部错误 string a = System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll"; if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll")) { return(-5); } } System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll");//加载前面生成的程序集 //Type t = asm.GetType(nameSpace + "." + className); Type t = asm.GetType(@namespace + "." + className); object o = Activator.CreateInstance(t); System.Reflection.MethodInfo method = t.GetMethod(funcName);//CONSULTAPPLYNOTICE_PATHOLOGY是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下 retItem = method.Invoke(o, parameters); } catch (WebException ex) { //网络异常异常 return(-1); } catch (Exception ex) { //未知错误 return(-99); } return(0); }
internal ServiceDescriptionImporter(System.CodeDom.CodeCompileUnit codeCompileUnit) : this() { this.codeCompileUnit = codeCompileUnit; }
public XmlSerializerImportOptions(System.CodeDom.CodeCompileUnit codeCompileUnit) { this.codeCompileUnit = codeCompileUnit; }
public Form1() { InitializeComponent(); cu = CreateGraph(); }
public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit) { return(typeDeclaration); // Not used }
public CompilerResults CompileAssemblyFromDom(CompilerParameters options, System.CodeDom.CodeCompileUnit compilationUnit) { return(_compiler.CompileAssemblyFromDom(options, compilationUnit)); }
// Create a CodeDOM graph. static void CreateGraph(CodeDomProvider provider, CodeCompileUnit cu) { if (!provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) { // Return if the generator does not support generics. return; } CodeNamespace ns = new CodeNamespace("DemoNamespace"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); cu.Namespaces.Add(ns); // Declare a generic class. CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "MyDictionary"; class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("TKey"), new CodeTypeReference("TValue"), })); CodeTypeParameter kType = new CodeTypeParameter("TKey"); kType.HasConstructorConstraint = true; kType.Constraints.Add(new CodeTypeReference(typeof(IComparable))); kType.CustomAttributes.Add(new CodeAttributeDeclaration( "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType")))); CodeTypeReference iComparableT = new CodeTypeReference("IComparable"); iComparableT.TypeArguments.Add(new CodeTypeReference(kType)); kType.Constraints.Add(iComparableT); CodeTypeParameter vType = new CodeTypeParameter("TValue"); vType.Constraints.Add(new CodeTypeReference(typeof(IList <System.String>))); vType.CustomAttributes.Add(new CodeAttributeDeclaration( "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("ValueType")))); class1.TypeParameters.Add(kType); class1.TypeParameters.Add(vType); ns.Types.Add(class1); // Declare a generic method. CodeMemberMethod printMethod = new CodeMemberMethod(); CodeTypeParameter sType = new CodeTypeParameter("S"); sType.HasConstructorConstraint = true; CodeTypeParameter tType = new CodeTypeParameter("T"); sType.HasConstructorConstraint = true; printMethod.Name = "Print"; printMethod.TypeParameters.Add(sType); printMethod.TypeParameters.Add(tType); printMethod.Statements.Add(ConsoleWriteLineStatement( new CodeDefaultValueExpression(new CodeTypeReference("T")))); printMethod.Statements.Add(ConsoleWriteLineStatement( new CodeDefaultValueExpression(new CodeTypeReference("S")))); printMethod.Attributes = MemberAttributes.Public; class1.Members.Add(printMethod); CodeTypeDeclaration class2 = new CodeTypeDeclaration(); class2.Name = "Demo"; CodeEntryPointMethod methodMain = new CodeEntryPointMethod(); CodeTypeReference myClass = new CodeTypeReference( "MyDictionary", new CodeTypeReference[] { new CodeTypeReference(typeof(int)), new CodeTypeReference("List", new CodeTypeReference[] { new CodeTypeReference("System.String") }) }); methodMain.Statements.Add( new CodeVariableDeclarationStatement(myClass, "dict", new CodeObjectCreateExpression(myClass))); methodMain.Statements.Add(ConsoleWriteLineStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("dict"), "Count"))); methodMain.Statements.Add(new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("dict"), "Print", new CodeTypeReference[] { new CodeTypeReference("System.Decimal"), new CodeTypeReference("System.Int32"), }), new CodeExpression[0]))); string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary <int, System.Collections.Generic.List <string> >[]).FullName; CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName); methodMain.Statements.Add( new CodeVariableDeclarationStatement(dictionaryType, "dict2", new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) }))); methodMain.Statements.Add(ConsoleWriteLineStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("dict2"), "Length"))); class2.Members.Add(methodMain); ns.Types.Add(class2); }
private static void GenerateViaCodeDOM(string outputFileName, System.CodeDom.Compiler.CodeDomProvider provider, System.CodeDom.CodeCompileUnit compileUnit) { System.CodeDom.Compiler.ICodeGenerator gen = provider.CreateGenerator(); System.CodeDom.Compiler.IndentedTextWriter tw; tw = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFileName, false), " "); System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; gen.GenerateCodeFromCompileUnit(compileUnit, tw, options); tw.Flush(); tw.Close(); }
// Create and compile code containing code directives. static void DemonstrateCodeDirectives(string providerName, string sourceFileName, string assemblyName) { CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName); Console.WriteLine("Building the CodeDOM graph..."); CodeCompileUnit cu = new CodeCompileUnit(); CreateGraph(cu); StringWriter sw = new StringWriter(); Console.WriteLine("Generating code..."); provider.GenerateCodeFromCompileUnit(cu, sw, null); string output = sw.ToString(); output = Regex.Replace(output, "Runtime Version:[^\r\n]*", "Runtime Version omitted for demo"); Console.WriteLine("Dumping source code..."); Console.WriteLine(output); Console.WriteLine("Writing source code to file..."); Stream s = File.Open(sourceFileName, FileMode.Create); StreamWriter t = new StreamWriter(s); t.Write(output); t.Close(); s.Close(); CompilerParameters opt = new CompilerParameters(new string[] { "System.dll", "System.Xml.dll", "System.Windows.Forms.dll", "System.Data.dll", "System.Drawing.dll" }); opt.GenerateExecutable = false; opt.TreatWarningsAsErrors = true; opt.IncludeDebugInformation = true; opt.GenerateInMemory = true; CompilerResults results; Console.WriteLine("Compiling with " + providerName); results = provider.CompileAssemblyFromFile(opt, sourceFileName); OutputResults(results); if (results.NativeCompilerReturnValue != 0) { Console.WriteLine(""); Console.WriteLine("Compilation failed."); } else { Console.WriteLine(""); Console.WriteLine("Demo complete."); } File.Delete(sourceFileName); }
public XsdDataContractImporter(System.CodeDom.CodeCompileUnit codeCompileUnit) { this.codeCompileUnit = codeCompileUnit; }
//<snippet7> public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit) { Console.WriteLine("ProcessImportedType"); foreach (CodeTypeMember member in typeDeclaration.Members) { object memberCustomData = member.UserData[typeof(IDataContractSurrogate)]; if (memberCustomData != null && memberCustomData is string && ((string)memberCustomData == "private")) { member.Attributes = ((member.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private); } } return(typeDeclaration); }
public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, System.CodeDom.CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { if (codeCompileUnit != null) { codeCompileUnit.ReferencedAssemblies.Add("System.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll"); } Hashtable namespaces = new Hashtable(); Hashtable exportContext = new Hashtable(); foreach (WebReference reference in webReferences) { ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit); XmlSchemas schemas = new XmlSchemas(); ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection(); foreach (DictionaryEntry entry in reference.Documents) { AddDocument((string)entry.Key, entry.Value, schemas, descriptions, reference.ValidationWarnings); } importer.Schemas.Add(schemas); foreach (ServiceDescription description in descriptions) { importer.AddServiceDescription(description, reference.AppSettingUrlKey, reference.AppSettingBaseUrl); } importer.CodeGenerator = codeProvider; importer.ProtocolName = reference.ProtocolName; importer.Style = options.Style; importer.CodeGenerationOptions = options.CodeGenerationOptions; foreach (string str in options.SchemaImporterExtensions) { importer.Extensions.Add(Type.GetType(str, true)); } System.Xml.Serialization.ImportContext importContext = Context(reference.ProxyCode, namespaces, options.Verbose); reference.Warnings = importer.Import(reference.ProxyCode, importContext, exportContext, reference.ValidationWarnings); if (reference.ValidationWarnings.Count != 0) { reference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation; } } StringCollection strings = new StringCollection(); if (options.Verbose) { foreach (System.Xml.Serialization.ImportContext context2 in namespaces.Values) { foreach (string str2 in context2.Warnings) { strings.Add(str2); } } } return(strings); }