コード例 #1
0
        public void BuildExtensionMethods(Compiler context)
        {
            List<MethodInfo> extensionMethods = GetExtensionMethods(Reflection).ToList();
            ExtensionMethodLookup = new Dictionary<string, MethodInfo>(extensionMethods.Count);

            foreach (MethodInfo mi in extensionMethods)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("M:{0}.{1}", mi.DeclaringType.FullName, mi.Name);
                if (mi.IsGenericMethodDefinition)
                    sb.Append("`");
                Type[] genericMethodArguments = mi.GetGenericArguments();
                if (genericMethodArguments != null && genericMethodArguments.Length > 0)
                    sb.AppendFormat("`{0}", genericMethodArguments.Length);
                ParameterInfo[] parameters = mi.GetParameters();
                if (parameters != null && parameters.Length > 0)
                {
                    sb.Append("(");
                    sb.Append(string.Join(",", parameters.Select(p => p.ParameterType).Select(pt => pt.ToCref()).ToArray()));
                    sb.Append(")");
                }
                MethodInfo existingExtensionMethod = null;
                if (ExtensionMethodLookup.TryGetValue(sb.ToString(), out existingExtensionMethod))
                {
                    context.LogWarning("Generated Extension Method Cref \"{0}\" is ambiguous\n\tExisting Method: \"{1}\"\n\tNew Method: \"{2}\"", sb.ToString(), existingExtensionMethod, mi);
                }
                else
                {
                    context.LogVerbose("Found Extension Method \"{0}\"\n\tGenerated Cref:\"{1}\"", mi, sb);
                    ExtensionMethodLookup.Add(sb.ToString(), mi);
                }

            }
        }
コード例 #2
0
        public void RuleExtensions()
        {
            SchematronDocument full = SchematronReader.ReadSchematron("Schematron/Samples/All.sch");
             SchematronDocument minimal = new Compiler().Compile(full);

             Rule r = FindRule(minimal, "rule-4");
             Assert.AreEqual(3, r.Assertions.Count);
             Assert.AreEqual(". = 'fixed'", r.Assertions[0].Test);
             Assert.AreEqual("starts-with(@name, 'x')", r.Assertions[1].Test);
             Assert.AreEqual("1=1", r.Assertions[2].Test);
        }
コード例 #3
0
        public void Minimal()
        {
            SchematronDocument full = SchematronReader.ReadSchematron("Schematron/Samples/All.sch");
             SchematronDocument minimal = new Compiler().Compile(full);

             Assert.IsNotNull(minimal);
             Assert.AreEqual(full.DefaultPhase, minimal.DefaultPhase);
             Assert.AreEqual(full.Diagnostics.Count, minimal.Diagnostics.Count);
             Assert.AreEqual(full.ID, minimal.ID);
             Assert.AreEqual(full.Namespaces.Count, minimal.Namespaces.Count);
             Assert.AreEqual(full.Phases.Count, minimal.Phases.Count);
             Assert.AreEqual(full.QueryLanguage, minimal.QueryLanguage);
        }
コード例 #4
0
        public RxTypeInfo FindOrBuildXType(Compiler context, Type type, string xid)
        {
            RxMemberInfo xMember;
            RxTypeInfo xType;
            if (Project.TryGetMember(xid, out xMember) && (xType = xMember as RxTypeInfo) != null)
                return xType;

            XElement commentElement = GetCommentElement(context, xid);
            xType = new RxTypeInfo();
            xType.Build(context, this, type, commentElement, xid);
            Project.AddMember(xType);
            return xType;
        }
コード例 #5
0
        public void MinimalIsValid()
        {
            SchematronDocument full = SchematronReader.ReadSchematron("Schematron/Samples/All.sch");
             SchematronDocument minimal = new Compiler().Compile(full);
             StringBuilder schematron = new StringBuilder();
             minimal.Save(schematron);

             XmlDocument minimalDocument = new XmlDocument();
             minimalDocument.LoadXml(schematron.ToString());

             SchematronValidator validator = new SchematronValidator(Schematron.Default.IsoSchematronSchema);
             validator.ValidationPhase = "minimal";
             validator.Validate(minimalDocument);

             SchematronDocument minimal2 = new SchematronDocument();
             minimal2.Load(schematron);
        }
コード例 #6
0
 public XElement GetCommentElement(Compiler context, string xid)
 {
     XElement ret = null;
     memberElements.TryGetValue(xid, out ret);
     if (ret == null)
     {
         context.LogWarning("Could not find XML comments for \"{0}\"", xid);
     }
     return ret;
 }
コード例 #7
0
        internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Assembly assembly, Hashtable assemblies, Stream stream)
        {
            var compiler = new Compiler();

            try
            {
                var scopeTable = new Hashtable();
                foreach (XmlMapping mapping in xmlMappings)
                {
                    scopeTable[mapping.Scope] = mapping;
                }

                var scopes = new TypeScope[scopeTable.Keys.Count];
                scopeTable.Keys.CopyTo(scopes, 0);
                assemblies.Clear();
                var 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(System.Xml.Serialization.XmlSerializer).Assembly);
                var writer = new IndentedWriter(compiler.Source, false);
                writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]");
                writer.WriteLine("[assembly:System.Security.SecurityTransparent()]");
                writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]");

                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(SR.Format(SR.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(")]");
                }

                var 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);
                var 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);
                var 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);
                var    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("}");

                string codecontent = compiler.Source.ToString();
                byte[] info        = new UTF8Encoding(true).GetBytes(codecontent);
                stream.Write(info, 0, info.Length);
                stream.Flush();
                return(true);
            }
            finally
            {
                compiler.Close();
            }
        }
コード例 #8
0
ファイル: compilation.cs プロジェクト: ArildF/masters
        public TempAssembly(XmlMapping[] xmlMappings) {
            Compiler compiler = new Compiler();
            allAssembliesAllowPartialTrust = false;
            try {
                IndentedWriter writer = new IndentedWriter(compiler.Source, false);
                writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]");
                writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {");
                writer.Indent++;
                writer.WriteLine();

                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);
                
                XmlSerializationWriterCodeGen writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes);
                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();
                
                XmlSerializationReaderCodeGen readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes);
                readerCodeGen.GenerateBegin();
                string[] readMethodNames = new string[xmlMappings.Length];
                for (int i = 0; i < xmlMappings.Length; i++)
                    readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]);
                readerCodeGen.GenerateEnd();
                    
                writer.Indent--;
                writer.WriteLine("}");
                allAssembliesAllowPartialTrust = true;
                assemblies = new Hashtable();
                foreach (TypeScope scope in scopes) {
                    foreach (Type t in scope.Types) {
                        compiler.AddImport(t);
                        Assembly a = t.Assembly;
                        if (allAssembliesAllowPartialTrust && !AssemblyAllowsPartialTrust(a))
                            allAssembliesAllowPartialTrust = false;
                        if (!a.GlobalAssemblyCache)
                            assemblies[a.FullName] = a;
                    }
                }
                compiler.AddImport(typeof(XmlWriter));
                compiler.AddImport(typeof(XmlSerializationWriter));
                compiler.AddImport(typeof(XmlReader));
                compiler.AddImport(typeof(XmlSerializationReader));

                assembly = compiler.Compile();

                methods = new TempMethod[xmlMappings.Length];
                
                readerType = GetTypeFromAssembly("XmlSerializationReader1");
                writerType = GetTypeFromAssembly("XmlSerializationWriter1");

                for (int i = 0; i < methods.Length; i++) {
                    TempMethod method = new TempMethod();
                    XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping;
                    if (xmlTypeMapping != null) {
                        method.name = xmlTypeMapping.ElementName;
                        method.ns = xmlTypeMapping.Namespace;
                    }
                    method.readMethod = GetMethodFromType(readerType, readMethodNames[i]);
                    method.writeMethod = GetMethodFromType(writerType, writeMethodNames[i]);
                    methods[i] = method;
                }
            }
            finally {
                compiler.Close();
            }
        }
コード例 #9
0
        /// <devdoc>
        ///    <para>
        ///    Attempts to load pre-generated serialization assembly.
        ///    First check for the [XmlSerializerAssembly] attribute
        ///    </para>
        /// </devdoc>
        // 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 static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
        {
            Assembly serializer = null;

            contract = null;
            string serializerName = null;

            // check to see if we loading explicit pre-generated assembly
            object[] attrs = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlSerializerAssemblyAttribute), false);
            if (attrs.Length == 0)
            {
                // Guess serializer name: if parent assembly signed use strong name
                AssemblyName name = type.Assembly.GetName();
                serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                // use strong name
                name.Name        = serializerName;
                name.CodeBase    = null;
                name.CultureInfo = CultureInfo.InvariantCulture;

                string serializerPath = null;

                try
                {
                    if (!string.IsNullOrEmpty(type.Assembly.Location))
                    {
                        serializerPath = Path.Combine(Path.GetDirectoryName(type.Assembly.Location), serializerName + ".dll");
                    }

                    if ((string.IsNullOrEmpty(serializerPath) || !File.Exists(serializerPath)) && !string.IsNullOrEmpty(Assembly.GetEntryAssembly().Location))
                    {
                        serializerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), serializerName + ".dll");
                    }

                    if (!string.IsNullOrEmpty(serializerPath))
                    {
                        serializer = Assembly.LoadFile(serializerPath);
                    }
                }
                catch (Exception e)
                {
                    if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                    {
                        throw;
                    }
                    byte[] token = name.GetPublicKeyToken();
                    if (token != null && token.Length > 0)
                    {
                        // the parent assembly was signed, so do not try to LoadWithPartialName
                        return(null);
                    }
                }

                if (serializer == null)
                {
                    if (XmlSerializer.Mode == SerializationMode.PreGenOnly)
                    {
                        throw new Exception(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName));
                    }

                    return(null);
                }

                if (!IsSerializerVersionMatch(serializer, type, defaultNamespace))
                {
                    XmlSerializationEventSource.Log.XmlSerializerExpired(serializerName, type.FullName);
                    return(null);
                }
            }
            else
            {
                System.Xml.Serialization.XmlSerializerAssemblyAttribute assemblyAttribute = (System.Xml.Serialization.XmlSerializerAssemblyAttribute)attrs[0];
                if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase"));
                }

                // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                if (assemblyAttribute.AssemblyName != null)
                {
                    serializerName = assemblyAttribute.AssemblyName;
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName);
#pragma warning restore 618
                }
                else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0)
                {
                    serializerName = assemblyAttribute.CodeBase;
                    serializer     = Assembly.LoadFrom(serializerName);
                }
                else
                {
                    serializerName = type.Assembly.FullName;
                    serializer     = type.Assembly;
                }
                if (serializer == null)
                {
                    throw new FileNotFoundException(null, serializerName);
                }
            }
            Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");
            contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType);
            if (contract.CanSerialize(type))
            {
                return(serializer);
            }

            return(null);
        }
コード例 #10
0
 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;
 }
コード例 #11
0
 internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
 {
     Assembly serializer = null;
     contract = null;
     string partialName = null;
     bool enabled = DiagnosticsSwitches.PregenEventLog.Enabled;
     object[] customAttributes = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
     if (customAttributes.Length == 0)
     {
         AssemblyName parent = GetName(type.Assembly, true);
         partialName = Compiler.GetTempAssemblyName(parent, defaultNamespace);
         parent.Name = partialName;
         parent.CodeBase = null;
         parent.CultureInfo = CultureInfo.InvariantCulture;
         try
         {
             serializer = Assembly.Load(parent);
         }
         catch (Exception exception)
         {
             if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
             {
                 throw;
             }
             if (enabled)
             {
                 Log(exception.Message, EventLogEntryType.Information);
             }
             byte[] publicKeyToken = parent.GetPublicKeyToken();
             if ((publicKeyToken != null) && (publicKeyToken.Length > 0))
             {
                 return null;
             }
             serializer = Assembly.LoadWithPartialName(partialName, null);
         }
         if (serializer == null)
         {
             if (enabled)
             {
                 Log(Res.GetString("XmlPregenCannotLoad", new object[] { partialName }), EventLogEntryType.Information);
             }
             return null;
         }
         if (!IsSerializerVersionMatch(serializer, type, defaultNamespace, null))
         {
             if (enabled)
             {
                 Log(Res.GetString("XmlSerializerExpiredDetails", new object[] { partialName, type.FullName }), EventLogEntryType.Error);
             }
             return null;
         }
     }
     else
     {
         XmlSerializerAssemblyAttribute attribute = (XmlSerializerAssemblyAttribute) customAttributes[0];
         if ((attribute.AssemblyName != null) && (attribute.CodeBase != null))
         {
             throw new InvalidOperationException(Res.GetString("XmlPregenInvalidXmlSerializerAssemblyAttribute", new object[] { "AssemblyName", "CodeBase" }));
         }
         if (attribute.AssemblyName != null)
         {
             partialName = attribute.AssemblyName;
             serializer = Assembly.LoadWithPartialName(partialName, null);
         }
         else if ((attribute.CodeBase != null) && (attribute.CodeBase.Length > 0))
         {
             partialName = attribute.CodeBase;
             serializer = Assembly.LoadFrom(partialName);
         }
         else
         {
             partialName = type.Assembly.FullName;
             serializer = type.Assembly;
         }
         if (serializer == null)
         {
             throw new FileNotFoundException(null, partialName);
         }
     }
     Type typeFromAssembly = GetTypeFromAssembly(serializer, "XmlSerializerContract");
     contract = (XmlSerializerImplementation) Activator.CreateInstance(typeFromAssembly);
     if (contract.CanSerialize(type))
     {
         return serializer;
     }
     if (enabled)
     {
         Log(Res.GetString("XmlSerializerExpiredDetails", new object[] { partialName, type.FullName }), EventLogEntryType.Error);
     }
     return null;
 }
コード例 #12
0
        internal TempAssembly(XmlMapping[] xmlMappings)
        {
            Compiler compiler = new Compiler();

            allAssembliesAllowPartialTrust = false;
            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);

                allAssembliesAllowPartialTrust = true;
                assemblies = new Hashtable();
                foreach (TypeScope scope in scopes)
                {
                    foreach (Type t in scope.Types)
                    {
                        compiler.AddImport(t);
                        Assembly a = t.Assembly;
                        if (allAssembliesAllowPartialTrust && !AssemblyAllowsPartialTrust(a))
                        {
                            allAssembliesAllowPartialTrust = false;
                        }
                        if (!a.GlobalAssemblyCache)
                        {
                            assemblies[a.FullName] = a;
                        }
                    }
                }
                compiler.AddImport(typeof(XmlWriter));
                compiler.AddImport(typeof(XmlSerializationWriter));
                compiler.AddImport(typeof(XmlReader));
                compiler.AddImport(typeof(XmlSerializationReader));

                IndentedWriter writer = new IndentedWriter(compiler.Source, false);

                // CONSIDER, alexdej: remove this (not necessary since generated assembly isn't signed)
                writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]");

                writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {");
                writer.Indent++;
                writer.WriteLine();

                XmlSerializationWriterCodeGen writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes);

                writerCodeGen.GenerateBegin();
                string[] writeMethodNames = new string[xmlMappings.Length];
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    if (!allAssembliesAllowPartialTrust)
                    {
                        writer.WriteLine(LinkDemandAttribute);
                    }
                    writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]);
                }
                writerCodeGen.GenerateEnd();

                writer.WriteLine();

                XmlSerializationReaderCodeGen readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes);

                readerCodeGen.GenerateBegin();
                string[] readMethodNames = new string[xmlMappings.Length];
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    if (!allAssembliesAllowPartialTrust)
                    {
                        writer.WriteLine(LinkDemandAttribute);
                    }
                    readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]);
                }
                readerCodeGen.GenerateEnd();

                writer.Indent--;
                writer.WriteLine("}");

                assembly = compiler.Compile();

                methods = new TempMethod[xmlMappings.Length];

                readerType = GetTypeFromAssembly("XmlSerializationReader1");
                writerType = GetTypeFromAssembly("XmlSerializationWriter1");

                for (int i = 0; i < methods.Length; i++)
                {
                    TempMethod method = new TempMethod();
                    method.isSoap = xmlMappings[i].IsSoap;
                    XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping;
                    if (xmlTypeMapping != null)
                    {
                        method.name = xmlTypeMapping.ElementName;
                        method.ns   = xmlTypeMapping.Namespace;
                    }
                    method.readMethod  = GetMethodFromType(readerType, readMethodNames[i]);
                    method.writeMethod = GetMethodFromType(writerType, writeMethodNames[i]);
                    methods[i]         = method;
                }
            }
            finally {
                compiler.Close();
            }
        }
コード例 #13
0
        /// <devdoc>
        ///    <para>
        ///    Attempts to load pre-generated serialization assembly.
        ///    First check for the [XmlSerializerAssembly] attribute
        ///    </para>
        /// </devdoc>
        // 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 static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
        {
            Assembly serializer = null;

            contract = null;
            string serializerName = null;

            // check to see if we loading explicit pre-generated assembly
            object[] attrs = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
            if (attrs.Length == 0)
            {
                // Guess serializer name: if parent assembly signed use strong name
                AssemblyName name = type.Assembly.GetName();
                serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                // use strong name
                name.Name        = serializerName;
                name.CodeBase    = null;
                name.CultureInfo = CultureInfo.InvariantCulture;
                try
                {
                    serializer = Assembly.Load(name);
                }
                catch (Exception e)
                {
                    if (e is OutOfMemoryException)
                    {
                        throw;
                    }
                    byte[] token = name.GetPublicKeyToken();
                    if (token != null && token.Length > 0)
                    {
                        // the parent assembly was signed, so do not try to LoadWithPartialName
                        return(null);
                    }
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName);
#pragma warning restore 618
                }
                if (serializer == null)
                {
                    return(null);
                }
            }
            else
            {
                XmlSerializerAssemblyAttribute assemblyAttribute = (XmlSerializerAssemblyAttribute)attrs[0];
                if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase"));
                }

                // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                if (assemblyAttribute.AssemblyName != null)
                {
                    serializerName = assemblyAttribute.AssemblyName;
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName);
#pragma warning restore 618
                }
                else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0)
                {
                    serializerName = assemblyAttribute.CodeBase;
                    serializer     = Assembly.LoadFrom(serializerName);
                }
                else
                {
                    serializerName = type.Assembly.FullName;
                    serializer     = type.Assembly;
                }
                if (serializer == null)
                {
                    throw new FileNotFoundException(null, serializerName);
                }
            }
            Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");
            contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType);
            if (contract.CanSerialize(type))
            {
                return(serializer);
            }

            return(null);
        }