public static Assembly GenerateSerializer(Type[] types, XmlMapping[] mappings, CompilerParameters parameters) { if ((types == null) || (types.Length == 0)) { return(null); } if (mappings == null) { throw new ArgumentNullException("mappings"); } if (XmlMapping.IsShallow(mappings)) { throw new InvalidOperationException(Res.GetString("XmlMelformMapping")); } Assembly assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(Res.GetString("XmlPregenTypeDynamic", new object[] { type.FullName })); } if (assembly == null) { assembly = type.Assembly; } else if (type.Assembly != assembly) { throw new ArgumentException(Res.GetString("XmlPregenOrphanType", new object[] { type.FullName, assembly.Location }), "types"); } } return(TempAssembly.GenerateAssembly(mappings, types, null, null, XmlSerializerCompilerParameters.Create(parameters, true), assembly, new Hashtable())); }
internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location, Evidence evidence) { bool containsSoapMapping = false; for (int i = 0; i < xmlMappings.Length; i++) { xmlMappings[i].CheckShallow(); if (xmlMappings[i].IsSoap) { containsSoapMapping = true; } } // We will make best effort to use RefEmit for assembly generation bool fallbackToCSharpAssemblyGeneration = false; if (!containsSoapMapping && !TempAssembly.UseLegacySerializerGeneration) { try { assembly = GenerateRefEmitAssembly(xmlMappings, types, defaultNamespace, evidence); } // Only catch and handle known failures with RefEmit catch (CodeGeneratorConversionException) { fallbackToCSharpAssemblyGeneration = true; } // Add other known exceptions here... // } else { fallbackToCSharpAssemblyGeneration = true; } if (fallbackToCSharpAssemblyGeneration) { assembly = GenerateAssembly(xmlMappings, types, defaultNamespace, evidence, XmlSerializerCompilerParameters.Create(location), null, assemblies); } #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (assembly == null) { throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Failed to generate XmlSerializer assembly, but did not throw")); } #endif InitAssemblyMethods(xmlMappings); }
internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies) { FileIOPermission.Assert(); Compiler compiler = new Compiler(); try { Hashtable scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) { scopeTable[mapping.Scope] = mapping; } TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); assemblies.Clear(); Hashtable importedTypes = new Hashtable(); foreach (TypeScope scope in scopes) { foreach (Type t in scope.Types) { compiler.AddImport(t, importedTypes); Assembly a = t.Assembly; string name = a.FullName; if (assemblies[name] != null) { continue; } if (!a.GlobalAssemblyCache) { assemblies[name] = a; } } } for (int i = 0; i < types.Length; i++) { compiler.AddImport(types[i], importedTypes); } compiler.AddImport(typeof(object).Assembly); compiler.AddImport(typeof(XmlSerializer).Assembly); IndentedWriter writer = new IndentedWriter(compiler.Source, false); writer.WriteLine("#if _DYNAMIC_XMLSERIALIZER_COMPILATION"); writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); writer.WriteLine("#endif"); // Add AssemblyVersion attribute to match parent accembly version if (types != null && types.Length > 0 && types[0] != null) { writer.WriteLine("[assembly:System.Reflection.AssemblyVersionAttribute(\"" + types[0].Assembly.GetName().Version.ToString() + "\")]"); } if (assembly != null && types.Length > 0) { for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) { continue; } if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(Res.GetString(Res.XmlPregenTypeDynamic, types[i].FullName)); } } writer.Write("[assembly:"); writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) { writer.Write(", Namespace="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } writer.WriteLine(")]"); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {"); writer.Indent++; writer.WriteLine(); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); XmlSerializationWriterCodeGen writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } writerCodeGen.GenerateEnd(); writer.WriteLine(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); XmlSerializationReaderCodeGen readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); Hashtable serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { if (serializers[xmlMappings[i].Key] == null) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); return(compiler.Compile(assembly, defaultNamespace, parameters, evidence)); } finally { compiler.Close(); } }
// SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parameters = xmlParameters.CodeDomParameters; parameters.ReferencedAssemblies.AddRange(Imports); if (_debugEnabled) { parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.TempFiles.KeepFiles = true; } if (parent != null && (parameters.OutputAssembly == null || parameters.OutputAssembly.Length == 0)) { string assemblyName = AssemblyNameFromOptions(parameters.CompilerOptions); if (assemblyName == null) { assemblyName = GetTempAssemblyPath(parameters.TempFiles.TempDir, parent, ns); } // CONSIDER: throw if OutputAssembly alredy specified or remove the /out switch from the compilerOptions parameters.OutputAssembly = assemblyName; } if (parameters.CompilerOptions == null || parameters.CompilerOptions.Length == 0) { parameters.CompilerOptions = "/nostdlib"; } else { parameters.CompilerOptions += " /nostdlib"; } parameters.CompilerOptions += " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; CompilerResults results = null; Assembly assembly = null; try { results = codeProvider.CompileAssemblyFromSource(parameters, _writer.ToString()); // check the output for errors or a certain level-1 warning (1595) if (results.Errors.Count > 0) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); stringWriter.WriteLine(SR.Format(SR.XmlCompilerError, results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture))); bool foundOne = false; foreach (CompilerError e in results.Errors) { // clear filename. This makes ToString() print just error number and message. e.FileName = ""; if (!e.IsWarning || e.ErrorNumber == "CS1595") { foundOne = true; stringWriter.WriteLine(e.ToString()); } } if (foundOne) { throw new InvalidOperationException(stringWriter.ToString()); } } assembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { // try to get the user token string user = GetCurrentUser(); if (user == null || user.Length == 0) { throw new UnauthorizedAccessException(SR.XmlSerializerAccessDenied); } else { throw new UnauthorizedAccessException(SR.Format(SR.XmlIdentityAccessDenied, user)); } } catch (FileLoadException fle) { throw new InvalidOperationException(SR.XmlSerializerCompileFailed, fle); } // somehow we got here without generating an assembly if (assembly == null) { throw new InvalidOperationException(SR.XmlInternalError); } return(assembly); }
internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parameters = xmlParameters.CodeDomParameters; parameters.ReferencedAssemblies.AddRange(Imports); if (debugEnabled) { parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.TempFiles.KeepFiles = true; } PermissionSet perms = new PermissionSet(PermissionState.None); if (xmlParameters.IsNeedTempDirAccess) { perms.AddPermission(TempAssembly.FileIOPermission); } perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence)); perms.Assert(); if (parent != null && (parameters.OutputAssembly == null || parameters.OutputAssembly.Length == 0)) { string assemblyName = AssemblyNameFromOptions(parameters.CompilerOptions); if (assemblyName == null) { assemblyName = GetTempAssemblyPath(parameters.TempFiles.TempDir, parent, ns); } // parameters.OutputAssembly = assemblyName; } if (parameters.CompilerOptions == null || parameters.CompilerOptions.Length == 0) { parameters.CompilerOptions = "/nostdlib"; } else { parameters.CompilerOptions += " /nostdlib"; } parameters.CompilerOptions += " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; #pragma warning disable 618 parameters.Evidence = evidence; #pragma warning restore 618 CompilerResults results = null; Assembly assembly = null; try { results = codeProvider.CompileAssemblyFromSource(parameters, writer.ToString()); // check the output for errors or a certain level-1 warning (1595) if (results.Errors.Count > 0) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture))); bool foundOne = false; foreach (CompilerError e in results.Errors) { // clear filename. This makes ToString() print just error number and message. e.FileName = ""; if (!e.IsWarning || e.ErrorNumber == "CS1595") { foundOne = true; stringWriter.WriteLine(e.ToString()); } } if (foundOne) { throw new InvalidOperationException(stringWriter.ToString()); } } assembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { // try to get the user token string user = GetCurrentUser(); if (user == null || user.Length == 0) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlSerializerAccessDenied)); } else { throw new UnauthorizedAccessException(Res.GetString(Res.XmlIdentityAccessDenied, user)); } } catch (FileLoadException fle) { throw new InvalidOperationException(Res.GetString(Res.XmlSerializerCompileFailed), fle); } finally { CodeAccessPermission.RevertAssert(); } // somehow we got here without generating an assembly if (assembly == null) { throw new InvalidOperationException(Res.GetString(Res.XmlInternalError)); } return(assembly); }
internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies) { FileIOPermission.Assert(); Compiler compiler = new Compiler(); try { Hashtable scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) scopeTable[mapping.Scope] = mapping; TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); assemblies.Clear(); Hashtable importedTypes = new Hashtable(); foreach (TypeScope scope in scopes) { foreach (Type t in scope.Types) { compiler.AddImport(t, importedTypes); Assembly a = t.Assembly; string name = a.FullName; if (assemblies[name] != null) continue; if (!a.GlobalAssemblyCache) { assemblies[name] = a; } } } for (int i = 0; i < types.Length; i++) { compiler.AddImport(types[i], importedTypes); } compiler.AddImport(typeof(object).Assembly); compiler.AddImport(typeof(XmlSerializer).Assembly); IndentedWriter writer = new IndentedWriter(compiler.Source, false); writer.WriteLine("#if _DYNAMIC_XMLSERIALIZER_COMPILATION"); writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); writer.WriteLine("#endif"); // Add AssemblyVersion attribute to match parent accembly version if (types != null && types.Length > 0 && types[0] != null) { writer.WriteLine("[assembly:System.Reflection.AssemblyVersionAttribute(\"" + types[0].Assembly.GetName().Version.ToString() + "\")]"); } if (assembly != null && types.Length > 0) { for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) continue; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(Res.GetString(Res.XmlPregenTypeDynamic, types[i].FullName)); } } writer.Write("[assembly:"); writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) { writer.Write(", Namespace="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } writer.WriteLine(")]"); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {"); writer.Indent++; writer.WriteLine(); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); XmlSerializationWriterCodeGen writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } writerCodeGen.GenerateEnd(); writer.WriteLine(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); XmlSerializationReaderCodeGen readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); Hashtable serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { if (serializers[xmlMappings[i].Key] == null) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); return compiler.Compile(assembly, defaultNamespace, parameters, evidence); } finally { compiler.Close(); } }
internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider provider = new CSharpCodeProvider(); CompilerParameters codeDomParameters = xmlParameters.CodeDomParameters; codeDomParameters.ReferencedAssemblies.AddRange(this.Imports); if (this.debugEnabled) { codeDomParameters.GenerateInMemory = false; codeDomParameters.IncludeDebugInformation = true; codeDomParameters.TempFiles.KeepFiles = true; } PermissionSet set = new PermissionSet(PermissionState.None); if (xmlParameters.IsNeedTempDirAccess) { set.AddPermission(TempAssembly.FileIOPermission); } set.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence)); set.Assert(); if ((parent != null) && ((codeDomParameters.OutputAssembly == null) || (codeDomParameters.OutputAssembly.Length == 0))) { string str = AssemblyNameFromOptions(codeDomParameters.CompilerOptions); if (str == null) { str = GetTempAssemblyPath(codeDomParameters.TempFiles.TempDir, parent, ns); } codeDomParameters.OutputAssembly = str; } if ((codeDomParameters.CompilerOptions == null) || (codeDomParameters.CompilerOptions.Length == 0)) { codeDomParameters.CompilerOptions = "/nostdlib"; } else { codeDomParameters.CompilerOptions = codeDomParameters.CompilerOptions + " /nostdlib"; } codeDomParameters.CompilerOptions = codeDomParameters.CompilerOptions + " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; codeDomParameters.Evidence = evidence; CompilerResults results = null; Assembly compiledAssembly = null; try { results = provider.CompileAssemblyFromSource(codeDomParameters, new string[] { this.writer.ToString() }); if (results.Errors.Count > 0) { StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); writer.WriteLine(Res.GetString("XmlCompilerError", new object[] { results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture) })); bool flag = false; foreach (CompilerError error in results.Errors) { error.FileName = ""; if (!error.IsWarning || (error.ErrorNumber == "CS1595")) { flag = true; writer.WriteLine(error.ToString()); } } if (flag) { throw new InvalidOperationException(writer.ToString()); } } compiledAssembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { string currentUser = GetCurrentUser(); if ((currentUser == null) || (currentUser.Length == 0)) { throw new UnauthorizedAccessException(Res.GetString("XmlSerializerAccessDenied")); } throw new UnauthorizedAccessException(Res.GetString("XmlIdentityAccessDenied", new object[] { currentUser })); } catch (FileLoadException exception) { throw new InvalidOperationException(Res.GetString("XmlSerializerCompileFailed"), exception); } finally { CodeAccessPermission.RevertAssert(); } if (compiledAssembly == null) { throw new InvalidOperationException(Res.GetString("XmlInternalError")); } return(compiledAssembly); }
internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parameters = xmlParameters.CodeDomParameters; parameters.ReferencedAssemblies.AddRange(Imports); if (debugEnabled) { parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.TempFiles.KeepFiles = true; } PermissionSet perms = new PermissionSet(PermissionState.None); if (xmlParameters.IsNeedTempDirAccess) { perms.AddPermission(TempAssembly.FileIOPermission); } perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence)); perms.Assert(); if (parent != null && (parameters.OutputAssembly == null || parameters.OutputAssembly.Length ==0)) { string assemblyName = AssemblyNameFromOptions(parameters.CompilerOptions); if (assemblyName == null) assemblyName = GetTempAssemblyPath(parameters.TempFiles.TempDir, parent, ns); // parameters.OutputAssembly = assemblyName; } if (parameters.CompilerOptions == null || parameters.CompilerOptions.Length == 0) parameters.CompilerOptions = "/nostdlib"; else parameters.CompilerOptions += " /nostdlib"; parameters.CompilerOptions += " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; #pragma warning disable 618 parameters.Evidence = evidence; #pragma warning restore 618 CompilerResults results = null; Assembly assembly = null; try { results = codeProvider.CompileAssemblyFromSource(parameters, writer.ToString()); // check the output for errors or a certain level-1 warning (1595) if (results.Errors.Count > 0) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture))); bool foundOne = false; foreach (CompilerError e in results.Errors) { // clear filename. This makes ToString() print just error number and message. e.FileName = ""; if (!e.IsWarning || e.ErrorNumber == "CS1595") { foundOne = true; stringWriter.WriteLine(e.ToString()); } } if (foundOne) { throw new InvalidOperationException(stringWriter.ToString()); } } assembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { // try to get the user token string user = GetCurrentUser(); if (user == null || user.Length == 0) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlSerializerAccessDenied)); } else { throw new UnauthorizedAccessException(Res.GetString(Res.XmlIdentityAccessDenied, user)); } } catch (FileLoadException fle) { throw new InvalidOperationException(Res.GetString(Res.XmlSerializerCompileFailed), fle); } finally { CodeAccessPermission.RevertAssert(); } // somehow we got here without generating an assembly if (assembly == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalError)); return assembly; }
internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider provider = new CSharpCodeProvider(); CompilerParameters codeDomParameters = xmlParameters.CodeDomParameters; codeDomParameters.ReferencedAssemblies.AddRange(this.Imports); if (this.debugEnabled) { codeDomParameters.GenerateInMemory = false; codeDomParameters.IncludeDebugInformation = true; codeDomParameters.TempFiles.KeepFiles = true; } PermissionSet set = new PermissionSet(PermissionState.None); if (xmlParameters.IsNeedTempDirAccess) { set.AddPermission(TempAssembly.FileIOPermission); } set.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence)); set.Assert(); if ((parent != null) && ((codeDomParameters.OutputAssembly == null) || (codeDomParameters.OutputAssembly.Length == 0))) { string str = AssemblyNameFromOptions(codeDomParameters.CompilerOptions); if (str == null) { str = GetTempAssemblyPath(codeDomParameters.TempFiles.TempDir, parent, ns); } codeDomParameters.OutputAssembly = str; } if ((codeDomParameters.CompilerOptions == null) || (codeDomParameters.CompilerOptions.Length == 0)) { codeDomParameters.CompilerOptions = "/nostdlib"; } else { codeDomParameters.CompilerOptions = codeDomParameters.CompilerOptions + " /nostdlib"; } codeDomParameters.CompilerOptions = codeDomParameters.CompilerOptions + " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; codeDomParameters.Evidence = evidence; CompilerResults results = null; Assembly compiledAssembly = null; try { results = provider.CompileAssemblyFromSource(codeDomParameters, new string[] { this.writer.ToString() }); if (results.Errors.Count > 0) { StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); writer.WriteLine(Res.GetString("XmlCompilerError", new object[] { results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture) })); bool flag = false; foreach (CompilerError error in results.Errors) { error.FileName = ""; if (!error.IsWarning || (error.ErrorNumber == "CS1595")) { flag = true; writer.WriteLine(error.ToString()); } } if (flag) { throw new InvalidOperationException(writer.ToString()); } } compiledAssembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { string currentUser = GetCurrentUser(); if ((currentUser == null) || (currentUser.Length == 0)) { throw new UnauthorizedAccessException(Res.GetString("XmlSerializerAccessDenied")); } throw new UnauthorizedAccessException(Res.GetString("XmlIdentityAccessDenied", new object[] { currentUser })); } catch (FileLoadException exception) { throw new InvalidOperationException(Res.GetString("XmlSerializerCompileFailed"), exception); } finally { CodeAccessPermission.RevertAssert(); } if (compiledAssembly == null) { throw new InvalidOperationException(Res.GetString("XmlInternalError")); } return compiledAssembly; }
// SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parameters = xmlParameters.CodeDomParameters; parameters.ReferencedAssemblies.AddRange(Imports); if (_debugEnabled) { parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.TempFiles.KeepFiles = true; } if (parent != null && (parameters.OutputAssembly == null || parameters.OutputAssembly.Length == 0)) { string assemblyName = AssemblyNameFromOptions(parameters.CompilerOptions); if (assemblyName == null) assemblyName = GetTempAssemblyPath(parameters.TempFiles.TempDir, parent, ns); // CONSIDER: throw if OutputAssembly alredy specified or remove the /out switch from the compilerOptions parameters.OutputAssembly = assemblyName; } if (parameters.CompilerOptions == null || parameters.CompilerOptions.Length == 0) parameters.CompilerOptions = "/nostdlib"; else parameters.CompilerOptions += " /nostdlib"; parameters.CompilerOptions += " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; CompilerResults results = null; Assembly assembly = null; try { results = codeProvider.CompileAssemblyFromSource(parameters, _writer.ToString()); // check the output for errors or a certain level-1 warning (1595) if (results.Errors.Count > 0) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); stringWriter.WriteLine(SR.Format(SR.XmlCompilerError, results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture))); bool foundOne = false; foreach (CompilerError e in results.Errors) { // clear filename. This makes ToString() print just error number and message. e.FileName = ""; if (!e.IsWarning || e.ErrorNumber == "CS1595") { foundOne = true; stringWriter.WriteLine(e.ToString()); } } if (foundOne) { throw new InvalidOperationException(stringWriter.ToString()); } } assembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { // try to get the user token string user = GetCurrentUser(); if (user == null || user.Length == 0) { throw new UnauthorizedAccessException(SR.XmlSerializerAccessDenied); } else { throw new UnauthorizedAccessException(SR.Format(SR.XmlIdentityAccessDenied, user)); } } catch (FileLoadException fle) { throw new InvalidOperationException(SR.XmlSerializerCompileFailed, fle); } // somehow we got here without generating an assembly if (assembly == null) throw new InvalidOperationException(SR.XmlInternalError); return assembly; }
internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies) { Assembly assembly3; FileIOPermission.Assert(); for (int i = 0; i < xmlMappings.Length; i++) { xmlMappings[i].CheckShallow(); } Compiler compiler = new Compiler(); try { Hashtable hashtable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) { hashtable[mapping.Scope] = mapping; } TypeScope[] array = new TypeScope[hashtable.Keys.Count]; hashtable.Keys.CopyTo(array, 0); assemblies.Clear(); Hashtable hashtable2 = new Hashtable(); foreach (TypeScope scope in array) { foreach (Type type in scope.Types) { compiler.AddImport(type, hashtable2); Assembly assembly2 = type.Assembly; string fullName = assembly2.FullName; if ((assemblies[fullName] == null) && !assembly2.GlobalAssemblyCache) { assemblies[fullName] = assembly2; } } } for (int j = 0; j < types.Length; j++) { compiler.AddImport(types[j], hashtable2); } compiler.AddImport(typeof(object).Assembly); compiler.AddImport(typeof(XmlSerializer).Assembly); IndentedWriter writer = new IndentedWriter(compiler.Source, false); writer.WriteLine("#if _DYNAMIC_XMLSERIALIZER_COMPILATION"); writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); writer.WriteLine("#endif"); if (((types != null) && (types.Length > 0)) && (types[0] != null)) { writer.WriteLine("[assembly:System.Reflection.AssemblyVersionAttribute(\"" + types[0].Assembly.GetName().Version.ToString() + "\")]"); } if ((assembly != null) && (types.Length > 0)) { for (int num3 = 0; num3 < types.Length; num3++) { Type type2 = types[num3]; if ((type2 != null) && DynamicAssemblies.IsTypeDynamic(type2)) { throw new InvalidOperationException(Res.GetString("XmlPregenTypeDynamic", new object[] { types[num3].FullName })); } } writer.Write("[assembly:"); writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, "4.0.0.0"); if (defaultNamespace != null) { writer.Write(", Namespace="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } writer.WriteLine(")]"); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string str2 = null; if (((types != null) && (types.Length == 1)) && (types[0] != null)) { str2 = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { str2 = str2 + "Array"; } } writer.WriteLine("namespace Microsoft.Xml.Serialization.GeneratedAssembly {"); writer.Indent++; writer.WriteLine(); string identifier = "XmlSerializationWriter" + str2; identifier = classes.AddUnique(identifier, identifier); XmlSerializationWriterCodeGen gen = new XmlSerializationWriterCodeGen(writer, array, "public", identifier); gen.GenerateBegin(); string[] writerMethods = new string[xmlMappings.Length]; for (int k = 0; k < xmlMappings.Length; k++) { writerMethods[k] = gen.GenerateElement(xmlMappings[k]); } gen.GenerateEnd(); writer.WriteLine(); string str4 = "XmlSerializationReader" + str2; str4 = classes.AddUnique(str4, str4); XmlSerializationReaderCodeGen gen2 = new XmlSerializationReaderCodeGen(writer, array, "public", str4); gen2.GenerateBegin(); string[] methods = new string[xmlMappings.Length]; for (int m = 0; m < xmlMappings.Length; m++) { methods[m] = gen2.GenerateElement(xmlMappings[m]); } gen2.GenerateEnd(methods, xmlMappings, types); string baseSerializer = gen2.GenerateBaseSerializer("XmlSerializer1", str4, identifier, classes); Hashtable serializers = new Hashtable(); for (int n = 0; n < xmlMappings.Length; n++) { if (serializers[xmlMappings[n].Key] == null) { serializers[xmlMappings[n].Key] = gen2.GenerateTypedSerializer(methods[n], writerMethods[n], xmlMappings[n], classes, baseSerializer, str4, identifier); } } gen2.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, str4, methods, identifier, writerMethods, serializers); writer.Indent--; writer.WriteLine("}"); assembly3 = compiler.Compile(assembly, defaultNamespace, parameters, evidence); } finally { compiler.Close(); } return assembly3; }
internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location, Evidence evidence) { this.assemblies = new Hashtable(); this.assembly = GenerateAssembly(xmlMappings, types, defaultNamespace, evidence, XmlSerializerCompilerParameters.Create(location), null, this.assemblies); this.InitAssemblyMethods(xmlMappings); }