示例#1
0
 static Data[] ReadScore(ref Score[] data)
 {
     Data[] datas = new Data[0];
     try{
         var dexmlSerializer = new XmlSerializer(typeof(Data[]));
         var xmlSettings     = new System.Xml.XmlReaderSettings()
         {
             CheckCharacters = false,
         };
         using (var streamReader = new StreamReader(".score", Encoding.UTF8))
             using (var xmlReader = System.Xml.XmlReader.Create(streamReader, xmlSettings))
             {
                 datas = (Data[])dexmlSerializer.Deserialize(xmlReader);
             }
         for (int i = 0; i < datas.Length; i++)
         {
             if (datas[i].Name == "Pacman")
             {
                 data = datas[i].data;
                 break;
             }
         }
     }catch {
     }
     return(datas);
 }
示例#2
0
        private System.Xml.XmlReaderSettings GetSettings()
        {
            if (m_xmlReaderSettings == null)
            {
                // Setting up validation settings
                var settings = new System.Xml.XmlReaderSettings
                {
                    CloseInput     = false,
                    ValidationType = System.Xml.ValidationType.Schema,
                    XmlResolver    = new System.Xml.XmlUrlResolver()
                    {
                        CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable)
                    }
                };
                settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
                settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ProcessIdentityConstraints;

                // Including only the required schemata to speed up validation.
                if (m_schemata.HasFlag(SchemaType.B2mml))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderB2mml + @"\b2mml\B2MML-V0600-ProductionSchedule.xsd");
                }
                if (m_schemata.HasFlag(SchemaType.Swe))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderRef + @"\swe\swe.xsd");
                }

                m_xmlReaderSettings = settings;
            }

            return(m_xmlReaderSettings);
        }
示例#3
0
 static public bool LoadXmlFile <T>(Stream filestream, out T obj, Type[] extra = null)
 {
     try
     {
         var xmlSettings = new System.Xml.XmlReaderSettings()
         {
             CheckCharacters = false,
         };
         XmlSerializer serializer = new XmlSerializer(typeof(T), extra);
         using (var streamReader = new StreamReader(filestream, Encoding.UTF8))
         {
             using (var xmlReader = System.Xml.XmlReader.Create(streamReader, xmlSettings))
             {
                 obj = (T)serializer.Deserialize(xmlReader);
             }
         }
     }
     catch (Exception ex)
     {
         LogStatics.Debug(ex.ToString());
         obj = default(T);
         return(false);
     }
     return(true);
 }
示例#4
0
        /// <summary>
        /// Reevaluates the key of a TEI entry. This is sometimes neccessary as some TEI files do not have unique keys. The call
        /// evaluates the TEI entry and tries to generate a key from the content.
        /// </summary>
        /// <param name="content">The content of the TEI entry.</param>
        /// <returns>An alternative key derived from the TEI content.</returns>
        private string ReevaluateKey(string content)
        {
            string key;
            string hint = null;

            var settings = new System.Xml.XmlReaderSettings()
            {
                CloseInput       = false,
                IgnoreWhitespace = true,
            };

            using (var xr = System.Xml.XmlReader.Create(new StringReader(content)))
            {
                xr.MoveToContent();
                xr.ReadStartElement("entry");
                xr.ReadStartElement("form");
                key = xr.ReadElementContentAsString("orth", xr.NamespaceURI);
                xr.ReadToFollowing("usg");
                if (xr.Name == "usg")
                {
                    hint = xr.ReadElementContentAsString("usg", xr.NamespaceURI);
                }
            }

            return(hint == null ? key : key + ", " + hint);
        }
示例#5
0
        public static void Main()
        {
            string title = Console.Title;

            Console.Title = "";
            Console.Clear();
            try{
                var xmlSerializer2 = new XmlSerializer(typeof(Data[][]));
                var xmlSettings    = new System.Xml.XmlReaderSettings()
                {
                    CheckCharacters = false,                     // (2)
                };
                using (var streamReader = new StreamReader("Data", Encoding.UTF8))
                    using (var xmlReader
                               = System.Xml.XmlReader.Create(streamReader, xmlSettings))
                    {
                        Data = (Data[][])xmlSerializer2.Deserialize(xmlReader);                         // (3)
                    }
            }catch {
                Data = new Data[3][] {
                    new Data[0],
                    new Data[0],
                    new Data[0]
                };
            }
            Console.WriteLine("ランキングに使うので、名前を入力してください。");
            PlayerName = Console.ReadLine();
            Console.Clear();
            Console.CursorVisible = false;
            Menu();
            Console.CursorVisible = true;
        }
示例#6
0
        public bool IsValid(string xml, XmlSchemaSet sc, bool reportWarnings = false)
        {
            _xml = xml;
            // Create reader settings
            var settings = new System.Xml.XmlReaderSettings();

            // Attach event handler which will be fired when validation error occurs
            settings.ValidationEventHandler += XmlReader_ValidationCallBack;
            // Set validation type to schema
            settings.ValidationType = System.Xml.ValidationType.Schema;
            if (reportWarnings)
            {
                settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            }
            //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema
            //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation
            // Add to the collection of schemas in readerSettings
            settings.Schemas = sc;
            //settings.ProhibitDtd = False
            // Create object of XmlReader using XmlReaderSettings
            var xmlMs  = new System.IO.StringReader(xml);
            var reader = System.Xml.XmlReader.Create(xmlMs, settings);

            Exceptions = new List <XmlSchemaException>();
            // Parse the file.
            while (reader.Read())
            {
            }
            reader.Dispose();
            return(Exceptions.Count == 0);
        }
示例#7
0
        internal void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (!CheckForError(e))
                {
                    // Process capabilities file
    #if WINDOWS_PHONE
                    System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
                    settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
                    XDocument xDoc = null;
                    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(
                               new System.IO.StringReader(e.Result), settings))
                        xDoc = XDocument.Load(reader);
    #else
                    XDocument xDoc = XDocument.Parse(e.Result);
    #endif
                    ParseCapabilities(xDoc);
                }
            }
            catch (Exception failure)
            {
                failure.Data["GetCapabilities"] = e.Result; //todo: add OGC exception info returned from WMS Service
                InitializationFailure           = failure;
            }

            // Call initialize regardless of error
            base.Initialize();
        }
示例#8
0
        /// <summary>
        /// 設定ファイルからの読み込み、GlobalConfigオブジェクトを生成する。
        /// </summary>
        public static GlobalConfig CreateInstance()
        {
            GlobalConfig config;
            var          xmlSerializer = new XmlSerializer(typeof(GlobalConfig));
            var          xmlSettings   = new System.Xml.XmlReaderSettings()
            {
                CheckCharacters = false,
            };

            try
            {
                using (var streamReader = new StreamReader(xmlFile, Encoding.UTF8))
                    using (var xmlReader
                               = System.Xml.XmlReader.Create(streamReader, xmlSettings))
                    {
                        config = (GlobalConfig)xmlSerializer.Deserialize(xmlReader);
                    }
            } catch
            {
                // 読み込めなかったので新規に作成する。
                config = new GlobalConfig();
            }

            config.Init();

            return(config);
        }
示例#9
0
文件: Form1.cs 项目: kleinsimon/TCMM
        public void cloneWS()
        {
            Makro newws;

            using (MemoryStream stream = new MemoryStream())
            {
                System.Xml.XmlWriterSettings ws = new System.Xml.XmlWriterSettings();
                ws.NewLineHandling = System.Xml.NewLineHandling.Entitize;

                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Makro));
                using (System.Xml.XmlWriter wr = System.Xml.XmlWriter.Create(stream, ws))
                {
                    x.Serialize(wr, CurrentMakro);
                }
                stream.Position = 0;

                System.Xml.XmlReaderSettings rs = new System.Xml.XmlReaderSettings();

                using (System.Xml.XmlReader rd = System.Xml.XmlReader.Create(stream, rs))
                {
                    newws = (Makro)x.Deserialize(rd, "");
                }
                //newws = (Makro)x.Deserialize(stream);
            }

            newws.Name += "_Copy";

            Makros.Add(newws);
            listBoxMakros.SelectedItem = newws;
        }
        /// <summary>
        /// Récupère tous les genres dans le fichier genres.xml
        /// </summary>
        /// <returns>La liste de tous les genres</returns>
        private IEnumerable <Genre> recupereGenres()
        {
            listeGenres.Clear();

            using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorage.FileExists(XMLTags.FICHIER_GENRES))
                {
                    using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorage.OpenFile(XMLTags.FICHIER_GENRES, System.IO.FileMode.Open))
                    {
                        System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
                        settings.IgnoreWhitespace             = true;
                        settings.IgnoreComments               = true;
                        settings.IgnoreProcessingInstructions = true;

                        using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
                        {
                            recupereDonneesGenresDansChambreIsolation(reader);
                        }
                    }
                }
                else
                {
                    sauvegarderData(isolatedStorage);
                }
            }

            return(listeGenres);
        }
        /// <summary>
        /// Récupère tous les films du fichier filmothèque.xml
        /// </summary>
        /// <returns>La liste des films</returns>
        private IEnumerable <Film> recupereFilms()
        {
            listeFilms.Clear();

            using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorage.FileExists(XMLTags.FICHIER_FILMOTHEQUE))
                {
                    using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorage.OpenFile(XMLTags.FICHIER_FILMOTHEQUE, System.IO.FileMode.Open))
                    {
                        System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
                        settings.IgnoreWhitespace             = true;
                        settings.IgnoreComments               = true;
                        settings.IgnoreProcessingInstructions = true;


                        using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
                        {
                            recupereDonneesFilmsDansChambreIsolation(reader);
                        }
                    }
                }
                else
                {
                    sauvegarderData(isolatedStorage);
                }
            }

            changeActeurFilmsAvecVraiActeur();
            changeRealisateurFilmsAvecVraiRealisateur();

            return(listeFilms);
        }
示例#12
0
        public static System.Xml.XmlDocument LoadFromFile(string fileName, ref string sError)
        {
            System.Xml.XmlDocument       returnValue = default(System.Xml.XmlDocument);
            System.Xml.XmlReaderSettings xmlSet      = new System.Xml.XmlReaderSettings();
            xmlSet.CheckCharacters = false;
            xmlSet.DtdProcessing   = System.Xml.DtdProcessing.Ignore;
            //xmlSet.ProhibitDtd = False
            xmlSet.ValidationType = System.Xml.ValidationType.None;
            xmlSet.XmlResolver    = null;

            System.Xml.XmlReader   xmlr   = System.Xml.XmlTextReader.Create(fileName, xmlSet);
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

            sError = "";
            try
            {
                xmlDoc.Load(xmlr);
                xmlr.Close();
                returnValue = xmlDoc;
            }
            catch (Exception ex)
            {
                sError      = ex.Message;
                returnValue = null;
            }
            return(returnValue);
        }
示例#13
0
 private static System.Xml.XmlReader GetXR(StringReader SR)
 {
     System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings()
     {
         XmlResolver = null
     };
     return(System.Xml.XmlReader.Create(SR, settings));
 }
示例#14
0
 /// <summary>
 /// Load (cannot use serializer at this level!)
 /// </summary>
 /// <param name="filename"></param>
 public override void Load(string filename = "bla.xml")
 {
     System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
     settings.IgnoreWhitespace = true;
     System.Xml.XmlReader reader = System.Xml.XmlReader.Create(filename, settings);
     ReadXml(reader);
     reader.Close();
 }
示例#15
0
        static Configuration()
        {
            ParseConfigFiles ();

            mt_root = GetVariable ("MONOTOUCH_PREFIX", "/Library/Frameworks/Xamarin.iOS.framework/Versions/Current");
            ios_destdir = GetVariable ("IOS_DESTDIR", null);
            sdk_version = GetVariable ("IOS_SDK_VERSION", "8.0");
            watchos_sdk_version = GetVariable ("WATCH_SDK_VERSION", "2.0");
            tvos_sdk_version = GetVariable ("TVOS_SDK_VERSION", "9.0");
            xcode_root = GetVariable ("XCODE_DEVELOPER_ROOT", "/Applications/Xcode.app/Contents/Developer");
            xcode5_root = GetVariable ("XCODE5_DEVELOPER_ROOT", "/Applications/Xcode511.app/Contents/Developer");
            xcode6_root = GetVariable ("XCODE6_DEVELOPER_ROOT", "/Applications/Xcode601.app/Contents/Developer");
            xcode72_root = GetVariable ("XCODE72_DEVELOPER_ROOT", "/Applications/Xcode72.app/Contents/Developer");
            include_ios = !string.IsNullOrEmpty (GetVariable ("INCLUDE_IOS", ""));
            include_mac = !string.IsNullOrEmpty (GetVariable ("INCLUDE_MAC", ""));
            include_tvos = !string.IsNullOrEmpty (GetVariable ("INCLUDE_TVOS", ""));
            include_watchos = !string.IsNullOrEmpty (GetVariable ("INCLUDE_WATCH", ""));

            var version_plist = Path.Combine (xcode_root, "..", "version.plist");
            if (File.Exists (version_plist)) {
                var settings = new System.Xml.XmlReaderSettings ();
                settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
                var doc = new System.Xml.XmlDocument ();
                using (var fs = new FileStream (version_plist, FileMode.Open, FileAccess.Read)) {
                    using (var reader = System.Xml.XmlReader.Create (fs, settings)) {
                        doc.Load (reader);
                        XcodeVersion = doc.DocumentElement.SelectSingleNode ("//dict/key[text()='CFBundleShortVersionString']/following-sibling::string[1]/text()").Value;
                    }
                }
            }
            #if MONOMAC
            mac_xcode_root = xcode_root;
            #endif

            if (!Directory.Exists (mt_root) && !File.Exists (mt_root) && string.IsNullOrEmpty (ios_destdir))
                mt_root = "/Developer/MonoTouch";

            if (Directory.Exists (Path.Combine (mt_root, "usr")))
                mt_root = Path.Combine (mt_root, "usr");

            if (!string.IsNullOrEmpty (ios_destdir))
                mt_root = Path.Combine (ios_destdir, mt_root.Substring (1));

            Console.WriteLine ("Test configuration:");
            Console.WriteLine ("  MONOTOUCH_PREFIX={0}", mt_root);
            Console.WriteLine ("  IOS_DESTDIR={0}", ios_destdir);
            Console.WriteLine ("  SDK_VERSION={0}", sdk_version);
            Console.WriteLine ("  XCODE_ROOT={0}", xcode_root);
            Console.WriteLine ("  XCODE5_ROOT={0}", xcode5_root);
            Console.WriteLine ("  XCODE6_ROOT={0} Exists={1}", xcode6_root, Directory.Exists (xcode6_root));
            #if MONOMAC
            Console.WriteLine ("  MAC_XCODE_ROOT={0}", mac_xcode_root);
            #endif
            Console.WriteLine ("  INCLUDE_IOS={0}", include_ios);
            Console.WriteLine ("  INCLUDE_MAC={0}", include_mac);
            Console.WriteLine ("  INCLUDE_TVOS={0}", include_tvos);
            Console.WriteLine ("  INCLUDE_WATCHOS={0}", include_watchos);
        }
        public async Task <byte[]> GetReport(string Type, string basepath, CustomClearanceBIZSearchDTO arg)
        {
            var helper     = new ReportHelper();
            var datasource = new Telerik.Reporting.ObjectDataSource();

            arg.gmsDashboardSearchFilter.pageNo = 0;
            datasource.DataSource = helper.GetGMSReleaseReportData(arg);
            Telerik.Reporting.Report instanceReport;
            var settings = new System.Xml.XmlReaderSettings();

            settings.IgnoreWhitespace = true;
            var path = basepath + "/Report/GMSStatusReport.trdx";

            using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(path, settings))
            {
                var xmlSerializer = new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();
                instanceReport = (Telerik.Reporting.Report)xmlSerializer.Deserialize(xmlReader);
            }
            Telerik.Reporting.Table tbl = instanceReport.Items.Find("table1", true)[0] as Telerik.Reporting.Table;
            tbl.DataSource = datasource;
            DateTime frmdate;

            if (DateTime.TryParseExact(arg.gmsDashboardSearchFilter.fromDT,
                                       "yyyy-MM-dd HH:mm:ss",
                                       System.Globalization.CultureInfo.InvariantCulture,
                                       System.Globalization.DateTimeStyles.None,
                                       out frmdate))
            {
                instanceReport.ReportParameters["FromDate"].Value = frmdate.ToString("dd/MM/yyyy");
            }
            else
            {
                instanceReport.ReportParameters["FromDate"].Value = string.Empty;
            }

            DateTime todate;

            if (DateTime.TryParseExact(arg.gmsDashboardSearchFilter.toDT,
                                       "yyyy-MM-dd HH:mm:ss",
                                       System.Globalization.CultureInfo.InvariantCulture,
                                       System.Globalization.DateTimeStyles.None,
                                       out todate))
            {
                instanceReport.ReportParameters["ToDate"].Value = todate.ToString("dd/MM/yyyy");
            }
            else
            {
                instanceReport.ReportParameters["ToDate"].Value = string.Empty;
            }

            //instanceReport.ReportParameters.Add("ToDate", parameters[1]);
            Telerik.Reporting.Processing.ReportProcessor reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
            Telerik.Reporting.Processing.RenderingResult result          = reportProcessor.RenderReport(Type, new InstanceReportSource {
                ReportDocument = instanceReport
            }, null);
            byte[] contents = result.DocumentBytes;
            return(contents);
        }
示例#17
0
        public XmlReader(Stream source, SharpNodeCollection nodes, Encoding encoding)
        {
            _source = source;
            _nodes  = nodes;

            var streamReader = new StreamReader(source, encoding);
            var settings     = new System.Xml.XmlReaderSettings();

            _reader = System.Xml.XmlReader.Create(streamReader, settings);
        }
示例#18
0
        private static System.Xml.XmlReader GetXR1(Stream XML)
        {
            System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings()
            {
                XmlResolver = null
            };
            return(System.Xml.XmlReader.Create(XML, settings));

            //return new System.Xml.XmlTextReader(XML);
        }
示例#19
0
        private System.Xml.XmlReaderSettings GetSettings()
        {
            if (m_xmlReaderSettings == null)
            {
                // Setting up validation settings
                var settings = new System.Xml.XmlReaderSettings
                {
                    CloseInput     = false,
                    ValidationType = System.Xml.ValidationType.Schema,
                    XmlResolver    = new System.Xml.XmlUrlResolver()
                    {
                        CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable)
                    }
                };
                settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
                settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ProcessIdentityConstraints;

                // Including only the required schemata to speed up validation.
                // The TSML schema refers to multiple other schemata. Adding them explicitly is redundant and causes an error.
                if (m_schemata.HasFlag(SchemaType.Custom1_GmlOmSweTsml))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderOpenGis + @"\cocopcustom\cocopcustom_1.1.xsd");
                }
                if (m_schemata.HasFlag(SchemaType.Custom2))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderOpenGis + @"\cocopcustom\cocopcustom_1.2.xsd");
                }
                if (m_schemata.HasFlag(SchemaType.Om_Gml))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderOpenGis + @"\om\2.0.0\observation.xsd");
                }
                if (m_schemata.HasFlag(SchemaType.Sos_GmlOmSwe))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderOpenGis + @"\sos\2.0.1\sos.xsd");
                }
                if (m_schemata.HasFlag(SchemaType.Sps_GmlSwe))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderOpenGis + @"\sps\2.0.0\sps.xsd");
                }
                if (m_schemata.HasFlag(SchemaType.Swe))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderOpenGis + @"\swe\swe.xsd");
                }
                if (m_schemata.HasFlag(SchemaType.Tsml_GmlOmSwe))
                {
                    settings.Schemas.Add(null, TestHelper.SchemaFolderOpenGis + @"\tsml\1.0.0\timeseriesML.xsd");
                }

                m_xmlReaderSettings = settings;
            }

            return(m_xmlReaderSettings);
        }
        public static AlarmSetting LoadSettingXml(string settingxml)
        {
            System.Xml.Serialization.XmlSerializer serializer =
                new System.Xml.Serialization.XmlSerializer(typeof(AlarmSetting));
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.GetEncoding("utf-8").GetBytes(settingxml));
            System.Xml.XmlReaderSettings xmlreadersettings = new System.Xml.XmlReaderSettings();
            xmlreadersettings.IgnoreWhitespace = true;
            System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(ms, xmlreadersettings);

            return (AlarmSetting)serializer.Deserialize(xmlReader);
        }
示例#21
0
        /// <summary>
        /// Creates the report.
        /// </summary>
        public string CreateReportXAML(string serverUrl, ReportConfig config)
        {
            if (config.StaticXAMLReport != null)
                return config.StaticXAMLReport;

            // load the xslt template
            System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
            try {
                LoadTemplate(xslt, serverUrl, config.ReportGroup, config.ReportTemplate);
            }
            catch (System.Exception) {
                throw new ScrumFactory.Exceptions.ScrumFactoryException("Error_reading_report_template");
            }

            // creates a buffer stream to write the report context in XML
            System.IO.BufferedStream xmlBuffer = new System.IO.BufferedStream(new System.IO.MemoryStream());
            System.Xml.XmlWriterSettings writerSettings = new System.Xml.XmlWriterSettings();
            writerSettings.CheckCharacters = false;
            writerSettings.OmitXmlDeclaration = true;

            System.Xml.XmlWriter reportDataStream = System.Xml.XmlWriter.Create(xmlBuffer, writerSettings);

            // write XML start tag
            reportDataStream.WriteStartDocument();
            reportDataStream.WriteStartElement("ReportData");

            // create report context in XML
            CreateDefaultXMLContext(reportDataStream, writerSettings, serverUrl, config);

            // finish XML document
            reportDataStream.WriteEndDocument();
            reportDataStream.Flush();

            xmlBuffer.Seek(0, System.IO.SeekOrigin.Begin);
            // debug
            //System.IO.StreamReader s = new System.IO.StreamReader(xmlBuffer);
            //string ss = s.ReadToEnd();

            System.Xml.XmlReaderSettings readerSettings = new System.Xml.XmlReaderSettings();
            readerSettings.CheckCharacters = false;
            System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(xmlBuffer, readerSettings);

            // creates a buffer stream to write the XAML flow document
            System.IO.StringWriter xamlBuffer = new System.IO.StringWriter();

            System.Xml.XmlWriter xamlWriter = System.Xml.XmlWriter.Create(xamlBuffer, writerSettings);

            // creates the flow document XMAL
            xslt.Transform(xmlReader, xamlWriter);

            // sets the flow document at the view
            return xamlBuffer.ToString();
        }
示例#22
0
        Report DeserializeReport(UriReportSource uriReportSource)
        {
            var settings = new System.Xml.XmlReaderSettings();

            settings.IgnoreWhitespace = true;
            using (var xmlReader = System.Xml.XmlReader.Create(uriReportSource.Uri, settings))
            {
                var xmlSerializer = new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();
                var report        = (Telerik.Reporting.Report)xmlSerializer.Deserialize(xmlReader);
                return(report);
            }
        }
示例#23
0
        public static T Deserialize <T>(TextReader sr)
        {
            System.Xml.XmlReaderSettings xmlReaderSettings = new System.Xml.XmlReaderSettings();
            xmlReaderSettings.IgnoreWhitespace = true;

            System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(sr, xmlReaderSettings);

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), getAVMClasses());

            var imported = (T)serializer.Deserialize(xmlReader);

            return(imported);
        }
示例#24
0
        /// <summary>
        /// 定義ファイルを読み込みます
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static FixedTextDefines Load(string path)
        {
            var xmlSerializer = new XmlSerializer(typeof(FixedTextDefines));
            FixedTextDefines result;
            var xmlSettings = new System.Xml.XmlReaderSettings();

            using (var streamReader = new StreamReader(path, Encoding.UTF8))
                using (var xmlReader = System.Xml.XmlReader.Create(streamReader, xmlSettings))
                {
                    result = (FixedTextDefines)xmlSerializer.Deserialize(xmlReader);
                }
            return(result);
        }
示例#25
0
        /// <summary>
        /// 读取XML数据
        /// </summary>
        /// <param name="xmlFile">虚拟路径</param>
        /// <param name="rootName">节点路径(例:/root/resourceclassify)</param>
        /// <param name="keyFiledName">主属性名称</param>
        /// <param name="arrFiledName">子节点名称数组</param>
        /// <returns></returns>
        public static DataTable GetXMLData(string xmlFile, string rootName, string keyFiledName, string[] arrFiledName)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(keyFiledName, typeof(string));
            foreach (string filed in arrFiledName)
            {
                dt.Columns.Add(filed, typeof(string));
            }

            System.Xml.XmlDocument       xmlDoc   = new System.Xml.XmlDocument();
            System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
            settings.IgnoreComments = true;//忽略文档里面的注释

            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlFile, settings);
            xmlDoc.Load(reader);                                       //加载Xml文件

            System.Xml.XmlNode xn = xmlDoc.SelectSingleNode(rootName); //获取根节点

            System.Xml.XmlNodeList xnl = xn.ChildNodes;                //得到根节点的所有子节点
            DataRow dr;

            foreach (System.Xml.XmlNode xn1 in xnl)
            {
                // 将节点转换为元素,便于得到节点的属性值
                System.Xml.XmlElement xe = (System.Xml.XmlElement)xn1;


                dr = dt.NewRow();

                //得到keyFiledName属性的属性值
                dr[keyFiledName] = xe.GetAttribute(keyFiledName).ToString();

                //得到Book节点的所有子节点
                System.Xml.XmlNodeList xnl0 = xe.ChildNodes;
                foreach (System.Xml.XmlNode xn2 in xnl0)
                {
                    foreach (string filed in arrFiledName)
                    {
                        if (xn2.Name == filed)
                        {
                            dr[filed] = xn2.InnerXml;
                            break;
                        }
                    }
                }
                dt.Rows.Add(dr);
            }
            reader.Close();
            return(dt);
        }
示例#26
0
        public static T Deserialize <T>(string filePath)
        {
            var xmlSerializer = CachingXmlSerializerFactory.Create(typeof(T));
            var xmlSettings   = new System.Xml.XmlReaderSettings()
            {
                CheckCharacters = false,
            };

            using (var streamReader = new StreamReader(filePath, new UTF8Encoding(false)))
                using (var xmlReader = System.Xml.XmlReader.Create(streamReader, xmlSettings))
                {
                    return((T)xmlSerializer.Deserialize(xmlReader));
                }
        }
示例#27
0
        Report DeserializeReport(XmlReportSource xmlReportSource)
        {
            var settings = new System.Xml.XmlReaderSettings();

            settings.IgnoreWhitespace = true;
            var textReader = new System.IO.StringReader(xmlReportSource.Xml);

            using (var xmlReader = System.Xml.XmlReader.Create(textReader, settings))
            {
                var xmlSerializer = new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();
                var report        = (Telerik.Reporting.Report)xmlSerializer.Deserialize(xmlReader);
                return(report);
            }
        }
示例#28
0
        public static string GetPListStringValue(string plist, string key)
        {
            var settings = new System.Xml.XmlReaderSettings();

            settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
            var doc = new System.Xml.XmlDocument();

            using (var fs = new FileStream(plist, FileMode.Open, FileAccess.Read)) {
                using (var reader = System.Xml.XmlReader.Create(fs, settings)) {
                    doc.Load(reader);
                    return(doc.DocumentElement.SelectSingleNode($"//dict/key[text()='{key}']/following-sibling::string[1]/text()").Value);
                }
            }
        }
示例#29
0
        private async static Task <SyndicationFeed> FetchRSSDataUTF8(string url, params KeyValuePair <string, string>[] headers)
        {
            var content = await MopsBot.Module.Information.GetURLAsync(url, headers);

            var stream   = new MemoryStream(Encoding.UTF8.GetBytes(content?.Replace("utf8", "utf-8") ?? ""));
            var settings = new System.Xml.XmlReaderSettings();

            settings.DtdProcessing = System.Xml.DtdProcessing.Parse;
            using (var reader = System.Xml.XmlReader.Create(stream, settings))
            {
                SyndicationFeed feed = SyndicationFeed.Load(reader);
                return(feed);
            }
        }
示例#30
0
        public override Message ReadMessage(ArraySegment <byte> buffer, BufferManager bufferManager, string contentType)
        {
            if (bufferManager == null)
            {
                throw new ArgumentNullException("bufferManager");
            }
            var settings = new System.Xml.XmlReaderSettings();

            settings.CheckCharacters = false;
            var ret = Message.CreateMessage(System.Xml.XmlDictionaryReader.CreateDictionaryReader(System.Xml.XmlReader.Create(new System.IO.StreamReader(new System.IO.MemoryStream(buffer.Array, buffer.Offset, buffer.Count), encoding), settings)), int.MaxValue, version);

            FillActionContentType(ret, contentType);
            return(ret);
        }
示例#31
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="settings"></param>
 public XmlTokenizer(System.Xml.XmlReaderSettings settings)
 {
     if (settings == null)
     {
         this.Settings = new System.Xml.XmlReaderSettings
         {
             CheckCharacters  = false,
             ConformanceLevel = System.Xml.ConformanceLevel.Auto
         };
     }
     else
     {
         this.Settings = settings;
     }
 }
示例#32
0
        public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders, string contentType)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            var settings = new System.Xml.XmlReaderSettings();

            settings.CheckCharacters = false;
            var ret = Message.CreateMessage(System.Xml.XmlDictionaryReader.CreateDictionaryReader(System.Xml.XmlReader.Create(new System.IO.StreamReader(stream, encoding), settings)), maxSizeOfHeaders, version);

            ret.Properties.Encoder = this;
            FillActionContentType(ret, contentType);
            return(ret);
        }
示例#33
0
        private static T LoadFromXMLFile(string path)
        {
            object result;
            var    instance    = GetInstance(typeof(T));
            var    xmlSettings = new System.Xml.XmlReaderSettings()
            {
                CheckCharacters = false
            };

            using (var streamReader = new StreamReader(path, new System.Text.UTF8Encoding(false)))
            {
                result = instance.Deserialize(streamReader);
            }

            return((T)result);
        }
示例#34
0
 private static void ReadTheXml()
 {
     System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
     oSettings.IgnoreComments = true;
     oSettings.IgnoreWhitespace = true;
     System.Xml.XmlReader oXmlReader = System.Xml.XmlReader.Create(sPathToXml, oSettings);
     while (oXmlReader.Read())
     {
         if (oXmlReader.Name == "preference" && oXmlReader.NodeType == System.Xml.XmlNodeType.Element)
         {
             string sName = oXmlReader.GetAttribute("name");
             string sText = oXmlReader.ReadString();
             oHashtable[sName] = sText.Trim();
         }
     }
 }
示例#35
0
        Validate()
        {
            var settings = new System.Xml.XmlReaderSettings();
            settings.ValidationType = System.Xml.ValidationType.Schema;
            settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ProcessIdentityConstraints;
            settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
            settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationCallBack);
            settings.XmlResolver = new XmlResolver();

            // Create the XmlReader object.
            using (var reader = System.Xml.XmlReader.Create(this.XMLFilename, settings))
            {
                // Parse the file.
                while (reader.Read()) ;
            }
        }
示例#36
0
        internal static void LoadLocations()
        {
            LocationsList = new List <JewishCalendar.Location>();
            using (var ms = new System.IO.StringReader(Properties.Resources.LocationsList))
            {
                var settings = new System.Xml.XmlReaderSettings()
                {
                    IgnoreWhitespace = true
                };
                using (var xr = System.Xml.XmlReader.Create(ms, settings))
                {
                    while (xr.ReadToFollowing("L"))
                    {
                        string name = xr.GetAttribute("N").Trim();
                        int    timeZone;
                        int    elevation = 0;
                        double latitude;
                        double longitute;
                        string timeZoneName = null;

                        xr.ReadToDescendant("T");
                        timeZone = xr.ReadElementContentAsInt("T", "");
                        if (xr.Name == "E")
                        {
                            elevation = xr.ReadElementContentAsInt("E", "");
                        }

                        latitude  = xr.ReadElementContentAsDouble("LT", "");
                        longitute = xr.ReadElementContentAsDouble("LN", "");

                        if (xr.Name == "TZN")
                        {
                            timeZoneName = xr.ReadElementContentAsString("TZN", "");
                        }
                        LocationsList.Add(new JewishCalendar.Location(name, timeZone, latitude, longitute)
                        {
                            Elevation    = elevation,
                            TimeZoneName = timeZoneName
                        });
                        LocationsList.Sort((a, b) => String.Compare(a.Name, b.Name));
                    }
                    xr.Close();
                }
                ms.Close();
            }
        }
示例#37
0
        /// <summary>
        /// 指定されたXML定義をデシリアライズ
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="xmlFile"></param>
        public static T Deserialize <T>(string xmlFile) where T : new()
        {
            var xmlSerializer2 = new XmlSerializer(typeof(T));
            T   result;
            var xmlSettings = new System.Xml.XmlReaderSettings()
            {
                CheckCharacters = false,
            };

            using (var streamReader = new StreamReader(xmlFile, Encoding.UTF8))
                using (var xmlReader
                           = System.Xml.XmlReader.Create(streamReader, xmlSettings))
                {
                    result = (T)xmlSerializer2.Deserialize(xmlReader);
                }

            return(result);
        }
示例#38
0
 public void LoadFromXml(string  xml)
 {
     System.Xml.XmlReaderSettings s = new System.Xml.XmlReaderSettings();
     s.IgnoreWhitespace = true;
     using (System.IO.StringReader sr = new System.IO.StringReader(xml))
     {
         using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr, s))
         {
             while (reader.Read())
             {
                 if (reader.Name.Equals("headeritem") && reader.IsStartElement())
                 {
                     string key = reader.GetAttribute("key");
                     string value = reader.ReadString();
                     _Header.Add(key, value);
                 }
             }
         }
     }
 }
		public override System.Net.CookieContainer GetAllCookies()
		{
			if (base.CookiePath == null || !System.IO.File.Exists(base.CookiePath)) {
				throw new CookieGetterException("Safariのクッキーパスが正しく設定されていません。");
			}

			System.Net.CookieContainer container = new System.Net.CookieContainer();

			try {
				System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();

				// DTDを取得するためにウェブアクセスするのを抑制する
				// (通信遅延や、アクセスエラーを排除するため)
				settings.XmlResolver = null;
				settings.ProhibitDtd = false;
				settings.CheckCharacters = false;

				using (System.Xml.XmlReader xtr = System.Xml.XmlTextReader.Create(base.CookiePath, settings)) {
					while (xtr.Read()) {
						switch (xtr.NodeType) {
							case System.Xml.XmlNodeType.Element:
								if (xtr.Name.ToLower().Equals("dict")) {
									System.Net.Cookie cookie = getCookie(xtr);
									try {
										Utility.AddCookieToContainer(container, cookie);
									} catch (Exception ex){
										CookieGetter.Exceptions.Enqueue(ex);
										Console.WriteLine(string.Format("Invalid Format! domain:{0},key:{1},value:{2}", cookie.Domain, cookie.Name, cookie.Value));
									}
								}
								break;
						}
					}
				}

			} catch (Exception ex) {
				throw new CookieGetterException("Safariのクッキー取得中にエラーが発生しました。", ex);
			}

			return container;
		}
示例#40
0
        /// <summary>
        /// The get report from file.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <returns>
        /// The <see cref="Report"/>.
        /// </returns>
        public static Report GetReportFromFile(string path)
        {
            Report report;
            var settings = new System.Xml.XmlReaderSettings {IgnoreWhitespace = true};
            try
            {
                using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(path, settings))
                {
                    var xmlSerializer =
                        new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();

                    report = (Report)
                        xmlSerializer.Deserialize(xmlReader);
                }
            }
            catch (Exception e)
            {

                throw;
            }
            return report;
        }
示例#41
0
 public static StockFilteredStrategyBase CreateFilteredStrategy(string name)
 {
     StockFilteredStrategyBase strategy = null;
      if (filteredStrategyList == null)
      {
     GetFilteredStrategyList(false);
      }
      if (filteredStrategyList.Contains(name))
      {
     // Deserialize strategy file
     string fileName = Settings.Default.RootFolder + @"\FilteredStrategies\" + name.Replace("@", "") + ".xml";
     using (FileStream fs = new FileStream(fileName, FileMode.Open))
     {
        System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
        settings.IgnoreWhitespace = true;
        System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(fs, settings);
        XmlSerializer serializer = new XmlSerializer(typeof(StockFilteredStrategyBase));
        strategy = (StockFilteredStrategyBase)serializer.Deserialize(xmlReader);
     }
      }
      return strategy;
 }
        private void OnParseWork(Object state)
        {
            try
            {
                AdDescriptor adDescriptor = null;

                System.IO.Stream stream = state as System.IO.Stream;

                System.Xml.XmlReaderSettings readerSettings = new System.Xml.XmlReaderSettings();
                readerSettings.IgnoreWhitespace = true;
                readerSettings.IgnoreComments = true;
                readerSettings.IgnoreProcessingInstructions = true;

                System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stream, readerSettings);

                Dictionary<string, string> adInfo = new Dictionary<string, string>();
                while (reader.Read())
                {
                    if (reader.IsStartElement())
                    {
                        if (reader.Name == "error")
                        {
                            string errorCode = reader.GetAttribute("code");
                            string errorMessage = string.Empty;

                            // read past the name
                            reader.Read();

                            // read the contents
                            switch (reader.NodeType)
                            {
                                case System.Xml.XmlNodeType.CDATA:
                                case System.Xml.XmlNodeType.Text:
                                    errorMessage = reader.ReadContentAsString();
                                    break;
                            }

                            if (this.errorCallback != null)
                            {
                                this.errorCallback(this, errorCode, errorMessage);

                                Cancel();
                            }

                            // no need to parse anything else
                            break;
                        }
                        else if (reader.Name == "ad")
                        {
                            string adType = reader.GetAttribute("type");

                            adInfo["type"] = adType;

                            // read each child node (passing ad node first)
                            while (reader.Read())
                            {
                                if (reader.IsStartElement() == false)
                                {
                                    if ((reader.NodeType == System.Xml.XmlNodeType.EndElement) && (reader.Name == "ad"))
                                    {
                                        // done with the descriptor
                                        break;
                                    }

                                    // advance to start of next descriptor property
                                    continue;
                                }

                                string name = reader.Name;

                                // read past the name
                                reader.Read();

                                // read the content which may be text or cdata from the ad server
                                string value = null;
                                switch (reader.NodeType)
                                {
                                    case System.Xml.XmlNodeType.CDATA:
                                    case System.Xml.XmlNodeType.Text:
                                        value = reader.ReadContentAsString();
                                        break;
                                }

                                if ((string.IsNullOrEmpty(name) == false) && (string.IsNullOrEmpty(value) == false))
                                {
                                    adInfo[name] = value;
                                }
                            }

                            adDescriptor = new AdDescriptor(adInfo);

                            // no need to parse anything else
                            break;
                        }
                    }
                }

                if (this.completedCallback != null)
                {
                    this.completedCallback(this, adDescriptor);
                }
            }
            catch (Exception ex)
            {
                if (this.failedCallback != null)
                {
                    this.failedCallback(this, ex);
                }
            }

            Cancel();
        }
示例#43
0
        public static eagle Deserialize(string xml) {
            System.IO.StringReader stringReader = null;
            try {
                stringReader = new System.IO.StringReader(xml);

                // add a settings to allow DTD
                System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
                settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
                // map empty namespace to eagle for DTD based XML
                var nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
                // Add your namespaces used in the XML
                nsmgr.AddNamespace(String.Empty, "eagle");
                // Create the XmlParserContext using the previous declared XmlNamespaceManager
                var ctx = new System.Xml.XmlParserContext(null, nsmgr, null, System.Xml.XmlSpace.None);

                return ((eagle)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader, settings, ctx))));
            }
            finally {
                if ((stringReader != null)) {
                    stringReader.Dispose();
                }
            }
        }
示例#44
0
		internal void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
            try
            {
			if (!CheckForError(e))
			{
				// Process capabilities file
#if WINDOWS_PHONE
				System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings(); 
				settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
				XDocument xDoc = null;
				using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(
					new System.IO.StringReader(e.Result), settings))
					xDoc = XDocument.Load(reader);
#else
				XDocument xDoc = XDocument.Parse(e.Result);
#endif
				ParseCapabilities(xDoc);
			}
            }
            catch (Exception failure)
            {
                failure.Data["GetCapabilities"] = e.Result; //todo: add OGC exception info returned from WMS Service
                InitializationFailure = failure;
            }

			// Call initialize regardless of error
			base.Initialize();
		}
示例#45
0
 private void Load(string fileName)
 {
     if (File.Exists(fileName)) LastRefreshDate = File.GetLastWriteTime(fileName);
      else
      {
     LastRefreshDate = DateTime.MinValue;
     return;
      }
      using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
      {
     System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
     settings.IgnoreWhitespace = true;
     System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(fs, settings);
     XmlSerializer serializer = new XmlSerializer(typeof (List<StockAlert>));
     this.Alerts = new ObservableCollection<StockAlert>((serializer.Deserialize(xmlReader) as List<StockAlert>).OrderByDescending(a => a.Date));
      }
 }
        private object[] GetMappedValues() { // mode 0
            if (null != _xmlMap) {
                for(int i = 0; i < _xmlMap.Length; ++i) {
                    if (0 != _xmlMap[i]) {
                        // get the string/SqlString xml value
                        string xml = _readerDataValues[i] as string;
                        if ((null == xml) && (_readerDataValues[i] is System.Data.SqlTypes.SqlString)) {
                            System.Data.SqlTypes.SqlString x = (System.Data.SqlTypes.SqlString)_readerDataValues[i];
                            if (!x.IsNull) {
                                xml = x.Value;
                            }
                            else {
                                switch(_xmlMap[i]) {
                                case SqlXml:
                                    // map strongly typed SqlString.Null to SqlXml.Null
                                    _readerDataValues[i] = System.Data.SqlTypes.SqlXml.Null;
                                    break;
                                default:
                                    _readerDataValues[i] = DBNull.Value;
                                    break;
                                }
                            }
                        }
                        if (null != xml) {
                            switch(_xmlMap[i]) {
                            case SqlXml: // turn string into a SqlXml value for DataColumn
                                System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
                                settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
                                System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(xml), settings, (string)null);
                                _readerDataValues[i] = new System.Data.SqlTypes.SqlXml(reader);
                                break;
                            case XmlDocument: // turn string into XmlDocument value for DataColumn
                                System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                                document.LoadXml(xml);
                                _readerDataValues[i] = document;
                                break;
                            }
                            // default: let value fallthrough to DataSet which may fail with ArgumentException
                        }
                    }
                }
            }

            switch(_mappedMode) {
            default:
            case MapExactMatch:
                Debug.Assert(0 == _mappedMode, "incorrect mappedMode");
                Debug.Assert((null == _chapterMap) && (null == _indexMap) && (null == _mappedDataValues), "incorrect MappedValues");
                return _readerDataValues;  // from reader to dataset
            case MapDifferentSize:
                Debug.Assert((null == _chapterMap) && (null == _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
                MappedValues();
                break;
            case MapReorderedValues:
                Debug.Assert((null == _chapterMap) && (null != _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
                MappedIndex();
                break;
            case MapChapters:
                Debug.Assert((null != _chapterMap) && (null == _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
                MappedChapter();
                break;
            case MapChaptersReordered:
                Debug.Assert((null != _chapterMap) && (null != _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
                MappedChapterIndex();
                break;
            }
            return _mappedDataValues;
        }
示例#47
0
 private static void ReadTheXml()
 {
     System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
     oSettings.IgnoreComments = true;
     oSettings.IgnoreWhitespace = true;
     System.Xml.XmlReader oXmlReader = System.Xml.XmlReader.Create(sPathToXml, oSettings);
     Tester oTester = new Tester();
     while (oXmlReader.Read())
     {
         if (oXmlReader.NodeType == System.Xml.XmlNodeType.EndElement)
         {
             if (oXmlReader.Name == "test")
             {
                 oHashtable.Add(oTester.Id, oTester);
                 oTester = new Tester();
             }
         }
         else
         {
             if (oXmlReader.Name == "id")
             {
                 oTester.Id = oXmlReader.ReadString().Trim();
             }
             else if (oXmlReader.Name == "group")
             {
                 oTester.Group = int.Parse(oXmlReader.ReadString().Trim());
             }
             else if (oXmlReader.Name == "gender")
             {
                 oTester.Gender = oXmlReader.ReadString().Trim();
             }
             else if (oXmlReader.Name == "familiar_name")
             {
                 oTester.familiar_name = oXmlReader.ReadString().Trim();
             }
             else if (oXmlReader.Name == "unfamiliar_name")
             {
                 oTester.unfamiliar_name = oXmlReader.ReadString().Trim();
             }
         }
     }
 }
        public void LoadTest()
        {
            try
            {
                FlowLayoutPanel flowLayoutPanel1 = new FlowLayoutPanel();
                flowLayoutPanel1.AutoScroll = true;
                flowLayoutPanel1.Dock = DockStyle.Fill;
                flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
                flowLayoutPanel1.WrapContents = false;
                flowLayoutPanel1.Click += new EventHandler(flowLayoutPanel1_Click);
                flowLayoutPanel1.MouseEnter += new EventHandler(flowLayoutPanel1_MouseEnter);

                tableLayoutPanel1.Controls.Remove(label1);
                tableLayoutPanel1.Controls.Add(flowLayoutPanel1, 0, 0);

                oArrayListTest.Clear();
                // loads all test to oArrayListTest, and displays the first text and title

                System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
                oSettings.IgnoreComments = true;
                oSettings.IgnoreWhitespace = true;
                System.Xml.XmlReader oXmlReader = System.Xml.XmlReader.Create(sXmlPath, oSettings);

                while (oXmlReader.Read()) // advance to first screen
                {
                    if (oXmlReader.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        if (oXmlReader.Name == "maintext")
                        {
                            // add a label and display the text
                            string[] sLines = oXmlReader.ReadString().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            string sText = "";
                            foreach (string line in sLines)
                            {
                                sText += line.Trim() + Environment.NewLine;
                            }
                            if (!String.IsNullOrWhiteSpace(sText))
                            {
                                Label oLabel = new Label();
                                oLabel.Text = sText.Trim();
                                oLabel.AutoSize = true;
                                oLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 50);
                                oLabel.Font = Styling.GetInstructionsFont();
                                flowLayoutPanel1.Controls.Add(oLabel);
                            }
                        }
                        else if (oXmlReader.Name == "question")
                        {
                            Question oQuestion = new Question();
                            oQuestion.sText = oXmlReader.ReadString().Trim();
                            oArrayListTest.Add(oQuestion);
                        }
                    }
                }

                // load all questions, each in its own flow layout
                for (int i = 0; i < oArrayListTest.Count; i++)
                {
                    try
                    {
                        FlowLayoutPanel oPanel = new FlowLayoutPanel();
                        oPanel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 50);
                        oPanel.FlowDirection = FlowDirection.TopDown;
                        oPanel.AutoSize = true;
                        Question nextQuestion = (Question)oArrayListTest[i];

                        Label oLabelQuestion = new Label();
                        oLabelQuestion.Text = (i + 1).ToString() + ") " + nextQuestion.sText;
                        oLabelQuestion.AutoSize = true;

                        oPanel.Controls.Add(oLabelQuestion);

                        TableLayoutPanel oTable = new TableLayoutPanel();
                        oTable.AutoSize = true;
                        oTable.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
                        // row 1 - titles

                        Label oLabel1 = new Label();
                        oLabel1.Text = Texts.GetScreenText(7, 1);
                        oLabel1.AutoSize = true;
                        int iMaxWidth = oLabel1.PreferredWidth;
                        Label oLabel2 = new Label();
                        oLabel2.Text = Texts.GetScreenText(7, 2);
                        oLabel2.AutoSize = true;
                        if (oLabel2.PreferredWidth > iMaxWidth)
                        {
                            iMaxWidth = oLabel2.PreferredWidth;
                        }
                        Label oLabel3 = new Label();
                        oLabel3.Text = Texts.GetScreenText(7, 3);
                        oLabel3.AutoSize = true;
                        if (oLabel3.PreferredWidth > iMaxWidth)
                        {
                            iMaxWidth = oLabel3.PreferredWidth;
                        }
                        oLabel1.Width = iMaxWidth;
                        oLabel1.AutoSize = false;
                        oLabel2.Width = iMaxWidth;
                        oLabel2.AutoSize = false;
                        oLabel3.Width = iMaxWidth;
                        oLabel3.AutoSize = false;

                        oTable.Controls.Add(oLabel1, 0, 0);
                        oTable.Controls.Add(oLabel2, 3, 0);
                        oTable.Controls.Add(oLabel3, 6, 0);

                        // insert empty labels for fixed sizing
                        for (int indexLabels = 1; indexLabels <= 5; indexLabels++)
                        {
                            if (indexLabels != 3)
                            {
                                Label oEmptyLabelForWidth1 = new Label();
                                oEmptyLabelForWidth1.Width = iMaxWidth;
                                oEmptyLabelForWidth1.AutoSize = false;
                                oEmptyLabelForWidth1.Text = "";
                                oTable.Controls.Add(oEmptyLabelForWidth1, indexLabels, 0);
                            }
                        }

                        for (int i1 = 0; i1 < 7; i1++)
                        {
                            RadioButton oRB = new RadioButton();
                            oRB.Name = i.ToString() + "." + (i1 + 1).ToString();
                            oRB.Text = (i1 + 1).ToString();

                            oRB.CheckedChanged += new EventHandler(oRB_CheckedChanged);
                            oRB.AutoSize = true;
                            oTable.Controls.Add(oRB,i1, 1);
                        }
                        oPanel.Controls.Add(oTable);
                        flowLayoutPanel1.Controls.Add(oPanel);
                    }
                    catch
                    {
                        MessageBox.Show("Problem loading question " + (i + 1).ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problem loading test.");
            }
        }
示例#49
0
 private static void ReadTheXml()
 {
     System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
     oSettings.IgnoreComments = true;
     oSettings.IgnoreWhitespace = true;
     System.Xml.XmlReader oXmlReader = System.Xml.XmlReader.Create(sPathToXml, oSettings);
     ArrayList oArrayListTexts = new ArrayList();
     while (oXmlReader.Read()) // advance to first screen
     {
         if (oXmlReader.NodeType == System.Xml.XmlNodeType.EndElement)
         {
             if (oXmlReader.Name == "screen")
             {
                 oArrayList.Add(oArrayListTexts);  //Guy: this array holds the texts for each screen
                 oArrayListTexts = new ArrayList();
             }
         }
         else
         {
             if (oXmlReader.Name == "text")
             {
                 string[] sLines = oXmlReader.ReadString().Split(new string[] {"\n","\r\n"}, StringSplitOptions.RemoveEmptyEntries);
                 string sText = "";
                 foreach (string line in sLines)
                 {
                     sText += line.Trim() + Environment.NewLine;
                 }
                 oArrayListTexts.Add(sText.Trim());
             }
         }
     }
 }
示例#50
0
        public static string TransformXml(System.Xml.XmlDocument Document, string XslPath)
        {
            XslCompiledTransform xTrans = null;

            #region Do the transform

            try
            {
                bool debugmode = false;
            #if DEBUG
                debugmode = true;
            #endif
                xTrans = new XslCompiledTransform(debugmode);
                xTrans.Load(XslPath);
            }
            catch (Exception ex)
            {
                throw new Exception("Could not load XSL Transform", ex);
            }

            string results = "";

            try
            {
                System.IO.StringReader SR = new System.IO.StringReader(Document.OuterXml);
                System.Xml.XmlReaderSettings xReadSettings = new System.Xml.XmlReaderSettings();
                xReadSettings.CloseInput = true;
                xReadSettings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
                xReadSettings.IgnoreComments = true;
                xReadSettings.IgnoreWhitespace = true;
                System.Xml.XmlReader xReader = System.Xml.XmlReader.Create(SR, xReadSettings);

                StringBuilder SB = new StringBuilder();
                System.IO.StringWriter SW = new System.IO.StringWriter(SB);
                System.Xml.XmlWriterSettings xWriteSettings = new System.Xml.XmlWriterSettings();
                xWriteSettings.CloseOutput = true;
                xWriteSettings.Indent = false;
                xWriteSettings.NewLineOnAttributes = false;
                xWriteSettings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;

                System.Xml.XmlWriter xWriter = System.Xml.XmlWriter.Create(SW, xWriteSettings);

                xTrans.Transform(xReader, xWriter);

                results = SB.ToString();

                xWriter.Close();
                xReader.Close();

                SR.Dispose();
                SR = null;
                SW.Dispose();
                SW = null;
            }
            catch (Exception ex)
            {
                throw new Exception("Could not transform Design XML.", ex);
            }

            #endregion

            return results;
        }
示例#51
0
        public void LoadTest(string sXmlPath, int minutes)
        {
            try
            {
                flowLayoutPanel1.Controls.Clear();
                oArrayListTest.Clear();
                // loads all test to oArrayListTest, and displays the first text and title
                System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
                oSettings.IgnoreComments = true;
                oSettings.IgnoreWhitespace = true;
                System.Xml.XmlReader oXmlReader = System.Xml.XmlReader.Create(sXmlPath, oSettings);
                Question oQuestion = new Question();
                while (oXmlReader.Read()) // advance to first screen
                {
                    if (oXmlReader.NodeType == System.Xml.XmlNodeType.EndElement)
                    {
                        if (oXmlReader.Name == "question")
                        {
                            oArrayListTest.Add(oQuestion);
                            oQuestion = new Question();
                        }
                    }
                    else
                    {
                        if (oXmlReader.Name == "maintext")
                        {
                            // add a label and display the text
                            string[] sLines = oXmlReader.ReadString().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            string sText = "";
                            foreach (string line in sLines)
                            {
                                sText += line.Trim() + Environment.NewLine;
                            }
                            if (!String.IsNullOrWhiteSpace(sText))
                            {
                                Label oLabel = new Label();
                                oLabel.Text = sText.Trim();
                                oLabel.AutoSize = true;
                                oLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 50);
                                oLabel.Font = Styling.GetInstructionsFont();
                                flowLayoutPanel1.Controls.Add(oLabel);

                                labelEndTime.Text = Environment.NewLine + TextsGlobal.GetText("endTime") + " " + DateTime.Now.AddMinutes(minutes).ToShortTimeString();
                                labelEndTime.AutoSize = true;
                                labelEndTime.Margin = new System.Windows.Forms.Padding(0, 0, 0, 0);
                                labelEndTime.Font = Styling.GetInstructionsFont();
                            }
                        }
                        else if (oXmlReader.Name == "text")
                        {
                            string[] sLines = oXmlReader.ReadString().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            string sText = "";
                            foreach (string line in sLines)
                            {
                                sText += line.Trim() + Environment.NewLine;
                            }
                            oQuestion.sText = sText.Trim();
                        }
                        else if (oXmlReader.Name == "beforeImageText")
                        {
                            string[] sLines = oXmlReader.ReadString().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            string sText = "";
                            foreach (string line in sLines)
                            {
                                sText += line.Trim() + Environment.NewLine;
                            }
                            oQuestion.sBeforeImageText = sText.Trim();
                        }
                        else if (oXmlReader.Name == "image")
                        {
                            oQuestion.sImage = oXmlReader.ReadString().Trim();
                        }
                        else if (oXmlReader.Name == "answer")
                        {
                            Answer oAnswer = new Answer();
                            try
                            {
                                oAnswer.bIsImage = bool.Parse(oXmlReader.GetAttribute("isImage"));
                            }
                            catch { }

                            oAnswer.sAnswer = oXmlReader.ReadString().Trim();

                            oQuestion.oAnswers.Add(oAnswer);
                        }
                    }
                }

                // load all questions, each in its own flow layout
                for (int i = 0; i < oArrayListTest.Count; i++)
                {
                    try
                    {
                        FlowLayoutPanel oPanel = new FlowLayoutPanel();
                        oPanel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 50);
                        oPanel.FlowDirection = FlowDirection.TopDown;
                        oPanel.AutoSize = true;
                        Question nextQuestion = (Question)oArrayListTest[i];

                        if (!String.IsNullOrWhiteSpace(nextQuestion.sBeforeImageText))
                        {
                            Label oLabelBeforeImageText = new Label();
                            oLabelBeforeImageText.Text = nextQuestion.sBeforeImageText;
                            oLabelBeforeImageText.AutoSize = true;
                            oLabelBeforeImageText.Font = Styling.GetLabelsFont();

                            oPanel.Controls.Add(oLabelBeforeImageText);
                        }

                        if (!String.IsNullOrWhiteSpace(nextQuestion.sImage))
                        {
                            PictureBox oPicture = new PictureBox();
                            oPicture.ImageLocation = sPathToImages + nextQuestion.sImage;
                            oPicture.SizeMode = PictureBoxSizeMode.AutoSize;
                            oPanel.Controls.Add(oPicture);
                        }

                        Label oLabelQuestion = new Label();
                        oLabelQuestion.Text = (i + 1).ToString() + ") " + nextQuestion.sText;
                        oLabelQuestion.AutoSize = true;
                        oLabelQuestion.Font = Styling.GetLabelsFont();

                        oPanel.Controls.Add(oLabelQuestion);

                        for (int i1 = 0; i1 < nextQuestion.oAnswers.Count; i1++)
                        {
                            RadioButton oRB = new RadioButton();
                            oRB.Name = i.ToString() + "." + (i1 + 1).ToString();
                            oRB.Font = Styling.GetLabelsFont();
                            Answer oAnswer = (Answer)nextQuestion.oAnswers[i1];
                            if (oAnswer.bIsImage)
                            {
                                oRB.Image = new Bitmap(sPathToImages + oAnswer.sAnswer);
                            }
                            else
                            {
                                oRB.Text = ((Answer)nextQuestion.oAnswers[i1]).sAnswer;
                            }
                            oRB.CheckedChanged += new EventHandler(oRB_CheckedChanged);
                            oRB.AutoSize = true;
                            oPanel.Controls.Add(oRB);
                        }

                        CheckBox oCheckBoxGuess = new CheckBox();
                        oCheckBoxGuess.Name = "checkboxGuess." + i.ToString();
                        oCheckBoxGuess.Text = TextsGlobal.GetText("Guess");
                        oCheckBoxGuess.AutoSize = true;
                        oCheckBoxGuess.CheckedChanged += new EventHandler(oCheckBoxGuess_CheckedChanged);
                        oPanel.Controls.Add(oCheckBoxGuess);

                        flowLayoutPanel1.Controls.Add(oPanel);
                    }
                    catch
                    {
                        MessageBox.Show("Problem loading question " + (i+1).ToString());
                    }
                }

                // start timer
                timer1.Interval = minutes * 60000;
                timer1.Start();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Problem loading test.");
            }
        }
示例#52
0
 private  TechnicalServices.Entity.XmlSerializableDictionary<string, int> GetDevicePositions()
 {
     string str = this.DevicePositionList;
     if (string.IsNullOrEmpty(str)) return new TechnicalServices.Entity.XmlSerializableDictionary<string,int>();
     System.IO.StringReader stringReader = new System.IO.StringReader(str);
     System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
     settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
     System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader, settings);
     TechnicalServices.Entity.XmlSerializableDictionary<string, int> dict = new TechnicalServices.Entity.XmlSerializableDictionary<string, int>();
     reader.Read();
     dict.ReadXml(reader);
     return dict;
 }
        /// <summary>
        /// Lê o arquivo XML que define o relatório.
        /// </summary>
        /// <param name="p_filename">Nome do arquivo XML.</param>
        private void ReadXml(string p_filename)
        {
            System.Xml.XmlReader v_reader, v_item;
            System.Xml.XmlReaderSettings v_settings;

            v_settings = new System.Xml.XmlReaderSettings();
            v_settings.IgnoreComments = true;
            v_settings.ConformanceLevel = System.Xml.ConformanceLevel.Document;

            try
            {
                v_reader = System.Xml.XmlReader.Create(p_filename, v_settings);

                while (v_reader.Read())
                {
                    if (v_reader.IsStartElement())
                    {
                        switch(v_reader.Name)
                        {
                            case "connection":
                                v_item = v_reader.ReadSubtree();
                                this.ReadConnection(v_item);
                                v_item.Close();
                                break;
                            case "settings":
                                v_item = v_reader.ReadSubtree();
                                this.ReadSettings(v_item);
                                v_item.Close();
                                break;
                            case "command":
                                v_item = v_reader.ReadSubtree();
                                this.ReadCommand(v_item);
                                v_item.Close();
                                break;
                            case "header":
                                v_item = v_reader.ReadSubtree();
                                this.ReadHeader(v_item);
                                v_item.Close();
                                break;
                            case "footer":
                                v_item = v_reader.ReadSubtree();
                                this.ReadFooter(v_item);
                                v_item.Close();
                                break;
                            case "fields":
                                v_item = v_reader.ReadSubtree();
                                this.ReadFields(v_item);
                                v_item.Close();
                                break;
                            case "groups":
                                v_item = v_reader.ReadSubtree();
                                this.ReadGroups(v_item);
                                v_item.Close();
                                break;
                            default:
                                break;
                        }
                    }
                }

                v_reader.Close();
            }
            catch (Spartacus.Reporting.Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// Creates a document from a stream.
        /// </summary>
        /// <returns>The document.</returns>
        /// <param name="sourceStream">Source stream.</param>
        /// <param name="sourceInfo">Source info.</param>
        /// <param name="encoding">Encoding.</param>
        public IZptDocument CreateDocument(Stream sourceStream, ISourceInfo sourceInfo, Encoding encoding)
        {
            if(sourceStream == null)
              {
            throw new ArgumentNullException(nameof(sourceStream));
              }
              if(sourceInfo == null)
              {
            throw new ArgumentNullException(nameof(sourceInfo));
              }
              if(encoding == null)
              {
            throw new ArgumentNullException(nameof(encoding));
              }

              var settings = new System.Xml.XmlReaderSettings() {
            XmlResolver = _resolverFactory.GetResolver(),
            DtdProcessing = System.Xml.DtdProcessing.Parse,
              };

              var doc = new System.Xml.XmlDocument();

              using(var streamReader = new StreamReader(sourceStream, encoding))
              using(var reader = System.Xml.XmlReader.Create(streamReader, settings))
              {
            doc.Load(reader);
              }

              return CreateDocument(doc, sourceInfo);
        }
示例#55
0
    private string GetId(ICSharpCode.AvalonEdit.Document.IDocument doc, ICSharpCode.AvalonEdit.Editing.Caret caret)
    {
      string amlQuery;
      var settings = new System.Xml.XmlReaderSettings();
      System.IO.TextReader reader;

      if (this.Helper == null)
      {
        reader = doc.CreateReader();
      }
      else
      {
        amlQuery = this.Helper.GetCurrentQuery(doc, caret.Offset);
        var loc = doc.GetLocation(doc.IndexOf(amlQuery, 0, doc.TextLength, StringComparison.Ordinal));
        reader = new System.IO.StringReader(amlQuery);
        settings.LineNumberOffset = loc.Line;
      }

      string lastItemId = null;
      string lastId = null;
      var elems = new Stack<string>();

      using (reader)
      using (var xmlReader = System.Xml.XmlReader.Create(reader))
      {
        var lineInfo = (System.Xml.IXmlLineInfo)xmlReader;
        while (xmlReader.Read())
        {
          switch (xmlReader.NodeType)
          {
            case System.Xml.XmlNodeType.Element:
            case System.Xml.XmlNodeType.EndElement:
              if (lineInfo.LineNumber > this.editor.TextArea.Caret.Line
                || (lineInfo.LineNumber == this.editor.TextArea.Caret.Line && (lineInfo.LinePosition - 1) > this.editor.TextArea.Caret.Column))
              {
                return lastId ?? lastItemId;
              }
              break;
          }

          switch (xmlReader.NodeType)
          {
            case System.Xml.XmlNodeType.Element:
              switch (xmlReader.LocalName)
              {
                case "Item":
                  lastItemId = xmlReader.GetAttribute("id");
                  lastId = xmlReader.GetAttribute("id");
                  break;
              }
              if (!xmlReader.IsEmptyElement) elems.Push(xmlReader.LocalName);
              break;
            case System.Xml.XmlNodeType.Text:
              if (xmlReader.Value.IsGuid())
              {
                switch (elems.Peek())
                {
                  case "id":
                    lastItemId = xmlReader.Value;
                    break;
                  default:
                    lastId = xmlReader.Value;
                    break;
                }
              }
              break;
            case System.Xml.XmlNodeType.EndElement:
              lastId = null;
              if (elems.Pop() == "Item")
              {
                lastItemId = null;
              }
              break;
          }
        }
      }

      return null;
    }
示例#56
0
        /// <summary>
        /// Send an xml request on the wire, get the response and parse it into an XML document
        /// </summary>
        /// <param name="oRequestDocument"></param>
        /// <param name="szUrl"></param>
        /// <param name="progressCallBack"></param>
        /// <returns></returns>
        protected System.Xml.XmlReader SendHttpInternal(string szUrl, System.Xml.XmlDocument oRequestDocument, UpdateProgessCallback progressCallBack)
        {
            System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
            oSettings.IgnoreWhitespace = true;
            int iCanKey = 0;
            if (m_bReadFromCan || m_bWriteToCan)
                iCanKey = szUrl.GetHashCode() ^ oRequestDocument.OuterXml.GetHashCode();

            // Get responses from the can if available
            if (m_bReadFromCan)
            {
            #if DEBUG
                System.Diagnostics.Debug.WriteLine("Loading can entry " + iCanKey.ToString("x"));
            #endif
                if (m_oResponseCan.ContainsKey(iCanKey))
                {
                    MemoryStream oBackingStore = new MemoryStream();
                    lock (((System.Collections.ICollection)m_oResponseCan).SyncRoot)
                    {
                        MemoryStream oCannedStore = m_oResponseCan[iCanKey];
                        oCannedStore.WriteTo(oBackingStore);
                        oCannedStore.Position = 0;
                        oBackingStore.Position = 0;
                    }

                    return System.Xml.XmlReader.Create(oBackingStore, oSettings);
                }
                else
                {
                    throw new WebException("Response can does not contain this datum", WebExceptionStatus.ConnectFailure);
                }
            }

            byte[] byte1;

            System.IO.StringWriter hRequest = null;
            System.IO.Stream hRequestStream = null;
            System.Xml.XmlReader oResponseXmlStream = null;

            System.Net.HttpWebRequest cHttpWReq = null;
            System.Net.HttpWebResponse cHttpWResp = null;

            try
            {
                // --- Initialize all the required streams to write out the xml request ---

                hRequest = new System.IO.StringWriter();

                // --- Create a HTTP Request to the Dap Server and HTTP Response Objects---

                cHttpWReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(szUrl);
                cHttpWReq.Pipelined = false;

            #if DAPPLE
                cHttpWReq.Proxy = ProxyHelper.DetermineProxyForUrl(
                                  szUrl,
                                  WorldWind.Net.WebDownload.useWindowsDefaultProxy,
                                  WorldWind.Net.WebDownload.useDynamicProxy,
                                  WorldWind.Net.WebDownload.proxyUrl,
                                  WorldWind.Net.WebDownload.proxyUserName,
                                  WorldWind.Net.WebDownload.proxyPassword);
            #endif

                // --- Encode the document into ascii ---

                System.Text.UTF8Encoding hRequestEncoding = new System.Text.UTF8Encoding();

                oRequestDocument.Save(hRequest);
                byte1 = hRequestEncoding.GetBytes(hRequest.GetStringBuilder().ToString());

                // --- Setup the HTTP Request ---

                cHttpWReq.Method = "POST";
            #if DAPPLE
                if (WorldWind.Net.WebDownload.useProto == WorldWind.Net.WebDownload.HttpProtoVersion.HTTP1_1)
                    cHttpWReq.ProtocolVersion = HttpVersion.Version11;
                else
                    cHttpWReq.ProtocolVersion = HttpVersion.Version10;
            #else
                cHttpWReq.ProtocolVersion = HttpVersion.Version11;
            #endif
                cHttpWReq.KeepAlive = false;
                cHttpWReq.ContentType = "application/x-www-form-urlencoded";
                cHttpWReq.ContentLength = byte1.Length;
                cHttpWReq.Timeout = m_iTimeout;

                // --- Serialize the XML document onto the wire ---

                hRequestStream = cHttpWReq.GetRequestStream();
                hRequestStream.Write(byte1, 0, byte1.Length);
                hRequestStream.Close();

                // --- Turn off connection keep-alives. ---

                cHttpWReq.KeepAlive = false;

                if (progressCallBack == null)
                {
                    // --- Get the response ---

                    cHttpWResp = (System.Net.HttpWebResponse)cHttpWReq.GetResponse();

                    if (m_bWriteToCan)
                    {
            #if DEBUG
                        System.Diagnostics.Debug.WriteLine("Saving can entry " + iCanKey.ToString("x"));
            #endif
                        MemoryStream oCannedData = bufferResponseStream(cHttpWResp.GetResponseStream());
                        MemoryStream oResponseBackingStore = new MemoryStream();
                        oCannedData.WriteTo(oResponseBackingStore);
                        oCannedData.Position = 0;
                        oResponseBackingStore.Position = 0;
                        oResponseXmlStream = System.Xml.XmlReader.Create(oResponseBackingStore, oSettings);

                        m_oResponseCan[iCanKey] = oCannedData;
                    }
                    else
                    {
                        oResponseXmlStream = System.Xml.XmlReader.Create(cHttpWResp.GetResponseStream(), oSettings);
                    }
                }
                else
                {
                    // Create the download thread (class) and populate with filename and callbacks
                    DownloadThread dl = new DownloadThread();
                    dl.ProgressCallback += progressCallBack;
                    dl.webReq = cHttpWReq;
                    // Start the download thread....
                    System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(dl.Download));
                    t.Start();
                    t.Join();

                    if (dl.excepted != null)
                        throw dl.excepted;

                    MemoryStream memStrm = new MemoryStream(dl.downloadedData);

                    if (m_bWriteToCan)
                    {
            #if DEBUG
                        System.Diagnostics.Debug.WriteLine("Saving can entry " + iCanKey.ToString("x"));
            #endif
                        MemoryStream oCannedData = new MemoryStream();
                        memStrm.WriteTo(oCannedData);
                        oCannedData.Position = 0;
                        memStrm.Position = 0;
                        oResponseXmlStream = System.Xml.XmlReader.Create(memStrm, oSettings);

                        lock (((System.Collections.ICollection)m_oResponseCan).SyncRoot)
                        {
            #if DEBUG
                            if (m_oResponseCan.ContainsKey(iCanKey))
                                System.Diagnostics.Debug.WriteLine("Duplicate can key detected");
            #endif
                            m_oResponseCan[iCanKey] = oCannedData;
                        }
                    }
                    else
                    {
                        oResponseXmlStream = System.Xml.XmlReader.Create(memStrm, oSettings);
                    }
                }
            }
            catch (Exception e)
            {
                oResponseXmlStream = null;
                throw e;
            }
            return oResponseXmlStream;
        }
        //dont even try to understand the following function

        /// <summary>
        /// Do NOT call this method from update thread.
        /// </summary>
        public static bool DownloadWorldModsBlocking(List<MyObjectBuilder_Checkpoint.ModItem> mods)
        {
            if (!MyFakes.ENABLE_WORKSHOP_MODS)
                return true;

            MySandboxGame.Log.WriteLine("Downloading world mods - START");
            MySandboxGame.Log.IncreaseIndent();

            m_stop = false;

            var result = true;
            if (mods != null && mods.Count > 0)
            {
                var publishedFileIds = new List<ulong>();
                foreach (var mod in mods)
                {
                    if (mod.PublishedFileId != 0)
                    {
                        publishedFileIds.Add(mod.PublishedFileId);
                    }
                    else if (MySandboxGame.IsDedicated)
                    {
                        MySandboxGame.Log.WriteLineAndConsole("Local mods are not allowed in multiplayer.");
                        MySandboxGame.Log.DecreaseIndent();
                        return false;
                    }
                }

                if (MySandboxGame.IsDedicated)
                {
                    using (ManualResetEvent mrEvent = new ManualResetEvent(false))
                    {
                        string xml = "";

                        MySteamWebAPI.GetPublishedFileDetails(publishedFileIds, delegate(bool success, string data)
                        {
                            if (!success)
                            {
                                MySandboxGame.Log.WriteLine("Could not retrieve mods details.");
                            }
                            else
                            {
                                xml = data;
                            }
                            result = success;
                            mrEvent.Set();
                        });

                        while (!mrEvent.WaitOne(17))
                        {
                            mrEvent.Reset();
                            if (MySteam.Server != null)
                                MySteam.Server.RunCallbacks();
                            else
                            {
                                MySandboxGame.Log.WriteLine("Steam server API unavailable");
                                result = false;
                                break;
                            }
                        }
                        if (result == true)
                        {
                            try
                            {
                                System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings()
                                {
                                    DtdProcessing = System.Xml.DtdProcessing.Ignore,
                                };
                                using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new StringReader(xml), settings))
                                {
                                    reader.ReadToFollowing("result");

                                    Result xmlResult = (Result)reader.ReadElementContentAsInt();

                                    if (xmlResult != Result.OK)
                                    {
                                        MySandboxGame.Log.WriteLine(string.Format("Failed to download mods: result = {0}", xmlResult));
                                        result = false;
                                    }

                                    reader.ReadToFollowing("resultcount");
                                    int count = reader.ReadElementContentAsInt();

                                    if (count != publishedFileIds.Count)
                                    {
                                        MySandboxGame.Log.WriteLine(string.Format("Failed to download mods details: Expected {0} results, got {1}", publishedFileIds.Count, count));
                                    }

                                    var array = mods.ToArray();

                                    for (int i = 0; i < array.Length; ++i)
                                    {
                                        array[i].FriendlyName = array[i].Name;
                                    }

                                    var processed = new List<ulong>(publishedFileIds.Count);

                                    for (int i = 0; i < publishedFileIds.Count; ++i)
                                    {
                                        mrEvent.Reset();

                                        reader.ReadToFollowing("publishedfileid");
                                        ulong publishedFileId = Convert.ToUInt64(reader.ReadElementContentAsString());

                                        if (processed.Contains(publishedFileId))
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Duplicate mod: id = {0}", publishedFileId));
                                            continue;
                                        }
                                        processed.Add(publishedFileId);

                                        reader.ReadToFollowing("result");
                                        Result itemResult = (Result)reader.ReadElementContentAsInt();

                                        if (itemResult != Result.OK)
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Failed to download mod: id = {0}, result = {1}", publishedFileId, itemResult));
                                            result = false;
                                            continue;
                                        }

                                        reader.ReadToFollowing("consumer_app_id");
                                        int appid = reader.ReadElementContentAsInt();
                                        if (appid != MySteam.AppId)
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Failed to download mod: id = {0}, wrong appid, got {1}, expected {2}", publishedFileId, appid, MySteam.AppId));
                                            result = false;
                                            continue;
                                        }

                                        reader.ReadToFollowing("file_size");
                                        long fileSize = reader.ReadElementContentAsLong();

                                        reader.ReadToFollowing("file_url");
                                        string url = reader.ReadElementContentAsString();

                                        reader.ReadToFollowing("title");
                                        string title = reader.ReadElementContentAsString();

                                        for (int j = 0; j < array.Length; ++j)
                                        {
                                            if (array[j].PublishedFileId == publishedFileId)
                                            {
                                                array[j].FriendlyName = title;
                                                break;
                                            }
                                        }

                                        reader.ReadToFollowing("time_updated");
                                        uint timeUpdated = (uint)reader.ReadElementContentAsLong();

                                        var mod = new SubscribedItem() { Title = title, PublishedFileId = publishedFileId, TimeUpdated = timeUpdated };

                                        if (IsModUpToDateBlocking(Path.Combine(MyFileSystem.ModsPath, publishedFileId.ToString() + ".sbm"), mod, false, fileSize))
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Up to date mod:  id = {0}", publishedFileId));
                                            continue;
                                        }

                                        MySandboxGame.Log.WriteLineAndConsole(string.Format("Downloading mod: id = {0}, size = {1,8:0.000} MiB", publishedFileId, (double)fileSize / 1024f / 1024f));

                                        if (fileSize > 10 * 1024 * 1024) // WTF Steam
                                        {
                                            if (!DownloadModFromURLStream(url, publishedFileId, delegate(bool success)
                                            {
                                                if (!success)
                                                {
                                                    MySandboxGame.Log.WriteLineAndConsole(string.Format("Could not download mod: id = {0}, url = {1}", publishedFileId, url));
                                                }
                                                mrEvent.Set();
                                            }))
                                            {
                                                result = false;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            if (!DownloadModFromURL(url, publishedFileId, delegate(bool success)
                                            {
                                                if (!success)
                                                {
                                                    MySandboxGame.Log.WriteLineAndConsole(string.Format("Could not download mod: id = {0}, url = {1}", publishedFileId, url));
                                                }
                                                mrEvent.Set();
                                            }))
                                            {
                                                result = false;
                                                break;
                                            }
                                        }

                                        while (!mrEvent.WaitOne(17))
                                        {
                                            mrEvent.Reset();
                                            if (MySteam.Server != null)
                                                MySteam.Server.RunCallbacks();
                                            else
                                            {
                                                MySandboxGame.Log.WriteLine("Steam server API unavailable");
                                                result = false;
                                                break;
                                            }
                                        }
                                    }
                                    mods.Clear();
                                    mods.AddArray(array);
                                }
                            }
                            catch (Exception e)
                            {
                                MySandboxGame.Log.WriteLine(string.Format("Failed to download mods: {0}", e));
                                result = false;
                            }
                        }
                    }
                }
                else // client
                {
                    var toGet = new List<SubscribedItem>(publishedFileIds.Count);

                    if (!GetItemsBlocking(toGet, publishedFileIds))
                    {
                        MySandboxGame.Log.WriteLine("Could not obtain workshop item details");
                        result = false;
                    }
                    else if (publishedFileIds.Count != toGet.Count)
                    {
                        MySandboxGame.Log.WriteLine(string.Format("Could not obtain all workshop item details, expected {0}, got {1}", publishedFileIds.Count, toGet.Count));
                        result = false;
                    }
                    else
                    {
                        m_asyncDownloadScreen.ProgressText = MyCommonTexts.ProgressTextDownloadingMods;

                        if (!DownloadModsBlocking(toGet))
                        {
                            MySandboxGame.Log.WriteLine("Downloading mods failed");
                            result = false;
                        }
                        else
                        {
                            var array = mods.ToArray();

                            for (int i = 0; i < array.Length; ++i)
                            {
                                var mod = toGet.Find(x => x.PublishedFileId == array[i].PublishedFileId);
                                if (mod != null)
                                {
                                    array[i].FriendlyName = mod.Title;
                                }
                                else
                                {
                                    array[i].FriendlyName = array[i].Name;
                                }
                            }
                            mods.Clear();
                            mods.AddArray(array);
                        }
                    }
                }
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("Downloading world mods - END");

            return result;
        }
示例#58
0
		internal void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			if (!CheckForError(e))
			{
				// Process capabilities file
#if WINDOWS_PHONE
				System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings(); 
				settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
				XDocument xDoc = null;
				using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(
					new System.IO.StringReader(e.Result), settings))
					xDoc = XDocument.Load(reader);
#else
				XDocument xDoc = XDocument.Parse(e.Result);
#endif
				ParseCapabilities(xDoc);
			}

			// Call initialize regardless of error
			base.Initialize();
		}
示例#59
0
 private static void ReadTheXml()
 {
     System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
     oSettings.IgnoreComments = true;
     oSettings.IgnoreWhitespace = true;
     System.Xml.XmlReader oXmlReader = System.Xml.XmlReader.Create(sPathToXml, oSettings);
     while (oXmlReader.Read())
     {
         if (oXmlReader.Name == "text" && oXmlReader.NodeType == System.Xml.XmlNodeType.Element)
         {
             string sName = oXmlReader.GetAttribute("name");
             string[] sLines = oXmlReader.ReadString().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
             string sText = "";
             foreach (string line in sLines)
             {
                 sText += line.Trim() + Environment.NewLine;
             }
             oHashtable[sName] = sText.Trim();
         }
     }
 }
示例#60
0
        /// <summary>
        /// Read an existing XML file into the instance.
        /// </summary>
        /// <param name="validateSchemaLocation">If set to <c>true</c> validate schema location.</param>
        /// <param name="validatePackageLocations">If set to <c>true</c> validate package locations.</param>
        /// <param name="enforceBamAssemblyVersions">If set to <c>true</c> enforce bam assembly versions.</param>
        public void Read(
            bool validateSchemaLocation,
            bool validatePackageLocations,
            bool enforceBamAssemblyVersions)
        {
            Log.DebugMessage("Reading package definition file: {0}", this.XMLFilename);

            var xmlReaderSettings = new System.Xml.XmlReaderSettings();
            xmlReaderSettings.CheckCharacters = true;
            xmlReaderSettings.CloseInput = true;
            xmlReaderSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document;
            xmlReaderSettings.IgnoreComments = true;
            xmlReaderSettings.IgnoreWhitespace = true;
            if (this.validate)
            {
                xmlReaderSettings.ValidationType = System.Xml.ValidationType.Schema;
            }
            xmlReaderSettings.ValidationEventHandler += ValidationCallBack;
            xmlReaderSettings.XmlResolver = new XmlResolver();

            // try reading the current schema version first
            if (this.ReadCurrent(xmlReaderSettings, validateSchemaLocation, validatePackageLocations, enforceBamAssemblyVersions))
            {
                if (Graph.Instance.ForceDefinitionFileUpdate)
                {
                    Log.DebugMessage("Forced writing of package definition file '{0}'", this.XMLFilename);
                    this.Write();
                }

                return;
            }

            // this is where earlier versions would be read
            // and immediately written back to update to the latest schema

            throw new Exception("An error occurred while reading a package or package definition file '{0}' does not satisfy any of the package definition schemas", this.XMLFilename);
        }