Exemplo n.º 1
0
        internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location)
        {
            if (xmlMapping == null)
            {
                throw new ArgumentNullException(nameof(xmlMapping));
            }

            xmlMapping.CheckShallow();
            if (xmlMapping.IsSoap)
            {
                return(null);
            }

            return(new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location));
        }
Exemplo n.º 2
0
        internal bool CanRead(XmlMapping mapping, XmlReader xmlReader)
        {
            if (mapping == null)
            {
                return(false);
            }

            if (mapping.Accessor.Any)
            {
                return(true);
            }
            TempMethod method = _methods[mapping.Key];

            return(xmlReader.IsStartElement(method.name, method.ns));
        }
Exemplo n.º 3
0
 public static QueryMapping GetMapping(string mappingId)
 {
     if (mappingId != null)
     {
         Type type = FindLoadedType(mappingId);
         if (type != null)
         {
             return(new AttributeMapping(type));
         }
         if (File.Exists(mappingId))
         {
             return(XmlMapping.FromXml(File.ReadAllText(mappingId)));
         }
     }
     return(new ImplicitMapping());
 }
Exemplo n.º 4
0
        /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="XmlReflectionImporter.ImportTypeMapping1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace)
        {
            ElementAccessor element = new ElementAccessor();

            element.IsSoap    = true;
            element.Mapping   = ImportTypeMapping(_modelScope.GetTypeModel(type), new RecursionLimiter());
            element.Name      = element.Mapping.DefaultElementName;
            element.Namespace = element.Mapping.Namespace == null ? defaultNamespace : element.Mapping.Namespace;
            element.Form      = XmlSchemaForm.Qualified;
            XmlTypeMapping xmlMapping = new XmlTypeMapping(_typeScope, element);

            xmlMapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, defaultNamespace));
            xmlMapping.IsSoap             = true;
            xmlMapping.GenerateSerializer = true;
            return(xmlMapping);
        }
    public void CallingDeserializeProperly()
    {
        // Arrange
        var called = false;
        Func <string, XmlMapping> fakeHandler = (string f) =>
        {
            called = true;     // do your test of the input and put your result here
            return(new XmlMapping());
        };
        // Act
        var m = XmlMapping.Create("test");

        XmlMapping.DeserializeHandler = fakeHandler;
        // Assert
        Assert.IsTrue(called);
    }
Exemplo n.º 6
0
        public void TestNestedEntity_XmlMapped_DeeplyNested()
        {
            var provider = GetProvider().WithMapping(XmlMapping.FromXml(Nested_XmlMapped_DeeplyNested.Xml));
            var items    = provider.GetTable <Nested_XmlMapped_DeeplyNested.Employee>().ToList();

            Assert.Equal(9, items.Count);

            foreach (var item in items)
            {
                Assert.NotEqual(null, item.Person);
                Assert.NotEqual(null, item.Person.Title);
                Assert.NotEqual(null, item.Person.Name);
                Assert.NotEqual(null, item.Person.Name.First);
                Assert.NotEqual(null, item.Address);
                Assert.NotEqual(null, item.Address.Street);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates the repository. Init the provider and establish
        /// a database connection
        /// </summary>
        /// <returns></returns>
        private static DbEntityRepository CreateRepository()
        {
            DbEntityProvider dbentprovider;

            string connectionString = ConfigurationManager.AppSettings["ConnORA"];
            string MapPath          = Utils.GetMapPath("MapORA");
            string provider         = ConfigurationManager.AppSettings["ProviderORA"];

            var mapping = XmlMapping.FromXml(File.ReadAllText(MapPath));

            dbentprovider = DbEntityProvider.From(provider, connectionString, mapping, QueryPolicy.Default);

            //May not be needed for all databases,
            //some need a little kick start before serving requests
            DbInit(dbentprovider);

            return(new DbEntityRepository(dbentprovider));
        }
        public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            Init(xmlWriter, namespaces, encodingStyle, id, null);

            if (!xmlMapping.IsWriteable || !xmlMapping.GenerateSerializer)
            {
                throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping)));
            }

            if (xmlMapping is XmlTypeMapping || xmlMapping is XmlMembersMapping)
            {
                _mapping = xmlMapping;
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping)));
            }
        }
Exemplo n.º 9
0
        public void TestAssociation_XmlMapping_DifferenteKeys_Customer()
        {
            var provider = GetProvider().WithMapping(
                XmlMapping.FromXml(Association_XmlMapping_DifferentKeys.Xml, typeof(Association_XmlMapping_DifferentKeys.Customer).Assembly));

            var items = provider.GetTable <Association_XmlMapping_DifferentKeys.Order>()
                        .Where(o => o.Customer.ContactName.StartsWith("Maria"))
                        .ToList();

            Assert.Equal(25, items.Count);

            foreach (var item in items)
            {
                Assert.NotEqual(null, item.ID);
                Assert.NotEqual(null, item.CustomerID);
                Assert.Equal(null, item.Customer); // not retrieved, no policy
            }
        }
Exemplo n.º 10
0
        public void TestAssociation_XmlMapping_DifferentKeys_Orders()
        {
            var provider = GetProvider().WithMapping(
                XmlMapping.FromXml(Association_XmlMapping_DifferentKeys.Xml, typeof(Association_XmlMapping_DifferentKeys.Customer).Assembly));

            var items = provider.GetTable <Association_XmlMapping_DifferentKeys.Customer>()
                        .Where(c => c.Orders.Count() > 1)
                        .ToList();

            Assert.Equal(88, items.Count);

            foreach (var item in items)
            {
                Assert.NotEqual(null, item.ID);
                Assert.NotEqual(null, item.ContactName);
                Assert.NotEqual(null, item.Phone);
                Assert.NotEqual(null, item.Orders);
                Assert.Equal(0, item.Orders.Count);
            }
        }
Exemplo n.º 11
0
        public XmlMapping AddMapping(DirectoryInfo sourceDir, bool includeAttributeData = false)
        {
            StringBuilder sb = new StringBuilder();

            if (sourceDir == null || !sourceDir.Exists)
            {
                throw new ArgumentException("Source Directory must exist.", nameof(sourceDir));
            }

            XmlMapping existingMapping = this.ImportMappings.FirstOrDefault(m => m.Source.Name == sourceDir.FullName);

            if (existingMapping != null)
            {
                throw new ArgumentException($"Can not add duplicate mapping with name \"{sourceDir.FullName}\". XML Mappings must have unique paths.", nameof(sourceDir));
            }

            XmlMapping mapping = new XmlMapping(sourceDir, includeAttributeData);

            this.addMapping(mapping);
            return(mapping);
        }
Exemplo n.º 12
0
        public override object[] GetInitializers(LogicalMethodInfo[] methodInfos)
        {
            XmlReflectionImporter importer = new XmlReflectionImporter();

            XmlMapping[] sers = new XmlMapping [methodInfos.Length];
            for (int n = 0; n < sers.Length; n++)
            {
                LogicalMethodInfo metinfo = methodInfos[n];
                if (metinfo.IsVoid)
                {
                    sers[n] = null;
                }
                else
                {
                    LogicalTypeInfo  sti  = TypeStubManager.GetLogicalTypeInfo(metinfo.DeclaringType);
                    object[]         ats  = methodInfos[n].ReturnTypeCustomAttributeProvider.GetCustomAttributes(typeof(XmlRootAttribute), true);
                    XmlRootAttribute root = ats.Length > 0 ? ats[0] as XmlRootAttribute : null;
                    sers[n] = importer.ImportTypeMapping(methodInfos[n].ReturnType, root, sti.GetWebServiceLiteralNamespace(sti.WebServiceNamespace));
                }
            }
            return(XmlSerializer.FromMappings(sers));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Validate required values for Import Job
        /// </summary>
        /// <returns>True if validation succeeds</returns>
        private bool validateData(XmlMapping mappingData)
        {
            var  errorList  = new List <string>();
            bool pathExists = true;

            if (mappingData.Source?.Source == null || !mappingData.Source.Source.Exists)
            {
                pathExists = false;
                string mapPath = mappingData.Source?.Source == null ? "Path is empty" : mappingData.Source.Source.FullName;
                errorList.Add($"Data source must be a valid directory. Verify the source path exists. Path: {mapPath}");
            }

            if (pathExists)
            {
                this.currentFileList = mappingData.Source.Source.GetFiles("*.*", SearchOption.AllDirectories);
                if (this.currentFileList == null || this.currentFileList.Length <= 0)
                {
                    errorList.Add("Source directory must contain valid XML files. No files were found.");
                }
            }

            if (mappingData.ParentIDSource == Enumerations.ParentSource.Global && mappingData.GlobalParentID == Guid.Empty)
            {
                errorList.Add("A valid GlobalParentID must be specified when TemplateMapSource is specified as Global");
            }

            if (errorList.Any())
            {
                foreach (var error in errorList)
                {
                    LogStatus(error);
                }
                return(false);
            }

            return(true);
        }
Exemplo n.º 14
0
        internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle)
        {
            XmlSerializationReader reader = null;

            try
            {
                encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key);
                reader        = Contract.Reader;
                reader.Init(xmlReader, events, encodingStyle, this);
                if (_methods[mapping.Key].readMethod == null)
                {
                    if (_readerMethods == null)
                    {
                        _readerMethods = Contract.ReadMethods;
                    }
                    string methodName = (string)_readerMethods[mapping.Key];
                    if (methodName == null)
                    {
                        throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name));
                    }
                    _methods[mapping.Key].readMethod = GetMethodFromType(reader.GetType(), methodName);
                }
                return(_methods[mapping.Key].readMethod.Invoke(reader, Array.Empty <object>()));
            }
            catch (SecurityException e)
            {
                throw new InvalidOperationException(SR.XmlNoPartialTrust, e);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
Exemplo n.º 15
0
        internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            XmlSerializationWriter writer = null;

            try
            {
                encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key);
                writer        = Contract.Writer;
                writer.Init(xmlWriter, namespaces, encodingStyle, id, this);
                if (_methods[mapping.Key].writeMethod == null)
                {
                    if (_writerMethods == null)
                    {
                        _writerMethods = Contract.WriteMethods;
                    }
                    string methodName = (string)_writerMethods[mapping.Key];
                    if (methodName == null)
                    {
                        throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name));
                    }
                    _methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName);
                }
                _methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o });
            }
            catch (SecurityException e)
            {
                throw new InvalidOperationException(SR.XmlNoPartialTrust, e);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
        }
Exemplo n.º 16
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            DefaultNamespace = defaultNamespace;
            _rootType        = type;
            XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);

            if (extraTypes != null)
            {
                for (int i = 0; i < extraTypes.Length; i++)
                {
                    importer.IncludeType(extraTypes[i]);
                }
            }
            _mapping = importer.ImportTypeMapping(type, root, defaultNamespace);

#if !uapaot
            _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location);
#endif
        }
Exemplo n.º 17
0
 internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping)
 {
     return(GenerateTempAssembly(xmlMapping, null, null));
 }
Exemplo n.º 18
0
        public void Run()
        {
            string absoluteAssemblyDir = Path.GetFullPath(BuildAssemblyPath);
            string assemblyPath        = Path.Combine(absoluteAssemblyDir, BuildAssemblyName);

            AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
            {
                // FIXME: Imprecise
                var requestedAssemblyName = new AssemblyName(e.Name).Name;
                if (!requestedAssemblyName.Contains("System"))
                {
                    string requestedAssemblyDll = requestedAssemblyName + ".dll";

                    foreach (string reference in References)
                    {
                        if (reference.ToLowerInvariant().Contains(requestedAssemblyDll.ToLowerInvariant()))
                        {
                            return(Assembly.LoadFrom(reference));
                        }
                    }

                    var candidateAssemblyPath = Path.Combine(absoluteAssemblyDir, requestedAssemblyDll);
                    if (File.Exists(candidateAssemblyPath))
                    {
                        return(Assembly.LoadFrom(candidateAssemblyPath));
                    }
                }

                return(null);
            };

            string   serializersAssemblyPath = Path.ChangeExtension(assemblyPath, ".XmlSerializers.dll");
            Assembly assembly = Assembly.LoadFrom(assemblyPath);

            List <Type> serializableTypes = new List <Type>();

            foreach (Type type in assembly.GetExportedTypes())
            {
                if (type.IsDefined(typeof(XmlRootAttribute), false))
                {
                    serializableTypes.Add(type);
                }
            }

            List <XmlMapping>     mappings = new List <XmlMapping>();
            XmlReflectionImporter importer = new XmlReflectionImporter();

            foreach (Type type in serializableTypes)
            {
                XmlMapping mapping = importer.ImportTypeMapping(type);
                mappings.Add(mapping);
            }

            CompilerParameters compilerParameters = new CompilerParameters();

            compilerParameters.TempFiles = new TempFileCollection();
            compilerParameters.IncludeDebugInformation = false;
            compilerParameters.GenerateInMemory        = false;
            compilerParameters.OutputAssembly          = serializersAssemblyPath;

            if (KeyFile != null)
            {
                compilerParameters.CompilerOptions += " /keyfile:\"" + KeyFile + "\"";
            }

            XmlSerializer.GenerateSerializer(serializableTypes.ToArray(),
                                             mappings.ToArray(), compilerParameters);
        }
Exemplo n.º 19
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSerializer(Type type, string defaultNamespace)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            DefaultNamespace = defaultNamespace;
            _rootType        = type;

            _mapping = GetKnownMapping(type, defaultNamespace);
            if (_mapping != null)
            {
                _primitiveType = type;
                return;
            }
#if !uapaot
            _tempAssembly = s_cache[defaultNamespace, type];
            if (_tempAssembly == null)
            {
                lock (s_cache)
                {
                    _tempAssembly = s_cache[defaultNamespace, type];
                    if (_tempAssembly == null)
                    {
                        {
                            XmlSerializerImplementation contract = null;
                            Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, null, out contract);
                            if (assembly == null)
                            {
                                // need to reflect and generate new serialization assembly
                                XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
                                _mapping      = importer.ImportTypeMapping(type, null, defaultNamespace);
                                _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
                            }
                            else
                            {
                                // we found the pre-generated assembly, now make sure that the assembly has the right serializer
                                // try to avoid the reflection step, need to get ElementName, namespace and the Key form the type
                                _mapping      = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
                                _tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract);
                            }
                        }
                    }
                    s_cache.Add(defaultNamespace, type, _tempAssembly);
                }
            }
            if (_mapping == null)
            {
                _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
            }
#else
            XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly();

            if (contract != null)
            {
                this.innerSerializer = contract.GetSerializer(type);
            }
            else if (ReflectionMethodEnabled)
            {
                var importer = new XmlReflectionImporter(defaultNamespace);
                _mapping = importer.ImportTypeMapping(type, null, defaultNamespace);

                if (_mapping == null)
                {
                    _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
                }
            }
#endif
        }
 private void WriteMember(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors, XmlMapping parentMapping = null)
 {
     if (memberTypeDesc.IsArrayLike &&
         !(elements.Length == 1 && elements[0].Mapping is ArrayMapping))
     {
         WriteArray(o, choiceSource, elements, text, choice, memberTypeDesc);
     }
     else
     {
         WriteElements(o, choiceSource, elements, text, choice, "a", writeAccessors, memberTypeDesc.IsNullable, parentMapping);
     }
 }
Exemplo n.º 21
0
 /// <summary>
 /// Method to simplify removeMapping
 /// </summary>
 /// <param name="mapping">Mapping to remove</param>
 private void removeMapping(XmlMapping mapping)
 {
     this.ImportMappings.Remove(mapping);
 }
Exemplo n.º 22
0
        internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
        {
            string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));

            serializerName = classes.AddUnique(serializerName + "Serializer", mapping);

            _writer.WriteLine();
            _writer.Write("public sealed class ");
            _writer.Write(CodeIdentifier.GetCSharpName(serializerName));
            _writer.Write(" : ");
            _writer.Write(baseSerializer);
            _writer.WriteLine(" {");
            _writer.Indent++;

            _writer.WriteLine();
            _writer.Write("public override ");
            _writer.Write(typeof(bool).FullName);
            _writer.Write(" CanDeserialize(");
            _writer.Write(typeof(XmlReader).FullName);
            _writer.WriteLine(" xmlReader) {");
            _writer.Indent++;

            if (mapping.Accessor.Any)
            {
                _writer.WriteLine("return true;");
            }
            else
            {
                _writer.Write("return xmlReader.IsStartElement(");
                WriteQuotedCSharpString(mapping.Accessor.Name);
                _writer.Write(", ");
                WriteQuotedCSharpString(mapping.Accessor.Namespace);
                _writer.WriteLine(");");
            }
            _writer.Indent--;
            _writer.WriteLine("}");

            if (writeMethod != null)
            {
                _writer.WriteLine();
                _writer.Write("protected override void Serialize(object objectToSerialize, ");
                _writer.Write(typeof(XmlSerializationWriter).FullName);
                _writer.WriteLine(" writer) {");
                _writer.Indent++;
                _writer.Write("((");
                _writer.Write(writerClass);
                _writer.Write(")writer).");
                _writer.Write(writeMethod);
                _writer.Write("(");
                if (mapping is XmlMembersMapping)
                {
                    _writer.Write("(object[])");
                }
                _writer.WriteLine("objectToSerialize);");
                _writer.Indent--;
                _writer.WriteLine("}");
            }
            if (readMethod != null)
            {
                _writer.WriteLine();
                _writer.Write("protected override object Deserialize(");
                _writer.Write(typeof(XmlSerializationReader).FullName);
                _writer.WriteLine(" reader) {");
                _writer.Indent++;
                _writer.Write("return ((");
                _writer.Write(readerClass);
                _writer.Write(")reader).");
                _writer.Write(readMethod);
                _writer.WriteLine("();");
                _writer.Indent--;
                _writer.WriteLine("}");
            }
            _writer.Indent--;
            _writer.WriteLine("}");

            return(serializerName);
        }
        private void WriteStructMethod(StructMapping mapping, string n, string ns, object o, bool isNullable, bool needType, XmlMapping parentMapping = null)
        {
            if (mapping.IsSoap && mapping.TypeDesc.IsRoot)
            {
                return;
            }

            if (!mapping.IsSoap)
            {
                if (o == null)
                {
                    if (isNullable)
                    {
                        WriteNullTagLiteral(n, ns);
                    }
                    return;
                }

                if (!needType &&
                    o.GetType() != mapping.TypeDesc.Type)
                {
                    if (WriteDerivedTypes(mapping, n, ns, o, isNullable))
                    {
                        return;
                    }

                    if (mapping.TypeDesc.IsRoot)
                    {
                        if (WriteEnumAndArrayTypes(mapping, o, n, ns, parentMapping))
                        {
                            return;
                        }

                        WriteTypedPrimitive(n, ns, o, true);
                        return;
                    }

                    throw CreateUnknownTypeException(o);
                }
            }

            if (!mapping.TypeDesc.IsAbstract)
            {
                if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type))
                {
                    EscapeName = false;
                }

                XmlSerializerNamespaces xmlnsSource = null;
                MemberMapping[]         members     = TypeScope.GetAllMembers(mapping);
                int xmlnsMember = FindXmlnsIndex(members);
                if (xmlnsMember >= 0)
                {
                    MemberMapping member = members[xmlnsMember];
                    xmlnsSource = (XmlSerializerNamespaces)GetMemberValue(o, member.Name);
                }

                if (!mapping.IsSoap)
                {
                    WriteStartElement(n, ns, o, false, xmlnsSource);

                    if (!mapping.TypeDesc.IsRoot)
                    {
                        if (needType)
                        {
                            WriteXsiType(mapping.TypeName, mapping.Namespace);
                        }
                    }
                }
                else if (xmlnsSource != null)
                {
                    WriteNamespaceDeclarations(xmlnsSource);
                }

                for (int i = 0; i < members.Length; i++)
                {
                    MemberMapping m           = members[i];
                    string        memberName  = m.Name;
                    object        memberValue = GetMemberValue(o, memberName);

                    bool isSpecified   = true;
                    bool shouldPersist = true;
                    if (m.CheckSpecified != SpecifiedAccessor.None)
                    {
                        string specifiedMemberName = m.Name + "Specified";
                        isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
                    }

                    if (m.CheckShouldPersist)
                    {
                        string     methodInvoke = "ShouldSerialize" + m.Name;
                        MethodInfo method       = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
                        shouldPersist = (bool)method.Invoke(o, Array.Empty <object>());
                    }

                    if (m.Attribute != null)
                    {
                        if (isSpecified && shouldPersist)
                        {
                            WriteMember(memberValue, m.Attribute, m.TypeDesc, o);
                        }
                    }
                }

                for (int i = 0; i < members.Length; i++)
                {
                    MemberMapping m           = members[i];
                    string        memberName  = m.Name;
                    object        memberValue = GetMemberValue(o, memberName);

                    bool isSpecified   = true;
                    bool shouldPersist = true;
                    if (m.CheckSpecified != SpecifiedAccessor.None)
                    {
                        string specifiedMemberName = m.Name + "Specified";
                        isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
                    }

                    if (m.CheckShouldPersist)
                    {
                        string     methodInvoke = "ShouldSerialize" + m.Name;
                        MethodInfo method       = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
                        shouldPersist = (bool)method.Invoke(o, Array.Empty <object>());
                    }

                    if (m.Xmlns != null)
                    {
                        continue;
                    }

                    bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null);

                    if (!checkShouldPersist)
                    {
                        shouldPersist = true;
                    }

                    object choiceSource = null;
                    if (m.ChoiceIdentifier != null)
                    {
                        choiceSource = GetMemberValue(o, m.ChoiceIdentifier.MemberName);
                    }

                    if (isSpecified && shouldPersist)
                    {
                        WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true, parentMapping);
                    }
                }
                if (!mapping.IsSoap)
                {
                    WriteEndElement(o);
                }
            }
        }
        private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string ns, XmlMapping parentMapping)
        {
            if (o is Enum)
            {
                Writer.WriteStartElement(n, ns);

                EnumMapping enumMapping = null;
                Type        enumType    = o.GetType();
                foreach (var m in parentMapping.Scope.TypeMappings)
                {
                    var em = m as EnumMapping;
                    if (em != null && em.TypeDesc.Type == enumType)
                    {
                        enumMapping = em;
                        break;
                    }
                }

                Debug.Assert(enumMapping != null);

                WriteXsiType(enumMapping.TypeName, ns);
                Writer.WriteString(WriteEnumMethod(enumMapping, o));
                Writer.WriteEndElement();
                return(true);
            }

            if (o is Array)
            {
                Debug.Assert(parentMapping != null);
                Writer.WriteStartElement(n, ns);
                ArrayMapping arrayMapping = null;
                Type         arrayType    = o.GetType();
                foreach (var m in parentMapping.Scope.TypeMappings)
                {
                    var am = m as ArrayMapping;
                    if (am != null && am.TypeDesc.Type == arrayType)
                    {
                        arrayMapping = am;
                        break;
                    }
                }

                Debug.Assert(arrayMapping != null);
                WriteXsiType(arrayMapping.TypeName, ns);
                WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true);
                Writer.WriteEndElement();

                return(true);
            }

            return(false);
        }
 public static System.Reflection.Assembly GenerateSerializer(Type[] types, XmlMapping[] mappings, System.CodeDom.Compiler.CompilerParameters parameters)
 {
 }
 public static System.Reflection.Assembly GenerateSerializer(Type[] types, XmlMapping[] mappings)
 {
 }
Exemplo n.º 27
0
 /// <summary>
 /// Method to simplify addMapping
 /// </summary>
 /// <param name="mapping">Mapping to add</param>
 private void addMapping(XmlMapping mapping)
 {
     this.ImportMappings.Add(mapping);
 }
Exemplo n.º 28
0
 internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace)
 {
     return(GenerateTempAssembly(xmlMapping, type, defaultNamespace, null));
 }
        private void WriteElement(object o, ElementAccessor element, string arrayName, bool writeAccessor, XmlMapping parentMapping = null)
        {
            string name = writeAccessor ? element.Name : element.Mapping.TypeName;
            string ns   = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : "");

            if (element.Mapping is NullableMapping)
            {
                if (o != null)
                {
                    ElementAccessor e = element.Clone();
                    e.Mapping = ((NullableMapping)element.Mapping).BaseMapping;
                    WriteElement(o, e, arrayName, writeAccessor);
                }
                else if (element.IsNullable)
                {
                    WriteNullTagLiteral(element.Name, ns);
                }
            }
            else if (element.Mapping is ArrayMapping)
            {
                var mapping = (ArrayMapping)element.Mapping;

                if (element.IsNullable && o == null)
                {
                    WriteNullTagLiteral(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : "");
                }
                else if (mapping.IsSoap)
                {
                    if (mapping.Elements == null || mapping.Elements.Length != 1)
                    {
                        throw new InvalidOperationException(SR.XmlInternalError);
                    }

                    var itemElement   = mapping.Elements[0];
                    var itemMapping   = itemElement.Mapping as StructMapping;
                    var itemName      = writeAccessor ? itemElement.Name : itemMapping.TypeName;
                    var itemNamespace = itemElement.Any && itemElement.Name.Length == 0 ? null : (itemElement.Form == XmlSchemaForm.Qualified ? (writeAccessor ? itemElement.Namespace : itemMapping.Namespace) : "");

                    if (!writeAccessor)
                    {
                        WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc.Type, true, element.IsNullable);
                    }
                    else
                    {
                        WritePotentiallyReferencingElement(name, ns, o, null, false, element.IsNullable);
                    }
                }
                else if (element.IsUnbounded)
                {
                    TypeDesc arrayTypeDesc = mapping.TypeDesc.CreateArrayTypeDesc();

                    var enumerable = (IEnumerable)o;
                    foreach (var e in enumerable)
                    {
                        element.IsUnbounded = false;
                        WriteElement(e, element, arrayName, writeAccessor);
                        element.IsUnbounded = true;
                    }
                }
                else
                {
                    if (o != null)
                    {
                        WriteStartElement(name, ns, false);
                        WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, o);
                        WriteEndElement();
                    }
                }
            }
            else if (element.Mapping is EnumMapping)
            {
                if (element.Mapping.IsSoap)
                {
                    Writer.WriteStartElement(name, ns);
                    WriteEnumMethod((EnumMapping)element.Mapping, o);
                    WriteEndElement();
                }
                else
                {
                    WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns, element.Default, o, element.Mapping, false, true, element.IsNullable);
                }
            }
            else if (element.Mapping is PrimitiveMapping)
            {
                PrimitiveMapping mapping = (PrimitiveMapping)element.Mapping;
                if (mapping.TypeDesc == QnameTypeDesc)
                {
                    WriteQualifiedNameElement(name, ns, element.Default, (XmlQualifiedName)o, element.IsNullable, mapping.IsSoap, mapping);
                }
                else
                {
                    WritePrimitiveMethodRequirement suffixNullable = mapping.IsSoap ? WritePrimitiveMethodRequirement.Encoded : WritePrimitiveMethodRequirement.None;
                    WritePrimitiveMethodRequirement suffixRaw      = mapping.TypeDesc.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None;
                    WritePrimitive(element.IsNullable
                        ? WritePrimitiveMethodRequirement.WriteNullableStringLiteral | suffixNullable | suffixRaw
                        : WritePrimitiveMethodRequirement.WriteElementString | suffixRaw,
                                   name, ns, element.Default, o, mapping, mapping.IsSoap, true, element.IsNullable);
                }
            }
            else if (element.Mapping is StructMapping)
            {
                var mapping = (StructMapping)element.Mapping;
                if (mapping.IsSoap)
                {
                    WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc.Type : null, !writeAccessor, element.IsNullable);
                }
                else
                {
                    WriteStructMethod(mapping, name, ns, o, element.IsNullable, needType: false, parentMapping: parentMapping);
                }
            }
            else if (element.Mapping is SpecialMapping)
            {
                if (element.Mapping is SerializableMapping)
                {
                    WriteSerializable((IXmlSerializable)o, name, ns, element.IsNullable, !element.Any);
                }
                else
                {
                    // XmlNode, XmlElement
                    var node = o as XmlNode;
                    if (node != null)
                    {
                        WriteElementLiteral(node, name, ns, element.IsNullable, element.Any);
                    }
                    else
                    {
                        throw CreateInvalidAnyTypeException(o);
                    }
                }
            }
            else
            {
                throw new InvalidOperationException(SR.XmlInternalError);
            }
        }
 public static XmlSerializer[] FromMappings(XmlMapping[] mappings);
        private void WriteElements(object o, object enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, string arrayName, bool writeAccessors, bool isNullable, XmlMapping parentMapping = null)
        {
            if (elements.Length == 0 && text == null)
            {
                return;
            }
            if (elements.Length == 1 && text == null)
            {
                WriteElement(o, elements[0], arrayName, writeAccessors, parentMapping);
            }
            else
            {
                if (isNullable && choice == null && o == null)
                {
                    return;
                }

                int             anyCount     = 0;
                var             namedAnys    = new List <ElementAccessor>();
                ElementAccessor unnamedAny   = null; // can only have one
                string          enumTypeName = choice == null ? null : choice.Mapping.TypeDesc.FullName;

                for (int i = 0; i < elements.Length; i++)
                {
                    ElementAccessor element = elements[i];

                    if (element.Any)
                    {
                        anyCount++;
                        if (element.Name != null && element.Name.Length > 0)
                        {
                            namedAnys.Add(element);
                        }
                        else if (unnamedAny == null)
                        {
                            unnamedAny = element;
                        }
                    }
                    else if (choice != null)
                    {
                        if (o != null && o.GetType() == element.Mapping.TypeDesc.Type)
                        {
                            WriteElement(o, element, arrayName, writeAccessors);
                            return;
                        }
                    }
                    else
                    {
                        TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc;
                        if (o.GetType() == td.Type)
                        {
                            WriteElement(o, element, arrayName, writeAccessors);
                            return;
                        }
                    }
                }

                if (anyCount > 0)
                {
                    var elem = o as XmlElement;
                    if (elem != null)
                    {
                        foreach (ElementAccessor element in namedAnys)
                        {
                            if (element.Name == elem.Name && element.Namespace == elem.NamespaceURI)
                            {
                                WriteElement(elem, element, arrayName, writeAccessors);
                                return;
                            }
                        }

                        if (choice != null)
                        {
                            throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName, elem.Name, elem.NamespaceURI);
                        }

                        if (unnamedAny != null)
                        {
                            WriteElement(elem, unnamedAny, arrayName, writeAccessors);
                            return;
                        }

                        throw CreateUnknownAnyElementException(elem.Name, elem.NamespaceURI);
                    }
                }

                if (text != null)
                {
                    bool   useReflection = text.Mapping.TypeDesc.UseReflection;
                    string fullTypeName  = text.Mapping.TypeDesc.CSharpName;
                    WriteText(o, text);
                    return;
                }

                if (elements.Length > 0 && o != null)
                {
                    throw CreateUnknownTypeException(o);
                }
            }
        }
 public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
 {
 }
Exemplo n.º 33
0
        private void importData(XmlMapping currentMapping)
        {
            SetParent(currentMapping);

            var template = (SCItems.TemplateItem) this.GetItem(currentMapping.TemplateID);
            var ds       = currentMapping.Source.Source;

            this._currentItemIndex = 0;
            for (; _currentItemIndex < this.currentFileList.Length; this._currentItemIndex++)
            {
                if (checkContinue())
                {
                    // run process to import the actual data
                    try
                    {
                        // load the xml document from file into an xdocument
                        var currentFileItem = this.currentFileList[this._currentItemIndex];
                        var currentXdoc     = new XmlDocument();
                        currentXdoc.Load(currentFileItem.FullName);
                        // select name element by xpath
                        var nameElement = currentXdoc.SelectSingleNode(currentMapping.NameNodePath);
                        var name        = nameElement == null ? "" : nameElement.Value ?? nameElement.InnerText;
                        if (string.IsNullOrWhiteSpace(name))
                        {
                            LogStatus("Name and Parent cannot be blank.", currentFileItem.Name);
                            continue;
                        }
                        if (currentMapping.CleanNames)
                        {
                            name = SCItems.ItemUtil.ProposeValidItemName(name);
                        }
                        // get parent according to import settings
                        var parent = this.getParent(currentMapping, currentXdoc);
                        // only proceed if a parent and name are present since they are required by Sitecore
                        if (string.IsNullOrWhiteSpace(name) || parent == null)
                        {
                            LogStatus("Name and Parent cannot be blank.", currentFileItem.Name);
                            continue;
                        }
                        var newItem = template.CreateItemFrom(name, parent);
                        fileToItemList.Add(currentFileItem.FullName, newItem.ID);   // this allows quick reference to all processed files related to a Sitecore item
                        var fields = newItem.GetEditableFields();

                        using (new SC.SecurityModel.SecurityDisabler())
                        {
                            using (new SCItems.EditContext(newItem))
                            {
                                foreach (var mapping in currentMapping.FieldMappings)
                                {
                                    try
                                    {
                                        var field = fields.FirstOrDefault(f => f.Name.ToLower() == mapping.FieldName.ToLower());
                                        if (field != null)
                                        {
                                            var fieldElement = currentXdoc.SelectSingleNode(mapping.XPath);
                                            var fieldValue   = fieldElement == null ? "" : fieldElement.Value ?? fieldElement.InnerText;
                                            if (!string.IsNullOrWhiteSpace(fieldValue))
                                            {
                                                field.SetValueByType(fieldValue);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogStatus($"[Field: {mapping.FieldName}] {ex.Message}", currentFileItem.Name);
                                    }
                                }
                            }
                        }

                        this.CurrentPercent = ((this._currentItemIndex + 1) * 100) / this.currentFileList.Length;
                        if (this.IsAsync)
                        {
                            this.BgWorker.ReportProgress(this.CurrentPercent, currentMapping.Source.Name);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogStatus(ex.Message);
                    }
                }
                else
                {
                    break;
                }
            }
        }
Exemplo n.º 34
0
 public XmlSerializerMappingKey(XmlMapping mapping)
 {
     this.Mapping = mapping;
 }
 public static XmlSerializer[] FromMappings(XmlMapping[] mappings, System.Security.Policy.Evidence evidence)
 {
 }