Exemplo n.º 1
0
        /// <summary>
        /// Check to see if the settings file already exists, then load and store the data.
        /// If not create a new configuration of settings.
        /// </summary>
        public void LoadConfigurationFile()
        {
            if(File.Exists(_configurationLocation))
            {
                XmlReader writer = null;
                try
                {
                    using (writer = XmlReader.Create(_configurationLocation))
                    {
                        var serializer = new XmlSerializer(typeof(Configuration));
                        _configuration = serializer.Deserialize(writer) as Configuration;
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogException(ex, "Error occured when attempting to load the current configuration file.");

                    CreateNewConfiguration();
                }
                finally
                {
                    writer?.Close();
                }
            }
            else
            {
                CreateNewConfiguration();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="languageFile">File name of the language XML file</param>
        public Language(string languageFile)
        {
            InitFlag         = false;
            LanguageFilePath = languageFile;

            // Init language
            try
            {
                //// Create the validating reader and specify DTD validation.
                //_xmlReaderSettings = new XmlReaderSettings();
                //_xmlReaderSettings.DtdProcessing = DtdProcessing.Parse;
                //_xmlReaderSettings.ValidationType = ValidationType.DTD;
                //_xmlReaderSettings.ValidationEventHandler += ValidationCallBack;

                _xmlReader = XmlReader.Create(LanguageFilePath, _xmlReaderSettings);

                // Pass the validating reader to the XML document.
                // Validation fails due to an undefined attribute, but the
                // data is still loaded into the document.
                _xmlDocument = new XmlDocument();
                _xmlDocument.Load(_xmlReader);

                InitFlag = true;
            }
            catch (Exception ex)
            {
                LastException = ex;

                InitFlag = false;
                _xmlReader?.Close();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets the version from XML stream.
        /// </summary>
        /// <param name="ms">The ms.</param>
        /// <returns></returns>
        public static ResourceTypeDescriptor GetVersionFromXmlStream(Stream ms)
        {
            string    version = "1.0.0"; //NOXLATE
            XmlReader xr      = null;

            try
            {
                xr = XmlReader.Create(ms);
                xr.MoveToContent();
                if (!xr.HasAttributes)
                {
                    throw new SerializationException();
                }

                //Parse version number from ResourceType-x.y.z.xsd
                string xsd = xr.GetAttribute("xsi:noNamespaceSchemaLocation"); //NOXLATE
                if (xsd == null)
                {
                    return(null);
                }

                int start = (xsd.LastIndexOf("-"));  //NOXLATE
                int end   = xsd.IndexOf(".xsd") - 1; //NOXLATE
                version = xsd.Substring(start + 1, xsd.Length - end);
                string typeStr = xsd.Substring(0, start);

                return(new ResourceTypeDescriptor(typeStr, version));
            }
            finally
            {
                xr?.Close();
                xr?.Dispose();
                xr = null;
            }
        }
Exemplo n.º 4
0
        //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Load the object from an stream.
        /// </summary>
        /// <typeparam name="Tobj">Type of the object to load</typeparam>
        /// <param name="stream">Stream to load the saved object from</param>
        /// <param name="decompress">Decompress the file using GZip or not</param>
        /// <param name="closeStreamAfterReading">Close the stream after reading or not</param>
        /// <returns>Loaded object</returns>
        public static Tobj LoadObjectFromStream <Tobj>(Stream stream, bool decompress, bool closeStreamAfterReading)
        {
            if (stream == null || stream.Length == 0)
            {
                return(default(Tobj));
            }

            Tobj       objectOut          = default(Tobj);
            GZipStream decompressedStream = null;
            XmlReader  reader             = null;

            try
            {
                List <Type> knownTypes = new List <Type>();

                Type objType = typeof(Tobj);
                if (objType.IsGenericType && objType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    knownTypes.Add(objType);
                    objType = objType.GetGenericArguments()[0];
                }
                else if (objType.IsArray)
                {
                    knownTypes.Add(objType);
                    objType = objType.GetElementType();
                }

                knownTypes.AddRange(objType.GetProperties().Select(p => p.PropertyType));
                Assembly    executingAssembly = Assembly.GetExecutingAssembly();
                List <Type> derivedTypes      = executingAssembly.GetTypes().Where(t => objType.IsAssignableFrom(t)).ToList();
                knownTypes.AddRange(derivedTypes);

                if (decompress)
                {
                    decompressedStream = new GZipStream(stream, CompressionMode.Decompress, false);
                }
                reader = XmlReader.Create(decompress ? decompressedStream : stream);
                DataContractSerializer serializer = new DataContractSerializer(typeof(Tobj), knownTypes);
                objectOut = (Tobj)serializer.ReadObject(reader);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                reader?.Close();
                decompressedStream?.Close();
                if (closeStreamAfterReading)
                {
                    stream?.Close();
                }
            }

            return(objectOut);
        }
Exemplo n.º 5
0
        private void Update()
        {
            const string url = "http://lux-hdro.de/serverstatus-rss.php";

            XmlReader       reader = null;
            SyndicationFeed feed   = null;

            try
            {
                reader = XmlReader.Create(url);
                feed   = SyndicationFeed.Load(reader);
            }
            catch (Exception e)
            {
                Logger.Write(e.Message);
            }
            finally
            {
                reader?.Close();
            }

            if (feed != null)
            {
                foreach (var item in feed.Items)
                {
                    //var subject = item.Title.Text;
                    var summary = item.Summary.Text;
                    foreach (var server in Servers)
                    {
                        if (summary.Contains(server.Name))
                        {
                            if (summary.Contains(OnlineString))
                            {
                                server.IsOnline = true;
                                break;
                            }

                            if (summary.Contains(OfflineString))
                            {
                                server.IsOnline = false;
                                break;
                            }

                            server.IsOnline = null;
                            break;
                        }
                    }
                }
            }
            else
            {
                SetAll(null);
            }

            _mainWindow.Dispatcher.Invoke(() => _mainWindow.UpdateServerStatusTarget());
        }
Exemplo n.º 6
0
        //// ---------------------------------------------------------------------

        #region PUBLIC METHODS
        /// <summary>
        /// Validates the specified XML file.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <param name="schemaFile">The schema file.</param>
        public static void ValidateXmlFile(string filename, string schemaFile)
        {
            // Set the validation settings.
            var settings = new XmlReaderSettings();

            settings.ValidationType          = ValidationType.Schema;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ProcessInlineSchema;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += ValidationCallBack;

            settings.CheckCharacters = true;

            var schema = ReadXmlSchema(schemaFile);

            if (schema == null)
            {
                // got no valid schema ...
                return;
            } // if

            // Parse the file.
            XmlReader reader = null;

            try
            {
                settings.Schemas.Add(schema);
                reader = XmlReader.Create(filename, settings);

                Log.Info("Starting validation ...");
                while (reader.Read())
                {
                    // intentionally empty!
                } // while

                Log.Info("Validation done.");
            }
            catch (XmlException xmlex)
            {
                Log.Error("XML parsing error", xmlex);
            }
            catch (Exception ex)
            {
                Log.Error("XML parsing error", ex);
            }
            finally
            {
                reader?.Close();
            } // finally
        }     // ValidateXmlFile()
Exemplo n.º 7
0
        public static SequenceGroup ReadSequenceGroup(string filePath)
        {
            if (!filePath.EndsWith($".{CommonConst.SequenceFileExtension}"))
            {
                I18N i18N = I18N.GetInstance(Constants.I18nName);
                throw new TestflowDataException(ModuleErrorCode.InvalidFileType, i18N.GetStr("InvalidFileType"));
            }
            XmlReader reader = null;

            try
            {
                reader = CreateXmlReader(filePath);
                Dictionary <string, Type> typeMapping = GetTypeMapping();
                // 找到TestProject节点后跳出
                while (reader.Read())
                {
                    if (XmlNodeType.Element != reader.NodeType)
                    {
                        continue;
                    }
                    if (typeof(SequenceGroup).Name.Equals(reader.Name))
                    {
                        break;
                    }
                }
                SequenceGroup sequenceGroup = new SequenceGroup();
                FillDataToObject(reader, sequenceGroup, typeMapping);
                return(sequenceGroup);
            }
            catch (ArgumentException ex)
            {
                ILogService logService = TestflowRunner.GetInstance().LogService;
                logService.Print(LogLevel.Error, CommonConst.PlatformLogSession, 0, ex);
                throw new TestflowDataException(ModuleErrorCode.DeSerializeFailed, ex.Message, ex);
            }
            catch (IOException ex)
            {
                ILogService logService = TestflowRunner.GetInstance().LogService;
                logService.Print(LogLevel.Error, CommonConst.PlatformLogSession, 0, ex);
                throw new TestflowRuntimeException(ModuleErrorCode.DeSerializeFailed, ex.Message, ex);
            }
            finally
            {
                reader?.Close();
            }
        }
Exemplo n.º 8
0
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                }

                _xmlReader?.Close();
                _xmlReader = null;

                // Note disposing has been done.
                disposed = true;
            }
        }
Exemplo n.º 9
0
        XDocument Open()
        {
            bool      isZipped = filePath.EndsWith(".mxl", StringComparison.InvariantCultureIgnoreCase);
            Stream    file     = null;
            XmlReader reader   = null;
            XDocument doc      = null;

            try
            {
                if (isZipped)
                {
                    file = Zip.OpenStreamFromArchiveWhere(
                        filePath,
                        x =>
                    {
                        return(x.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase) &&
                               !x.StartsWith("META-INF", StringComparison.InvariantCultureIgnoreCase));
                    }
                        );
                }
                else
                {
                    file = new FileStream(filePath, FileMode.Open);
                }

                reader = XmlReader.Create(file, new XmlReaderSettings()
                {
                    Async = true, DtdProcessing = DtdProcessing.Parse
                });

                doc = XDocument.Load(reader);
            }
            catch (Exception ex)
            {
                throw new XmlParsingException("An error occured while parsing", ex);
            } finally
            {
                file?.Close();
                reader?.Close();
            }

            return(doc);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 校验Xml字符串是否符合指定Xml架构文件
        /// </summary>
        /// <param name="xmlFile">Xml文件</param>
        /// <param name="schemaFile">架构文件</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static void Validate(string xmlFile, string schemaFile)
        {
            if (string.IsNullOrWhiteSpace(xmlFile))
            {
                throw new ArgumentNullException(nameof(xmlFile));
            }
            if (string.IsNullOrWhiteSpace(schemaFile))
            {
                throw new ArgumentNullException(nameof(schemaFile));
            }
            XmlReader reader = null;

            try
            {
                var result   = new Tuple <bool, string>(true, string.Empty);
                var settings = new XmlReaderSettings();
                settings.ValidationType   = ValidationType.Schema;
                settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
                settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.Schemas.Add(null, schemaFile);
                // 设置验证Xml出错时的事件
                settings.ValidationEventHandler += (obj, e) =>
                {
                    result = new Tuple <bool, string>(false, e.Message);
                };
                using (reader = XmlReader.Create(xmlFile, settings))
                {
                    while (reader.Read())
                    {
                    }
                }
                if (!result.Item1)
                {
                    throw new ArgumentException(result.Item2);
                }
            }
            finally
            {
                reader?.Close();
            }
        }
Exemplo n.º 11
0
        public static List <BaseItemType> LoadFood()
        {
            List <BaseItemType> food = new List <BaseItemType>();

            string    filePath = Directory.GetCurrentDirectory() + "//Data//Items//Food//Food.xml";
            XmlReader reader   = XmlReader.Create(filePath);

            List <IdentifiedItem> identifiedItems = new List <IdentifiedItem>();
            string actionWord     = "strikes";
            string governingSkill = "None";
            string category       = "None";

            while (reader.Read())
            {
                if (reader.Depth == 0 && reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("Items"))
                {
                    break;
                }

                if (reader.Name.Equals("Category") && reader.NodeType == XmlNodeType.Element)
                {
                    category = reader.ReadElementContentAsString();
                }

                if (reader.Name.Equals("IdentifiedItem") && reader.NodeType == XmlNodeType.Element)
                {
                    IdentifiedItem item = new IdentifiedItem();
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name.Equals("Name"))
                        {
                            item.name = reader.ReadElementContentAsString();
                        }
                        else if (reader.Name.Equals("Description"))
                        {
                            item.description = reader.ReadElementContentAsString();
                        }
                        else if (reader.Name.Equals("Value"))
                        {
                            item.value = reader.ReadElementContentAsInt();
                        }
                        else if (reader.Name.Equals("Effect"))
                        {
                            item.interactionFile = Directory.GetCurrentDirectory() + "//Data//Scripts//Items//Food//" + reader.ReadElementContentAsString();
                        }
                        else if (reader.Name.Equals("SpawnWeight"))
                        {
                            item.weighting = reader.ReadElementContentAsInt();
                        }
                        else if (reader.Name.Equals("Materials"))
                        {
                            string materials = reader.ReadElementContentAsString();
                            item.materials = materials.Split(',');
                        }
                        else if (reader.Name.Equals("Size"))
                        {
                            item.size = reader.ReadElementContentAsFloat();
                        }
                    }
                    item.category = category;
                    identifiedItems.Add(item);
                }
                else if (reader.Name.Equals("ActionWord"))
                {
                    actionWord = reader.ReadElementContentAsString();
                }
            }

            reader.Close();

            ItemMaterial foodMaterial = MaterialHandler.GetMaterial("Food");

            for (int i = 0; i < identifiedItems.Count; i++)
            {
                food.Add(new BaseItemType(identifiedItems[i].category, identifiedItems[i].description, identifiedItems[i].description, identifiedItems[i].name,
                                          identifiedItems[i].name, "None", identifiedItems[i].size, foodMaterial, "Food", governingSkill, actionWord,
                                          identifiedItems[i].interactionFile, identifiedItems[i].value, identifiedItems[i].weighting));
            }

            return(food);
        }
Exemplo n.º 12
0
 protected virtual string EncryptPassword(string document)
 {
   string str1 = document;
   XmlWriter xmlWriter = (XmlWriter) null;
   XmlReader reader = (XmlReader) null;
   bool flag1 = false;
   try
   {
     StringBuilder sb = new StringBuilder();
     xmlWriter = (XmlWriter) new XmlTextWriter((TextWriter) new StringWriter(sb));
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.IgnoreWhitespace = true;
     reader = XmlReader.Create((TextReader) new StringReader(document), settings);
     if (reader.Read())
     {
       do
       {
         if (reader.NodeType == XmlNodeType.Element && (reader.LocalName == "__session" || reader.LocalName == "__connect"))
           reader.Read();
         else if (reader.NodeType == XmlNodeType.Element && (reader.LocalName == "password" || reader.LocalName == "sessionId"))
         {
           for (bool flag2 = reader.MoveToFirstAttribute(); flag2; flag2 = reader.MoveToNextAttribute())
           {
             if (reader.LocalName == "__encrypted" && string.Compare(reader.Value, "yes", true) == 0)
               flag1 = true;
           }
           reader.Close();
         }
         else
           reader.Read();
       }
       while (!reader.EOF && reader.ReadState != System.Xml.ReadState.Closed);
     }
     reader = XmlReader.Create((TextReader) new StringReader(document), settings);
     if (reader.Read())
     {
       do
       {
         if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "__InSite")
         {
           string str2 = (string) null;
           xmlWriter.WriteStartElement(reader.LocalName);
           for (bool flag2 = reader.MoveToFirstAttribute(); flag2; flag2 = reader.MoveToNextAttribute())
           {
             if (reader.LocalName == "__encryption")
               str2 = reader.Value;
             else
               xmlWriter.WriteAttributeString(reader.LocalName, reader.Value);
           }
           if (!flag1)
             str2 = "2";
           if (!string.IsNullOrEmpty(str2))
             xmlWriter.WriteAttributeString("__encryption", str2);
           reader.Read();
         }
         else if (reader.NodeType == XmlNodeType.Element && (reader.LocalName == "__session" || reader.LocalName == "__connect"))
         {
           xmlWriter.WriteStartElement(reader.LocalName);
           xmlWriter.WriteAttributes(reader, true);
           reader.Read();
         }
         else if (reader.NodeType == XmlNodeType.EndElement && (reader.LocalName == "__session" || reader.LocalName == "__connect"))
         {
           xmlWriter.WriteEndElement();
           reader.Read();
         }
         else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "password")
         {
           if (!flag1)
           {
             xmlWriter.WriteStartElement(reader.LocalName);
             for (bool flag2 = reader.MoveToFirstAttribute(); flag2; flag2 = reader.MoveToNextAttribute())
             {
               if (reader.LocalName != "__encrypted")
                 xmlWriter.WriteAttributeString(reader.LocalName, reader.Value);
             }
             xmlWriter.WriteAttributeString("__encrypted", "yes");
             int content = (int) reader.MoveToContent();
             string fieldData = reader.ReadElementContentAsString();
             xmlWriter.WriteValue(CryptUtil.Encrypt(fieldData));
             xmlWriter.WriteEndElement();
           }
           else
             xmlWriter.WriteNode(reader, true);
         }
         else
           xmlWriter.WriteNode(reader, true);
       }
       while (!reader.EOF);
       str1 = sb.ToString();
     }
   }
   catch (Exception ex)
   {
     str1 = document;
     this.LogEntry(string.Format("Password encrypting error: {0}", (object) ex.Message), EventLogEntryType.Error);
   }
   finally
   {
     reader?.Close();
     xmlWriter?.Close();
   }
   return str1;
 }
Exemplo n.º 13
0
 public void Dispose()
 {
     reader.Close();
     currentNode = null;
 }
Exemplo n.º 14
0
        /// <summary>
        /// Load data base from file
        /// </summary>
        /// <param name="fileName">The full path of database file</param>
        public static void LoadDatabase(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return;
            }
            //1 clear the database
            _databaseRoms.Clear();
            //2 read the xml file
            Stream databaseStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            XmlReaderSettings sett = new XmlReaderSettings();

            sett.DtdProcessing    = DtdProcessing.Ignore;
            sett.IgnoreWhitespace = true;
            XmlReader XMLread = XmlReader.Create(databaseStream, sett);

            NesCartDatabaseGameInfo drom = new NesCartDatabaseGameInfo();

            // To avoid nulls ..
            drom.Cartridges       = new List <NesCartDatabaseCartridgeInfo>();
            drom.Game_AltName     = "";
            drom.Game_Catalog     = "";
            drom.Game_Class       = "";
            drom.Game_Developer   = "";
            drom.Game_Name        = "";
            drom.Game_Players     = "";
            drom.Game_Publisher   = "";
            drom.Game_Region      = "";
            drom.Game_ReleaseDate = "";

            while (XMLread.Read())
            {
                //database Game info
                if (XMLread.Name == "xml" & XMLread.IsStartElement())
                {
                    if (XMLread.MoveToAttribute("version"))
                    {
                        DBVersion = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("conformance"))
                    {
                        DBConformance = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("agent"))
                    {
                        DBAgent = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("author"))
                    {
                        DBAuthor = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("timestamp"))
                    {
                        DBTimeStamp = XMLread.Value;
                    }
                }
                //Is it a game ?
                else if (XMLread.Name == "game" & XMLread.IsStartElement())
                {
                    drom = new NesCartDatabaseGameInfo();

                    if (XMLread.MoveToAttribute("name"))
                    {
                        drom.Game_Name = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("altname"))
                    {
                        drom.Game_AltName = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("class"))
                    {
                        drom.Game_Class = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("catalog"))
                    {
                        drom.Game_Catalog = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("publisher"))
                    {
                        drom.Game_Publisher = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("developer"))
                    {
                        drom.Game_Developer = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("region"))
                    {
                        drom.Game_Region = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("players"))
                    {
                        drom.Game_Players = XMLread.Value;
                    }
                    if (XMLread.MoveToAttribute("date"))
                    {
                        drom.Game_ReleaseDate = XMLread.Value;
                    }

                    NesCartDatabaseCartridgeInfo crt = new NesCartDatabaseCartridgeInfo();
                    crt.PAD_h        = "";
                    crt.PAD_v        = "";
                    crt.PRG_crc      = "";
                    crt.PRG_name     = "";
                    crt.PRG_sha1     = "";
                    crt.PRG_size     = "";
                    crt.chip_type    = new List <string>();
                    crt.CHR_crc      = "";
                    crt.CHR_name     = "";
                    crt.CHR_sha1     = "";
                    crt.CHR_size     = "";
                    crt.CIC_type     = "";
                    crt.Board_Mapper = "";
                    crt.Board_Pcb    = "";
                    crt.Board_Type   = "";
                    crt.VRAM_sizes   = new List <string>();
                    crt.WRAMBanks    = new List <SRAMBankInfo>();
                    // Load carts
                    while (XMLread.Read())
                    {
                        //End of game info ?
                        if (XMLread.Name == "game" & !XMLread.IsStartElement())
                        {
                            _databaseRoms.Add(drom);
                            break;
                        }
                        //cartridge info
                        if (XMLread.Name == "cartridge" & XMLread.IsStartElement())
                        {
                            if (drom.Cartridges == null)
                            {
                                drom.Cartridges = new List <NesCartDatabaseCartridgeInfo>();
                            }
                            crt              = new NesCartDatabaseCartridgeInfo();
                            crt.PAD_h        = "";
                            crt.PAD_v        = "";
                            crt.PRG_crc      = "";
                            crt.PRG_name     = "";
                            crt.PRG_sha1     = "";
                            crt.PRG_size     = "";
                            crt.chip_type    = new List <string>();
                            crt.CHR_crc      = "";
                            crt.CHR_name     = "";
                            crt.CHR_sha1     = "";
                            crt.CHR_size     = "";
                            crt.CIC_type     = "";
                            crt.Board_Mapper = "";
                            crt.Board_Pcb    = "";
                            crt.Board_Type   = "";
                            crt.VRAM_sizes   = new List <string>();
                            crt.WRAMBanks    = new List <SRAMBankInfo>();
                            if (XMLread.MoveToAttribute("system"))
                            {
                                crt.System = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("crc"))
                            {
                                crt.CRC = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("sha1"))
                            {
                                crt.SHA1 = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("dump"))
                            {
                                crt.Dump = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("dumper"))
                            {
                                crt.Dumper = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("datedumped"))
                            {
                                crt.DateDumped = XMLread.Value;
                            }
                        }
                        else if (XMLread.Name == "cartridge" & !XMLread.IsStartElement())
                        {
                            drom.Cartridges.Add(crt); continue;
                        }
                        //board info
                        else if (XMLread.Name == "board" & XMLread.IsStartElement())
                        {
                            if (XMLread.MoveToAttribute("type"))
                            {
                                crt.Board_Type = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("pcb"))
                            {
                                crt.Board_Pcb = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("mapper"))
                            {
                                crt.Board_Mapper = XMLread.Value;
                            }
                        }
                        //prg info
                        else if (XMLread.Name == "prg" & XMLread.IsStartElement())
                        {
                            if (XMLread.MoveToAttribute("name"))
                            {
                                crt.PRG_name = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("size"))
                            {
                                crt.PRG_size = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("crc"))
                            {
                                crt.PRG_crc = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("sha1"))
                            {
                                crt.PRG_sha1 = XMLread.Value;
                            }
                        }
                        //chr info
                        else if (XMLread.Name == "chr" & XMLread.IsStartElement())
                        {
                            if (XMLread.MoveToAttribute("name"))
                            {
                                crt.CHR_name = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("size"))
                            {
                                crt.CHR_size = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("crc"))
                            {
                                crt.CHR_crc = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("sha1"))
                            {
                                crt.CHR_sha1 = XMLread.Value;
                            }
                        }
                        //vram info
                        else if (XMLread.Name == "vram" & XMLread.IsStartElement())
                        {
                            if (XMLread.MoveToAttribute("size"))
                            {
                                crt.VRAM_sizes.Add(XMLread.Value);
                            }
                        }
                        //wram info
                        else if (XMLread.Name == "wram" & XMLread.IsStartElement())
                        {
                            string wsize   = "";
                            bool   battery = false;
                            int    id      = 0;

                            if (XMLread.MoveToAttribute("size"))
                            {
                                wsize = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("battery"))
                            {
                                battery = XMLread.Value == "1";
                            }
                            if (XMLread.MoveToAttribute("id"))
                            {
                                int.TryParse(XMLread.Value, out id);
                            }
                            crt.WRAMBanks.Add(new SRAMBankInfo(id, wsize, battery));
                        }
                        //chip info
                        else if (XMLread.Name == "chip" & XMLread.IsStartElement())
                        {
                            if (XMLread.MoveToAttribute("type"))
                            {
                                if (crt.chip_type == null)
                                {
                                    crt.chip_type = new List <string>();
                                }
                                crt.chip_type.Add(XMLread.Value);
                            }
                        }
                        //cic info
                        else if (XMLread.Name == "cic" & XMLread.IsStartElement())
                        {
                            if (XMLread.MoveToAttribute("type"))
                            {
                                crt.CIC_type = XMLread.Value;
                            }
                        }
                        //pad info
                        else if (XMLread.Name == "pad" & XMLread.IsStartElement())
                        {
                            if (XMLread.MoveToAttribute("h"))
                            {
                                crt.PAD_h = XMLread.Value;
                            }
                            if (XMLread.MoveToAttribute("v"))
                            {
                                crt.PAD_v = XMLread.Value;
                            }
                        }
                    }
                }
            }
            XMLread.Close();
            databaseStream.Close();
        }
Exemplo n.º 15
0
    // Use this for initialization
    void Start()
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        reader = XmlReader.Create(xmlSourceUrlName, settings);

        XmlDocument doc = new XmlDocument();
        doc.Load(reader);

        if (reader == null)
        {
            reader.Close();
            print("error: file could not be found");
        }

        else
        {
            constructTileSets(doc);
            constructMap(doc);

            EditorApplication.SaveScene(sceneDestinationUrlName, true);
        }
    }
Exemplo n.º 16
0
 //doesn't use the serialization APIs, but just looks at attributes at the top level
 public static List<BounceFileMetaData> RetrieveMetaData()
 {
     //List<string> fullFileList = Directory.GetFiles (saveDirectory, savePrefix + "*" + saveSuffix,
     //                                                SearchOption.TopDirectoryOnly).ToList();
     List<string> fullFileList = Directory.GetFiles (saveDirectory, savePrefix + "*" + saveSuffix).ToList ();
     List<BounceFileMetaData> dataList = new List<BounceFileMetaData> ();
     foreach (string filename in fullFileList)
     {
         reader = XmlReader.Create(filename);
         XmlDocument doc = new XmlDocument();
         doc.Load(reader);
         XmlNodeList nodeLst = doc.ChildNodes;
         foreach (XmlNode node in nodeLst)
         {
             if (node.Name == "PlayerData") {
                 BounceFileMetaData metadata = new BounceFileMetaData();
                 if (node.Attributes["numberDeaths"] != null)
                     metadata.numberDeaths = long.Parse(node.Attributes["numberDeaths"].Value);
                 if (node.Attributes["numberCollectibles"] != null)
                     metadata.numberCollectibles = int.Parse(node.Attributes["numberCollectibles"].Value);
                 if (node.Attributes["playTime"] != null)
                     metadata.numberSeconds = long.Parse(node.Attributes["playTime"].Value);
                 if (node.Attributes["lastCheckpoint"] != null)
                     metadata.lastCheckpoint = int.Parse(node.Attributes["lastCheckpoint"].Value);
                 //Debug.Log (filename);
                 string truncStr = filename.Substring((saveDirectory + savePrefix).Length);
                 //Debug.Log (truncStr);
                 truncStr = truncStr.Substring(0, truncStr.Length - saveSuffix.Length);
                 //Debug.Log (truncStr);
                 metadata.index = int.Parse(truncStr);
                 dataList.Add(metadata);
             }
         }
         reader.Close();
     }
     return dataList;
 }
Exemplo n.º 17
0
        private bool WriteFilesToDevice(string portName, string swPath, string rawFilePath)
        {
            bool flag1 = true;

            Log.w(comm.serialPort.PortName, string.Format("open program file {0}", rawFilePath));
            FlashingDevice.UpdateDeviceStatus(comm.serialPort.PortName, new float?(), rawFilePath, "flashing", false);
            XmlDocument xmlDocument = new XmlDocument();
            XmlReader   reader      = XmlReader.Create(rawFilePath, new XmlReaderSettings()
            {
                IgnoreComments = true
            });

            xmlDocument.Load(reader);
            XmlNodeList childNodes = xmlDocument.SelectSingleNode("data").ChildNodes;
            bool        flag2      = false;
            string      str1       = "";
            string      str2       = "0";
            string      str3       = "0";
            string      str4       = "0";
            string      str5       = "0";
            string      str6       = "512";
            string      str7       = "";

            foreach (XmlElement xmlElement in childNodes)
            {
                if (!(xmlElement.Name.ToLower() != "program"))
                {
                    foreach (XmlAttribute attribute in xmlElement.Attributes)
                    {
                        switch (attribute.Name.ToLower())
                        {
                        case "file_sector_offset":
                            str2 = attribute.Value;
                            continue;

                        case "filename":
                            str1 = attribute.Value;
                            continue;

                        case "num_partition_sectors":
                            str4 = attribute.Value;
                            continue;

                        case "start_sector":
                            str3 = attribute.Value;
                            continue;

                        case "sparse":
                            flag2 = attribute.Value == "true";
                            continue;

                        case "sector_size_in_bytes":
                            str6 = attribute.Value;
                            continue;

                        case "physical_partition_number":
                            str5 = attribute.Value;
                            continue;

                        case "label":
                            str7 = attribute.Value;
                            continue;

                        default:
                            continue;
                        }
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        str1 = swPath + "\\" + str1;
                        if (str1.IndexOf("gpt_main1") >= 0 || str1.IndexOf("gpt_main2") >= 0)
                        {
                            Thread.Sleep(3000);
                        }
                        if (flag2)
                        {
                            Log.w(comm.serialPort.PortName, string.Format("Write sparse file {0} to partition[{1}] sector {2}", str1, str7, str3));
                            new FileTransfer(comm.serialPort.PortName, str1).WriteSparseFileToDevice(this, str3, str4, str1, str2, str6, str5);
                        }
                        else
                        {
                            Log.w(comm.serialPort.PortName, string.Format("Write file {0} to partition[{1}] sector {2}", str1, str7, str3));
                            new FileTransfer(comm.serialPort.PortName, str1).WriteFile(this, str3, str4, str1, str2, "0", str6, str5);
                        }
                        Log.w(comm.serialPort.PortName, string.Format("Image {0} transferred successfully", str1));
                    }
                }
            }
            reader.Close();
            return(flag1);
        }
        /// <summary>
        /// Look up the shared content elements, find their corresponding shared content item and replace the
        /// elements with the content item value.
        /// </summary>
        /// <param name="key">The document key</param>
        /// <param name="document">The document containing the topic</param>
        /// <param name="start">The XPath navigator to search for content elements</param>
        /// <remarks>This method will replace content items within other content items recursively</remarks>
        private void ResolveContent(string key, XmlDocument document, XPathNavigator start)
        {
            List <string> parameters = new List <string>();

            // For each kind of shared content element...
            foreach (SharedContentElement element in elements)
            {
                // Find all such elements, convert to an array so as not to cause an error when manipulating the
                // document, and process each element.
                foreach (XPathNavigator node in start.Select(element.Path).ToArray())
                {
                    // Get the item key
                    string item = node.Evaluate(element.Item).ToString();

                    // Check for a missing item key
                    if (String.IsNullOrEmpty(item))
                    {
                        base.WriteMessage(key, MessageLevel.Warn, "A shared content element did not specify an item");
                    }
                    else
                    {
                        // Extract any parameters
                        parameters.Clear();

                        XPathNodeIterator parameterNodes = node.Select(element.Parameters);

                        foreach (XPathNavigator parameterNode in parameterNodes)
                        {
                            parameters.Add(parameterNode.GetInnerXml());
                        }

                        // Find the content item and format the parameters into the value
                        string contentValue = null;

                        if (content.TryGetValue(item, out contentValue))
                        {
                            try
                            {
                                contentValue = String.Format(CultureInfo.InvariantCulture, contentValue,
                                                             parameters.ToArray());
                            }
                            catch (FormatException)
                            {
                                base.WriteMessage(key, MessageLevel.Error, "The shared content item '{0}' " +
                                                  "could not be formatted with {1} parameters.", item, parameters.Count);
                            }
                        }

                        // Check for missing content
                        if (contentValue == null)
                        {
                            base.WriteMessage(key, MessageLevel.Warn, "Missing shared content item. Tag: " +
                                              "'{0}'; Id:'{1}'.", node.LocalName, item);
                        }
                        else
                        {
                            // Store the content in a document fragment
                            XmlDocumentFragment fragment = document.CreateDocumentFragment();
                            fragment.InnerXml = contentValue;

                            // Resolve any shared content in the fragment
                            this.ResolveContent(key, document, fragment.CreateNavigator());

                            // Look for an attribute name
                            string attribute = node.Evaluate(element.Attribute).ToString();

                            // Insert the resolved content...
                            if (String.IsNullOrEmpty(attribute))
                            {
                                // ...as mixed content
                                XmlWriter writer = node.InsertAfter();
                                fragment.WriteTo(writer);
                                writer.Close();
                            }
                            else
                            {
                                // ...as an attribute
                                XPathNavigator parent = node.CreateNavigator();
                                parent.MoveToParent();
                                parent.CreateAttribute(String.Empty, attribute, String.Empty, fragment.InnerText);
                            }
                        }
                    }

                    // Keep a reference to the parent element
                    XPathNavigator parentElement = node.CreateNavigator();
                    parentElement.MoveToParent();

                    // Remove the node
                    node.DeleteSelf();

                    // If there is no content left in the parent element, make sure it is self-closing
                    if (!parentElement.HasChildren && !parentElement.IsEmptyElement)
                    {
                        // If the node was already the root then we will have a blank node now and
                        // doing an InsertAfter() will throw an exception.
                        if (parentElement.Name.Length > 0)
                        {
                            // Create a new element
                            XmlWriter attributeWriter = parentElement.InsertAfter();
                            attributeWriter.WriteStartElement(parentElement.Prefix, parentElement.LocalName,
                                                              parentElement.NamespaceURI);

                            // Copy attributes to it
                            XmlReader attributeReader = parentElement.ReadSubtree();
                            attributeReader.Read();
                            attributeWriter.WriteAttributes(attributeReader, false);
                            attributeReader.Close();

                            // Close it
                            attributeWriter.WriteEndElement();
                            attributeWriter.Close();

                            // Delete the old element
                            parentElement.DeleteSelf();
                        }
                        else
                        {
                            // If we are inside a tag such as title, removing the content will leave it in the
                            // form "<title />" which is not allowed in HTML.  Since this usually means there is
                            // a problem with the shared content or the transforms leading up to this, we will
                            // just report the error here.
                            base.WriteMessage(key, MessageLevel.Error, "Error replacing item.  Root document " +
                                              "element encountered.");
                        }
                    }
                }
            }
        }
Exemplo n.º 19
0
        public override bool Read()
        {
            // First call to Read
            if (ReadState == System.Xml.ReadState.Initial)
            {
                nodeStack.Push(rootNode);
                currentNode = rootNode.GetFirstChild();
                return(CheckReadStateAndReturn());
            }

            if (xmlReader != null)
            {
                var result = xmlReader.Read();
                if (result && xmlReader.Depth > 0)
                {
                    return(result);
                }
                else
                {
                    xmlReader.Close();
                    textReader.Dispose();
                    xmlReader  = null;
                    textReader = null;
                }
            }

            switch (traverseDirection)
            {
            case TraverseDirection.Down:
                // As long as there're children go down (depth first)
                if (currentNode.HasChildren)
                {
                    nodeStack.Push(currentNode);
                    currentNode = currentNode.GetFirstChild();
                }
                else
                {
                    var parent    = nodeStack.Peek();
                    var lastChild = parent.GetLastChild();
                    if (currentNode.IsSame(lastChild))
                    {
                        // Time to move back up
                        nodeStack.Pop();
                        traverseDirection = TraverseDirection.Up;
                        currentNode.Dispose();
                        currentNode = parent;
                    }
                    else
                    {
                        // There're still siblings left to visit
                        currentNode = currentNode.GetNextSibling();
                    }
                    lastChild.Dispose();
                }
                break;

            case TraverseDirection.Up:
                // See if we can find siblings (need to have a parent)
                if (nodeStack.Count > 1)
                {
                    var parent = nodeStack.Peek();
                    //var parent = currentNode.GetParent();
                    var lastChild = parent.GetLastChild();
                    if (currentNode.IsSame(lastChild))
                    {
                        // No sibling left, go further up
                        nodeStack.Pop();
                        currentNode.Dispose();
                        currentNode = parent;
                    }
                    else
                    {
                        // There's a sibling, try to traverse down again (depth first)
                        traverseDirection = TraverseDirection.Down;
                        currentNode       = currentNode.GetNextSibling();
                    }
                    lastChild.Dispose();
                }
                else
                {
                    // No parent left, we have to be the root -> EOF
                    currentNode.Dispose();
                    currentNode = null;
                    readState   = System.Xml.ReadState.EndOfFile;
                    return(false);
                }
                break;
            }

            if (currentNode != null)
            {
                // See if this node defines a new namespace
                if (currentNode.HasElementAttributes())
                {
                    attributeMap = currentNode.GetElementAttributes();
                    switch (traverseDirection)
                    {
                    case TraverseDirection.Down:
                        for (int i = 0; i < attributeMap.Count; i++)
                        {
                            string key, value;
                            if (attributeMap.TryGetKey(i, out key) && attributeMap.TryGetValue(i, out value))
                            {
                                if (key.StartsWith("xmlns"))
                                {
                                    var prefix = GetPrefix(key);
                                    namespaceManager.AddNamespace(prefix, value);
                                }
                            }
                        }
                        namespaceManager.PushScope();
                        break;

                    case TraverseDirection.Up:
                        namespaceManager.PopScope();
                        break;
                    }
                }
                else
                {
                    attributeMap = null;
                }
            }

            return(CheckReadStateAndReturn());
        }
Exemplo n.º 20
0
        public bool getInfomation(string[] indexGroup, string filePath, string outputPath)
        {
            fs_out = new FileStream(outputPath, FileMode.Create, FileAccess.Write);
            sw     = new StreamWriter(fs_out);
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.DtdProcessing = DtdProcessing.Parse;
            XmlReader reader = XmlReader.Create(filePath, settings);


            //XmlReader reader = XmlReader.Create(filepath, settings);

            //reader的create函数也需要加入settings设置

            //if (Infomation == null)
            //{
            //    Infomation = new List<string>();
            //}
            if (indexGroup == null)
            {
                return(false);
            }


            foreach (string index in indexGroup)
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.GetAttribute("index") == index)
                        {
                            //通过index定位当前的标签的name是什么并且选择
                            //由于XmlReader是按行读取的 所以需要按行判断标签的名字是否符合要求
                            //此处属于投机取巧 因为author journal标签是字标签
                            //当遍历到最后一位时 遇到article或者inproceedings等大标签即停止
                            //搜索花的时间最长为1分钟
                            switch (reader.Name)//article inproceeding incollection
                            {
                            case "article":
                                reader.MoveToElement();    //跳过空白节点 免得影响条件判断
                                while (reader.Read())
                                {
                                    reader.MoveToContent();
                                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "author" || reader.Name == "volume" || reader.Name == "ee" || reader.Name == "isbn" || reader.Name == "url" || reader.Name == "journal" || reader.Name == "month" || reader.Name == "year" || reader.Name == "title" || reader.Name == "publisher"))
                                    {
                                        sw.Write(reader.Name + ":" + reader.ReadInnerXml() + '\n');
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                break;

                            case "book":
                                reader.MoveToElement();
                                while (reader.Read())
                                {
                                    reader.MoveToContent();
                                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "author" || reader.Name == "title" || reader.Name == "year" ||
                                                                                     reader.Name == "series" || reader.Name == "publisher" || reader.Name == "isbn" || reader.Name == "ee"))
                                    {
                                        sw.Write(reader.Name + ":" + reader.ReadInnerXml() + '\n');
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                break;

                            case "incollection":
                                reader.MoveToElement();
                                while (reader.Read())
                                {
                                    reader.MoveToContent();
                                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "author" || reader.Name == "title" || reader.Name == "pages" ||
                                                                                     reader.Name == "year" || reader.Name == "booktitle" || reader.Name == "url" || reader.Name == "crossref" ||
                                                                                     reader.Name == "ee" || reader.Name == "cdrom" || reader.Name == "note" || reader.Name == "month"))
                                    {
                                        sw.Write(reader.Name + ":" + reader.ReadInnerXml() + '\n');
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                break;

                            case "inproceedings":
                                reader.MoveToElement();
                                while (reader.Read())
                                {
                                    reader.MoveToContent();
                                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "author" || reader.Name == "title" || reader.Name == "pages" ||
                                                                                     reader.Name == "year" || reader.Name == "booktitle" || reader.Name == "url" ||
                                                                                     reader.Name == "crossref" || reader.Name == "ee" || reader.Name == "cdrom" || reader.Name == "note" ||
                                                                                     reader.Name == "month"))
                                    {
                                        sw.Write(reader.Name + ":" + reader.ReadInnerXml() + '\n');
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                break;

                            case "www":
                                reader.MoveToElement();
                                while (reader.Read())
                                {
                                    reader.MoveToContent();
                                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "volume" || reader.Name == "editor" ||
                                                                                     reader.Name == "author" || reader.Name == "title" || reader.Name == "pages" || reader.Name == "year" ||
                                                                                     reader.Name == "booktitle" || reader.Name == "url" || reader.Name == "crossref" || reader.Name == "ee" ||
                                                                                     reader.Name == "cdrom" || reader.Name == "note" || reader.Name == "month"))
                                    {
                                        sw.Write(reader.Name + ":" + reader.ReadInnerXml() + '\n');
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                break;

                            case "phdthesis":
                                reader.MoveToElement();
                                while (reader.Read())
                                {
                                    reader.MoveToContent();
                                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "author" || reader.Name == "title" || reader.Name == "year" || reader.Name == "school" || reader.Name == "pages" || reader.Name == "publisher" || reader.Name == "series" || reader.Name == "volume" || reader.Name == "isbn" || reader.Name == "ee"))
                                    {
                                        sw.Write(reader.Name + ":" + reader.ReadInnerXml() + '\n');
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                break;
                            }
                            sw.Write('\n');
                            break;
                            //这个break是为了避免reader停不下来知道最后一行
                        }
                    }
                }
            }
            reader.Close();
            sw.Close();
            fs_out.Close();
            return(true);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Parse the command line arguments.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        private void ParseCommandline(string[] args)
        {
            foreach (string arg in args)
            {
                if (arg.StartsWith("-") || arg.StartsWith("/"))
                {
                    string parameter = arg.Substring(1);

                    if ("?" == parameter)
                    {
                        this.showHelp = true;
                        return;
                    }
                    else if (parameter.StartsWith("env:"))
                    {
                        parameter = parameter.Substring("env:".Length);
                        int equalPos = parameter.IndexOf('=');
                        if (0 > equalPos)
                        {
                            throw new ArgumentException("env parameters require a name=value pair.");
                        }
                        string name  = parameter.Substring(0, equalPos);
                        string value = parameter.Substring(equalPos + 1);
                        this.environmentVariables.Add(new KeyValuePair <string, string>(name, value));
                    }
                    else if ("notidy" == parameter)
                    {
                        this.noTidy = true;
                    }
                    else if ("rf" == parameter)
                    {
                        this.rerunFailedTests = true;
                        ArrayList previouslyFailedTests = null;

                        if (File.Exists(this.failedTestsFile))
                        {
                            XmlReader reader = null;

                            try
                            {
                                reader = XmlReader.Create(this.failedTestsFile);
                                XmlSerializer serializer = new XmlSerializer(typeof(ArrayList));
                                previouslyFailedTests = (ArrayList)serializer.Deserialize(reader);
                            }
                            catch (InvalidOperationException e)
                            {
                                Console.WriteLine(String.Concat("There was an error loading the failed tests from ", this.failedTestsFile));
                                Console.WriteLine(e.Message);
                            }
                            finally
                            {
                                if (null != reader)
                                {
                                    reader.Close();
                                }

                                if (File.Exists(this.failedTestsFile))
                                {
                                    File.Delete(this.failedTestsFile);
                                }
                            }
                        }

                        if (null != previouslyFailedTests)
                        {
                            this.unitTests.AddRange(previouslyFailedTests);
                        }
                    }
                    else if ("st" == parameter)
                    {
                        this.singleThreaded = true;
                    }
                    else if (parameter.StartsWith("test:"))
                    {
                        this.unitTests.Add(parameter.Substring(5));
                    }
                    else if ("update" == parameter)
                    {
                        this.updateTests = true;
                    }
                    else if ("v" == parameter)
                    {
                        this.verbose = true;
                    }
                    else if ("val" == parameter)
                    {
                        this.validate = true;
                    }
                    else
                    {
                        throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Unrecognized commandline parameter '{0}'.", arg));
                    }
                }
                else if (null == this.unitTestsFile)
                {
                    this.unitTestsFile = arg;
                }
                else
                {
                    throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Unrecognized argument '{0}'.", arg));
                }
            }

            // no individual unit tests were selected, so match all unit tests
            if (0 == this.unitTests.Count && !this.rerunFailedTests)
            {
                this.unitTests.Add(".*");
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// 超找MDK节点分组
        /// </summary>
        /// <param name="xmlRead"></param>
        /// <param name="str"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        private CProjectGroup FindMDKSubNodeGroup(XmlReader xmlRead, string str, CProjectGroup parent = null)
        {
            CProjectGroup _return = new CProjectGroup(parent);

            if (xmlRead.NodeType != XmlNodeType.Element || xmlRead.Name != str)
            {
                xmlRead.ReadToFollowing(str);
            }
            if (xmlRead.EOF)
            {
                return(_return);
            }
            XmlReader subXmlRead = xmlRead.ReadSubtree();

            do
            {
                subXmlRead.Read();
            }while (subXmlRead.NodeType != XmlNodeType.Text);
            _return.mName = subXmlRead.Value;
            do
            {
                if (subXmlRead.Read() && subXmlRead.NodeType == XmlNodeType.Element)
                {
                    switch (subXmlRead.Name)
                    {
                    case "Group":

                        //---子分组信息---递归调用
                        _return.mChildGroup.Add(this.FindMDKSubNodeGroup(subXmlRead, str, _return));
                        break;

                    case "Files":

                        //---获取节点
                        XmlReader subSubXmlRead = subXmlRead.ReadSubtree();
                        do
                        {
                            subSubXmlRead.Read();
                            switch (subSubXmlRead.Name)
                            {
                            case "FilePath":                                            //"FilePath":
                                if (subSubXmlRead.Read() && (subSubXmlRead.NodeType == XmlNodeType.Text) && subSubXmlRead.HasValue && (subSubXmlRead.Depth == 3))
                                {
                                    _return.mFile.Add(new CProjectFile());
                                    string temp = subSubXmlRead.Value;
                                    temp = temp.Replace("$PROJ_DIR$\\", "");
                                    temp = temp.Replace("$PROJ_DIR$/", "");
                                    temp = temp.Replace("\\", "/");
                                    _return.mFile.Last().mName = temp;                                                    //subsubReader.Value;
                                }
                                break;

                            case "excluded":
                                if (subSubXmlRead.NodeType == XmlNodeType.Element)
                                {
                                    XmlReader subSubSubXmlRead = subSubXmlRead.ReadSubtree();
                                    do
                                    {
                                        subSubSubXmlRead.Read();
                                        if (subSubSubXmlRead.NodeType == XmlNodeType.Text)
                                        {
                                            _return.mFile.Last().mExclude.Add(subSubSubXmlRead.Value);
                                        }
                                    }while (!subSubSubXmlRead.EOF);
                                    subSubSubXmlRead.Close();
                                }
                                break;

                            default:
                                break;
                            }
                        }while (!subSubXmlRead.EOF);
                        subSubXmlRead.Close();
                        break;

                    case "excluded":
                        do
                        {
                            if (subXmlRead.Read() && (subXmlRead.NodeType == XmlNodeType.Text) && (subXmlRead.HasValue))
                            {
                                _return.mExclude.Add(subXmlRead.Value);
                            }
                        }while (xmlRead.Name != "excluded");
                        break;

                    default:
                        break;
                    }
                }
            }while (!subXmlRead.EOF);
            subXmlRead.Close();
            return(_return);
        }
Exemplo n.º 23
0
        /// <summary>
        /// IAR项目转VS工程
        /// </summary>
        /// <param name="projectName"></param>
        public bool IARToVisualStudio(string projectName)
        {
            //---判断文件是否存在
            if (!File.Exists(projectName))
            {
                return(false);
            }

            //---变量定义
            CProjectConfig       prjcfg   = new CProjectConfig();
            List <CProjectGroup> prjgroup = new List <CProjectGroup>();

            //---读取设备的文件---创建XmlReader对象的实例并将其返回给调用程序
            XmlReader xmlRead = XmlReader.Create(new StringReader(File.ReadAllText(projectName)));

            //---读取配置文件---不断读取直至找到指定的元素
            xmlRead.ReadToFollowing("configuration");
            do
            {
                //---读取子节点---而是用于创建 XML 元素周围的边界
                XmlReader subXmlRead = xmlRead.ReadSubtree();

                //---移动读取器至下一个匹配子孙元素的节点
                subXmlRead.ReadToDescendant("name");

                //---从流中读取下一个节点
                subXmlRead.Read();
                prjcfg.mName = subXmlRead.Value;

                //---获取设置
                subXmlRead.ReadToFollowing("settings");

                //---
                subXmlRead.ReadToDescendant("archiveVersion");

                //---从流中读取下一个节点
                subXmlRead.Read();

                //---判断数据值
                if (int.Parse(subXmlRead.Value) > 0)
                {
                    prjcfg.mCMSIS = true;
                }
                else
                {
                    prjcfg.mCMSIS = false;
                }

                //---读取下一个节点
                subXmlRead.ReadToFollowing("settings");
                prjcfg.mDefine = this.FindIARSubNodeValue(subXmlRead, "CCDefines");

                //---IAR中增加的信息
                prjcfg.mDefine.Add("_IAR_");
                prjcfg.mDefine.Add("__ICCARM__");
                prjcfg.mDefine.Add("_Pragma(x)=");
                prjcfg.mDefine.Add("__interrupt=");

                //prjcfg._define.Add("__packed=");
                //prjcfg._define.Add("__weak=");
                prjcfg.mDefine.Add("__packed=__attribute__((__packed__))");
                prjcfg.mDefine.Add("__weak=__attribute__((weak))");

                //prjcfg._define.Add("__attribute__((x))=");
                //prjcfg._define.Add("__STATIC_INLINE=");
                //---获取预包含的头文件
                prjcfg.mPreInclude = this.FindIARSubNodeValue(subXmlRead, "PreInclude");

                //---获取包含文件的路径
                prjcfg.mIncludePath = this.FindIARSubNodeValue(subXmlRead, "CCIncludePath2");
            }while (xmlRead.ReadToNextSibling("configuration"));
            xmlRead.Close();

            xmlRead = XmlReader.Create(new StringReader(File.ReadAllText(projectName)));

            //---读取配置文件---不断读取直至找到指定的元素
            //---获取组文件
            xmlRead.ReadToFollowing("group");
            do
            {
                CProjectGroup _return = FindIARSubNodeGroup(xmlRead, "group");
                if (_return != null)
                {
                    prjgroup.Add(_return);
                }
            }while (xmlRead.ReadToNextSibling("group"));
            xmlRead.Close();

            //---获取C文件
            xmlRead = XmlReader.Create(new StringReader(File.ReadAllText(projectName)));
            do
            {
                xmlRead.ReadToFollowing("file");
                if (xmlRead.Depth == 1 && xmlRead.NodeType == XmlNodeType.Element)
                {
                    CProjectGroup _return = FindIARSubNodeFile(xmlRead, "file");
                    if (_return != null)
                    {
                        prjgroup.Add(_return);
                    }
                }
            }while (!xmlRead.EOF);
            xmlRead.Close();

            //string configurations = "Debug" + "\", \"" + "Release";
            //StreamWriter file =new StreamWriter(Path.GetDirectoryName(projectName) + "\\IARToVS.lua");
            StreamWriter file = new StreamWriter(Path.GetDirectoryName(projectName) + "\\premake5.lua");

            //StreamWriter file = new StreamWriter(Directory.GetParent(Path.GetDirectoryName(projectName)).FullName + "\\premake5.lua");
            {
                //
                file.WriteLine("  solution \"" + Path.GetFileNameWithoutExtension(projectName) + "\"");
                file.WriteLine("  configurations { \"" + string.Join("\", \"", prjcfg.mName) + "\" }");

                //file.WriteLine("  configurations { \"" + configurations + "\" }");
                file.WriteLine("  project\"" + Path.GetFileNameWithoutExtension(projectName) + "\"");
                file.WriteLine("  kind \"ConsoleApp\"");
                file.WriteLine("  language \"C\"");
                file.WriteLine("  filter \"configurations:" + prjcfg.mName + "\"");
                file.WriteLine("  sysincludedirs  {\"$(VC_IncludePath)\"}");
                file.WriteLine("  defines { \"" + string.Join("\", \"", prjcfg.mDefine) + "\" }");
                file.WriteLine("  forceincludes { \"" + string.Join("\", \"", prjcfg.mPreInclude) + "\" }");
                file.WriteLine("  includedirs { \"" + string.Join("\", \"", prjcfg.mIncludePath) + "\" }");
                List <string> srcFiles = new CProjectGroup().GetFile(prjgroup, prjcfg.mName);
                file.WriteLine("  files { \"" + string.Join("\", \"", srcFiles) + "\" }");
                List <string> vGroups = new CProjectGroup().GetPath(prjgroup, prjcfg.mName);
                file.WriteLine("  vpaths {" + string.Join(" , ", vGroups) + " }");

                //file.Write(IncOverride);
                file.Close();
            }

            return(true);
        }
Exemplo n.º 24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="projectName"></param>
        /// <returns></returns>
        public bool MDKToVisualStudio(string projectName)
        {
            //---判断文件是否存在
            if (!File.Exists(projectName))
            {
                return(false);
            }

            //---变量定义
            CProjectConfig       prjcfg   = new CProjectConfig();
            List <CProjectGroup> prjgroup = new List <CProjectGroup>();

            //---读取设备的文件---创建XmlReader对象的实例并将其返回给调用程序
            XmlReader xmlRead = XmlReader.Create(new StringReader(File.ReadAllText(projectName)));

            //---读取配置文件---不断读取直至找到指定的元素
            xmlRead.ReadToFollowing("TargetOption");
            do
            {
                //---读取子节点---而是用于创建 XML 元素周围的边界
                XmlReader subXmlRead = xmlRead.ReadSubtree();

                //---移动读取器至下一个匹配子孙元素的节点
                subXmlRead.ReadToDescendant("OutputName");

                //---从流中读取下一个节点
                subXmlRead.Read();
                prjcfg.mName = subXmlRead.Value;

                //---获取设置
                subXmlRead.ReadToFollowing("Cads");

                //---
                subXmlRead.ReadToDescendant("Optim");

                //---从流中读取下一个节点
                subXmlRead.Read();

                //---判断数据值
                if (int.Parse(subXmlRead.Value) > 0)
                {
                    prjcfg.mCMSIS = true;
                }
                else
                {
                    prjcfg.mCMSIS = false;
                }

                //---读取下一个节点
                subXmlRead.ReadToFollowing("VariousControls");
                subXmlRead.ReadToFollowing("Define");
                prjcfg.mDefine = this.FindMDKSubNodeValue(subXmlRead.ReadSubtree());

                //----Keil工程的生成中借用了IAR的一些文件,用于避免一些数据类型报错的问题
                //---IAR中增加的信息
                prjcfg.mDefine.Add("_IAR_");
                prjcfg.mDefine.Add("__ICCARM__");
                prjcfg.mDefine.Add("__CC_ARM");
                prjcfg.mDefine.Add("_Pragma(x)=");
                prjcfg.mDefine.Add("__interrupt=");

                //prjcfg._define.Add("__packed=");
                //prjcfg._define.Add("__weak=");
                prjcfg.mDefine.Add("__packed=__attribute__((__packed__))");
                prjcfg.mDefine.Add("__weak=__attribute__((weak))");

                //prjcfg._define.Add("__attribute__((x))=");
                //prjcfg._define.Add("__STATIC_INLINE=");
                //---获取预包含的头文件
                //subXmlRead.ReadToFollowing("PreInclude");
                //prjcfg._preInclude = this.GetKeilSubNodeValue(subXmlRead,';');
                //---获取包含文件的路径
                subXmlRead.ReadToFollowing("IncludePath");
                prjcfg.mIncludePath = this.FindMDKSubNodeValue(subXmlRead.ReadSubtree(), ';');
            }while (xmlRead.ReadToNextSibling("TargetOption"));
            xmlRead.Close();

            xmlRead = XmlReader.Create(new StringReader(File.ReadAllText(projectName)));

            //---读取配置文件---不断读取直至找到指定的元素
            //---获取组文件

            do
            {
                xmlRead.ReadToFollowing("Group");
                if (xmlRead.Depth == 4 && xmlRead.NodeType == XmlNodeType.Element)
                {
                    CProjectGroup _return = FindMDKSubNodeGroup(xmlRead, "Group");
                    if (_return != null)
                    {
                        prjgroup.Add(_return);
                    }
                }
            }while (!xmlRead.EOF);
            xmlRead.Close();

            //---处理MDK文档
            //foreach (var temp in prjgroup)
            //{
            //	if (temp._name.Contains("MDK"))
            //	{
            //		temp._name = temp._name.Substring(temp._name.IndexOf("/MDK") + 1);
            //	}
            //	else
            //	{
            //		continue;
            //	}
            //}

            //---获取C文件
            xmlRead = XmlReader.Create(new StringReader(File.ReadAllText(projectName)));
            do
            {
                xmlRead.ReadToFollowing("Files");
                if (xmlRead.Depth == 3 && xmlRead.NodeType == XmlNodeType.Element)
                {
                    CProjectGroup _return = FindMDKSubNodeFile(xmlRead, "Files");
                    if (_return != null)
                    {
                        prjgroup.Add(_return);
                    }
                }
            }while (!xmlRead.EOF);
            xmlRead.Close();

            //---获取Keil的执行路径
            //---Keil5

            /*
             * string keilPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetProcessesByName("UV4")[0].MainModule.FileName);
             * if (keilPath == null)
             * {
             *      //---keil4
             *      keilPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetProcessesByName("UV3")[0].MainModule.FileName);
             * }
             * if (keilPath == null)
             * {
             *      //---keil2
             *      keilPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetProcessesByName("UV2")[0].MainModule.FileName);
             * }
             */
            string keilPath    = this.GetMDKPatch();
            string includedirs = string.Join("\", \"", prjcfg.mIncludePath);

            if (keilPath != null)
            {
                keilPath    += @"\RV31";
                keilPath     = keilPath.Replace("\\", "/");
                includedirs += "\", \"" + keilPath;
            }

            //string configurations = "Debug" + "\", \"" + "Release";
            //StreamWriter file = new StreamWriter(Path.GetDirectoryName(projectName) + "\\KeilToVS.lua");
            StreamWriter file = new StreamWriter(Path.GetDirectoryName(projectName) + "\\premake5.lua");

            //StreamWriter file = new StreamWriter(Directory.GetParent(Path.GetDirectoryName(projectName)).FullName + "\\premake5.lua");
            {
                //
                file.WriteLine("  solution \"" + Path.GetFileNameWithoutExtension(projectName) + "\"");
                file.WriteLine("  configurations { \"" + string.Join("\", \"", prjcfg.mName) + "\" }");

                //file.WriteLine("  configurations { \"" + configurations + "\" }");
                file.WriteLine("  project\"" + Path.GetFileNameWithoutExtension(projectName) + "\"");
                file.WriteLine("  kind \"ConsoleApp\"");
                file.WriteLine("  language \"C\"");
                file.WriteLine("  filter \"configurations:" + prjcfg.mName + "\"");
                file.WriteLine("  sysincludedirs  {\"$(VC_IncludePath)\"}");
                file.WriteLine("  defines { \"" + string.Join("\", \"", prjcfg.mDefine) + "\" }");
                file.WriteLine("  forceincludes { \"" + string.Join("\", \"", prjcfg.mPreInclude) + "\" }");
                file.WriteLine("  includedirs { \"" + includedirs + "\" }");
                List <string> srcFiles = new CProjectGroup().GetFile(prjgroup, prjcfg.mName);
                file.WriteLine("  files { \"" + string.Join("\", \"", srcFiles) + "\"}");
                List <string> vGroups = new CProjectGroup().GetPath(prjgroup, prjcfg.mName);
                file.WriteLine("  vpaths {" + string.Join(" , ", vGroups) + " }");

                //file.Write(IncOverride);
                file.Close();
            }

            return(true);
        }
Exemplo n.º 25
0
        public static void UpdateNewsFeed()
        {
            string newsFeedURL        = ConfigurationManager.AppSettings["BBCFeedURL"];
            string sharpCloudUsername = ConfigurationManager.AppSettings["SharpCloudUsername"];
            string sharpCloudPassword = ConfigurationManager.AppSettings["SharpCloudPassword"];
            string sharpCloudStoryID  = ConfigurationManager.AppSettings["SharpCloudStoryID"];

            //First, download the RSS feed data from the BBC News website
            XmlReader       reader = XmlReader.Create(newsFeedURL);
            SyndicationFeed feed   = SyndicationFeed.Load(reader);

            reader.Close();

            //Connect to SharpCloud, and load the story
            var   _client = new SharpCloudApi(sharpCloudUsername, sharpCloudPassword);
            Story rm      = _client.LoadStory(sharpCloudStoryID);

            //Ensure that the categories exist, if not then create them
            Category worldCat  = rm.Category_FindByName("World") ?? rm.Category_AddNew("World");
            Category busCat    = rm.Category_FindByName("Business") ?? rm.Category_AddNew("Business");
            Category sportCat  = rm.Category_FindByName("Sport") ?? rm.Category_AddNew("Sport");
            Category techCat   = rm.Category_FindByName("Technology") ?? rm.Category_AddNew("Technology");
            Category enterCat  = rm.Category_FindByName("Entertainment") ?? rm.Category_AddNew("Entertainment");
            Category healthCat = rm.Category_FindByName("Health") ?? rm.Category_AddNew("Health");
            Category otherCat  = rm.Category_FindByName("Other") ?? rm.Category_AddNew("Other");

            foreach (SyndicationItem newsItem in feed.Items)
            {
                //Try to find the item in the story using the news item id as the external id
                Item scItem = rm.Item_FindByExternalId(newsItem.Id);
                if (scItem == null)
                {
                    var    wc         = new WebClient();
                    byte[] imageBytes = null;
                    if (newsItem.ElementExtensions.Count > 0)
                    {
                        //download the news story image from the web
                        try
                        {
                            string imageURL = newsItem.ElementExtensions[1].GetObject <XElement>().LastAttribute.PreviousAttribute.Value;
                            imageBytes = wc.DownloadData(imageURL);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    String newsTitle = newsItem.Title.Text;
                    String summary   = newsItem.Summary.Text;

                    //create a new item in SharpCloud, with a name which is the title of the news story
                    scItem = rm.Item_AddNew(newsTitle);

                    //look at the URL of the news story to figure out which category it should be in
                    if (newsItem.Links[0].Uri.ToString().Contains("world"))
                    {
                        scItem.Category = worldCat;
                    }
                    else if (newsItem.Links[0].Uri.ToString().Contains("business"))
                    {
                        scItem.Category = busCat;
                    }
                    else if (newsItem.Links[0].Uri.ToString().Contains("sport"))
                    {
                        scItem.Category = sportCat;
                    }
                    else if (newsItem.Links[0].Uri.ToString().Contains("technology"))
                    {
                        scItem.Category = techCat;
                    }
                    else if (newsItem.Links[0].Uri.ToString().Contains("entertainment"))
                    {
                        scItem.Category = enterCat;
                    }
                    else if (newsItem.Links[0].Uri.ToString().Contains("health"))
                    {
                        scItem.Category = healthCat;
                    }
                    else
                    {
                        scItem.Category = otherCat;
                    }

                    scItem.Description = summary;
                    scItem.ExternalId  = newsItem.Id;
                    scItem.StartDate   = newsItem.PublishDate.DateTime;
                    scItem.Resource_AddName("BBC News URL", "Click here to view the news story on the web", newsItem.Links[0].Uri.ToString());

                    if (imageBytes != null)
                    {
                        scItem.ImageId = _client.UploadImageData(imageBytes, "", false);
                    }

                    try
                    {
                        //now look at the web page for the story and extract the main text
                        var getHtmlWeb = new HtmlWeb();
                        var document   = getHtmlWeb.Load(newsItem.Links[0].Uri.ToString());
                        if (document != null)
                        {
                            var node = document.DocumentNode.SelectSingleNode("//div[@class='story-body__inner']");
                            if (newsItem.Links[0].Uri.ToString().Contains("sport"))
                            {
                                node = document.DocumentNode.SelectSingleNode("//div[@class='article']");
                            }
                            if (node != null)
                            {
                                string newsText = "";
                                foreach (var child in node.ChildNodes)
                                {
                                    if (child.Name == "p")
                                    {
                                        if (newsText != "")
                                        {
                                            newsText += "<BR><BR>";
                                        }
                                        newsText += child.InnerHtml;
                                    }
                                    else if (child.Name == "span")
                                    {
                                        if (newsText != "")
                                        {
                                            newsText += "<BR><BR>";
                                        }
                                        newsText += "<b>" + child.InnerHtml + "</b>";
                                    }
                                }
                                //create a text panel on the item with the text of the story that we have from the web page
                                scItem.Panel_Add("News Detail", Panel.PanelType.RichText, newsText);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            //update the story description with the date/time
            rm.Description = string.Format("Last Updated (UTC): {0:ddd dd MMM yyyy HH:mm}", DateTime.UtcNow);

            //save the story to SharpCloud
            rm.Save();

            //now see if we need to delete any items
            bool deletedAnyItems = false;

            foreach (Item scnewsItem in rm.Items)
            {
                bool FoundItem = false;
                foreach (SyndicationItem newsItem in feed.Items)
                {
                    if (scnewsItem.ExternalId == newsItem.Id)
                    {
                        FoundItem = true;
                        break;
                    }
                }
                if (FoundItem == false)
                {
                    //delete it
                    rm.Item_DeleteById(scnewsItem.Id);
                    deletedAnyItems = true;
                }
            }
            if (deletedAnyItems)
            {
                rm.Save();
            }


            Environment.Exit(0);
        }
Exemplo n.º 26
0
 private void SaveMethod(common_method_node cfn)
 {
     if (!string.IsNullOrEmpty(cfn.documentation))
     {
         if (!cfn.documentation.Trim(' ', '\t').StartsWith("<summary>"))
         {
             xtw.WriteStartElement("member");
             xtw.WriteStartAttribute("name");
             if (is_assembly)
             {
                 if (!cfn.is_constructor)
                 {
                     xtw.WriteString("M:" + get_name(cfn.cont_type) + "." + cfn.name + GetGenericFlag(cfn) + GetParameters(cfn));
                 }
                 else
                 {
                     xtw.WriteString("M:" + get_name(cfn.cont_type) + ".#ctor" + GetGenericFlag(cfn) + GetParameters(cfn));
                 }
             }
             else
             {
                 if (!cfn.is_constructor)
                 {
                     xtw.WriteString("M:" + cfn.cont_type.name + "." + cfn.name + GetGenericFlag(cfn) + GetParameters(cfn));
                 }
                 else
                 {
                     xtw.WriteString("M:" + cfn.cont_type.name + ".#ctor" + GetGenericFlag(cfn) + GetParameters(cfn));
                 }
             }
             xtw.WriteEndAttribute();
             xtw.WriteStartElement("summary");
             xtw.WriteString(cfn.documentation);
             xtw.WriteEndElement();
             xtw.WriteEndElement();
         }
         else
         {
             string descr = null;
             if (is_assembly)
             {
                 if (!cfn.is_constructor)
                 {
                     descr = "M:" + get_name(cfn.cont_type) + "." + cfn.name + GetGenericFlag(cfn) + GetParameters(cfn);
                 }
                 else
                 {
                     descr = "M:" + get_name(cfn.cont_type) + ".#ctor" + GetGenericFlag(cfn) + GetParameters(cfn);
                 }
             }
             else
             {
                 if (!cfn.is_constructor)
                 {
                     descr = "M:" + cfn.cont_type.name + "." + cfn.name + GetGenericFlag(cfn) + GetParameters(cfn);
                 }
                 else
                 {
                     descr = "M:" + cfn.cont_type.name + ".#ctor" + GetGenericFlag(cfn) + GetParameters(cfn);
                 }
             }
             string       doc = string.Concat("<member name=\"" + descr + "\">", cfn.documentation, "</member>");
             StringReader sr  = new StringReader(doc);
             XmlReader    xr  = XmlTextReader.Create(sr);
             xr.Read();
             xtw.WriteNode(xr.ReadSubtree(), false);
             sr.Close();
             xr.Close();
         }
     }
 }
        /// <include file='doc\AssemblyInstaller.uex' path='docs/doc[@for="AssemblyInstaller.Uninstall"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override void Uninstall(IDictionary savedState)
        {
            PrintStartText(Res.GetString(Res.InstallActivityUninstalling));
            if (!initialized)
            {
                InitializeFromAssembly();
            }
            // Get the location of the InstallState file
            string filePath = GetInstallStatePath(Path);

            if (filePath != null && File.Exists(filePath))
            {
                FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
                xmlReaderSettings.CheckCharacters = false;
                xmlReaderSettings.CloseInput      = false; // We'll close the filestream ourselves

                XmlReader xmlFile = null;

                if (null != file)
                {
                    xmlFile = XmlReader.Create(file, xmlReaderSettings);
                }
                try {
                    if (null != xmlFile)
                    {
                        NetDataContractSerializer serializer = new NetDataContractSerializer();
                        savedState = (Hashtable)serializer.ReadObject(xmlFile);
                    }
                }
                catch {
                    Context.LogMessage(Res.GetString(Res.InstallSavedStateFileCorruptedWarning, Path, filePath));
                    savedState = null;
                }
                finally {
                    if (null != xmlFile)
                    {
                        xmlFile.Close();
                    }
                    if (null != file)
                    {
                        file.Close();
                    }
                }
            }
            else
            {
                savedState = null;
            }

            base.Uninstall(savedState);

            if (filePath != null && filePath.Length != 0)
            {
                try {
                    File.Delete(filePath);
                }
                catch {
                    //Throw an exception if we can't delete the file (but we were able to read from it)
                    throw new InvalidOperationException(Res.GetString(Res.InstallUnableDeleteFile, filePath));
                }
            }
        }
 public override void Close()
 {
     _reader.Close();
 }
Exemplo n.º 29
0
        /// <summary>
        /// 查找MDK节点文件
        /// </summary>
        /// <param name="xmlRead"></param>
        /// <param name="NodeName"></param>
        /// <returns></returns>
        public CProjectGroup FindMDKSubNodeFile(XmlReader xmlRead, string NodeName)
        {
            CProjectGroup _return = new CProjectGroup();

            //---是否位于结尾
            if (xmlRead.EOF)
            {
                return(null);
            }
            _return.mName = string.Empty;

            //---读取包含的文件信息
            do
            {
                //---Files后的节点深度是5
                if (xmlRead.Depth != 3)
                {
                    continue;
                }
                XmlReader subXmlRead = xmlRead.ReadSubtree();
                if (subXmlRead.Read() && (subXmlRead.NodeType == XmlNodeType.Element))
                {
                    //---读取当前节点以及子节点
                    XmlReader subsubXmlRead = subXmlRead.ReadSubtree();
                    do
                    {
                        subsubXmlRead.Read();
                        switch (subsubXmlRead.Name)
                        {
                        case "FileName":
                            subsubXmlRead.Read();
                            if (/*subsubXmlRead.Read() && */ (subsubXmlRead.NodeType == XmlNodeType.Text) && (subsubXmlRead.HasValue) && (subsubXmlRead.Depth == 3))
                            {
                                _return.mFile.Add(new CProjectFile());
                                string temp = subsubXmlRead.Value;
                                temp = temp.Replace("$PROJ_DIR$\\", "");
                                temp = temp.Replace("$PROJ_DIR$/", "");
                                temp = temp.Replace("\\", "/");
                                _return.mFile.Last().mName = temp;
                            }
                            break;

                        case "excluded":
                            if (subsubXmlRead.NodeType == XmlNodeType.Element)
                            {
                                XmlReader subSubSubXmlRead = subsubXmlRead.ReadSubtree();
                                do
                                {
                                    if (subSubSubXmlRead.Read() && (subSubSubXmlRead.NodeType == XmlNodeType.Text) && (subSubSubXmlRead.HasValue))
                                    {
                                        _return.mFile.Last().mExclude.Add(subSubSubXmlRead.Value);
                                    }
                                }while (!subSubSubXmlRead.EOF);
                                subSubSubXmlRead.Close();
                            }
                            break;
                        }
                    }while (!subsubXmlRead.EOF);
                    subsubXmlRead.Close();
                }
            }while (xmlRead.ReadToNextSibling(NodeName));
            return(_return);
        }
Exemplo n.º 30
0
        public PlayerData(string path)
        {
            ServerPlayer.ResetUUID();
            if (File.Exists(path))
            {
                XmlReaderSettings settings = new XmlReaderSettings {
                    IgnoreComments = true
                };
                //忽略文档里面的注释
                XmlDocument xmlDoc = new XmlDocument();
                XmlReader   reader = XmlReader.Create(path, settings);
                xmlDoc.Load(reader);
                XmlNode xn   = xmlDoc.SelectSingleNode("Players");
                var     list = xn.ChildNodes;
                Dictionary <string, Mod> modTable = new Dictionary <string, Mod>();
                foreach (var mod in ModLoader.LoadedMods)
                {
                    modTable.Add(mod.Name, mod);
                }
                foreach (var node in list)
                {
                    XmlElement   pData  = (XmlElement)node;
                    ServerPlayer player = new ServerPlayer();
                    var          info   = pData.ChildNodes;
                    int          i      = 0;
                    player.Name = pData.GetAttribute("name");
                    player.UUID = int.Parse(pData.GetAttribute("uuid"));
                    try
                    {
                        player.PermissionGroup = ServerSideCharacter.GroupManager.Groups[pData.GetAttribute("group")];
                    }
                    catch
                    {
                        player.PermissionGroup = ServerSideCharacter.GroupManager.Groups["default"];
                    }
                    foreach (var pair in ModDataHooks.InterpretPlayerStringTable)
                    {
                        pair.Value(pData.GetAttribute(pair.Key), player);
                    }
                    player.HasPassword = Convert.ToBoolean(ReadNext(info, ref i));
                    player.Password    = ReadNext(info, ref i);
                    player.LifeMax     = Convert.ToInt32(ReadNext(info, ref i));
                    player.StatLife    = Convert.ToInt32(ReadNext(info, ref i));
                    player.ManaMax     = Convert.ToInt32(ReadNext(info, ref i));
                    player.StatMana    = Convert.ToInt32(ReadNext(info, ref i));
                    for (int id = 0; id < player.inventory.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.inventory);
                        //player.inventory[id].Prefix(Convert.ToByte((info.Item(i - 1) as XmlElement).GetAttribute("prefix")));
                        //player.inventory[id].stack =
                        //	Convert.ToInt32((info.Item(i - 1) as XmlElement).GetAttribute("stack"));
                    }
                    for (int id = 0; id < player.armor.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.armor);
                    }
                    for (int id = 0; id < player.dye.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.dye);
                    }
                    for (int id = 0; id < player.miscEquips.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.miscEquips);
                    }
                    for (int id = 0; id < player.miscDye.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.miscDye);
                    }
                    for (int id = 0; id < player.bank.item.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.bank.item);
                    }
                    for (int id = 0; id < player.bank2.item.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.bank2.item);
                    }
                    for (int id = 0; id < player.bank3.item.Length; id++)
                    {
                        TryReadItemInfo(modTable, info, player, ref i, id, ref player.bank3.item);
                    }

                    Data.Add(player.Name, player);
                    ServerPlayer.IncreaseUUID();
                }
                ServerSideCharacter.MainWriter = new XMLWriter(path);
                reader.Close();
            }
            else
            {
                XMLWriter writer = new XMLWriter(path);
                writer.Create();
                ServerSideCharacter.MainWriter = writer;
            }
        }
Exemplo n.º 31
0
 protected override void CloseReader()
 {
     XmlReader?.Close();
 }
Exemplo n.º 32
0
        /// <summary>Performs validation of the document using the received reader.</summary>
        /// <remarks>Where the actual work takes place</remarks>
        /// <param name="reader">The reader pointing to the document to validate.</param>
        /// <exception cref="ValidationException">
        /// The document is invalid with respect to the loaded schemas.
        /// </exception>
        /// <returns>The loaded <see cref="IXPathNavigable"/> instance.</returns>
        public IXPathNavigable Validate(XmlReader reader)
        {
            try
            {
                _errors = new StringBuilder();

                // Temporary variables to hold error flags and messages.
                bool          hasxml    = false;
                StringBuilder xmlerrors = null;
                bool          hassch    = false;
                StringBuilder scherrors = null;

                var settings = new XmlReaderSettings()
                {
                    ValidationType = ValidationType.Schema,
                };
                settings.ValidationEventHandler += new ValidationEventHandler(OnValidation);

                foreach (XmlSchema xsd in _xmlschemas.Schemas())
                {
                    settings.Schemas.Add(xsd);
                }

                var r = XmlReader.Create(reader, settings);


                IXPathNavigable navdoc;
                XPathNavigator  nav;

                if (_navtype == NavigableType.XmlDocument)
                {
                    navdoc = new XmlDocument(r.NameTable);
                    ((XmlDocument)navdoc).Load(r);
                }
                else
                {
                    navdoc = new XPathDocument(r);
                }

                nav = navdoc.CreateNavigator();

                if (_haserrors)
                {
                    _evaluationctx.Formatter.Format(r.Settings.Schemas, _errors);
                    _evaluationctx.Formatter.Format(r, _errors);
                    hasxml    = true;
                    xmlerrors = _errors;
                }

                _evaluationctx.Source = nav;

                // Reset shared variables
                _haserrors = false;
                _errors    = new StringBuilder();

                foreach (Schema sch in _schematrons)
                {
                    PerformValidation(sch);
                    if (_evaluationctx.HasErrors)
                    {
                        _haserrors = true;
                        _errors.Append(_evaluationctx.Messages.ToString());
                    }
                }

                if (_haserrors)
                {
                    _evaluationctx.Formatter.Format(_schematrons, _errors);
                    hassch    = true;
                    scherrors = _errors;
                }

                _errors = new StringBuilder();
                if (hasxml)
                {
                    _errors.Append(xmlerrors.ToString());
                }
                if (hassch)
                {
                    _errors.Append(scherrors.ToString());
                }

                if (hasxml || hassch)
                {
                    _evaluationctx.Formatter.Format(_errors);
                    throw new ValidationException(_errors.ToString());
                }

                return(navdoc);
            }
            catch
            {
                // Rethrow.
                throw;
            }
            finally
            {
                reader.Close();
            }
        }