示例#1
0
    // Here we deserialize it back into its original form
    public static object DeserializeObject(string pXmlizedString, string rootElementName, Type ObjectType, EncodingType encodingType)
    {
        XmlRootAttribute xRoot = new XmlRootAttribute();
        xRoot.ElementName = rootElementName;

        XmlSerializer xs = new XmlSerializer(ObjectType, xRoot);
        MemoryStream memoryStream = null;

        switch (encodingType)
        {
            case EncodingType.Unicode:
                memoryStream = new MemoryStream(StringToUTFUnicodeByteArray(pXmlizedString));
                break;
            case EncodingType.UTF8:
                memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
                break;
            case EncodingType.UTF7:
                break;
            default:
                memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
                break;
        }

        return xs.Deserialize(memoryStream);
    }
示例#2
0
    public SaveData( string xmlElementName, string xmlNamespace, string fileAndpath )
    {
        // Start Overloaded constructor.

        // Settings XML/Saving data:
        _xmlRoot = new XmlRootAttribute();
        _xmlRoot.Namespace = xmlNamespace;
        _xmlRoot.ElementName = xmlElementName;
        _fileAndPath = fileAndpath;

         #region Settings File Loading/Gernerating
        // Attempting to load an XML file and set the settings
        // If this does not work then we load the default settings:
        if( !load() )
        { // Start if loading did not work.

            // Setting all the data to default:
            setAllDataToDefault();

            // Saving the Default Settings File:
            if( !save() )
                Debug.Log ( "Settings file faled to save!" );

        }// End if loading did not work.
        #endregion
    }
示例#3
0
    // Here we serialize our UserData object of myData
    public static string SerializeObject(object pObject, string rootElementName, Type ObjectType)
    {
        XmlRootAttribute xRoot = new XmlRootAttribute();
        xRoot.ElementName = rootElementName;

        string XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(ObjectType, xRoot);
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        xs.Serialize(xmlTextWriter, pObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }
示例#4
0
        //TODO:create key value pairs in web.config for file path to the config file
        void SeedStockCollection()
        {
            var securitiesFileName = HostingEnvironment.MapPath("~/App_Data/securities.json");
            List <Securities> securityList = JsonConvert.DeserializeObject <List <Securities> >(File.ReadAllText(securitiesFileName));
            Dictionary <string, Dictionary <DateTime, string> > aliceClosePriceMap, bobClosePriceMap, charlieClosePriceMap;
            HashSet <DateTime> allDateTimes = new HashSet <DateTime>();

            //ALICE
            var aliceInWonderland = HostingEnvironment.MapPath("~/App_Data/StocksPrices-ALICE.csv");

            using (var sr = new StreamReader(aliceInWonderland))
            {
                var          reader = new CsvReader(sr);
                List <Alice> alice  = reader.GetRecords <Alice>().ToList();
                foreach (var alice1 in alice)
                {
                    if (allDateTimes.Contains(alice1.date))
                    {
                        continue;
                    }
                    else
                    {
                        allDateTimes.Add(alice1.date);
                    }
                }
                aliceClosePriceMap = secCloseDatePriceMap(alice);
            }

            //BOB
            var bobTheBuilder          = HostingEnvironment.MapPath("~/App_Data/StocksPrices-BOB.xls");
            var rawData                = OpenExcel(bobTheBuilder, "StocksPrices-BOB");
            IEnumerable <DataRow> rows = rawData.Rows.Cast <DataRow>();

            foreach (var row in rows)
            {
                if (allDateTimes.Contains(DateTime.Parse(row["date"].ToString())))
                {
                    continue;
                }
                else
                {
                    allDateTimes.Add(DateTime.Parse(row["date"].ToString()));
                }
            }

            bobClosePriceMap = secCloseDatePriceMap(rows);

            //Charlies Angel

            XmlRootAttribute xRoot = new XmlRootAttribute();

            xRoot.ElementName = "root";
            xRoot.IsNullable  = true;
            XmlSerializer serializer    = new XmlSerializer(typeof(List <row>), xRoot);
            var           charliesAngel = HostingEnvironment.MapPath("~/App_Data/StocksPrices-CHARLIE.xml");

            using (var sr = new StreamReader(charliesAngel))
            {
                List <row> charlie = (List <row>)serializer.Deserialize(sr);
                foreach (var alice1 in charlie)
                {
                    if (allDateTimes.Contains(alice1.date))
                    {
                        continue;
                    }
                    else
                    {
                        allDateTimes.Add(alice1.date);
                    }
                }
                charlieClosePriceMap = secCloseDatePriceMap(charlie);
            }

            foreach (var security in securityList)
            {
                Security s = new Security();
                s.symbol       = security.symbol;
                s.Sector       = security.Sector;
                s.SecurityName = security.Security;
                s.SubIndustry  = security.SubIndustry;
                ICollection <Prices> pricesCollection = new List <Prices>();
                foreach (var dateTime in allDateTimes)
                {
                    Prices p = new Prices();
                    p.symbol    = security.symbol;
                    p.CloseDate = dateTime;
                    if (aliceClosePriceMap.ContainsKey(security.symbol))
                    {
                        if (aliceClosePriceMap[security.symbol].ContainsKey(dateTime))
                        {
                            string close = aliceClosePriceMap[security.symbol][dateTime];
                            if (String.IsNullOrEmpty(close))
                            {
                                p.Alice = "NA";
                            }
                            else
                            {
                                p.Alice = close;
                            }
                        }
                    }
                    if (bobClosePriceMap.ContainsKey(security.symbol))
                    {
                        if (bobClosePriceMap[security.symbol].ContainsKey(dateTime))
                        {
                            string close = bobClosePriceMap[security.symbol][dateTime];
                            if (String.IsNullOrEmpty(close))
                            {
                                p.Bob = "NA";
                            }
                            else
                            {
                                p.Bob = close;
                            }
                        }
                    }
                    if (charlieClosePriceMap.ContainsKey(security.symbol))
                    {
                        if (charlieClosePriceMap[security.symbol].ContainsKey(dateTime))
                        {
                            string close = charlieClosePriceMap[security.symbol][dateTime];
                            if (String.IsNullOrEmpty(close))
                            {
                                p.Charlie = "NA";
                            }
                            else
                            {
                                p.Charlie = close;
                            }
                        }
                    }
                    pricesCollection.Add(p);
                }
                s.PriceCollection = pricesCollection;
                _ctx.SecuritySet.Add(s);
            }
            _ctx.SaveChanges();
        }
 public XmlSerializer CreateSerializer(Type type, XmlRootAttribute root)
 {
 }
示例#6
0
 private BSData SerializeData(string p)
 {
     XmlRootAttribute root = new XmlRootAttribute();
     root.ElementName = "Data";
     root.IsNullable = true;
     XmlSerializer dataSerializer = new XmlSerializer(typeof(BSData), root);
     using (TextReader reader = new StreamReader(Server.MapPath(String.Format("~/Setup/Data/{0}.xml", p))))
     {
         BSData data = (BSData)dataSerializer.Deserialize(reader);
         return data;
     }
 }
 public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root, string defaultNamespace);
        private TLCGenDefaultsModel DeserializeDefaultsFile(string filename)
        {
            var defaults = new TLCGenDefaultsModel();
            var doc      = new XmlDocument();
            var reader   =
                XmlReader.Create(
                    filename,
                    new XmlReaderSettings()
            {
                IgnoreComments = true
            });

            doc.Load(reader);
            reader.Dispose();
            var defs = doc.DocumentElement?.SelectSingleNode("Defaults");

            if (defs == null)
            {
                return(null);
            }
            foreach (XmlNode def in defs.ChildNodes)
            {
                var x = def.SelectSingleNode("DataType");
                var t = x.InnerText;
                // correct old files
                if (t.EndsWith(",TLCGen.Model"))
                {
                    t = t.Replace(",TLCGen.Model", ",TLCGen.Dependencies");
                }
                var type  = Type.GetType(t);
                var xRoot = new XmlRootAttribute
                {
                    ElementName = "Data",
                    IsNullable  = true
                };
                if (type == null)
                {
                    continue;
                }
                var ser = new XmlSerializer(type, xRoot);
                // http://stackoverflow.com/questions/1563473/xmlnode-to-objects
                var o    = ser.Deserialize(new XmlNodeReader(def.SelectSingleNode("Data")));
                var item = new TLCGenDefaultModel
                {
                    DefaultName = def.SelectSingleNode("DefaultName")?.InnerText,
                    DataType    = def.SelectSingleNode("DataType")?.InnerText,
                    Category    = def.SelectSingleNode("Category")?.InnerText
                };
                var n1 = def.SelectSingleNode("Selector1");
                if (n1 != null)
                {
                    item.Selector1 = n1.InnerText;
                }
                var n2 = def.SelectSingleNode("Selector2");
                if (n2 != null)
                {
                    item.Selector2 = n2.InnerText;
                }
                item.Data = o;
                defaults.Defaults.Add(item);
            }
            return(defaults);
        }
示例#9
0
        public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib)
        {
            object retValue      = null;
            bool   isBaseCLRType = false;
            bool   legacyUDT     = false; // in 1.0 and 1.1 we used to call ToString on CDT obj. so if we have the same case

            // we need to handle the case when we have column type as object.
            if (null == xmlAttrib)
            { // this means type implements IXmlSerializable
                Type   type     = null;
                string typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS);
                if (typeName == null || typeName.Length == 0)
                {                                                                               // No CDT polumorphism
                    string xsdTypeName = xmlReader.GetAttribute(Keywords.TYPE, Keywords.XSINS); // this xsd type: Base type polymorphism
                    if (null != xsdTypeName && xsdTypeName.Length > 0)
                    {
                        string[] _typename = xsdTypeName.Split(':');
                        if (_typename.Length == 2)
                        { // split will return aray of size 1 if ":" is not there
                            if (xmlReader.LookupNamespace(_typename[0]) == Keywords.XSDNS)
                            {
                                xsdTypeName = _typename[1]; // trim the prefix and just continue with
                            }
                        } // for other case, let say we have two ':' in type, the we throws (as old behavior)
                        type          = XSDSchema.XsdtoClr(xsdTypeName);
                        isBaseCLRType = true;
                    }
                    else if (_dataType == typeof(object))
                    {                     // there is no Keywords.MSD_INSTANCETYPE and no Keywords.TYPE
                        legacyUDT = true; // see if our type is object
                    }
                }

                if (legacyUDT)
                { // if Everett UDT, just read it and return string
                    retValue = xmlReader.ReadString();
                }
                else
                {
                    if (typeName == Keywords.TYPEINSTANCE)
                    {
                        retValue = Type.GetType(xmlReader.ReadString());
                        xmlReader.Read(); // need to move to next node
                    }
                    else
                    {
                        if (null == type)
                        {
                            type = (typeName == null) ? _dataType : DataStorage.GetType(typeName);
                        }

                        if (type == typeof(char) || type == typeof(Guid))
                        { //msdata:char and msdata:guid imply base types.
                            isBaseCLRType = true;
                        }

                        if (type == typeof(object))
                        {
                            throw ExceptionBuilder.CanNotDeserializeObjectType();
                        }
                        if (!isBaseCLRType)
                        {
                            retValue = System.Activator.CreateInstance(type, true);
                            Debug.Assert(xmlReader is DataTextReader, "Invalid DataTextReader is being passed to customer");
                            ((IXmlSerializable)retValue).ReadXml(xmlReader);
                        }
                        else
                        {  // Process Base CLR type
                           // for Element Node, if it is Empty, ReadString does not move to End Element; we need to move it
                            if (type == typeof(string) && xmlReader.NodeType == XmlNodeType.Element && xmlReader.IsEmptyElement)
                            {
                                retValue = string.Empty;
                            }
                            else
                            {
                                retValue = xmlReader.ReadString();
                                if (type != typeof(byte[]))
                                {
                                    retValue = SqlConvert.ChangeTypeForXML(retValue, type);
                                }
                                else
                                {
                                    retValue = Convert.FromBase64String(retValue.ToString());
                                }
                            }
                            xmlReader.Read();
                        }
                    }
                }
            }
            else
            {
                XmlSerializer deserializerWithRootAttribute = ObjectStorage.GetXmlSerializer(_dataType, xmlAttrib);
                retValue = deserializerWithRootAttribute.Deserialize(xmlReader);
            }
            return(retValue);
        }
示例#10
0
        public static string ToTextAll <TRec>(IEnumerable <TRec> records, ChoXmlRecordConfiguration configuration = null, TraceSwitch traceSwitch = null, string xpath = null)
            where TRec : class
        {
            if (records == null)
            {
                return(null);
            }

            var pe = new ChoPeekEnumerator <TRec>(records, (Func <TRec, bool?>)null);

            if (configuration == null)
            {
                configuration = new ChoXmlRecordConfiguration();
            }

            configuration.IgnoreRootName = false;

            TRec record = pe.Peek;

            if (record != null)
            {
                if (configuration.NodeName.IsNullOrWhiteSpace())
                {
                    ChoDynamicObject rec1 = record as ChoDynamicObject;
                    if (rec1 != null)
                    {
                        configuration.NodeName = rec1.DynamicObjectName;
                        if (configuration.RootName.IsNullOrWhiteSpace())
                        {
                            configuration.RootName = configuration.NodeName.ToPlural();
                        }
                    }
                    else
                    {
                        XmlRootAttribute root     = ChoType.GetCustomAttribute <XmlRootAttribute>(record.GetType(), false);
                        string           nodeName = "XElement";
                        if (root != null && !root.ElementName.IsNullOrWhiteSpace())
                        {
                            nodeName = root.ElementName.Trim();
                        }
                        else
                        {
                            nodeName = record.GetType().Name;
                        }

                        if (configuration.RootName.IsNullOrWhiteSpace())
                        {
                            configuration.RootName = nodeName.ToPlural();
                        }
                        configuration.NodeName = nodeName;
                    }
                }
            }
            else
            {
                if (configuration.RootName.IsNullOrWhiteSpace())
                {
                    configuration.RootName = "Root";
                }
            }

            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var parser = new ChoXmlWriter <TRec>(writer, configuration)
                        {
                            TraceSwitch = traceSwitch == null ? ChoETLFramework.TraceSwitch : traceSwitch
                        })
                        {
                            //parser.Configuration.XPath = xpath;

                            parser.Write(pe.ToEnumerable());

                            parser.Close();

                            writer.Flush();
                            stream.Position = 0;

                            return(reader.ReadToEnd());
                        }
        }
示例#11
0
        public static string ToText <TRec>(TRec record, ChoXmlRecordConfiguration configuration = null, TraceSwitch traceSwitch = null, string xpath = null)
            where TRec : class
        {
            if (configuration == null)
            {
                configuration = new ChoXmlRecordConfiguration();
                configuration.IgnoreRootName = true;
                configuration.RootName       = null;
            }

            configuration.IgnoreNodeName = true;

            if (record != null)
            {
                if (configuration.NodeName.IsNullOrWhiteSpace())
                {
                    ChoDynamicObject rec1 = record as ChoDynamicObject;
                    if (rec1 != null)
                    {
                        if (rec1.DynamicObjectName != ChoDynamicObject.DefaultName)
                        {
                            configuration.NodeName = rec1.DynamicObjectName;
                        }
                        else
                        {
                            //configuration.IgnoreNodeName = true;
                            //configuration.NodeName = null;
                        }
                    }
                    else
                    {
                        XmlRootAttribute root     = ChoType.GetCustomAttribute <XmlRootAttribute>(record.GetType(), false);
                        string           nodeName = "XElement";
                        if (root != null && !root.ElementName.IsNullOrWhiteSpace())
                        {
                            nodeName = root.ElementName.Trim();
                        }
                        else
                        {
                            nodeName = record.GetType().Name;
                        }

                        configuration.NodeName = nodeName;
                    }
                }
            }

            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var parser = new ChoXmlWriter <TRec>(writer, configuration)
                        {
                            TraceSwitch = traceSwitch == null ? ChoETLFramework.TraceSwitch : traceSwitch
                        })
                        {
                            //parser.Configuration.XPath = xpath;

                            if (record != null)
                            {
                                parser.Write(ChoEnumerable.AsEnumerable <TRec>(record));
                            }

                            parser.Close();

                            writer.Flush();
                            stream.Position = 0;

                            return(reader.ReadToEnd());
                        }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:System.Xml.Serialization.XmlSerializer"/> class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. It also specifies the class to use as the XML root element.
 /// </summary>
 /// <param name="type">The type of the object that this <see cref="T:System.Xml.Serialization.XmlSerializer"/> can serialize. </param><param name="root">An <see cref="T:System.Xml.Serialization.XmlRootAttribute"/> that represents the XML root element. </param>
 public XmlSerializerWrap(Type type,
                          XmlRootAttribute root)
 {
     this.XmlSerializerInstance = new XmlSerializer(type, root);
 }
示例#13
0
 public virtual void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) {
     xmlWriter.WriteString(ConvertObjectToXml(value));// should it be NO OP?
 }
示例#14
0
 public virtual object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) {
     return ConvertXmlToObject(xmlReader.Value);
 }
示例#15
0
 /// <summary>
 /// See <see cref="XmlSerializer(Type, XmlRootAttribute)"/>.
 /// </summary>
 public XmlSerializer(XmlRootAttribute root)
     : base(typeof(TRoot), root)
 {
 }
示例#16
0
 /// <summary>
 /// See <see cref="XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, string, string)"/>.
 /// </summary>
 public XmlSerializer(XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location)
     : base(typeof(TRoot), overrides, extraTypes, root, defaultNamespace, location)
 {
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:System.Xml.Serialization.XmlSerializer"/> class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. It also specifies the class to use as the XML root element.
 /// </summary>
 /// <param name="type">The type of the object that this <see cref="T:System.Xml.Serialization.XmlSerializer"/> can serialize. </param><param name="root">An <see cref="T:System.Xml.Serialization.XmlRootAttribute"/> that represents the XML root element. </param>
 public IXmlSerializer Create(Type type,
                              XmlRootAttribute root)
 {
     return(new XmlSerializerWrap(type, root));
 }
示例#18
0
 public WebXMLFileAsset(string url = null, XmlRootAttribute attr = null, AssetLoaded <T> callback = null)
 {
     serializer = new XmlSerializer(typeof(T), attr);
     this.url   = url;
     Load(callback);
 }
        public static string ImportProjects(TeisterMaskContext context, string xmlString)
        {
            var attr       = new XmlRootAttribute("Projects");
            var serializer = new XmlSerializer(typeof(List <ProjectImportDto>), attr);

            StringBuilder sb            = new StringBuilder();
            var           validProjects = new List <Project>();

            using (StringReader reader = new StringReader(xmlString))
            {
                var projectsDto = (List <ProjectImportDto>)serializer.Deserialize(reader);

                foreach (var dto in projectsDto)
                {
                    if (!IsValid(dto))
                    {
                        sb.AppendLine(ErrorMessage);
                        continue;
                    }

                    var project = new Project
                    {
                        Name     = dto.Name,
                        OpenDate = DateTime.ParseExact(dto.OpenDate, "dd/MM/yyyy", CultureInfo.InvariantCulture),
                        DueDate  = string.IsNullOrEmpty(dto.DueDate)
                            ? (DateTime?)null
                            : DateTime.ParseExact(dto.DueDate, "dd/MM/yyyy", CultureInfo.InvariantCulture)
                    };

                    var projectTasks = new List <Task>();

                    foreach (var task in dto.Tasks)
                    {
                        if (!IsValid(task))
                        {
                            sb.AppendLine(ErrorMessage);
                            continue;
                        }

                        var taskOpDate  = DateTime.ParseExact(task.OpenDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                        var taskDueDate = DateTime.ParseExact(task.DueDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                        bool isTaskOpDateValid = true;
                        if (taskOpDate < project.OpenDate)
                        {
                            isTaskOpDateValid = false;
                        }

                        bool isTaskDueDateValid = true;
                        if (taskDueDate > project.DueDate)
                        {
                            isTaskDueDateValid = false;
                        }

                        if (!isTaskDueDateValid || !isTaskOpDateValid)
                        {
                            sb.AppendLine(ErrorMessage);
                            continue;
                        }

                        var taskToAdd = new Task
                        {
                            Name          = task.Name,
                            OpenDate      = taskOpDate,
                            DueDate       = taskDueDate,
                            ExecutionType = Enum.Parse <ExecutionType>(task.ExecutionType),
                            LabelType     = Enum.Parse <LabelType>(task.LabelType),
                            Project       = project
                        };

                        projectTasks.Add(taskToAdd);
                    }

                    project.Tasks = projectTasks;

                    validProjects.Add(project);

                    sb.AppendLine(string.Format(SuccessfullyImportedProject, project.Name, project.Tasks.Count));
                }
            }

            context.Projects.AddRange(validProjects);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }
示例#20
0
        private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlReader row)
        {
            // read table information
            if (ds != null)
            {
                table = ds.Tables.GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI);
            }
            else
            {
                table = GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI);
            }

            if (table == null)
            {
                row.Skip(); // need to skip this element if we dont know about it, before returning -1
                return(-1);
            }

            int    iRowDepth = row.Depth;
            string value     = null;

            if (table == null)
            {
                throw ExceptionBuilder.DiffgramMissingTable(XmlConvert.DecodeName(row.LocalName));
            }


            value = row.GetAttribute(Keywords.ROWORDER, Keywords.MSDNS);
            if (!string.IsNullOrEmpty(value))
            {
                pos = (int)Convert.ChangeType(value, typeof(int), null);
            }

            int record = table.NewRecord();

            foreach (DataColumn col in table.Columns)
            {
                col[record] = DBNull.Value;
            }

            foreach (DataColumn col in table.Columns)
            {
                if ((col.ColumnMapping == MappingType.Element) ||
                    (col.ColumnMapping == MappingType.SimpleContent))
                {
                    continue;
                }

                if (col.ColumnMapping == MappingType.Hidden)
                {
                    value = row.GetAttribute("hidden" + col.EncodedColumnName, Keywords.MSDNS);
                }
                else
                {
                    value = row.GetAttribute(col.EncodedColumnName, col.Namespace);
                }

                if (value == null)
                {
                    continue;
                }

                col[record] = col.ConvertXmlToObject(value);
            }

            row.Read();
            SkipWhitespaces(row);

            int currentDepth = row.Depth;

            if (currentDepth <= iRowDepth)
            {
                // the node is empty
                if (currentDepth == iRowDepth && row.NodeType == XmlNodeType.EndElement)
                {
                    // read past the EndElement of the current row
                    // note: (currentDepth == iRowDepth) check is needed so we do not skip elements on parent rows.
                    row.Read();
                    SkipWhitespaces(row);
                }
                return(record);
            }

            if (table.XmlText != null)
            {
                DataColumn col = table.XmlText;
                col[record] = col.ConvertXmlToObject(row.ReadString());
            }
            else
            {
                while (row.Depth > iRowDepth)
                {
                    string     ln     = XmlConvert.DecodeName(row.LocalName);
                    string     ns     = row.NamespaceURI;
                    DataColumn column = table.Columns[ln, ns];

                    if (column == null)
                    {
                        while ((row.NodeType != XmlNodeType.EndElement) && (row.LocalName != ln) && (row.NamespaceURI != ns))
                        {
                            row.Read(); // consume the current node
                        }
                        row.Read();     // now points to the next column
                        //SkipWhitespaces(row); seems no need, just in case if we see other issue , this will be here as hint
                        continue;       // add a read here!
                    }

                    if (column.IsCustomType)
                    {
                        // if column's type is object or column type does not implement IXmlSerializable
                        bool isPolymorphism = (column.DataType == typeof(object) || (row.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS) != null) ||
                                               (row.GetAttribute(Keywords.TYPE, Keywords.XSINS) != null));

                        bool skipped = false;
                        if (column.Table.DataSet != null && column.Table.DataSet._udtIsWrapped)
                        {
                            row.Read(); // if UDT is wrapped, skip the wrapper
                            skipped = true;
                        }

                        XmlRootAttribute xmlAttrib = null;

                        if (!isPolymorphism && !column.ImplementsIXMLSerializable)
                        { // THIS CHECK MAY BE IS WRONG think more
                            // if does not implement IXLSerializable, need to go with XmlSerializer: pass XmlRootAttribute
                            if (skipped)
                            {
                                xmlAttrib           = new XmlRootAttribute(row.LocalName);
                                xmlAttrib.Namespace = row.NamespaceURI;
                            }
                            else
                            {
                                xmlAttrib           = new XmlRootAttribute(column.EncodedColumnName);
                                xmlAttrib.Namespace = column.Namespace;
                            }
                        }
                        // for else case xmlAttrib MUST be null
                        column[record] = column.ConvertXmlToObject(row, xmlAttrib); // you need to pass null XmlAttib here


                        if (skipped)
                        {
                            row.Read(); // if Wrapper is skipped, skip its end tag
                        }
                    }
                    else
                    {
                        int iColumnDepth = row.Depth;
                        row.Read();

                        // SkipWhitespaces(row);seems no need, just in case if we see other issue , this will be here as hint
                        if (row.Depth > iColumnDepth)
                        { //we are inside the column
                            if (row.NodeType == XmlNodeType.Text || row.NodeType == XmlNodeType.Whitespace || row.NodeType == XmlNodeType.SignificantWhitespace)
                            {
                                string text = row.ReadString();
                                column[record] = column.ConvertXmlToObject(text);

                                row.Read(); // now points to the next column
                            }
                        }
                        else
                        {
                            // <element></element> case
                            if (column.DataType == typeof(string))
                            {
                                column[record] = string.Empty;
                            }
                        }
                    }
                }
            }
            row.Read(); //now it should point to next row
            SkipWhitespaces(row);
            return(record);
        }
示例#21
0
        /// <summary>
        /// 将指定的实体对象序列化为XML文档
        /// </summary>
        /// <typeparam name="T">实体对象的类型</typeparam>
        /// <param name="entity">要序列化的实体对象</param>
        /// <param name="isOmit">指示序列化时是否需要编写XML声明</param>
        /// <param name="fileName">如果要将序列化后的内容保存到文件,该参数用于指定保存文件的服务器绝对路径(以~开头的路径)</param>
        /// <param name="rootName">指定序列化时XML文档根节点的名称,默认使用对象的类名</param>
        /// <returns>如果保存为文件,则返回保存后的文件所在路径,否则返回XML文档内容</returns>
        public static string Serialize <T>(T entity, bool isOmit = false, string fileName = "", string rootName = "")
        {
            Stream        stream     = null;
            XmlWriter     writer     = null;
            string        result     = string.Empty;
            XmlSerializer serializer = null;
            Type          type       = typeof(T);

            if (!General.IsNullable(rootName))
            {
                XmlRootAttribute rootAttr = new XmlRootAttribute(rootName);
                serializer = new XmlSerializer(type, rootAttr);
            }
            else
            {
                serializer = new XmlSerializer(type);
            }

            try
            {
                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    string path = FileHelper.MapPath(fileName);
                    if (!File.Exists(path))
                    {
                        if (!FileHelper.CreateDirectory(fileName))
                        {
                            throw new Exception(string.Format("无法为指定的路径:{0}创建相应的目录结构", fileName));
                        }
                    }

                    stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                    result = fileName;
                }
                else
                {
                    stream = new MemoryStream();
                }

                writer = XmlWriter.Create(
                    stream,
                    new XmlWriterSettings
                {
                    Encoding           = Encoding.UTF8,
                    Indent             = true,
                    OmitXmlDeclaration = isOmit
                }
                    );

                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add("", "");

                serializer.Serialize(writer, entity, namespaces);

                if (stream is MemoryStream)
                {
                    result = Encoding.UTF8.GetString(((MemoryStream)stream).ToArray());
                }
            }
            catch (Exception ex)
            {
                result = string.Empty;
                throw ex;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }

                if (stream != null)
                {
                    stream.Close();
                }
            }

            return(result);
        }
 public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root);
示例#23
0
 // Token: 0x0600003C RID: 60 RVA: 0x00003FEC File Offset: 0x000021EC
 public SafeXmlSerializer(Type type, XmlRootAttribute root) : base(type, root)
 {
 }
示例#24
0
    public void Initialize( bool masterSoundON, bool musicOn, bool soundOn, float musicVolume, float soundVolume, bool timerOn, bool randomStartAndEnd, bool randomPassages, int numberOfPossablePassages, bool mouseLook, string xmlElementName, string xmlNamespace, string fileAndpath )
    {
        // Sound Variables:
        _masterSoundOn = masterSoundON;
        _musicOn = musicOn;
        _soundEffectsOn = soundOn;
        _musicVolume = musicVolume;
        _soundVolume = soundVolume;

        // Timmer variables:
        _timerOn = timerOn;

        // Maze spicific variables:
        _randomStartAndEnd = randomStartAndEnd;
        _randomPassages = randomPassages;
        _numberOfPossablePassages = numberOfPossablePassages;

        // Input Variables:
        _mouseLook = mouseLook;

        // Settings XML/Saving data:
        XmlRootAttribute _xmlRoot = new XmlRootAttribute();
        _xmlRoot.Namespace = xmlNamespace;
        _xmlRoot.ElementName = xmlElementName;
        _fileAndPath = fileAndpath;

        Instance = this;
    }
示例#25
0
 // Token: 0x0600003D RID: 61 RVA: 0x00003FF6 File Offset: 0x000021F6
 public SafeXmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : base(type, overrides, extraTypes, root, defaultNamespace)
 {
 }
 // Methods
 public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace)
 {
 }
示例#27
0
 public XmlSubtreeReader(IXmlNode node, XmlRootAttribute root)
     : this(node, root.ElementName, root.Namespace)
 {
 }
 public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location, System.Security.Policy.Evidence evidence)
 {
 }
示例#29
0
        public static string ImportPlays(TheatreContext context, string xmlString)
        {
            XmlRootAttribute xmlRoot       = new XmlRootAttribute("Plays");
            XmlSerializer    xmlSerializer = new XmlSerializer(typeof(ImportPlayDto[]), xmlRoot);

            StringReader stringReader = new StringReader(xmlString);

            ImportPlayDto[] importPlayDtos = (ImportPlayDto[])xmlSerializer.Deserialize(stringReader);

            StringBuilder sb = new StringBuilder();

            ICollection <Play> plays = new HashSet <Play>();

            foreach (var playDto in importPlayDtos)
            {
                if (!IsValid(playDto))
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                bool IsDurationValid =
                    TimeSpan.TryParseExact(playDto.Duration, "c", CultureInfo.InvariantCulture, out TimeSpan duration);

                if (!IsDurationValid)
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                if (duration.TotalMinutes < 60)
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                if (playDto.Genre != "Drama" &&
                    playDto.Genre != "Comedy" &&
                    playDto.Genre != "Romance" &&
                    playDto.Genre != "Musical")
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                Play play = new Play()
                {
                    Title        = playDto.Title,
                    Duration     = duration,
                    Rating       = playDto.Rating,
                    Genre        = (Genre)Enum.Parse(typeof(Genre), playDto.Genre),
                    Description  = playDto.Description,
                    Screenwriter = playDto.Screenwriter
                };

                plays.Add(play);

                sb.AppendLine(string.Format(SuccessfulImportPlay, play.Title, play.Genre, play.Rating));
            }

            context.Plays.AddRange(plays);

            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }