Наследование: System.ComponentModel.Component
 private static string EscapeKeywords(string identifier, CodeDomProvider codeProvider)
 {
     if ((identifier == null) || (identifier.Length == 0))
     {
         return identifier;
     }
     string str = identifier;
     string[] strArray = identifier.Split(new char[] { '.', ',', '<', '>' });
     StringBuilder sb = new StringBuilder();
     int startIndex = -1;
     for (int i = 0; i < strArray.Length; i++)
     {
         if (startIndex >= 0)
         {
             sb.Append(str.Substring(startIndex, 1));
         }
         startIndex++;
         startIndex += strArray[i].Length;
         EscapeKeywords(strArray[i].Trim(), codeProvider, sb);
     }
     if (sb.Length != str.Length)
     {
         return sb.ToString();
     }
     return str;
 }
Пример #2
0
 public OutputClass(string name, System.CodeDom.Compiler.CodeDomProvider codedomprovider, int savefilterindex)
 {
     this.name            = string.Empty;
     this.name            = name;
     this.codedomprovider = codedomprovider;
     this.savefilterindex = savefilterindex;
 }
Пример #3
0
 public bool Compile(CodeDomProvider codeProvider, string source, TempFileRef dataContextAssembly, QueryLanguage queryKind, string compilerOptions)
 {
     if (this.IsMyExtensions)
     {
         string directoryName = Path.GetDirectoryName(MyExtensions.QueryFilePath);
         if (!Directory.Exists(directoryName))
         {
             Directory.CreateDirectory(directoryName);
         }
         TempFileRef ref2 = new TempFileRef(Path.ChangeExtension(MyExtensions.QueryFilePath, ".dll")) {
             AutoDelete = false
         };
         this.OutputFile = ref2;
         TempFileRef ref3 = new TempFileRef(Path.ChangeExtension(MyExtensions.QueryFilePath, ".pdb")) {
             AutoDelete = false
         };
         this.PDBFile = ref3;
     }
     else
     {
         this.OutputFile = TempFileRef.GetRandom("query", ".dll");
         this.PDBFile = new TempFileRef(Path.ChangeExtension(this.OutputFile.FullPath, ".pdb"));
     }
     List<string> references = new List<string>(this.References);
     if (!((dataContextAssembly == null) || string.IsNullOrEmpty(dataContextAssembly.FullPath)))
     {
         references.Add(dataContextAssembly.FullPath);
     }
     return base.Compile(codeProvider, references, source.ToString(), this.OutputFile.FullPath, compilerOptions);
 }
        //public override string ImportSchemaType(
        //    string name, 
        //    string ns, 
        //    XmlSchemaObject context, 
        //    XmlSchemas schemas, 
        //    XmlSchemaImporter importer,
        //    CodeCompileUnit compileUnit, 
        //    CodeNamespace mainNamespace, 
        //    CodeGenerationOptions options, 
        //    CodeDomProvider codeProvider)
        //{

        //    XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType) schemas.Find(new XmlQualifiedName(name, ns), typeof(XmlSchemaSimpleType));
        //    return ImportSchemaType(
        //        simpleType, 
        //        context, 
        //        schemas, 
        //        importer, 
        //        compileUnit, 
        //        mainNamespace, 
        //        options, 
        //        codeProvider);
        //}

        public override string ImportSchemaType(
            XmlSchemaType type, 
            XmlSchemaObject context, 
            XmlSchemas schemas, 
            XmlSchemaImporter importer,
            CodeCompileUnit compileUnit, 
            CodeNamespace mainNamespace, 
            CodeGenerationOptions options, 
            CodeDomProvider codeProvider)
        {

            XmlSchemaAnnotated annotatedType  = type as XmlSchemaAnnotated;
            if (annotatedType == null)
                return null;

            if (annotatedType.Annotation == null)
                return null;

            // create the comments and add them to the hash table under the namespace of the object
            CreateComments(annotatedType);

            //mainNamespace.Types.

            return null;

        }
Пример #5
0
 public SimpleCSharpCompiler(string UniqueIdentifier)
 {
     uniqueIdentifier = UniqueIdentifier;
     Provider = CreateCodeDomProvider("Microsoft.CSharp.CSharpCodeProvider", "System");
     //Compiler = provider.CreateCompiler();
     //CodeGen = provider.CreateGenerator();
 }
 public override void StartProcessingRun(CodeDomProvider languageProvider, string templateContents, System.CodeDom.Compiler.CompilerErrorCollection errors)
 {
     callContextMembersWriter = new StringWriter();
     fieldWriter = new StringWriter();
     this.languageProvider = languageProvider;
     base.StartProcessingRun(languageProvider, templateContents, errors);
 }
Пример #7
0
        /// <summary>Called when extension shall processs generated CodeDOM</summary>
        /// <param name="code">Object tree representing generated CodeDOM</param>
        /// <param name="schema">Input XML schema</param>
        /// <param name="provider">CodeDOM provider (the language)</param>
        /// <version version="1.5.3">Added documentation</version>
        /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version>
        public void Process(CodeNamespace code, XmlSchema schema, CodeDomProvider provider)
        {
            // Copy as we will be adding types.
            CodeTypeDeclaration[] types =
                new CodeTypeDeclaration[code.Types.Count];
            code.Types.CopyTo(types, 0);

            foreach (CodeTypeDeclaration type in types) {
                if (type.IsClass || type.IsStruct) {
                    foreach (CodeTypeMember member in type.Members) {
                        if (member is CodeMemberField && ((CodeMemberField)member).Type.ArrayElementType != null) {
                            CodeMemberField field = (CodeMemberField)member;
                            // Change field type to collection.
                            field.Type = GetCollection(field.Type.ArrayElementType);
                            field.InitExpression = new CodeObjectCreateExpression(field.Type);
                            if (field.Name.EndsWith("Field"))
                                field.Comments.Add(new CodeCommentStatement(string.Format("<summary>Contains value of the <see cref='{0}'/> property</summary>", field.Name.Substring(0, field.Name.Length - "field".Length)), true));
                        } else if (member is CodeMemberProperty && ((CodeMemberProperty)member).Type.ArrayElementType != null) {
                            CodeMemberProperty Property = (CodeMemberProperty)member;
                            Property.Type = GetCollection(Property.Type.ArrayElementType);
                            Property.HasSet = false;
                        }
                    }
                }
            }
        }
Пример #8
0
        internal static bool CompileCode(CodeDomProvider provider, Assembly userAssembly, string[] generatedSrcFiles)
        {
            // Parameters for compilation
            String[] referenceAssemblies = {
                "System.dll",
                "System.ServiceModel.dll",
                "System.Configuration.dll",
                userAssembly.Location
                                            };
            string compiledFile = "temp.dll";

            CompilerParameters cp = new CompilerParameters(referenceAssemblies, compiledFile, false);
            cp.GenerateExecutable = false;

            Console.WriteLine("Compiling files: ");
            foreach (string fileName in generatedSrcFiles)
            {
                Console.WriteLine(fileName);
            }
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, generatedSrcFiles);

            if (cr.Errors.Count > 0)
            {
                Console.WriteLine("Please investigate. The tool encountered errors during compilation");
                foreach (CompilerError ce in cr.Errors)
                    Console.WriteLine(ce.ToString());
                return false;
            }
            else
            {
                Console.WriteLine("No errors encountered during compilation");
                File.Delete(compiledFile);
            }
            return true;
        }
Пример #9
0
		public static Assembly Compile(CodeDomProvider cp, string scriptCode, IList assemblies)
		{
			ICodeCompiler ic = cp.CreateCompiler();
			CompilerParameters cpar = GetCompilerParameters(assemblies);
			CompilerResults cr = ic.CompileAssemblyFromSource(cpar, scriptCode);

			bool errors = false;

			if (cr.Errors.Count > 0)
			{
				StringBuilder sb = new StringBuilder("Error compiling the composition script:\n");
				foreach (CompilerError ce in cr.Errors)
				{
					if (!ce.IsWarning)
					{
						errors = true;

						sb.Append("\nError number:\t")
							.Append(ce.ErrorNumber)
							.Append("\nMessage:\t ")
							.Append(ce.ErrorText)
							.Append("\nLine number:\t")
							.Append(ce.Line);
					}
				}
				if (errors)
				{
					throw new PicoCompositionException(sb.ToString());
				}
			}

			return cr.CompiledAssembly;
		}
Пример #10
0
 public void Dispose()
 {
     if (provider == null)
         return;
     provider.Dispose();
     provider = null;
 }
Пример #11
0
 private void Compile(CodeDom.CodeDomProvider provider, string source)
 {
     CodeDom.CompilerParameters param = new CodeDom.CompilerParameters();
     param.GenerateExecutable      = false;
     param.IncludeDebugInformation = false;
     param.GenerateInMemory        = true;
     CodeDom.CompilerResults      cr     = provider.CompileAssemblyFromSource(param, source);
     Specialized.StringCollection output = cr.Output;
     if (cr.Errors.Count != 0)
     {
         System.Console.WriteLine("Error invoking scripts.");
         CodeDom.CompilerErrorCollection es = cr.Errors;
         foreach (CodeDom.CompilerError s in es)
         {
             System.Console.WriteLine(s.ErrorText);
         }
     }
     else
     {
         object      o    = cr.CompiledAssembly.CreateInstance("Script");
         System.Type type = o.GetType();
         type.InvokeMember("ScriptExecute",
                           Reflection.BindingFlags.InvokeMethod |
                           Reflection.BindingFlags.Default, null, o, null);
     }
 }
		//construct, given the code provider being used.
		public CompileDirectives(CodeDomProvider codeProvider)
		{
			this.codeProvider = codeProvider;

			if (codeProvider.FileExtension == "cs")
			{
				readonlySnip = new CodeSnippetTypeMember("readonly ");
				isCSharp = true;
			}
			if (codeProvider.FileExtension == "vb")
				readonlySnip = new CodeSnippetTypeMember("ReadOnly ");


			//try and load the directives from the user config.
			try
			{
				//GenericType
				string defaultDiretive = Properties.Settings.Default.DefaultCompilerDirectives.Trim();
				if (defaultDiretive.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Length == 3)
					directives = defaultDiretive.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

				System.Reflection.PropertyInfo[] properties = Properties.Settings.Default.GetType().GetProperties();

				foreach (System.Reflection.PropertyInfo property in properties)
				{
					if (property.PropertyType == typeof(string) && property.Name.EndsWith("CompilerDirectives", StringComparison.InvariantCultureIgnoreCase))
					{
						string directive = property.GetValue(Properties.Settings.Default, null) as string;

						if (directive != null)
						{
							string[] lines = directive.Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
							if (lines.Length == 4)
							{
								if (("*." + codeProvider.FileExtension).Equals(lines[0].Trim(), StringComparison.InvariantCultureIgnoreCase))
								{
									for (int i = 0; i < 3; i++)
									{
										directives[i] = lines[i + 1];
									}
								}
							}
						}
					}
				}

				for (int i = 0; i < directives.Length; i++)
				{
					directives[i] = directives[i].Trim();
				}

				if (directives[0].Contains("{0}") == false)
					throw new Exception("Could not find {0} in directive 0");

			}
			catch (Exception e)
			{
				throw new Exception("Error in user.config file", e);
			}
		}
Пример #13
0
 /// <summary>Called when extension shall process generated code</summary>
 /// <param name="code">The code</param>
 /// <param name="provider">CodeDOM provider (the language)</param>
 /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version>
 public void PostProcess(ref string code, CodeDomProvider provider)
 {
     System.IO.StringWriter tw = new System.IO.StringWriter();
     provider.GenerateCodeFromStatement(new CodeCommentStatement(FirtsLineOfAccessor), tw, new System.CodeDom.Compiler.CodeGeneratorOptions());
     string srch = tw.GetStringBuilder().ToString();
     if (srch.EndsWith("\r\n")) srch = srch.Substring(0, srch.Length - 2);
     else if (srch.EndsWith("\r") || srch.EndsWith("\n")) srch = srch.Substring(0, srch.Length - 1);
     tw = new System.IO.StringWriter();
     CodeTypeDeclaration foo = new CodeTypeDeclaration("foo");
     foo.CustomAttributes.Add(NewAttribute);
     provider.GenerateCodeFromType(foo, tw, new System.CodeDom.Compiler.CodeGeneratorOptions());
     string attr = new System.IO.StringReader(tw.GetStringBuilder().ToString()).ReadLine();
     System.IO.StringReader sr = new System.IO.StringReader(code);
     List<String> Lines = new List<string>();
     do {
         string line = sr.ReadLine();
         if (line == null) break;
         if (line.EndsWith(srch))
             Lines[Lines.Count - 1] = attr + "\r\n" + Lines[Lines.Count - 1];
         else
             Lines.Add(line);
     } while (true);
     System.Text.StringBuilder b = new System.Text.StringBuilder();
     foreach (string line in Lines)
         b.AppendLine(line);
     code = b.ToString();
 }
 internal AssemblyBuilder(CompilationSection compConfig, ICollection referencedAssemblies, CompilerType compilerType, string outputAssemblyName)
 {
     this._compConfig = compConfig;
     this._outputAssemblyName = outputAssemblyName;
     this._initialReferencedAssemblies = AssemblySet.Create(referencedAssemblies);
     this._compilerType = compilerType.Clone();
     if (BuildManager.PrecompilingWithDebugInfo)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = true;
     }
     else if (BuildManager.PrecompilingForDeployment)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = false;
     }
     else if (DeploymentSection.RetailInternal)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = false;
     }
     else if (this._compConfig.AssemblyPostProcessorTypeInternal != null)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = true;
     }
     this._tempFiles.KeepFiles = this._compilerType.CompilerParameters.IncludeDebugInformation;
     this._codeProvider = CompilationUtil.CreateCodeDomProviderNonPublic(this._compilerType.CodeDomProviderType);
     this._maxBatchSize = this._compConfig.MaxBatchSize;
     this._maxBatchGeneratedFileSize = this._compConfig.MaxBatchGeneratedFileSize * 0x400;
 }
Пример #15
0
		public Dictionary<string, List<NSObjectTypeInfo>> GetTypeUpdates (IProgressMonitor monitor, CodeDomProvider provider,
			out Dictionary<string, NSObjectTypeInfo> newTypes,
			out Dictionary<string, ProjectFile> newFiles)
		{
			Dictionary<string, List<NSObjectTypeInfo>> designerFiles = new Dictionary<string, List<NSObjectTypeInfo>> ();
			string defaultNamespace;
			
			// First, we need to name any new user-defined types.
			foreach (var job in TypeSyncJobs) {
				if (!job.IsFreshlyAdded) {
					monitor.Log.WriteLine ("Found updated class: {0}", job.Type.CliName);
					continue;
				}
				
				defaultNamespace = Project.GetDefaultNamespace (job.RelativePath);
				job.Type.CliName = defaultNamespace + "." + provider.CreateValidIdentifier (job.Type.ObjCName);
				monitor.Log.WriteLine ("Found newly-added class: {0}", job.Type.CliName);
				ProjectInfo.InsertUpdatedType (job.Type);
			}
			
			// Next we can resolve base-types, outlet types, and action parameter types for each of our user-defined types.
			foreach (var job in TypeSyncJobs) {
				defaultNamespace = Project.GetDefaultNamespace (job.RelativePath);
				ProjectInfo.ResolveObjcToCli (monitor, job.Type, provider, defaultNamespace);
			}
			
			AggregateTypeUpdates (monitor, provider, designerFiles, out newTypes, out newFiles);
			MergeExistingTypes (designerFiles);
			
			return designerFiles;
		}
		public override void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors)
		{
			base.StartProcessingRun (languageProvider, templateContents, errors);
			provider = languageProvider;
			postStatements.Clear ();
			members.Clear ();
		}
Пример #17
0
 public ProjectCompiler(Logger logger, CodeDomProvider codeProvider,
     IEnumerable<Path> referencedAssemblies)
 {
     this.logger = logger;
     this.codeProvider = codeProvider;
     this.referencedAssemblies = referencedAssemblies;
 }
Пример #18
0
        protected bool Supports (CodeDomProvider provider, GeneratorSupport support) {
#if WHIDBEY
            return provider.Supports (support);
#else
            return (provider.CreateGenerator ()).Supports (support);
#endif
        }
Пример #19
0
        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;
            }
        }
 internal string GenerateTypedDataSet(XmlSchemaElement element, XmlSchemas schemas, CodeNamespace codeNamespace, StringCollection references, CodeDomProvider codeProvider)
 {
     if (element == null)
     {
         return null;
     }
     if (this.importedTypes[element.SchemaType] != null)
     {
         return (string) this.importedTypes[element.SchemaType];
     }
     IList list = schemas.GetSchemas(element.QualifiedName.Namespace);
     if (list.Count != 1)
     {
         return null;
     }
     XmlSchema schema = list[0] as XmlSchema;
     if (schema == null)
     {
         return null;
     }
     DataSet dataSet = new DataSet();
     using (MemoryStream stream = new MemoryStream())
     {
         schema.Write(stream);
         stream.Position = 0L;
         dataSet.ReadXmlSchema(stream);
     }
     string name = new TypedDataSetGenerator().GenerateCode(dataSet, codeNamespace, codeProvider.CreateGenerator()).Name;
     this.importedTypes.Add(element.SchemaType, name);
     references.Add("System.Data.dll");
     return name;
 }
 internal static CodeCompileUnit Create(IDictionary resourceList, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out string[] unmatchable)
 {
     if (resourceList == null)
     {
         throw new ArgumentNullException("resourceList");
     }
     Dictionary<string, ResourceData> dictionary = new Dictionary<string, ResourceData>(StringComparer.InvariantCultureIgnoreCase);
     foreach (DictionaryEntry entry in resourceList)
     {
         ResourceData data;
         ResXDataNode node = entry.Value as ResXDataNode;
         if (node != null)
         {
             string key = (string) entry.Key;
             if (key != node.Name)
             {
                 throw new ArgumentException(Microsoft.Build.Tasks.SR.GetString("MismatchedResourceName", new object[] { key, node.Name }));
             }
             Type type = Type.GetType(node.GetValueTypeName((AssemblyName[]) null));
             string valueIfItWasAString = null;
             if (type == typeof(string))
             {
                 valueIfItWasAString = (string) node.GetValue((AssemblyName[]) null);
             }
             data = new ResourceData(type, valueIfItWasAString);
         }
         else
         {
             Type type2 = (entry.Value == null) ? typeof(object) : entry.Value.GetType();
             data = new ResourceData(type2, entry.Value as string);
         }
         dictionary.Add((string) entry.Key, data);
     }
     return InternalCreate(dictionary, baseName, generatedCodeNamespace, resourcesNamespace, codeProvider, internalClass, out unmatchable);
 }
Пример #22
0
 public MigrationContext(
     MigrationSettings settings,
     OrmPackage package,
     PortalApplication portal,
     BundleManifest manifest,
     IVSProject vsProject,
     CodeDomProvider codeProvider,
     StrongNameKeyPair keyPair,
     IExtendedLog log,
     IOperationStatus status,
     ICollection<Plugin> plugins)
 {
     _settings = settings;
     _package = package;
     _portal = portal;
     _manifest = manifest;
     _vsProject = vsProject;
     _codeProvider = codeProvider;
     _keyPair = keyPair;
     _log = log;
     _status = status;
     _plugins = plugins;
     _forms = new Dictionary<string, FormInfo>(StringComparer.InvariantCultureIgnoreCase);
     _mainViews = new Dictionary<string, MainViewInfo>(StringComparer.InvariantCultureIgnoreCase);
     _navigation = new List<NavigationInfo>();
     _scripts = new Dictionary<string, ScriptInfo>(StringComparer.InvariantCultureIgnoreCase);
     _tables = new Dictionary<string, TableInfo>(StringComparer.InvariantCultureIgnoreCase);
     _entities = new Dictionary<string, OrmEntity>(StringComparer.InvariantCultureIgnoreCase);
     _relationships = new Dictionary<DataPathJoin, RelationshipInfo>();
     _linkedFiles = new List<LinkedFile>();
     _localizedStrings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
     _references = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
     _smartParts = new List<SmartPartMapping>();
     _secondaryJoins = new Dictionary<DataPathJoin, DataPathJoin>();
 }
 internal AssemblyBuilder(CompilationSection compConfig, ICollection referencedAssemblies, CompilerType compilerType, string outputAssemblyName)
 {
     this._compConfig                  = compConfig;
     this._outputAssemblyName          = outputAssemblyName;
     this._initialReferencedAssemblies = AssemblySet.Create(referencedAssemblies);
     this._compilerType                = compilerType.Clone();
     if (BuildManager.PrecompilingWithDebugInfo)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = true;
     }
     else if (BuildManager.PrecompilingForDeployment)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = false;
     }
     else if (DeploymentSection.RetailInternal)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = false;
     }
     else if (this._compConfig.AssemblyPostProcessorTypeInternal != null)
     {
         this._compilerType.CompilerParameters.IncludeDebugInformation = true;
     }
     this._tempFiles.KeepFiles       = this._compilerType.CompilerParameters.IncludeDebugInformation;
     this._codeProvider              = CompilationUtil.CreateCodeDomProviderNonPublic(this._compilerType.CodeDomProviderType);
     this._maxBatchSize              = this._compConfig.MaxBatchSize;
     this._maxBatchGeneratedFileSize = this._compConfig.MaxBatchGeneratedFileSize * 0x400;
 }
        internal BindingElementExtensionSectionGenerator(Type bindingElementType, Assembly userAssembly, CodeDomProvider provider)
        {
            this.bindingElementType = bindingElementType;
            this.userAssembly = userAssembly;
            this.provider = provider;

            string typePrefix = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement));
            this.generatedClassName = typePrefix + Constants.ElementSuffix;
            this.constantsClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.ConfigurationStrings;
            this.defaultValuesClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.Defaults;

            this.customBEVarInstance = Helpers.TurnFirstCharLower(bindingElementType.Name);
            customBEArgRef = new CodeArgumentReferenceExpression(customBEVarInstance);

            this.customBETypeRef = new CodeTypeReference(bindingElementType.Name);
            this.customBETypeOfRef = new CodeTypeOfExpression(customBETypeRef);
            this.customBENewVarAssignRef = new CodeVariableDeclarationStatement(
                                                customBETypeRef,
                                                customBEVarInstance,
                                                new CodeObjectCreateExpression(customBETypeRef));
            this.bindingElementMethodParamRef = new CodeParameterDeclarationExpression(
                                                    CodeDomHelperObjects.bindingElementTypeRef,
                                                    Constants.bindingElementParamName);

        }
Пример #25
0
 public CodeDomFileCodeModel(DTE dte, IVsTextLines buffer, CodeDomProvider provider, string moniker)
     : base(dte, moniker)
 {
     this.textBuffer = buffer;
     this.provider = provider as IMergableProvider;
     if (provider == null) throw new ArgumentException("provider must implement IMergeableProvider interface");
 }
Пример #26
0
        private CodeDomCodeNamespace vsTopNamespace; // top-level CodeModel namespace

        #endregion Fields

        #region Constructors

        public CodeDomFileCodeModel(DTE dte, ProjectItem parent, CodeDomProvider provider, string filename)
            : base(dte, filename)
        {
            this.parent = parent;
            this.provider = provider as IMergableProvider;
            if (provider == null) throw new ArgumentException("provider must implement IMergeableProvider interface");
        }
 public static FileCodeModel CreateFileCodeModel(DTE dte, ProjectItem item, CodeDomProvider provider, string fileName)
 {
     if (null == item) {
         throw new ArgumentNullException("item");
     }
     return new CodeDomFileCodeModel(dte, item, provider, fileName);
 }
Пример #28
0
		private void WriteClassFile(Project project, String name, CodeNamespace ns, CodeDomProvider provider)
		{
			String filename =  String.Format("{0}.{1}", name, provider.FileExtension);

			FileInfo fileInfo = new FileInfo( Path.Combine(project.LastOutDir, filename) );

			if (fileInfo.Exists && !project.OverwriteFiles)
			{
				Log( String.Format("Skipping {0} as it already exists", filename) );
			}
			else
			{
				Log( String.Format("Writing {0}...", filename) );

				try
				{
					using(FileStream stream = new FileStream(fileInfo.FullName, FileMode.Create, FileAccess.Write))
					{
						StreamWriter writer = new StreamWriter(stream);
						CodeGeneratorOptions opts = new CodeGeneratorOptions();
						opts.BracingStyle = "C";
						opts.BlankLinesBetweenMembers = true;
						provider.CreateGenerator().GenerateCodeFromNamespace(ns, writer, opts);
						writer.Flush();
						writer.Close();
					}
				}
				catch(Exception ex)
				{
					Log( String.Format("Error Writing {0} []", filename, ex.Message) );
				}
			}
		}
 internal QueryHandler(CodeDomProvider codeProvider, DesignTable designTable)
 {
     this.codeGenerator = new TypedDataSourceCodeGenerator();
     this.codeGenerator.CodeProvider = codeProvider;
     this.designTable = designTable;
     this.languageSupportsNullables = this.codeGenerator.CodeProvider.Supports(GeneratorSupport.GenericTypeReference);
 }
 internal string GenerateTypedDataSet(XmlSchemaElement element, XmlSchemas schemas, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeDomProvider codeProvider)
 {
     if (element == null)
     {
         return null;
     }
     if (this.importedTypes[element.SchemaType] != null)
     {
         return (string) this.importedTypes[element.SchemaType];
     }
     IList list = schemas.GetSchemas(element.QualifiedName.Namespace);
     if (list.Count != 1)
     {
         return null;
     }
     XmlSchema schema = list[0] as XmlSchema;
     if (schema == null)
     {
         return null;
     }
     MemoryStream stream = new MemoryStream();
     schema.Write(stream);
     stream.Position = 0L;
     DesignDataSource designDS = new DesignDataSource();
     designDS.ReadXmlSchema(stream, null);
     stream.Close();
     string str = TypedDataSetGenerator.GenerateInternal(designDS, compileUnit, mainNamespace, codeProvider, this.dataSetGenerateOptions, null);
     this.importedTypes.Add(element.SchemaType, str);
     return str;
 }
Пример #31
0
        /// <summary>
        /// once the grammar compiles correctly, the code can be built.
        /// </summary>
        private void BuildCode()
        {
            string language = Grammar.Directives["TinyPG"]["Language"];

            CodeDom.CompilerResults Result;
            CodeDom.CodeDomProvider provider = CodeGeneratorFactory.CreateCodeDomProvider(language);
            if (provider == null)
            {
                Errors.Add("Can't compile " + language + " project.");
                return;
            }
            System.CodeDom.Compiler.CompilerParameters compilerparams = new System.CodeDom.Compiler.CompilerParameters();
            compilerparams.GenerateInMemory   = true;
            compilerparams.GenerateExecutable = false;
            compilerparams.ReferencedAssemblies.Add("System.dll");
            compilerparams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            compilerparams.ReferencedAssemblies.Add("System.Drawing.dll");
            compilerparams.ReferencedAssemblies.Add("System.Xml.dll");

            // reference this assembly to share interfaces (for debugging only)

            string tinypgfile = Assembly.GetExecutingAssembly().Location;

            compilerparams.ReferencedAssemblies.Add(tinypgfile);

            // generate the code with debug interface enabled
            List <string>  sources = new List <string>();
            ICodeGenerator generator;

            foreach (Directive d in Grammar.Directives)
            {
                generator = CodeGeneratorFactory.CreateGenerator(d.Name, language);
                if (generator != null && d.ContainsKey("FileName"))
                {
                    generator.FileName = d["FileName"];
                }

                if (generator != null && d["Generate"].ToLower() == "true")
                {
                    sources.Add(generator.Generate(Grammar, true));
                }
            }

            if (sources.Count > 0)
            {
                Result = provider.CompileAssemblyFromSource(compilerparams, sources.ToArray());

                if (Result.Errors.Count > 0)
                {
                    foreach (CodeDom.CompilerError o in Result.Errors)
                    {
                        Errors.Add(o.ErrorText + " on line " + o.Line.ToString());
                    }
                }
                else
                {
                    assembly = Result.CompiledAssembly;
                }
            }
        }
Пример #32
0
		public static string Generate (string inputFileContent, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeDomProvider codeProvider)
		{
			var dataSet = new DataSet ();
			dataSet.ReadXmlSchema (inputFileContent);
			T.Generate (dataSet, mainNamespace, codeProvider.CreateGenerator ());
			return null;
		}
		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 override bool Execute() {
            try {
                try {
                    codeDomProvider = CodeDomProvider.CreateProvider(Language);
                } catch (ConfigurationErrorsException) {
                    LogError(classNameLineNumber, 1, "CodeDom provider for language '" + Language + "' not found.");
                    return false;
                }

                typeAttributesConverter = codeDomProvider.GetConverter(typeof(TypeAttributes));

                if (!ParseInput()) {
                    return false;
                }

                if (lambdas.Count == 0) {
                    OutputFileName = null;
                    return true;
                }

                if (className == null) {
                    LogError(classNameLineNumber, 1501, "x:Class not found on root element.");
                    return false;
                }
                if (!className.Contains(".")) {
                    LogError(classNameLineNumber, 1502, "x:Class does not include namespace name.");
                    return false;
                }

                return GenerateOutput();
            } catch (Exception ex) {
                LogError(null, 0, 0, ex.Message);
                return false;
            }
        }
Пример #35
0
        /// <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);
            }
        }
Пример #36
0
 private void Dispose(bool dispose)
 {
     if (dispose && (this.codeDomProvider != null))
     {
         this.codeDomProvider.Dispose();
         this.codeDomProvider = null;
     }
 }
Пример #37
0
 /// <summary>
 /// Initialize the static members of the Middle Tier Compiler.
 /// </summary>
 static MiddleTierCompiler()
 {
     // Initialize the object
     MiddleTierCompiler.codeProvider         = CodeDomProvider.CreateProvider("C#");
     MiddleTierCompiler.codeGeneratorOptions = new CodeGeneratorOptions();
     MiddleTierCompiler.codeGeneratorOptions.BlankLinesBetweenMembers = true;
     MiddleTierCompiler.codeGeneratorOptions.BracingStyle             = "C";
     MiddleTierCompiler.codeGeneratorOptions.IndentString             = "\t";
 }
Пример #38
0
        public override void StartProcessingRun(System.CodeDom.Compiler.CodeDomProvider languageProvider,
                                                string templateContents,
                                                System.CodeDom.Compiler.CompilerErrorCollection errors)
        {
            AssertNotProcessing();
            isInProcessingRun = true;
            base.StartProcessingRun(languageProvider, templateContents, errors);

            throw new NotImplementedException();
        }
Пример #39
0
        /// <summary>
        /// Initializes the properties code writer.
        /// </summary>
        public override void StartProcessingRun(CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors)
        {
            base.StartProcessingRun(languageProvider, templateContents, errors);

            if (languageProvider == null)
            {
                throw new ArgumentNullException("languageProvider");
            }
            this.codeWriter       = new StringWriter(CultureInfo.CurrentCulture);
            this.languageProvider = languageProvider;
        }
    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();
    }
Пример #41
0
        private static Type CreateCodeGeneratorType(System.CodeDom.Compiler.CodeDomProvider compilerProvider, string resourceName, string typeName)
        {
            string sourceCode = null;

            using (Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(sourceStream))
                {
                    sourceCode = reader.ReadToEnd();
                }

            CompilerParameters compilerParams = new CompilerParameters();

            compilerParams.CompilerOptions    = "/d:PREPROCESSED_TEMPLATE";
            compilerParams.GenerateInMemory   = true;
            compilerParams.GenerateExecutable = false;
            // grab the assemblies by location so that we don't compile against one that we didn't reference
            compilerParams.ReferencedAssemblies.AddRange(new string[] {
                typeof(System.CodeDom.Compiler.CodeDomProvider).Assembly.Location,                      // System.dll
                typeof(System.Linq.Enumerable).Assembly.Location,                                       // System.Core.dll
                typeof(System.Data.Objects.ObjectContext).Assembly.Location,                            // System.Data.Entity.dll
                typeof(System.Data.Entity.Design.EntityCodeGenerator).Assembly.Location,                // System.Data.Entity.Design.dll
                typeof(System.Data.DbType).Assembly.Location,                                           // System.Data.dll
                typeof(System.Xml.XmlAttribute).Assembly.Location,                                      // System.Xml.dll
                typeof(System.Xml.Linq.XElement).Assembly.Location,                                     // System.Xml.Linq.dll
            });

#if !ENABLE_TEMPLATE_DEBUGGING
            CompilerResults results = compilerProvider.CompileAssemblyFromSource(compilerParams, sourceCode);
#else
            // enables debugging
            compilerParams.GenerateInMemory        = false;
            compilerParams.IncludeDebugInformation = true;
            string baseName = Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".";
            compilerParams.OutputAssembly = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Assembly.dll");
            string sourceFileName = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Source." + compilerProvider.FileExtension);
            File.WriteAllText(sourceFileName, sourceCode);
            CompilerResults results = compilerProvider.CompileAssemblyFromFile(compilerParams, sourceFileName);
#warning DO NOT CHECK IN LIKE THIS, Dynamic Assembly Debugging is enabled
#endif


            if (results.Errors.HasErrors)
            {
                string message = results.Errors.OfType <CompilerError>().Aggregate(string.Empty, (accumulated, input) => accumulated == string.Empty ? input.ToString() : accumulated + Environment.NewLine + input.ToString());
                throw EDesignUtil.InvalidOperation(message);
            }

            return(results.CompiledAssembly.GetType(typeName));
        }
Пример #42
0
        private System.CodeDom.Compiler.CodeDomProvider GetCodeDomProvider(string language)
        {
            System.CodeDom.Compiler.CodeDomProvider provider = null;
            var binding = GetLanguageBinding(language);

            if (binding == null)
            {
                throw new InvalidOperationException(GettextCatalog.GetString("No LanguageBinding was found for the language '{0}'.", language));
            }

            provider = binding.GetCodeDomProvider();
            if (provider == null)
            {
                throw new InvalidOperationException(GettextCatalog.GetString("No CodeDomProvider was found for the language '{0}'.", language));
            }
            return(provider);
        }
Пример #43
0
        private System.CodeDom.Compiler.CodeDomProvider GetCodeDomProvider(string language)
        {
            System.CodeDom.Compiler.CodeDomProvider provider = null;
            IDotNetLanguageBinding binding = GetLanguageBinding(language) as IDotNetLanguageBinding;

            if (binding == null)
            {
                throw new InvalidOperationException("No LanguageBinding was found for the language '" + language + "'.");
            }

            provider = binding.GetCodeDomProvider();
            if (provider == null)
            {
                throw new InvalidOperationException("No CodeDomProvider was found for the language '" + language + "'.");
            }
            return(provider);
        }
Пример #44
0
        public override void ModifyTags(SolutionFolderItem policyParent, Project project, string language, string identifier, string fileName, ref Dictionary <string, string> tags)
        {
            //prevent parser breakage from missing tags, which SingleFile only provides for DotNetProject
            //if ((project as DotNetProject) == null)
            //	throw new InvalidOperationException ("CodeTranslationFileDescriptionTemplate can only be used with a DotNetProject");

            base.ModifyTags(policyParent, project, language, identifier, fileName, ref tags);

            //swap out the escaped keyword identifiers for the target language with the source language
            //CodeDOM should take care of handling it for the target language
            System.CodeDom.Compiler.CodeDomProvider provider = GetCodeDomProvider(sourceLang);
            tags ["EscapedIdentifier"] = provider.CreateEscapedIdentifier((string)tags ["Name"]);

            //This is a bit hacky doing it here instead of in CreateContent, but need to
            //substitute all tags in code before language is translated, because language
            //translation gets confused by unsubstituted  substitution tokens.
            tempSubstitutedContent = StringParserService.Parse(content, tags);
        }
Пример #45
0
 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();
         }
     }
 }
Пример #46
0
        private void Compile(bool file)
        {
            System.CodeDom.Compiler.CodeDomProvider CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");

            System.CodeDom.Compiler.CompilerParameters CompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
            CompilerParameters.ReferencedAssemblies.Add("System.dll");
            CompilerParameters.ReferencedAssemblies.Add("System.Data.dll");
            CompilerParameters.ReferencedAssemblies.Add("System.Xml.dll");
            CompilerParameters.ReferencedAssemblies.Add("System.Linq.dll");
            CompilerParameters.ReferencedAssemblies.Add("RakNetSwig.dll");
            CompilerParameters.ReferencedAssemblies.Add("GMP_Server.exe");


            foreach (String str in Program.serverOptions.AdditionalLibs)
            {
                CompilerParameters.ReferencedAssemblies.Add(str);
            }



            CompilerParameters.CompilerOptions = "/t:library";///debug:full
            for (int i = 0; i < Program.serverOptions.AdditionalSymbols.Count; i++)
            {
                String str = Program.serverOptions.AdditionalSymbols[i];
                if (i == 0)
                {
                    CompilerParameters.CompilerOptions += "/define: ";
                }
                CompilerParameters.CompilerOptions += str;
                if (i != Program.serverOptions.AdditionalLibs.Count - 1)
                {
                    CompilerParameters.CompilerOptions += ";";
                }
            }

            CompilerParameters.IncludeDebugInformation = true;

            if (!file)
            {
                CompilerParameters.GenerateInMemory = true;
            }
            else
            {
                CompilerParameters.GenerateInMemory = false;
                CompilerParameters.OutputAssembly   = "scripts/_compiled/ServerScripts.dll";
            }

            List <String> fileList = new List <string>();

            GetFileList(fileList, "scripts/server");
            //getFileList(fileList, "scripts/both");

            System.CodeDom.Compiler.CompilerResults CompilerResults = CodeDomProvider.CompileAssemblyFromFile(CompilerParameters, fileList.ToArray());
            if (CompilerResults.Errors.Count > 0)
            {
                foreach (CompilerError col in CompilerResults.Errors)
                {
                    Log.Logger.log(Log.Logger.LOG_ERROR, col.FileName + ":" + col.Line + " \t" + col.ErrorText);
                }
                return;
            }


            m_Assembly = CompilerResults.CompiledAssembly;
        }
Пример #47
0
    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);
    }
Пример #48
0
        /// <summary>
        /// Function to compile .Net C#/VB source codes at runtime
        /// </summary>
        /// <param name="_CodeProvider">Base class for compiler provider</param>
        /// <param name="_SourceCode">C# or VB source code as a string</param>
        /// <param name="_SourceFile">External file containing C# or VB source code</param>
        /// <param name="_ExeFile">File path to create external executable file</param>
        /// <param name="_AssemblyName">File path to create external assembly file</param>
        /// <param name="_ResourceFiles">Required resource files to compile the code</param>
        /// <param name="_Errors">String variable to store any errors occurred during the process</param>
        /// <returns>Return TRUE if successfully compiled the code, else return FALSE</returns>
        private bool CompileCode(System.CodeDom.Compiler.CodeDomProvider _CodeProvider, string _SourceCode, string _SourceFile, string _ExeFile, string _AssemblyName, string[] _ResourceFiles, ref string _Errors)
        {
            // set interface for compilation
            System.CodeDom.Compiler.ICodeCompiler _CodeCompiler = _CodeProvider.CreateCompiler();

            // Define parameters to invoke a compiler
            System.CodeDom.Compiler.CompilerParameters _CompilerParameters =
                new System.CodeDom.Compiler.CompilerParameters();

            if (_ExeFile != null)
            {
                // Set the assembly file name to generate.
                _CompilerParameters.OutputAssembly = _ExeFile;

                // Generate an executable instead of a class library.
                _CompilerParameters.GenerateExecutable = true;
                _CompilerParameters.GenerateInMemory   = false; // Esto será lo que haya que cambiar para que se cargue en memoria
            }
            else if (_AssemblyName != null)
            {
                // Set the assembly file name to generate.
                _CompilerParameters.OutputAssembly = _AssemblyName;

                // Generate an executable instead of a class library.
                _CompilerParameters.GenerateExecutable = false;
                _CompilerParameters.GenerateInMemory   = false;
            }
            else
            {
                // Generate an executable instead of a class library.
                _CompilerParameters.GenerateExecutable = false;
                _CompilerParameters.GenerateInMemory   = true;
            }


            // Generate debug information.
            //_CompilerParameters.IncludeDebugInformation = true;

            // Set the level at which the compiler
            // should start displaying warnings.
            _CompilerParameters.WarningLevel = 3;

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

            // Set compiler argument to optimize output.
            _CompilerParameters.CompilerOptions = "/optimize";

            // Set a temporary files collection.
            // The TempFileCollection stores the temporary files
            // generated during a build in the current directory,
            // and does not delete them after compilation.
            _CompilerParameters.TempFiles = new System.CodeDom.Compiler.TempFileCollection(".", true);

            if (_ResourceFiles != null && _ResourceFiles.Length > 0)
            {
                foreach (string _ResourceFile in _ResourceFiles)
                {
                    // Set the embedded resource file of the assembly.
                    _CompilerParameters.EmbeddedResources.Add(_ResourceFile);
                }
            }


            try
            {
                // Invoke compilation
                System.CodeDom.Compiler.CompilerResults _CompilerResults = null;

                if (_SourceFile != null && System.IO.File.Exists(_SourceFile))
                {
                    // soruce code in external file
                    _CompilerResults = _CodeCompiler.CompileAssemblyFromFile(_CompilerParameters, _SourceFile);
                }
                else
                {
                    // source code pass as a string
                    _CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, _SourceCode);
                }

                if (_CompilerResults.Errors.Count > 0)
                {
                    // Return compilation errors
                    _Errors = "";
                    foreach (System.CodeDom.Compiler.CompilerError CompErr in _CompilerResults.Errors)
                    {
                        _Errors += "Line number " + CompErr.Line +
                                   ", Error Number: " + CompErr.ErrorNumber +
                                   ", '" + CompErr.ErrorText + ";\r\n\r\n";
                    }

                    // Return the results of compilation - Failed
                    return(false);
                }
                else
                {
                    // no compile errors
                    _Errors = null;
                }
            }
            catch (Exception _Exception)
            {
                // Error occurred when trying to compile the code
                _Errors = _Exception.Message;
                return(false);
            }

            // Return the results of compilation - Success
            return(true);
        }
Пример #49
0
 public override void StartProcessingRun(CodeDomProvider languageProvider,
                                         string templateContents, CompilerErrorCollection errors)
 {
     this.languageProvider = languageProvider;
     base.StartProcessingRun(languageProvider, templateContents, errors);
 }
Пример #50
0
        public void GenerateProxyClass()
        {
            EndpointAddress metadataAddress = new EndpointAddress("http://localhost/Sofka.Automation.Dummy.Wcf/Loan.svc?wsdl");
            //string  = "http://localhost/Sofka.Automation.Dummy.Wcf/Loan.svc";
            string outputFile = @"d:\dev\Sofka\Test\TempFiles";
            MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress);

            mexClient.ResolveMetadataReferences = false;
            MetadataSet metaDocs = mexClient.GetMetadata();

            WsdlImporter             importer  = new WsdlImporter(metaDocs);
            ServiceContractGenerator generator = new ServiceContractGenerator();

            // Add our custom DCAnnotationSurrogate
            // to write XSD annotations into the comments.
            object dataContractImporter;
            XsdDataContractImporter xsdDCImporter;

            if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter))
            {
                Console.WriteLine("Couldn't find the XsdDataContractImporter! Adding custom importer.");
                xsdDCImporter         = new XsdDataContractImporter();
                xsdDCImporter.Options = new ImportOptions();
                importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter);
            }
            else
            {
                xsdDCImporter = (XsdDataContractImporter)dataContractImporter;
                if (xsdDCImporter.Options == null)
                {
                    Console.WriteLine("There were no ImportOptions on the importer.");
                    xsdDCImporter.Options = new ImportOptions();
                }
            }
            //xsdDCImporter.Options.DataContractSurrogate = new DCAnnotationSurrogate();

            // Uncomment the following code if you are going to do your work programmatically rather than add
            // the WsdlDocumentationImporters through a configuration file.

            /*
             * // The following code inserts a custom WsdlImporter without removing the other
             * // importers already in the collection.
             * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlImportExtensions;
             * System.Collections.Generic.List<IWsdlImportExtension> newExts
             * = new System.Collections.Generic.List<IWsdlImportExtension>();
             * foreach (IWsdlImportExtension ext in exts)
             * {
             * Console.WriteLine("Default WSDL import extensions: {0}", ext.GetType().Name);
             * newExts.Add(ext);
             * }
             * newExts.Add(new WsdlDocumentationImporter());
             * System.Collections.Generic.IEnumerable<IPolicyImportExtension> polExts = importer.PolicyImportExtensions;
             * importer = new WsdlImporter(metaDocs, polExts, newExts);
             */

            System.Collections.ObjectModel.Collection <ContractDescription> contracts
                = importer.ImportAllContracts();
            importer.ImportAllEndpoints();
            foreach (ContractDescription contract in contracts)
            {
                generator.GenerateServiceContractType(contract);
            }
            if (generator.Errors.Count != 0)
            {
                throw new Exception("There were errors during code compilation.");
            }

            // Write the code dom
            System.CodeDom.Compiler.CodeGeneratorOptions options
                = new System.CodeDom.Compiler.CodeGeneratorOptions();
            options.BracingStyle = "C";
            System.CodeDom.Compiler.CodeDomProvider codeDomProvider
                = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#");
            System.CodeDom.Compiler.IndentedTextWriter textWriter
                = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile));
            codeDomProvider.GenerateCodeFromCompileUnit(
                generator.TargetCompileUnit, textWriter, options
                );
            textWriter.Close();
        }