public IEnumerable<DetailedQuoteQueryResultModel> RetrieveStockDetailedInfos(List<string> codeList)
      {
         string urlPrefix = @"https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol in (";
         string codes = string.Join(@""",""", codeList);
         string urlSuffix = ")&env=store://datatables.org/alltableswithkeys";
         string url = string.Format(@"{0}""{1}""{2}", urlPrefix, codes, urlSuffix);
         HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
         webReq.Method = "GET";
         HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();

         XmlTextReader reader = new XmlTextReader(webResponse.GetResponseStream());
         XmlSerializer serializer = new XmlSerializer(typeof(DetailedQuoteQueryResultModel));

         var detailedList = new List<Models.DetailedQuoteQueryResultModel>();
         while(reader.Read())
         {
            if(reader.Name == "quote" && reader.IsStartElement())
            {
               DetailedQuoteQueryResultModel item = (DetailedQuoteQueryResultModel)serializer.Deserialize(reader.ReadSubtree());
               detailedList.Add(item);
            }
         }
         reader.Close();
         return detailedList;
      }
Example #2
0
        public static string ExtractQuery(string fileName, TextWriter errorlogger)
        {
            try
            {
                string data = File.ReadAllText(fileName);
                XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.None);
                Stream xmlFragment = new MemoryStream(Encoding.UTF8.GetBytes(data));
                XmlTextReader reader = new XmlTextReader(xmlFragment, XmlNodeType.Element, context);
                reader.MoveToContent();
                if (reader.NodeType == XmlNodeType.Text)
                {
                    return data;
                }
                XmlReader reader2 = reader.ReadSubtree();
                StringBuilder output = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(output))
                {
                    writer.WriteNode(reader2, true);
                }

                StringReader reader3 = new StringReader(data);
                for (int i = 0; i < reader.LineNumber; i++)
                {
                    reader3.ReadLine();
                }
                return reader3.ReadToEnd().Trim();
            }
            catch (Exception ex)
            {
                errorlogger.WriteLine(ex.Message);
                errorlogger.WriteLine(ex.StackTrace);
            }

            return string.Format("//Error loading the file - {0} .The the linq file might be a linqpad expression which is not supported in the viewer currently." ,fileName);
        }
        /// <summary>
        /// Main function that retrieves the list from API, including paging
        /// </summary>
        /// <param name="url">URL of API request</param>
        /// <param name="haveSoFar">Number of pages already retrieved, for upper limit control</param>
        /// <returns>List of pages</returns>
        public List<Article> ApiMakeList(string url, int haveSoFar)
        {
            // TODO: error handling
            List<Article> list = new List<Article>();
            string postfix = "";

            string newUrl = url;

            while (list.Count + haveSoFar < Limit)
            {
                string text = Tools.GetHTML(newUrl + postfix);

                XmlTextReader xml = new XmlTextReader(new StringReader(text));
                xml.MoveToContent();
                postfix = "";

                while (xml.Read())
                {
                    if (xml.Name == "query-continue")
                    {
                        XmlReader r = xml.ReadSubtree();

                        r.Read();

                        while (r.Read())
                        {
                            if (!r.IsStartElement()) continue;
                            if (!r.MoveToFirstAttribute())
                                throw new FormatException("Malformed element '" + r.Name + "' in <query-continue>");
                            postfix += "&" + r.Name + "=" + HttpUtility.UrlEncode(r.Value);
                        }
                    }
                    else if (PageElements.Contains(xml.Name) && xml.IsStartElement())
                    {
                        if (!EvaluateXmlElement(xml))
                            continue;

                        //int ns = -1;
                        //int.TryParse(xml.GetAttribute("ns"), out ns);
                        string name = xml.GetAttribute("title");

                        if (string.IsNullOrEmpty(name))
                        {
                            System.Windows.Forms.MessageBox.Show(xml.ReadInnerXml());
                            break;
                        }

                        // HACK: commented out until we make AWB always load namespaces from the wiki,
                        // to avoid problems with unknown namespace
                        //if (ns >= 0) list.Add(new Article(name, ns));
                        //else
                        list.Add(new Article(name));
                    }

                }
                if (string.IsNullOrEmpty(postfix)) break;
            }

            return list;
        }
        /// <summary> Static class is used to read the configuration file defining oai-pmh elements and metadata prefixes </summary>
        /// <param name="ConfigFile"> Path and name of the configuration XML file to read </param>
        /// <param name="SystemName"> System name from the system-wide settings, used as a default name for OAI-PMH </param>
        /// <param name="SystemAbbreviation"> System identifyer from the system-wide settings, used as a default identifier for OAI-PMH </param>
        /// <param name="SystemEmail"> System email(s) from the system-wide settings, used as default admin email(s) for OAI-PMH </param>
        /// <returns> Fully configured OAI-PMH configuration object </returns>
        public static OAI_PMH_Configuration Read_Config(string ConfigFile, string SystemName, string SystemAbbreviation, string SystemEmail )
        {
            // Create config value and set some default values
            OAI_PMH_Configuration returnValue = new OAI_PMH_Configuration
            {
                Identifier = SystemAbbreviation,
                Name = SystemName,
                Identifier_Base = "oai:" + SystemAbbreviation.ToLower() + ":"
            };
            returnValue.Add_Admin_Email(SystemEmail);

            // Streams used for reading
            Stream readerStream = null;
            XmlTextReader readerXml = null;

            try
            {
                // Open a link to the file
                readerStream = new FileStream(ConfigFile, FileMode.Open, FileAccess.Read);

                // Open a XML reader connected to the file
                readerXml = new XmlTextReader(readerStream);

                while (readerXml.Read())
                {
                    if (readerXml.NodeType == XmlNodeType.Element)
                    {
                        switch (readerXml.Name.ToLower())
                        {
                            case "oai-pmh":
                                read_oai_details(readerXml.ReadSubtree(), returnValue);
                                break;
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                returnValue.Error = ee.Message;
            }
            finally
            {
                if (readerXml != null)
                {
                    readerXml.Close();
                }
                if (readerStream != null)
                {
                    readerStream.Close();
                }
            }

            return returnValue;
        }
Example #5
0
        public static Dictionary<String, Brute> Read()
        {
            Dictionary<String, Brute> brutes = new Dictionary<String, Brute>();
            Console.WriteLine(File.Exists("Users.xml"));
            if(File.Exists("Users.xml"))
            {
                XmlTextReader xml = new XmlTextReader("Users.xml");
                while (xml.Read())
                {
                    if (xml.Name.Equals("Brute") && (xml.NodeType == XmlNodeType.Element))
                    {
                        xml.Read();
                        String name = xml.ReadElementString("Name");
                        short level = Convert.ToInt16(xml.ReadElementString("Level"));
                        short life = Convert.ToInt16(xml.ReadElementString("Life"));
                        short strength = Convert.ToInt16(xml.ReadElementString("Strength"));
                        short agility = Convert.ToInt16(xml.ReadElementString("Agility"));
                        short speed = Convert.ToInt16(xml.ReadElementString("Speed"));
                        int image = Convert.ToInt32(xml.ReadElementString("Image"));
                        Brute brute = new Brute(name, level, life, strength, agility, speed, image);
                        if(xml.Name.Equals("BonusList") && (xml.NodeType == XmlNodeType.Element))
                        {
                            XmlReader inner = xml.ReadSubtree();
                            while (inner.Read())
                            {
                                if (inner.Name.Equals("Bonus") && (xml.NodeType == XmlNodeType.Element))
                                {
                                    xml.Read();
                                    name = xml.ReadElementString("Name");
                                    life = Convert.ToInt16(xml.ReadElementString("Life"));
                                    strength = Convert.ToInt16(xml.ReadElementString("Strength"));
                                    agility = Convert.ToInt16(xml.ReadElementString("Agility"));
                                    speed = Convert.ToInt16(xml.ReadElementString("Speed"));
                                    image = Convert.ToInt32(xml.ReadElementString("Image"));
                                    brute.BonusList.Add(new Bonus(name, life, strength, agility, speed, image));
                                }
                            }
                            inner.Close();
                            Console.WriteLine(brute.ToString());
                        }
                        brutes.Add(brute.Name, brute);
                    }

                }
                xml.Close();
            }
            return brutes;
        }
        /// <summary> Static class is used to read the configuration file defining microservice endpoints </summary>
        /// <param name="ConfigFile"> Path and name of the configuration XML file to read </param>
        /// <param name="SystemBaseUrl"> System base URL </param>
        /// <returns> Fully configured microservices configuration object </returns>
        public static MicroservicesClient_Configuration Read_Config(string ConfigFile, string SystemBaseUrl )
        {
            MicroservicesClient_Configuration returnValue = new MicroservicesClient_Configuration();

            // Streams used for reading
            Stream readerStream = null;
            XmlTextReader readerXml = null;

            try
            {
                // Open a link to the file
                readerStream = new FileStream(ConfigFile, FileMode.Open, FileAccess.Read);

                // Open a XML reader connected to the file
                readerXml = new XmlTextReader(readerStream);

                while (readerXml.Read())
                {
                    if (readerXml.NodeType == XmlNodeType.Element)
                    {
                        switch (readerXml.Name.ToLower())
                        {
                            case "microservicesclient":
                                read_microservices_client_details(readerXml.ReadSubtree(), returnValue, SystemBaseUrl);
                                break;
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                returnValue.Error = ee.Message;
            }
            finally
            {
                if (readerXml != null)
                {
                    readerXml.Close();
                }
                if (readerStream != null)
                {
                    readerStream.Close();
                }
            }

            return returnValue;
        }
        /// <summary> Read the contact form system configuration file from within the config subfolder on the web app </summary>
        /// <param name="ConfigFile"> Complete path and name of the configuration file to read </param>
        /// <returns> Built configuration object for the contact form </returns>
        public static ContactForm_Configuration Read_Config(string ConfigFile)
        {
            ContactForm_Configuration returnValue = new ContactForm_Configuration();

            // Streams used for reading
            Stream readerStream = null;
            XmlTextReader readerXml = null;

            try
            {
                // Open a link to the file
                readerStream = new FileStream(ConfigFile, FileMode.Open, FileAccess.Read);

                // Open a XML reader connected to the file
                readerXml = new XmlTextReader(readerStream);

                while (readerXml.Read())
                {
                    if (readerXml.NodeType == XmlNodeType.Element)
                    {
                        switch (readerXml.Name.ToLower())
                        {
                            case "contactform":
                                Read_ContactForm_Details(readerXml.ReadSubtree(), returnValue);
                                break;
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                returnValue.Error = ee.Message;
            }
            finally
            {
                if (readerXml != null)
                {
                    readerXml.Close();
                }
                if (readerStream != null)
                {
                    readerStream.Close();
                }
            }

            return returnValue;
        }
        public static Location GetLocationData(string street,
            string zip,
            string city,
            string state,
            string country)
        {
            // Use an invariant culture for formatting numbers.
             NumberFormatInfo numberFormat = new NumberFormatInfo();
             Location loc = new Location();
             XmlTextReader xmlReader = null;

             try
             {
             HttpWebRequest webRequest = GetWebRequest(street, zip, city, state);
             HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

             using (xmlReader = new XmlTextReader(response.GetResponseStream()))
             {
             while (xmlReader.Read())
             {
                 if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "Result")
                 {
                     XmlReader resultReader = xmlReader.ReadSubtree();
                     while (resultReader.Read())
                     {
                         if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "Latitude")
                             loc.Latitude = Convert.ToDouble(xmlReader.ReadInnerXml(), numberFormat);

                         if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "Longitude")
                         {
                             loc.Longitude = Convert.ToDouble(xmlReader.ReadInnerXml(), numberFormat);
                             break;
                         }
                     }
                 }
             }
             }
             }
             finally
             {
               if (xmlReader != null)
            xmlReader.Close();
             }

              // Return the location data.
              return loc;
        }
Example #9
0
        public MaterialReader()
        {
            try
            {
                XmlTextReader reader = new XmlTextReader(Application.StartupPath + "\\config\\materials.xml");
                reader.MoveToContent();

                while (reader.ReadToFollowing("material"))
                {
                    ProcessItem(reader.ReadSubtree());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #10
0
        public string GetBody()
        {
            using (var reader = new XmlTextReader(new StringReader(Body)))
            {
                reader.DtdProcessing = DtdProcessing.Ignore;
                reader.WhitespaceHandling = WhitespaceHandling.None;

                reader.ReadToFollowing("body");
                var builder = new StringBuilder();
                var sub = reader.ReadSubtree();
                while (sub.Read())
                {
                    builder.Append(sub.ReadInnerXml());
                }
                return builder.ToString();
            }
        }
Example #11
0
 public static void AddEntryIntoWebConfig(String webConfigFilePath, String path, SPWebConfigModification.SPWebConfigModificationType type, String value)
 {
     XmlTextReader reader = null;
     XmlNode compareNode = null;
     string[] nodePath = null;
     try
     {
         reader = new XmlTextReader(webConfigFilePath);
         nodePath = path.Split('/');
         var notificationDataXmlDocument = new XmlDocument();
         notificationDataXmlDocument.LoadXml(value);
         compareNode = notificationDataXmlDocument.DocumentElement;
         _nodeAttributesFound = new List<bool>();
         if (compareNode != null)
             if (compareNode.Attributes != null)
     #pragma warning disable 168
                 foreach (object t in compareNode.Attributes)
     #pragma warning restore 168
                     _nodeAttributesFound.Add(false);
     }
     catch (Exception)
     {
         _isValueExists = false;
     }
     if (nodePath != null)
         if (nodePath.GetUpperBound(0) > -1 && compareNode != null)
         {
             while (reader.NodeType != XmlNodeType.Element)
                 reader.Read();
             _isValueExists = false;
             IsXmlEntryFoundInWebConfig(path, reader.ReadSubtree(), 0, compareNode);
             try
             {
                 reader.Close();
             }
             catch
             {
                 reader.Close();
             }
             if (_isValueExists == false)
                 AddEntrytoWebConfig(webConfigFilePath, path, value);
         }
 }
Example #12
0
 void readObjectFromXML()
 {
     using (XmlTextReader reader = new XmlTextReader("map.xml"))
     {
         while (reader.Read())
         {
             if (reader.NodeType == XmlNodeType.Element)
             {
                 switch (reader.Name)
                 {
                     case "Player":
                         {
                             createPlayer(reader.ReadSubtree());
                         }
                         break;
                 }
             }
         }
     }
 }
Example #13
0
		public void Load ()
		{
			if (!File.Exists (_path))
				return;
			_privateKeys.Clear ();
			_publicKeys.Clear ();
			using (XmlTextReader reader = new XmlTextReader (_path)) {
				while (reader.Read ()) {
					if (!reader.IsStartElement ())
						continue;
					if (reader.Name != "private" && reader.Name != "public")
						continue;
					bool isPrivate = (reader.Name == "private");
					string name = null, key = null;
					XmlReader sub_reader = reader.ReadSubtree ();
					while (sub_reader.Read ()) {
						if (!sub_reader.IsStartElement ()) continue;
						switch (sub_reader.Name) {
							case "name":
								name = sub_reader.ReadElementString ();
								break;
							case "key":
								key = sub_reader.ReadElementString ();
								break;
						}
					}
					if (name != null && key != null) {
						if (isPrivate)
							_privateKeys.Add (new KeyEntry (name, key));
						else
							_publicKeys.Add (new KeyEntry (name, key));
					}
				}
			}

			if (_privateKeys.Count > 0)
				RaisePrivateKeyUpdatedEvent ();
			if (_publicKeys.Count > 0)
				RaisePublicKeyUpdatedEvent ();
		}
Example #14
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length >= 4 && args[0] == "Define")
                {
                    var list = new List<string>();

                    using (FileStream inStream = new FileStream(args[3], FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    {
                        for (;;)
                        {
                            string line = reader.ReadLine();
                            if (line == null) break;

                            list.Add(line);
                        }
                    }

                    bool flag = (args[1] == "on");

                    foreach (var item in list)
                    {
                        Program.Define(item, flag, args[2]);
                    }
                }
                else if (args.Length >= 3 && args[0] == "Increment")
                {
                    string projectFilePath = args[1];

                    string baseDirectory = Path.GetDirectoryName(projectFilePath);
                    var filePaths = new List<string>();

                    using (Stream stream = new FileStream(projectFilePath, FileMode.Open))
                    using (XmlTextReader xml = new XmlTextReader(stream))
                    {
                        while (xml.Read())
                        {
                            if (xml.NodeType == XmlNodeType.Element)
                            {
                                if (xml.LocalName == "Compile")
                                {
                                    var path = xml.GetAttribute("Include");
                                    string dependentUponBaseDirectory = Path.GetDirectoryName(path);
                                    filePaths.Add(Path.Combine(baseDirectory, path).Replace('\\', '/'));

                                    using (var xmlSubtree = xml.ReadSubtree())
                                    {
                                        while (xmlSubtree.Read())
                                        {
                                            if (xmlSubtree.NodeType == XmlNodeType.Element)
                                            {
                                                if (xmlSubtree.LocalName == "DependentUpon")
                                                {
                                                    filePaths.Add(Path.Combine(baseDirectory, dependentUponBaseDirectory, xml.ReadString()).Replace('\\', '/'));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    string assemblyInfoFilePath = Path.Combine(baseDirectory, args[2]).Replace('\\', '/');

                    filePaths.Remove(assemblyInfoFilePath);
                    filePaths.Sort();

                    var regex = new Regex(@"^( *)\[( *)assembly( *):( *)AssemblyVersion( *)\(( *)" + "\"" + @"(\d*)\.(\d*)\.(\d*)\.(\d*)" + "\"" + @"( *)\)( *)\](.*)$");
                    byte[] hash = Program.GetHash(filePaths);

                    using (var readerStream = new StreamReader(assemblyInfoFilePath))
                    using (var writerStream = new StreamWriter(assemblyInfoFilePath + "~", false, Encoding.UTF8))
                    {
                        for (;;)
                        {
                            var line = readerStream.ReadLine();
                            if (line == null) break;

                            var match = regex.Match(line);

                            if (match.Success)
                            {
                                int i = int.Parse(match.Groups[10].Value);

                                if (match.Groups[13].Value.TrimStart().StartsWith("//"))
                                {
                                    if (!Unsafe.Equals(hash, NetworkConverter.FromBase64UrlString(match.Groups[13].Value.TrimStart().Remove(0, 2).Trim())))
                                    {
                                        i++;
                                    }
                                }

                                writerStream.WriteLine(
                                string.Format(
                                    "{0}[{1}assembly{2}:{3}AssemblyVersion{4}({5}\"{6}.{7}.{8}.{9}\"{10}){11}]{12}",
                                    match.Groups[1].Value,
                                    match.Groups[2].Value,
                                    match.Groups[3].Value,
                                    match.Groups[4].Value,
                                    match.Groups[5].Value,
                                    match.Groups[6].Value,
                                    match.Groups[7].Value,
                                    match.Groups[8].Value,
                                    match.Groups[9].Value,
                                    i.ToString(),
                                    match.Groups[11].Value,
                                    match.Groups[12].Value,
                                    " // " + NetworkConverter.ToBase64UrlString(hash)));
                            }
                            else
                            {
                                writerStream.WriteLine(line);
                            }
                        }
                    }

                    File.Delete(assemblyInfoFilePath);
                    File.Move(assemblyInfoFilePath + "~", assemblyInfoFilePath);
                }
                else if (args.Length >= 1 && args[0] == "Settings")
                {
                    string settingsPath = args[1];

                    var builder = new StringBuilder();
                    var builder2 = new StringBuilder();
                    var regex = new Regex("new Library\\.Configuration\\.SettingContent<(.*)>\\(\\) { Name = \"(.*)\", Value = .* },(.*)$");

                    using (FileStream inStream = new FileStream(settingsPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    {
                        bool isRead = false;

                        for (;;)
                        {
                            string line = reader.ReadLine();
                            if (line == null) break;

                            if (line.Contains("new Library.Configuration.SettingContent"))
                            {
                                builder2.AppendLine(line);
                                isRead = true;
                            }
                            else if (isRead && line.Trim() == "")
                            {
                                builder2.AppendLine("");
                            }
                            else if (isRead)
                            {
                                break;
                            }
                        }
                    }

                    foreach (var item in builder2.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None))
                    {
                        if (item.Trim() == "")
                        {
                            builder.AppendLine("");
                        }
                        else
                        {
                            Match match = regex.Match(item);

                            var attributeBuilder = new StringBuilder();

                            {
                                var text = match.Groups[3].Value;

                                if (!string.IsNullOrWhiteSpace(text))
                                {
                                    text = text.Trim().TrimStart('/').Replace("]", "]\n");

                                    foreach (var line in text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(n => n.Trim()))
                                    {
                                        attributeBuilder.AppendLine("        " + line);
                                    }
                                }
                            }

                            builder.AppendLine(attributeBuilder.ToString() + string.Format(
                                "        public {0} {1} {{ get {{ return ({0})this[\"{1}\"]; }} set {{ this[\"{1}\"] = value; }} }}",
                                match.Groups[1].Value,
                                match.Groups[2].Value));
                        }
                    }

                    using (FileStream inStream = new FileStream(settingsPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    using (FileStream outStream = new FileStream(settingsPath + ".tmp", FileMode.Create))
                    using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8))
                    {
                        bool isRegion = false;
                        bool isRewrite = false;

                        for (;;)
                        {
                            string line = reader.ReadLine();
                            if (line == null) break;

                            if (!isRewrite)
                            {
                                if (line.Contains("#region Property"))
                                {
                                    isRegion = true;
                                }
                                else if (line.Contains("#endregion"))
                                {
                                    writer.Write("        #region Property\r\n\r\n" +
                                        builder.ToString().Trim('\r', '\n') +
                                        "\r\n\r\n");

                                    isRegion = false;
                                    isRewrite = true;
                                }
                            }

                            if (!isRegion)
                            {
                                writer.WriteLine(line);
                            }
                        }
                    }

                    File.Delete(settingsPath);
                    File.Move(settingsPath + ".tmp", settingsPath);
                }
                else if (args.Length >= 3 && args[0] == "Languages")
                {
                    string languageManagerPath = args[1];
                    string languageXmlPath = Path.Combine(args[2], "English.xml");
                    var builder = new StringBuilder();

                    using (FileStream stream = new FileStream(languageXmlPath, FileMode.Open))
                    using (XmlTextReader xml = new XmlTextReader(stream))
                    {
                        try
                        {
                            while (xml.Read())
                            {
                                if (xml.NodeType == XmlNodeType.Element)
                                {
                                    if (xml.LocalName == "Translate")
                                    {
                                        builder.AppendLine(string.Format(
                                            "        public string {0} {{ get {{ lock (this.ThisLock) {{ return this.Translate(\"{0}\"); }} }} }}",
                                            xml.GetAttribute("Key")));
                                    }
                                }
                                else if (xml.NodeType == XmlNodeType.Whitespace)
                                {
                                    if (xml.Value.StartsWith("\r\n\r\n"))
                                    {
                                        builder.AppendLine("");
                                    }
                                }
                            }
                        }
                        catch (XmlException)
                        {

                        }
                    }

                    using (FileStream inStream = new FileStream(languageManagerPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    using (FileStream outStream = new FileStream(languageManagerPath + ".tmp", FileMode.Create))
                    using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8))
                    {
                        bool isRegion = false;
                        bool isRewrite = false;

                        for (;;)
                        {
                            string line = reader.ReadLine();
                            if (line == null) break;

                            if (!isRewrite)
                            {
                                if (line.Contains("#region Property"))
                                {
                                    isRegion = true;
                                }
                                else if (line.Contains("#endregion"))
                                {
                                    writer.Write("        #region Property\r\n\r\n" +
                                        builder.ToString().Trim('\r', '\n') +
                                        "\r\n\r\n");

                                    isRegion = false;
                                    isRewrite = true;
                                }
                            }

                            if (!isRegion)
                            {
                                writer.WriteLine(line);
                            }
                        }
                    }

                    File.Delete(languageManagerPath);
                    File.Move(languageManagerPath + ".tmp", languageManagerPath);

                    Program.LanguageSetting(languageXmlPath);
                }
                else if (args.Length >= 2 && args[0] == "Sync")
                {
                    string configPath = args[1];

                    var headerSettings = new Dictionary<string, List<string>>();

                    int wordCount = -1;

                    using (FileStream configStream = new FileStream(configPath, FileMode.Open))
                    using (StreamReader configReader = new StreamReader(configStream))
                    {
                        for (;;)
                        {
                            string line = configReader.ReadLine();
                            if (string.IsNullOrEmpty(line)) break;

                            var list = Program.Decode(line).ToList();
                            headerSettings[list[0]] = list.Skip(1).ToList();

                            // Check
                            if (wordCount == -1) wordCount = list.Count - 1;
                            else if (wordCount != list.Count - 1) throw new Exception("WordCount");
                        }

                        for (;;)
                        {
                            var pathSettings = new Dictionary<string, string>();

                            for (;;)
                            {
                                string line = configReader.ReadLine();
                                if (string.IsNullOrEmpty(line)) break;

                                var list = Program.Decode(line).ToList();
                                pathSettings[list[1]] = list[0];
                            }

                            var sortedPathSettings = pathSettings.ToList();
                            sortedPathSettings.Sort((x, y) =>
                            {
                                return new FileInfo(y.Key).LastWriteTimeUtc.CompareTo(new FileInfo(x.Key).LastWriteTimeUtc);
                            });

                            var sourceSettings = sortedPathSettings[0];

                            foreach (var targetSettings in sortedPathSettings.Skip(1))
                            {
                                if (new FileInfo(targetSettings.Key).LastWriteTimeUtc == new FileInfo(sourceSettings.Key).LastWriteTimeUtc) continue;

                                using (FileStream sourceStream = new FileStream(sourceSettings.Key, FileMode.Open))
                                using (StreamReader sourceReader = new StreamReader(sourceStream))
                                using (FileStream targetStream = new FileStream(targetSettings.Key, FileMode.Create))
                                using (StreamWriter targetWriter = new StreamWriter(targetStream, Encoding.UTF8))
                                {
                                    var sb = new StringBuilder(sourceReader.ReadToEnd());

                                    var sourceWords = headerSettings[sourceSettings.Value];
                                    var targetWords = headerSettings[targetSettings.Value];

                                    for (int i = 0; i < wordCount; i++)
                                    {
                                        sb.Replace(sourceWords[i], targetWords[i]);
                                    }

                                    targetWriter.Write(sb.ToString());
                                }

                                new FileInfo(targetSettings.Key).LastWriteTimeUtc = new FileInfo(sourceSettings.Key).LastWriteTimeUtc;
                            }

                            if (configReader.EndOfStream) break;
                        }
                    }
                }
                else if (args.Length >= 3 && args[0] == "Run")
                {
                    var startInfo = new ProcessStartInfo();
                    startInfo.FileName = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), args[1]));
                    startInfo.WorkingDirectory = Path.GetFullPath(Path.GetFullPath(args[2]));

                    Process.Start(startInfo);
                }
                else if (args.Length >= 2 && args[0] == "Template")
                {
                    var settings = new List<List<string>>();

                    using (StreamReader reader = new StreamReader(args[1], Encoding.UTF8))
                    {
                        string line;

                        do
                        {
                            var list = new List<string>();

                            while (!string.IsNullOrWhiteSpace(line = reader.ReadLine()))
                            {
                                list.Add(line);
                            }

                            if (list.Count > 0) settings.Add(list);

                        } while (line != null);
                    }

                    foreach (var setting in settings)
                    {
                        if (setting.Count < 2) continue;

                        var sourcePath = setting[0];

                        foreach (var item in setting.Skip(1))
                        {
                            string text;

                            using (StreamReader reader = new StreamReader(sourcePath, Encoding.UTF8))
                            {
                                text = reader.ReadToEnd();
                            }

                            var commands = Decode(item).ToList();
                            if (commands.Count < 2) continue;

                            var targetPath = commands[0];

                            int count = 1;

                            foreach (var item2 in commands.Skip(1))
                            {
                                text = Regex.Replace(text, string.Format(@"<#\s*{0}\s*#>", count++), item2);
                            }

                            using (StreamWriter writer = new StreamWriter(targetPath))
                            {
                                writer.Write(text);
                            }
                        }
                    }
                }
                else if (args.Length >= 3 && args[0] == "Watcher")
                {
                    Process parentProcess = null;
                    {
                        var id = int.Parse(args[1]);
                        parentProcess = Process.GetProcessById(id);
                    }

                    if (parentProcess == null) return;

                    Process childProcess = null;
                    {
                        childProcess = new Process();
                        childProcess.StartInfo.FileName = Path.GetFullPath(args[2]);
                        childProcess.StartInfo.Arguments = string.Join(" ", args.Skip(3).Select(n => string.Format("\"{0}\"", n)));
                        childProcess.StartInfo.RedirectStandardInput = true;
                        childProcess.StartInfo.RedirectStandardOutput = true;
                        childProcess.StartInfo.CreateNoWindow = true;
                        childProcess.StartInfo.UseShellExecute = false;
                    }

                    childProcess.Start();

                    var thread1 = new Thread(() =>
                    {
                        try
                        {
                            byte[] buffer = new byte[1024 * 4];

                            using (var targetOutputStream = childProcess.StandardOutput.BaseStream)
                            using (var myOutputStream = System.Console.OpenStandardOutput())
                            {
                                int length = 0;

                                while ((length = targetOutputStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    myOutputStream.Write(buffer, 0, length);
                                }
                            }
                        }
                        catch (Exception)
                        {

                        }
                    });
                    thread1.IsBackground = true;
                    thread1.Start();

                    var thread2 = new Thread(() =>
                    {
                        try
                        {
                            byte[] buffer = new byte[1024 * 4];

                            using (var targetInputStream = childProcess.StandardInput.BaseStream)
                            using (var myInputStream = System.Console.OpenStandardInput())
                            {
                                int length = 0;

                                while ((length = myInputStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    targetInputStream.Write(buffer, 0, length);
                                }
                            }
                        }
                        catch (Exception)
                        {

                        }
                    });
                    thread2.IsBackground = true;
                    thread2.Start();

                    try
                    {
                        for (;;)
                        {
                            Thread.Sleep(1000);

                            if (parentProcess.HasExited)
                            {
                                childProcess.Kill();
                            }

                            if (childProcess.HasExited)
                            {
                                thread1.Join();
                                thread2.Join();

                                return;
                            }
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
                else if (args.Length >= 2 && args[0] == "LineCount")
                {
                    string basePath = args[1];
                    int count = 0;

                    var list = new List<KeyValuePair<int, string>>();

                    foreach (var path in Program.GetFiles(basePath))
                    {
                        int tcount = 0;
                        using (StreamReader reader = new StreamReader(path))
                        {
                            tcount = reader.ReadToEnd().Count(n => n == '\n');
                        }

                        list.Add(new KeyValuePair<int, string>(tcount, path));
                        count += tcount;
                    }

                    list.Sort((KeyValuePair<int, string> kvp1, KeyValuePair<int, string> kvp2) =>
                    {
                        return kvp1.Key.CompareTo(kvp2.Key);
                    });

                    using (var writer = new StreamWriter("LineCount.txt", false, Encoding.UTF8))
                    {
                        foreach (var item in list)
                        {
                            var text = item.Value.Substring(basePath.Length).Replace(@"\", "/");
                            writer.WriteLine(string.Format("{0}\t{1}", item.Key, text));
                        }

                        writer.WriteLine(string.Format("Total\t{0}", count));
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Library.Tool Error", MessageBoxButtons.OK);
                MessageBox.Show(e.StackTrace, "Library.Tool Error", MessageBoxButtons.OK);
            }
        }
Example #15
0
        public void Load(string levelFileName)
        {
            this.levelFileName = levelFileName;

            List<string> controllerId = new List<string>();
            List<string> controlledId = new List<string>();

            XmlTextReader reader = new XmlTextReader("Content/level/" + levelFileName);
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "size")
                    {
                        string width = reader.GetAttribute("width");
                        string height = reader.GetAttribute("height");
                        string treasureCountStr = reader.GetAttribute("treasureCount");

                        int treasureCount = int.Parse(treasureCountStr);
                        this.width = int.Parse(width);
                        this.height = int.Parse(height);

                        this.treasureMgr = new TreasureManager(this.levelFileName, treasureCount);
                    }
                    else if (reader.Name == "background")
                    {
                        backgroundTextureAssetName = reader.GetAttribute("texture");
                        string backgroundColorStr = reader.GetAttribute("color");
                        if (backgroundColorStr == "black")
                            backgroundColor = Color.Black;
                    }
                    else if (reader.Name == "foreground")
                    {
                        foregroundTextureAssetName = reader.GetAttribute("texture");
                        string bottom = reader.GetAttribute("bottom");
                    }
                    else if (reader.Name == "bound")
                    {
                        string leftStr = reader.GetAttribute("left");
                        string rightStr = reader.GetAttribute("right");
                        string topStr = reader.GetAttribute("top");
                        string bottomStr = reader.GetAttribute("bottom");
                        leftBound = int.Parse(leftStr);
                        rightBound = int.Parse(rightStr);
                        topBound = int.Parse(topStr);
                        bottomBound = int.Parse(bottomStr);
                        Block leftBoundBlock = new Block(game, new Vector2(leftBound, 0), 0, height);
                        Block rightBoundBlock = new Block(game, new Vector2(rightBound, 0), 0, height);
                        Block topBoundBlock = new Block(game, new Vector2(0, topBound), width, 0);
                        Block bottomBoundBlock = new Block(game, new Vector2(0, bottomBound), width, 0);
                        objects.Add(leftBoundBlock);
                        objects.Add(rightBoundBlock);
                        objects.Add(topBoundBlock);
                        objects.Add(bottomBoundBlock);
                    }
                    else if (reader.Name == "player")
                    {
                        player = new Player(game, reader);
                    }
                    else if (reader.Name == "enemy")
                    {
                        Enemy enemy = new Enemy(game, reader);
                    }
                    else if (reader.Name == "shiftStick")
                    {
                        ShiftStick stick = new ShiftStick(game, reader);

                        XmlReader subtree = reader.ReadSubtree();
                        while (subtree.Read())
                        {
                            if (subtree.NodeType == XmlNodeType.Element &&
                                subtree.Name == "controlled")
                            {
                                controllerId.Add(stick.Id);
                                controlledId.Add(subtree.GetAttribute("objId"));
                            }
                        }
                    }
                    else if (reader.Name == "lightsource")
                    {
                        LightSource light1 = new LightSource(game, reader);
                        lightSource.Add(light1);
                    }
                    else if (reader.Name == "mirror")
                    {
                        Mirror mirror1 = new Mirror(game, reader);
                    }
                    else if (reader.Name == "switch")
                    {
                        Switch switch1 = new Switch(game, reader);

                        XmlReader subtree = reader.ReadSubtree();
                        while (subtree.Read())
                        {
                            if (subtree.NodeType == XmlNodeType.Element &&
                                subtree.Name == "controlled")
                            {
                                controllerId.Add(switch1.Id);
                                controlledId.Add(subtree.GetAttribute("objId"));
                            }
                        }
                    }
                    else if (reader.Name == "ladder")
                    {
                        Ladder ladder = new Ladder(game, reader);
                    }
                    else if (reader.Name == "door")
                    {
                        Door door = new Door(game, reader);
                    }
                    else if (reader.Name == "platform")
                    {
                        Platform platform = new Platform(game, reader);
                    }
                    else if (reader.Name == "block")
                    {
                        Block block = new Block(game, reader);
                    }
                    else if (reader.Name == "launcher")
                    {
                        Launcher launcher = new Launcher(game, reader);
                    }
                    else if (reader.Name == "treasure")
                    {
                        Treasure treasure;
                        bool flag = false;
                        List<String> ids = this.treasureMgr.AreGotten();
                        foreach (String id in ids)
                        {
                            if (reader.GetAttribute("id") == id)
                            {
                                treasure = new Treasure(game, reader, true);
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            treasure = new Treasure(game, reader, false);
                        }
                    }
                    else if (reader.Name == "deadlyobj")
                    {
                        DeadlyObject deadlyobj = new DeadlyObject(game, reader);
                    }
                    else if (reader.Name == "ogre")
                    {
                        Ogre ogre = new Ogre(game, reader);
                    }
                    else if (reader.Name == "gate")
                    {
                        Gate gate = new Gate(game, reader);
                    }
                    else if (reader.Name == "topic")
                    {
                        string pxStr = reader.GetAttribute("px");
                        string pyStr = reader.GetAttribute("py");

                        topic = reader.ReadElementString();

                        float px = float.Parse(pxStr);
                        float py = float.Parse(pyStr);
                        topicPos = new Vector2(px, py);
                    }
                    else if (reader.Name == "bindingPoint")
                    {
                        if (Game.BindingPoint == null)
                        {
                            Game.BindingPoint = new BindingPoint();
                            XmlReader subtree = reader.ReadSubtree();
                            while (subtree.Read())
                            {
                                if (subtree.NodeType == XmlNodeType.Element &&
                                subtree.Name == "p")
                                {
                                    string pxStr = subtree.GetAttribute("px");
                                    string pyStr = subtree.GetAttribute("py");
                                    string id = subtree.GetAttribute("id");

                                    Vector2 pos = new Vector2(int.Parse(pxStr), int.Parse(pyStr));
                                    Game.BindingPoint.Add(pos, levelFileName, id);
                                }
                            }
                        }
                    }
                }
            }

            reader.Close();

            List<string>.Enumerator controllerEnum = controllerId.GetEnumerator();
            List<string>.Enumerator controlledEnum = controlledId.GetEnumerator();
            while (controllerEnum.MoveNext() && controlledEnum.MoveNext())
            {
                string controllerStr = controllerEnum.Current;
                string controlledStr = controlledEnum.Current;
                IController controller = (IController)GetObjectById(controllerStr);
                IControlledObject controlled = (IControlledObject)GetObjectById(controlledStr);
                controller.Add(controlled);
            }

            Initialize();
            LoadContent();
        }
Example #16
0
 public void ReadLog(XmlTextReader reader)
 {
     while (reader.Read()) //need end element otherwise will step through entire log
     {
         if (reader.Name == "Event")
         {
             Dictionary<string, string> attributes = new Dictionary<string, string>();
             if (reader.HasAttributes)
             {
                 for (int i = 0; i < reader.AttributeCount; i++)
                 {
                     reader.MoveToAttribute(i);
                     attributes.Add(reader.Name, reader.Value);
                 }
             }
             Events e = new Events(attributes);
             e.ReadLog(reader.ReadSubtree());
             Events.AddLast(e);
         }
         else if (reader.Name == "Feedback")
         {
             Dictionary<string, string> attributes = new Dictionary<string, string>();
             if (reader.HasAttributes)
             {
                 for (int i = 0; i < reader.AttributeCount; i++)
                 {
                     reader.MoveToAttribute(i);
                     attributes.Add(reader.Name, reader.Value);
                 }
             }
             Feedback e = new Feedback(attributes, reader.ReadElementString());
             Events.AddLast(e);
         }
         else
         {
             return;
         }
     }
 }
Example #17
0
        public static void readcerts()
        {
            string vendor = "";
            string publickey = "";

            using (XmlTextReader xmlreader = new XmlTextReader(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"validcertificates.xml"))
            {
                while (xmlreader.Read())
                {
                    if (xmlreader.ReadToFollowing("CERTIFICATE"))
                    {
                        var xmlreader2 = xmlreader.ReadSubtree();

                        while (xmlreader2.Read())
                        {
                            switch (xmlreader2.Name)
                            {
                                case "VENDOR":
                                    vendor = xmlreader2.ReadString();
                                    break;
                                case "PUBLICKEY":
                                    publickey = xmlreader2.ReadString();
                                    break;
                            }
                        }

                        if (vendor != "")
                        {
                            certs.Add(new KeyValuePair<string, string>(vendor, publickey));

                            vendor = "";
                            publickey = "";
                        }
                    }
                }
            }
        }
Example #18
0
        static void Main(string[] args)
        {
            Stream s;

            if (args.Length == 1)
            {
                s = new FileStream(args[0], FileMode.Open, FileAccess.Read);
            }
            else
            {
                s = Console.OpenStandardInput();
            }

            System.Xml.XmlTextReader xr = new System.Xml.XmlTextReader(s);
            xr.MoveToContent();
            if (!xr.LocalName.Equals("packetSequence"))
            {
                throw new System.FormatException("Not a packetSequence");
            }

            int result = nextElement(ref xr);

            UInt32 msg_no = 0;
            Stream outp   = Console.OpenStandardOutput();

            //StreamWriter sw = new StreamWriter(outp);
            while (result == 1)
            {
                if (xr.LocalName.Equals("packetSequence"))
                {
                    break;
                }

                StringWriter  sw  = new StringWriter();
                XmlTextWriter tw  = new XmlTextWriter(sw);
                XmlDocument   doc = new XmlDocument();
                doc.Load(xr.ReadSubtree());
                doc.WriteContentTo(tw);

                LTKD.Message       msg;
                ENUM_LLRP_MSG_TYPE dummy;

                try
                {
                    LLRPXmlParser.ParseXMLToLLRPMessage(sw.ToString(), out msg, out dummy);
                }
                catch (Exception e)
                {
                    String desc = "ParseXMLToLLRPMessage failure on Packet #" + msg_no + ", " + e.Message;
                    Console.Error.WriteLine(desc);
                    String err_msg =
                        "<ERROR_MESSAGE MessageID=\"0\" Version=\"0\">\r\n" +
                        "  <LLRPStatus>\r\n" +
                        "    <StatusCode>M_Success</StatusCode>\r\n" +
                        "    <ErrorDescription>" + desc + "</ErrorDescription>\r\n" +
                        "  </LLRPStatus>\r\n" +
                        "</ERROR_MESSAGE>\r\n";

                    LLRPXmlParser.ParseXMLToLLRPMessage(err_msg, out msg, out dummy);
                }

                byte[] packet = LTKD.Util.ConvertBitArrayToByteArray(msg.ToBitArray());
                outp.Write(packet, 0, packet.Length);

                /* next XML subdocument */
                result = nextElement(ref xr);
                msg_no++;
            }
        }
        public Gate(Game1 game, XmlTextReader reader)
            : base(game, reader)
        {
            string pxStr = reader.GetAttribute("px");
            string pyStr = reader.GetAttribute("py");
            string widthStr = reader.GetAttribute("width");
            string heightStr = reader.GetAttribute("height");

            float px = float.Parse(pxStr);
            float py = float.Parse(pyStr);
            int width = int.Parse(widthStr);
            int height = int.Parse(heightStr);

            this.position = new Vector2(px, py);
            this.Width = width;
            this.Height = height;

            XmlReader subtree = reader.ReadSubtree();
            while (subtree.Read())
            {
                if (subtree.NodeType == XmlNodeType.Element)
                {
                    if (subtree.Name == "bound")
                    {
                        string leftStr = reader.GetAttribute("left");
                        string rightStr = reader.GetAttribute("right");
                        string topStr = reader.GetAttribute("top");
                        string bottomStr = reader.GetAttribute("bottom");
                        float left = float.Parse(leftStr);
                        float right = float.Parse(rightStr);
                        float top = float.Parse(topStr);
                        float bottom = float.Parse(bottomStr);
                        this.blockInfo = new BlockInfo(left, right, top, bottom, true);
                    }
                }
            }
        }
Example #20
0
        private void FillFilesystems()
        {
            _logger.Log(Level.FINE, "FillFilesystems started.");

            var createdVertexTypes = new List<IVertexType>();
            try
            {

                using (_reader = new XmlTextReader(stream))
                {
                    try
                    {
                        //we move to the first element in this file.
                        _reader.MoveToContent();

                        //extract data from xml... (types, import)
                        ExecuteBulkInsert(_reader.ReadSubtree());
                    }
                    finally
                    {
                        if (!_closed)
                            _reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Log(Level.SEVERE, "Exception thrown: {0}", ex);
            }
            finally
            {
                _logger.Log(Level.FINE, "FillFilesystems finished.");
            }
        }
        public static bool Load(ICurricularUnitFormRepository<CurricularUnitForm> _repo, String _filePath)
        {
            try
            {
                CurricularUnitForm cuf = new CurricularUnitForm();

                if (_repo == null || _filePath == null) return false;

                XmlTextReader xmlFile = new XmlTextReader(_filePath);
                //xmlFile.Read();

                while (xmlFile.Read())
                {
                    xmlFile.MoveToElement();
                    if (xmlFile.NodeType == XmlNodeType.Element && xmlFile.Name.Equals("fuc"))
                    {
                        ulong id = ulong.Parse(xmlFile.GetAttribute("id"));

                        XmlReader xmlTree = xmlFile.ReadSubtree();
                        while (xmlTree.Read())
                        {
                            if (xmlFile.NodeType == XmlNodeType.Element)
                            {
                                switch (xmlTree.Name)
                                {
                                    case "uc":
                                        String acr = xmlFile.GetAttribute("acronym");
                                        cuf = _repo.GetByAcronym(acr);
                                        if (cuf == null)
                                            cuf = new CurricularUnitForm(xmlFile.GetAttribute("name"), acr);
                                        cuf.CUnit.Name = xmlFile.GetAttribute("name");
                                        cuf.ID = id;
                                        try
                                        {
                                            cuf.CUnit.ECTS = Convert.ToDouble(xmlFile.GetAttribute("ects"));
                                        }
                                        catch (FormatException e)
                                        {
                                            cuf.CUnit.ECTS = 0;
                                        }
                                        break;
                                    case "ruc":
                                        acr = xmlFile.GetAttribute("acronym");
                                        CurricularUnitForm cuf_aux = _repo.GetByAcronym(acr);
                                        if (cuf_aux == null)
                                            cuf_aux = new CurricularUnitForm(xmlFile.GetAttribute("name"), acr);
                                        _repo.Add(cuf_aux);
                                        cuf.AddRequiredCourses(cuf_aux);
                                        break;
                                    case "type-uc":
                                        cuf.Type.CourseType = (CourseType)Enum.Parse(typeof(CourseType), xmlFile.GetAttribute("courseType"));
                                        cuf.Type.Semester = (Semester)Enum.Parse(typeof(Semester), xmlFile.GetAttribute("semester"));
                                        cuf.Type.Degree = (Degree)Enum.Parse(typeof(Degree), xmlFile.GetAttribute("degree"));
                                        break;
                                    case "objectives":
                                        cuf.Description.Objectives = xmlFile.ReadString();
                                        break;
                                    case "learningResults":
                                        cuf.Description.LearningResults = xmlFile.ReadString();
                                        break;
                                    case "resultEvaluation":
                                        cuf.Description.ResultEvaluation = xmlFile.ReadString();
                                        break;
                                    case "courseProgram":
                                        cuf.Description.CourseProgram = xmlFile.ReadString();
                                        break;
                                    case "language":
                                        cuf.Description.Language = xmlFile.ReadString();
                                        break;
                                }
                            }
                        }
                        if (cuf.Type.Degree.Equals(Degree.EIC))
                            _repo.Add(cuf);
                    }
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
            return true;
        }
Example #22
0
    public bool Import(string fileName, bool deleteBeforeImport, bool showProgress)
    {
      //System.Diagnostics.Debugger.Launch();
      _errorMessage = "";
      if (_isImporting == true)
      {
        _errorMessage = "already importing...";
        return false;
      }
      _isImporting = true;

      bool result = false;
      XmlTextReader xmlReader = null;


      // remove old programs
      _status.Status = "Removing old programs";
      _status.Channels = 0;
      _status.Programs = 0;
      _status.StartTime = DateTime.Now;
      _status.EndTime = new DateTime(1971, 11, 6);
      if (showProgress && ShowProgress != null) ShowProgress(_status);

      layer.RemoveOldPrograms();

      /*
      // for each channel, get the last program's time
      Dictionary<int, DateTime> lastProgramForChannel = new Dictionary<int, DateTime>();
      IList channels = Channel.ListAll();
      foreach (Channel ch in channels)
      {
        SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof(TvDatabase.Program));
        sb.AddConstraint(Operator.Equals, "idChannel", ch.IdChannel);
        sb.AddOrderByField(false, "starttime");
        sb.SetRowLimit(1);
        SqlStatement stmt = sb.GetStatement(true);
        IList programsInDbs = ObjectFactory.GetCollection(typeof(TvDatabase.Program), stmt.Execute());

        DateTime lastProgram = DateTime.MinValue;
        if (programsInDbs.Count > 0)
        {
          TvDatabase.IProgram p = (TvDatabase.Program)programsInDbs[0];
          lastProgram = p.EndTime;
        }
        lastProgramForChannel[ch.IdChannel] = lastProgram;
      }*/

      //TVDatabase.SupressEvents = true;
      bool useTimeZone = layer.GetSetting("xmlTvUseTimeZone", "false").Value == "true";
      int hours = Int32.Parse(layer.GetSetting("xmlTvTimeZoneHours", "0").Value);
      int mins = Int32.Parse(layer.GetSetting("xmlTvTimeZoneMins", "0").Value);
      int timeZoneCorrection = hours * 60 + mins;

      ArrayList Programs = new ArrayList();
      Dictionary<int, ChannelPrograms> dChannelPrograms = new Dictionary<int, ChannelPrograms>();
      try
      {
        Log.WriteFile("xmltv import {0}", fileName);

        //
        // Make sure the file exists before we try to do any processing
        //
        if (File.Exists(fileName))
        {
          _status.Status = "Loading channel list";
          _status.Channels = 0;
          _status.Programs = 0;
          _status.StartTime = DateTime.Now;
          _status.EndTime = new DateTime(1971, 11, 6);
          if (showProgress && ShowProgress != null) ShowProgress(_status);

          Dictionary<int, Channel> guideChannels = new Dictionary<int, Channel>();

          IList<Channel> allChannels = Channel.ListAll();

          int iChannel = 0;

          xmlReader = new XmlTextReader(fileName);

          #region import non-mapped channels by their display-name

          if (xmlReader.ReadToDescendant("tv"))
          {
            // get the first channel
            if (xmlReader.ReadToDescendant("channel"))
            {
              do
              {
                String id = xmlReader.GetAttribute("id");
                if (id == null || id.Length == 0)
                {
                  Log.Error("  channel#{0} doesnt contain an id", iChannel);
                }
                else
                {
                  String displayName = null;

                  XmlReader xmlChannel = xmlReader.ReadSubtree();
                  xmlChannel.ReadStartElement(); // read channel
                  // now, xmlChannel is positioned on the first sub-element of <channel>
                  while (!xmlChannel.EOF)
                  {
                    if (xmlChannel.NodeType == XmlNodeType.Element)
                    {
                      switch (xmlChannel.Name)
                      {
                        case "display-name":
                        case "Display-Name":
                          if (displayName == null) displayName = xmlChannel.ReadString();
                          else xmlChannel.Skip();
                          break;
                          // could read more stuff here, like icon...
                        default:
                          // unknown, skip entire node
                          xmlChannel.Skip();
                          break;
                      }
                    }
                    else
                      xmlChannel.Read();
                  }
                  if (xmlChannel != null)
                  {
                    xmlChannel.Close();
                    xmlChannel = null;
                  }

                  if (displayName == null || displayName.Length == 0)
                  {
                    Log.Error("  channel#{0} xmlid:{1} doesnt contain an displayname", iChannel, id);
                  }
                  else
                  {
                    Channel chan = null;

                    // a guide channel can be mapped to multiple tvchannels
                    foreach (Channel ch in allChannels)
                    {
                      if (ch.ExternalId == id)
                      {
                        chan = ch;
                        chan.ExternalId = id;
                      }

                      if (chan == null)
                      {
                        // no mapping found, ignore channel
                        continue;
                      }

                      ChannelPrograms newProgChan = new ChannelPrograms();
                      newProgChan.Name = chan.DisplayName;
                      newProgChan.ExternalId = chan.ExternalId;
                      Programs.Add(newProgChan);

                      Log.WriteFile("  channel#{0} xmlid:{1} name:{2} dbsid:{3}", iChannel, chan.ExternalId,
                                    chan.DisplayName, chan.IdChannel);
                      if (!guideChannels.ContainsKey(chan.IdChannel))
                      {
                        guideChannels.Add(chan.IdChannel, chan);
                        dChannelPrograms.Add(chan.IdChannel, newProgChan);
                      }
                    }

                    _status.Channels++;
                    if (showProgress && ShowProgress != null) ShowProgress(_status);
                  }
                }
                iChannel++;
                // get the next channel
              } while (xmlReader.ReadToNextSibling("channel"));
            }
          }

          //xmlReader.Close();

          #endregion

          SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
          sb.AddOrderByField(true, "externalId");
          sb.AddConstraint("externalId IS NOT null");
          sb.AddConstraint(Operator.NotEquals, "externalId", "");

          SqlStatement stmt = sb.GetStatement(true);
          allChannels = ObjectFactory.GetCollection<Channel>(stmt.Execute());
          if (allChannels.Count == 0)
          {
            _isImporting = false;
            if (xmlReader != null)
            {
              xmlReader.Close();
              xmlReader = null;
            }

            return true;
          }

          ///////////////////////////////////////////////////////////////////////////
          /*  design:
           * 1. create a Dictionary<string,Channel> using the externalid as the key,
           *    add all channels to this Dictionary 
           *    Note: channel -> guidechannel is a one-to-many relationship. 
           * 2. Read all programs from the xml file
           * 3. Create a program for each mapped channel
           */
          ///////////////////////////////////////////////////////////////////////////
          Dictionary<string, List<Channel>> allChannelMappingsByExternalId = new Dictionary<string, List<Channel>>();

          string previousExternalId = null;
          // one-to-many so we need a collection of channels for each externalId
          List<Channel> eidMappedChannels = new List<Channel>();

          for (int i = 0; i < allChannels.Count; i++)
          {
            Channel ch = (Channel)allChannels[i];

            if (previousExternalId == null)
            {
              eidMappedChannels.Add(ch);
              previousExternalId = ch.ExternalId;
            }
            else if (ch.ExternalId == previousExternalId)
            {
              eidMappedChannels.Add(ch);
            }
            else
            {
              // got all channels for this externalId. Add the mappings
              allChannelMappingsByExternalId.Add(previousExternalId, eidMappedChannels);
              // new externalid, create a new List & add the channel to the new List
              eidMappedChannels = new List<Channel>();
              eidMappedChannels.Add(ch);
              previousExternalId = ch.ExternalId;
            }

            if (i == allChannels.Count - 1)
            {
              allChannelMappingsByExternalId.Add(previousExternalId, eidMappedChannels);
            }
          }

          int programIndex = 0;
          _status.Status = "Loading TV programs";
          if (showProgress && ShowProgress != null) ShowProgress(_status);

          Log.Debug("xmltvimport: Reading TV programs");
          if (xmlReader != null)
          {
            xmlReader.Close();
            xmlReader = null;
          }
          xmlReader = new XmlTextReader(fileName);
          if (xmlReader.ReadToDescendant("tv"))
          {
            // get the first programme
            if (xmlReader.ReadToDescendant("programme"))
            {
              #region read programme node

              do
              {
                ChannelPrograms channelPrograms = new ChannelPrograms();

                String nodeStart = xmlReader.GetAttribute("start");
                String nodeStop = xmlReader.GetAttribute("stop");
                String nodeChannel = xmlReader.GetAttribute("channel");

                String nodeTitle = null;
                String nodeCategory = null;
                String nodeDescription = null;
                String nodeEpisode = null;
                String nodeRepeat = null;
                String nodeEpisodeNum = null;
                String nodeEpisodeNumSystem = null;
                String nodeDate = null;
                String nodeStarRating = null;
                String nodeClassification = null;

                XmlReader xmlProg = xmlReader.ReadSubtree();
                xmlProg.ReadStartElement(); // read programme
                // now, xmlProg is positioned on the first sub-element of <programme>
                while (!xmlProg.EOF)
                {
                  if (xmlProg.NodeType == XmlNodeType.Element)
                  {
                    switch (xmlProg.Name)
                    {
                      case "title":
                        if (nodeTitle == null) nodeTitle = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "category":
                        if (nodeCategory == null) nodeCategory = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "desc":
                        if (nodeDescription == null) nodeDescription = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "sub-title":
                        if (nodeEpisode == null) nodeEpisode = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "previously-shown":
                        if (nodeRepeat == null) nodeRepeat = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "episode-num":
                        if (xmlProg.GetAttribute("system").Equals("xmltv_ns")) 
                        {
                            nodeEpisodeNumSystem = xmlProg.GetAttribute("system");
                            nodeEpisodeNum = xmlProg.ReadString();
                        }
                        else if (nodeEpisodeNum == null && xmlProg.GetAttribute("system").Equals("onscreen"))
                        {
                          nodeEpisodeNumSystem = xmlProg.GetAttribute("system");
                          nodeEpisodeNum = xmlProg.ReadString();
                        }
                        else xmlProg.Skip();
                        break;
                      case "date":
                        if (nodeDate == null) nodeDate = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "star-rating":
                        if (nodeStarRating == null) nodeStarRating = xmlProg.ReadInnerXml();
                        else xmlProg.Skip();
                        break;
                      case "rating":
                        if (nodeClassification == null) nodeClassification = xmlProg.ReadInnerXml();
                        else xmlProg.Skip();
                        break;
                      default:
                        // unknown, skip entire node
                        xmlProg.Skip();
                        break;
                    }
                  }
                  else
                    xmlProg.Read();
                }
                if (xmlProg != null)
                {
                  xmlProg.Close();
                  xmlProg = null;
                }

                #endregion

                #region verify/convert values (programme)

                if (nodeStart != null && nodeChannel != null && nodeTitle != null &&
                    nodeStart.Length > 0 && nodeChannel.Length > 0 && nodeTitle.Length > 0)
                {
                  string description = "";
                  string category = "-";
                  string serEpNum = "";
                  string date = "";
                  string seriesNum = "";
                  string episodeNum = "";
                  string episodeName = "";
                  string episodePart = "";
                  int starRating = -1;
                  string classification = "";

                  string title = ConvertHTMLToAnsi(nodeTitle);

                  long startDate = 0;
                  if (nodeStart.Length >= 14)
                  {
                    if (Char.IsDigit(nodeStart[12]) && Char.IsDigit(nodeStart[13]))
                      startDate = Int64.Parse(nodeStart.Substring(0, 14)); //20040331222000
                    else
                      startDate = 100 * Int64.Parse(nodeStart.Substring(0, 12)); //200403312220
                  }
                  else if (nodeStart.Length >= 12)
                  {
                    startDate = 100 * Int64.Parse(nodeStart.Substring(0, 12)); //200403312220
                  }

                  long stopDate = startDate;
                  if (nodeStop != null)
                  {
                    if (nodeStop.Length >= 14)
                    {
                      if (Char.IsDigit(nodeStop[12]) && Char.IsDigit(nodeStop[13]))
                        stopDate = Int64.Parse(nodeStop.Substring(0, 14)); //20040331222000
                      else
                        stopDate = 100 * Int64.Parse(nodeStop.Substring(0, 12)); //200403312220
                    }
                    else if (nodeStop.Length >= 12)
                    {
                      stopDate = 100 * Int64.Parse(nodeStop.Substring(0, 12)); //200403312220
                    }
                  }

                  startDate = CorrectIllegalDateTime(startDate);
                  stopDate = CorrectIllegalDateTime(stopDate);
                  string timeZoneStart = "";
                  string timeZoneEnd = "";
                  if (nodeStart.Length > 14)
                  {
                    timeZoneStart = nodeStart.Substring(14);
                    timeZoneStart = timeZoneStart.Trim();
                    timeZoneEnd = timeZoneStart;
                  }
                  if (nodeStop != null)
                  {
                    if (nodeStop.Length > 14)
                    {
                      timeZoneEnd = nodeStop.Substring(14);
                      timeZoneEnd = timeZoneEnd.Trim();
                    }
                  }

                  //
                  // add time correction
                  //

                  // correct program starttime
                  DateTime dateTimeStart = longtodate(startDate);
                  dateTimeStart = dateTimeStart.AddMinutes(timeZoneCorrection);

                  if (useTimeZone)
                  {
                    int off = GetTimeOffset(timeZoneStart);
                    int h = off / 100; // 220 -> 2,  -220 -> -2
                    int m = off - (h * 100); // 220 -> 20, -220 -> -20

                    dateTimeStart = dateTimeStart.AddHours(-h);
                    dateTimeStart = dateTimeStart.AddMinutes(-m);
                    dateTimeStart = dateTimeStart.ToLocalTime();
                  }
                  startDate = datetolong(dateTimeStart);

                  if (nodeStop != null)
                  {
                    // correct program endtime
                    DateTime dateTimeEnd = longtodate(stopDate);
                    dateTimeEnd = dateTimeEnd.AddMinutes(timeZoneCorrection);

                    if (useTimeZone)
                    {
                      int off = GetTimeOffset(timeZoneEnd);
                      int h = off / 100; // 220 -> 2,  -220 -> -2
                      int m = off - (h * 100); // 220 -> 20, -220 -> -20

                      dateTimeEnd = dateTimeEnd.AddHours(-h);
                      dateTimeEnd = dateTimeEnd.AddMinutes(-m);
                      dateTimeEnd = dateTimeEnd.ToLocalTime();
                    }
                    stopDate = datetolong(dateTimeEnd);
                  }
                  else stopDate = startDate;

                  //int channelId = -1;
                  //string channelName = "";

                  if (nodeCategory != null)
                    category = nodeCategory;

                  if (nodeDescription != null)
                  {
                    description = ConvertHTMLToAnsi(nodeDescription);
                  }
                  if (nodeEpisode != null)
                  {
                    episodeName = ConvertHTMLToAnsi(nodeEpisode);
                    if (title.Length == 0)
                      title = nodeEpisode;
                  }

                  if (nodeEpisodeNum != null)
                  {
                    if (nodeEpisodeNumSystem != null)
                    {
                      // http://xml.coverpages.org/XMLTV-DTD-20021210.html
                      if (nodeEpisodeNumSystem == "xmltv_ns")
                      {
                        serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum.Replace(" ", ""));
                        int dot1 = serEpNum.IndexOf(".", 0);
                        int dot2 = serEpNum.IndexOf(".", dot1 + 1);
                        seriesNum = serEpNum.Substring(0, dot1);
                        episodeNum = serEpNum.Substring(dot1 + 1, dot2 - (dot1 + 1));
                        episodePart = serEpNum.Substring(dot2 + 1, serEpNum.Length - (dot2 + 1));
                        //xmltv_ns is theorically zero-based number will be increased by one
                        seriesNum = CorrectEpisodeNum(seriesNum, 1);
                        episodeNum = CorrectEpisodeNum(episodeNum, 1);
                        episodePart = CorrectEpisodeNum(episodePart, 1);
                      }
                      else if (nodeEpisodeNumSystem == "onscreen")
                      {
                        // example: 'Episode #FFEE' 
                        serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum);
                        int num1 = serEpNum.IndexOf("#", 0);
                        if (num1 > 0)
                        {
                          episodeNum = CorrectEpisodeNum(serEpNum.Substring(num1, serEpNum.Length - num1), 0);
                        }
                        else
                        {
                          if (serEpNum.IndexOf(":", 0) > 0)
                          {
                            episodeNum = CorrectEpisodeNum(serEpNum, 0);
                          }
                          else
                          {
                            Regex regEpisode = new Regex("(?<episode>\\d*)\\D*(?<series>\\d*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
                            Match m = regEpisode.Match(serEpNum);
                            if (m.Success)
                            {
                              episodeNum = CorrectEpisodeNum(m.Groups["episode"].Value, 0);
                              seriesNum = CorrectEpisodeNum(m.Groups["series"].Value, 0);
                            }
                            else
                            {
                              episodeNum = CorrectEpisodeNum(serEpNum, 0);
                            }
                          }
                        }
                      }
                    }
                    else
                      // fixing mantis bug 1486: XMLTV import doesn't take episode number from TVGuide.xml made by WebEPG 
                    {
                      // example: '5' like WebEPG is creating
                      serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum.Replace(" ", ""));
                      episodeNum = CorrectEpisodeNum(serEpNum, 0);
                    }
                  }

                  if (nodeDate != null)
                  {
                    date = nodeDate;
                  }

                  if (nodeStarRating != null)
                  {
                    starRating = ParseStarRating(nodeStarRating);
                  }

                  if (nodeClassification != null)
                  {
                    classification = nodeClassification;
                  }

                  if (showProgress && ShowProgress != null && (_status.Programs % 100) == 0) ShowProgress(_status);

                  #endregion

                  #region create a program for every mapped channel

                  List<Channel> mappedChannels;

                  if (allChannelMappingsByExternalId.ContainsKey(nodeChannel))
                  {
                    mappedChannels = allChannelMappingsByExternalId[nodeChannel];
                    if (mappedChannels != null && mappedChannels.Count > 0)
                    {
                      foreach (Channel chan in mappedChannels)
                      {
                        // get the channel program
                        channelPrograms = dChannelPrograms[chan.IdChannel];

                        if (chan.IdChannel < 0)
                        {
                          continue;
                        }

                        title = title.Replace("\r\n", " ");
                        title = title.Replace("\n\r", " ");
                        title = title.Replace("\r", " ");
                        title = title.Replace("\n", " ");
                        title = title.Replace("  ", " ");

                        description = description.Replace("\r\n", " ");
                        description = description.Replace("\n\r", " ");
                        description = description.Replace("\r", " ");
                        description = description.Replace("\n", " ");
                        description = description.Replace("  ", " ");

                        episodeName = episodeName.Replace("\r\n", " ");
                        episodeName = episodeName.Replace("\n\r", " ");
                        episodeName = episodeName.Replace("\r", " ");
                        episodeName = episodeName.Replace("\n", " ");
                        episodeName = episodeName.Replace("  ", " ");

                        Program prog = new Program(chan.IdChannel, longtodate(startDate), longtodate(stopDate), title,
                                                   description, category, Program.ProgramState.None,
                                                   System.Data.SqlTypes.SqlDateTime.MinValue.Value, seriesNum,
                                                   episodeNum, episodeName, episodePart, starRating, classification, -1);
                        channelPrograms.programs.Add(prog);
                        programIndex++;
                        //prog.Description = ConvertHTMLToAnsi(strDescription);
                        //prog.StartTime = iStart;
                        //prog.EndTime = iStop;
                        //prog.Title = ConvertHTMLToAnsi(strTitle);
                        //prog.Genre = ConvertHTMLToAnsi(strCategory);
                        //prog.Channel = ConvertHTMLToAnsi(strChannelName);
                        //prog.Date = strDate;
                        //prog.Episode = ConvertHTMLToAnsi(strEpisode);
                        //prog.Repeat = ConvertHTMLToAnsi(strRepeat);
                        //prog.SeriesNum = ConvertHTMLToAnsi(strSeriesNum);
                        //prog.EpisodeNum = ConvertHTMLToAnsi(strEpisodeNum);
                        //prog.EpisodePart = ConvertHTMLToAnsi(strEpisodePart);
                        //prog.StarRating = ConvertHTMLToAnsi(strStarRating);
                        //prog.Classification = ConvertHTMLToAnsi(strClasification);
                        _status.Programs++;
                      }
                    }
                  }
                }
                // get the next programme
              } while (xmlReader.ReadToNextSibling("programme"));
              //if (xmlReader != null) xmlReader.Close();

              #endregion

              #region sort & remove invalid programs. Save all valid programs

              Log.Debug("xmltvimport: Sorting TV programs");

              _status.Programs = 0;
              _status.Status = "Sorting TV programs";
              if (showProgress && ShowProgress != null) ShowProgress(_status);
              DateTime dtStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0);
              //dtStartDate=dtStartDate.AddDays(-4);

              foreach (ChannelPrograms progChan in Programs)
              {
                // empty, skip it
                if (progChan.programs.Count == 0) continue;

                progChan.programs.Sort();
                progChan.programs.AlreadySorted = true;
                progChan.programs.FixEndTimes();
                progChan.programs.RemoveOverlappingPrograms(); // be sure that we do not have any overlapping

                // get the id of the channel, just get the IdChannel of the first program
                int idChannel = progChan.programs[0].IdChannel;

                if (!deleteBeforeImport)
                {
                  // retrieve all programs for this channel
                  SqlBuilder sb2 = new SqlBuilder(StatementType.Select, typeof (Program));
                  sb2.AddConstraint(Operator.Equals, "idChannel", idChannel);
                  sb2.AddOrderByField(false, "starttime");
                  SqlStatement stmt2 = sb2.GetStatement(true);
                  ProgramList dbPrograms = new ProgramList();
                  ObjectFactory.GetCollection<Program>(stmt2.Execute(), dbPrograms);
                  progChan.programs.RemoveOverlappingPrograms(dbPrograms, true);
                }

                for (int i = 0; i < progChan.programs.Count; ++i)
                {
                  Program prog = progChan.programs[i];
                  // don't import programs which have already ended...
                  if (prog.EndTime <= dtStartDate)
                  {
                    progChan.programs.RemoveAt(i);
                    i--;
                    continue;
                  }

                  DateTime start = prog.StartTime;
                  DateTime end = prog.EndTime;
                  DateTime airDate = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
                  try
                  {
                    airDate = prog.OriginalAirDate;
                    if (airDate > System.Data.SqlTypes.SqlDateTime.MinValue.Value &&
                        airDate < System.Data.SqlTypes.SqlDateTime.MaxValue.Value)
                      prog.OriginalAirDate = airDate;
                  }
                  catch (Exception)
                  {
                    Log.Info("XMLTVImport: Invalid year for OnAirDate - {0}", prog.OriginalAirDate);
                  }

                  if (prog.StartTime < _status.StartTime)
                    _status.StartTime = prog.StartTime;
                  if (prog.EndTime > _status.EndTime)
                    _status.EndTime = prog.EndTime;
                  _status.Programs++;
                  if (showProgress && ShowProgress != null && (_status.Programs % 100) == 0) ShowProgress(_status);
                }
                Log.Info("XMLTVImport: Inserting {0} programs for {1}", progChan.programs.Count.ToString(),
                         progChan.Name);
                layer.InsertPrograms(progChan.programs,
                                     deleteBeforeImport
                                       ? DeleteBeforeImportOption.OverlappingPrograms
                                       : DeleteBeforeImportOption.None, ThreadPriority.BelowNormal);
              }
            }

            #endregion

            //TVDatabase.RemoveOverlappingPrograms();

            //TVDatabase.SupressEvents = false;
            if (programIndex > 0)
            {
              _errorMessage = "File imported successfully";
              result = true;
            }
            else
              _errorMessage = "No programs found";
          }
        }
        else
        {
          _errorMessage = "No xmltv file found";
          _status.Status = _errorMessage;
          Log.Error("xmltv data file was not found");
        }
      }
      catch (Exception ex)
      {
        _errorMessage = String.Format("Invalid XML file:{0}", ex.Message);
        _status.Status = String.Format("invalid XML file:{0}", ex.Message);
        Log.Error("XML tv import error loading {0} err:{1} \n {2}", fileName, ex.Message, ex.StackTrace);

        //TVDatabase.RollbackTransaction();
      }

      Programs.Clear();
      Programs = null;

      _isImporting = false;
      //      TVDatabase.SupressEvents = false;
      if (xmlReader != null)
      {
        xmlReader.Close();
        xmlReader = null;
      }
      return result;
    }
        /// <summary> Read the metadata configuration from a correctly-formatted metadata configuration XML file </summary>
        /// <param name="Configuration_XML_File"> File/path for the metadata configuration XML file to read </param>
        /// <returns> TRUE if successful, otherwise FALSE </returns>
        public bool Read_Metadata_Configuration(string Configuration_XML_File)
        {
            attemptedRead = true;

            // Clear all the values first
            Clear();

            bool returnValue = true;
            // Streams used for reading
            Stream readerStream = null;
            XmlTextReader readerXml = null;

            try
            {
                // Open a link to the file
                readerStream = new FileStream(Configuration_XML_File, FileMode.Open, FileAccess.Read);

                // Open a XML reader connected to the file
                readerXml = new XmlTextReader(readerStream);

                while (readerXml.Read())
                {
                    if (readerXml.NodeType == XmlNodeType.Element)
                    {
                        switch (readerXml.Name.ToLower())
                        {
                            case "profiles":
                                read_qc_profiles(readerXml.ReadSubtree());
                                break;
                        }
                    }
                }
            }
            catch
            {
                returnValue = false;
            }
            finally
            {
                if (readerXml != null)
                {
                    readerXml.Close();
                }
                if (readerStream != null)
                {
                    readerStream.Close();
                }
            }

            // If there was an error while reading, use the system defaults
            if (!returnValue)
            {
                Clear();
                Set_Default_Values();
            }

            return returnValue;
        }
Example #24
0
        /// <summary>
        /// Reads the specified set of XML source files, yielding each item as an <see cref="IImportItem"/>.
        /// </summary>
        /// <param name="sourceFiles"></param>
        /// <returns></returns>
        private static IEnumerable<IImportItem> ReadSourceFiles(IEnumerable<string> sourceFiles)
        {
            foreach (string sourceFile in sourceFiles)
            {
                using (StreamReader reader = File.OpenText(sourceFile))
                {
                    XmlTextReader xmlReader = new XmlTextReader(reader);
                    xmlReader.WhitespaceHandling = WhitespaceHandling.None;

                    // advance to root tag
                    if (xmlReader.ReadToFollowing(RootTag))
                    {
                        // advance to first child
                        while (xmlReader.Read() && xmlReader.NodeType != XmlNodeType.Element) ;

                        // if child nodes exist, read them
                        if (xmlReader.NodeType == XmlNodeType.Element)
                        {
                            string itemTag = xmlReader.Name;
                            for (bool more = true; more; more = xmlReader.ReadToNextSibling(itemTag))
                            {
                                yield return new ImportItem(xmlReader.ReadSubtree());
                            }
                        }
                    }
                    xmlReader.Close();
                }
            }
        }
Example #25
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length >= 2 && args[0] == "DigitalSignature_Create")
                {
                    var path = args[2];
                    var signPath = args[1];

                    DigitalSignature digitalSignature;

                    using (FileStream inStream = new FileStream(signPath, FileMode.Open))
                    {
                        digitalSignature = DigitalSignatureConverter.FromDigitalSignatureStream(inStream);
                    }

                    using (FileStream inStream = new FileStream(path, FileMode.Open))
                    using (FileStream outStream = new FileStream(path + ".certificate", FileMode.Create))
                    {
                        var certificate = DigitalSignature.CreateFileCertificate(digitalSignature, inStream.Name, inStream);

                        using (var certificateStream = CertificateConverter.ToCertificateStream(certificate))
                        {
                            var buffer = new byte[1024 * 4];

                            int i = -1;

                            while ((i = certificateStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                outStream.Write(buffer, 0, i);
                            }
                        }
                    }
                }
                else if (args.Length >= 2 && args[0] == "DigitalSignature_Verify")
                {
                    var path = args[2];
                    var signPath = args[1];

                    Certificate certificate;

                    using (FileStream inStream = new FileStream(signPath, FileMode.Open))
                    {
                        certificate = CertificateConverter.FromCertificateStream(inStream);
                    }

                    using (FileStream inStream = new FileStream(path, FileMode.Open))
                    {
                        MessageBox.Show(DigitalSignature.VerifyFileCertificate(certificate, inStream.Name, inStream).ToString());
                    }
                }
                else if (args.Length >= 4 && args[0] == "define")
                {
                    List<string> list = new List<string>();

                    using (FileStream inStream = new FileStream(args[2], FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    {
                        for (; ; )
                        {
                            string line = reader.ReadLine();
                            if (line == null) break;

                            list.Add(line);
                        }
                    }

                    bool flag = (args[1] == "on");

                    foreach (var item in list)
                    {
                        Program.Define(item, flag, args[3]);
                    }
                }
                else if (args.Length >= 3 && args[0] == "increment")
                {
                    //{
                    //    var path = args[1];
                    //    bool flag = false;

                    //    using (var stream = new FileStream(path, FileMode.Open))
                    //    {
                    //        byte[] b = new byte[3];
                    //        stream.Read(b, 0, b.Length);

                    //        flag = CollectionUtilities.Equals(b, new byte[] { 0xEF, 0xBB, 0xBF });
                    //    }

                    //    if (!flag) goto End;

                    //    string newPath;

                    //    using (var reader = new StreamReader(path))
                    //    using (var newStream = Program.GetUniqueFileStream(path))
                    //    using (var writer = new StreamWriter(newStream, new UTF8Encoding(false)))
                    //    {
                    //        newPath = newStream.Name;

                    //        writer.Write(reader.ReadToEnd());
                    //    }

                    //    File.Delete(path);
                    //    File.Move(newPath, path);

                    //End: ;
                    //}

                    string baseDirectory = Path.GetDirectoryName(args[1]);
                    List<string> filePaths = new List<string>();

                    using (Stream stream = new FileStream(args[1], FileMode.Open))
                    using (XmlTextReader xml = new XmlTextReader(stream))
                    {
                        while (xml.Read())
                        {
                            if (xml.NodeType == XmlNodeType.Element)
                            {
                                if (xml.LocalName == "Compile")
                                {
                                    var path = xml.GetAttribute("Include");
                                    string dependentUponBaseDirectory = Path.GetDirectoryName(path);
                                    filePaths.Add(Path.Combine(baseDirectory, path));

                                    using (var xmlSubtree = xml.ReadSubtree())
                                    {
                                        while (xmlSubtree.Read())
                                        {
                                            if (xmlSubtree.NodeType == XmlNodeType.Element)
                                            {
                                                if (xmlSubtree.LocalName == "DependentUpon")
                                                {
                                                    filePaths.Add(Path.Combine(Path.Combine(baseDirectory, dependentUponBaseDirectory), xml.ReadString()));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    filePaths.Remove(args[2]);
                    filePaths.Sort();

                    Regex regex = new Regex(@"^( *)\[( *)assembly( *):( *)AssemblyVersion( *)\(( *)" + "\"" + @"(\d*)\.(\d*)\.(\d*)\.(\d*)" + "\"" + @"( *)\)( *)\](.*)$");
                    byte[] hash = Program.GetHash(filePaths);
                    bool rewrite = false;

                    using (var readerStream = new StreamReader(args[2]))
                    using (var writerStream = new StreamWriter(args[2] + "~", false, new UTF8Encoding(false)))
                    {
                        for (; ; )
                        {
                            var line = readerStream.ReadLine();
                            if (line == null)
                            {
                                break;
                            }

                            var match = regex.Match(line);

                            if (match.Success)
                            {
                                int i = int.Parse(match.Groups[10].Value);

                                if (match.Groups[13].Value.TrimStart().StartsWith("//"))
                                {
                                    if (!Program.ArrayEquals(hash, Convert.FromBase64String(match.Groups[13].Value.TrimStart().Remove(0, 2).Trim())))
                                    {
                                        i++;
                                        rewrite = true;
                                    }
                                }
                                else
                                {
                                    rewrite = true;
                                }

                                writerStream.WriteLine(
                                string.Format(
                                    "{0}[{1}assembly{2}:{3}AssemblyVersion{4}({5}\"{6}.{7}.{8}.{9}\"{10}){11}]{12}",
                                    match.Groups[1].Value,
                                    match.Groups[2].Value,
                                    match.Groups[3].Value,
                                    match.Groups[4].Value,
                                    match.Groups[5].Value,
                                    match.Groups[6].Value,
                                    match.Groups[7].Value,
                                    match.Groups[8].Value,
                                    match.Groups[9].Value,
                                    i.ToString(),
                                    match.Groups[11].Value,
                                    match.Groups[12].Value,
                                    " // " + Convert.ToBase64String(hash)));
                            }
                            else
                            {
                                writerStream.WriteLine(line);
                            }
                        }
                    }

                    if (rewrite)
                    {
                        File.Delete(args[2]);
                        File.Move(args[2] + "~", args[2]);
                    }
                    else
                    {
                        File.Delete(args[2] + "~");
                    }
                }
                else if (args.Length >= 1 && args[0] == "settings")
                {
                    string settingsPath = args[1];

                    StringBuilder builder = new StringBuilder();
                    StringBuilder builder2 = new StringBuilder();
                    Regex regex = new Regex("new Library\\.Configuration\\.SettingContent<(.*)>\\(\\) { Name = \"(.*)\", Value = .* },(.*)$");

                    using (FileStream inStream = new FileStream(settingsPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    {
                        bool isRead = false;

                        for (; ; )
                        {
                            string line = reader.ReadLine();
                            if (line == null)
                            {
                                break;
                            }

                            if (line.Contains("new Library.Configuration.SettingContent"))
                            {
                                builder2.AppendLine(line);
                                isRead = true;
                            }
                            else if (isRead && line.Trim() == "")
                            {
                                builder2.AppendLine("");
                            }
                            else if (isRead)
                            {
                                break;
                            }
                        }
                    }

                    foreach (var item in builder2.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None))
                    {
                        if (item.Trim() == "")
                        {
                            builder.AppendLine("");
                        }
                        else
                        {
                            Match match = regex.Match(item);

                            var attributeBuilder = new StringBuilder();

                            {
                                var text = match.Groups[3].Value;

                                if (!string.IsNullOrWhiteSpace(text))
                                {
                                    text = text.Trim().TrimStart('/').Replace("]", "]\n");

                                    foreach (var line in text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(n => n.Trim()))
                                    {
                                        attributeBuilder.AppendLine("        " + line);
                                    }
                                }
                            }

                            builder.AppendLine(attributeBuilder.ToString() + string.Format(
                                "        public {0} {1}\r\n" +
                                "        {{\r\n" +
                                "            get\r\n" +
                                "            {{\r\n" +
                                "                lock (this.ThisLock)\r\n" +
                                "                {{\r\n" +
                                "                    return ({0})this[\"{1}\"];\r\n" +
                                "                }}\r\n" +
                                "            }}\r\n" +
                                "            set\r\n" +
                                "            {{\r\n" +
                                "                lock (this.ThisLock)\r\n" +
                                "                {{\r\n" +
                                "                    this[\"{1}\"] = value;\r\n" +
                                "                }}\r\n" +
                                "            }}\r\n" +
                                "        }}\r\n",
                                match.Groups[1].Value,
                                match.Groups[2].Value));
                        }
                    }

                    using (FileStream inStream = new FileStream(settingsPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    using (FileStream outStream = new FileStream(settingsPath + ".tmp", FileMode.Create))
                    using (StreamWriter writer = new StreamWriter(outStream, new UTF8Encoding(false)))
                    {
                        bool isRegion = false;
                        bool isRewrite = false;

                        for (; ; )
                        {
                            string line = reader.ReadLine();
                            if (line == null)
                            {
                                break;
                            }

                            if (!isRewrite)
                            {
                                if (line.Contains("#region Property"))
                                {
                                    isRegion = true;
                                }
                                else if (line.Contains("#endregion"))
                                {
                                    writer.Write("        #region Property\r\n\r\n" +
                                        builder.ToString().Trim('\r', '\n') +
                                        "\r\n\r\n");

                                    isRegion = false;
                                    isRewrite = true;
                                }
                            }

                            if (!isRegion)
                            {
                                writer.WriteLine(line);
                            }
                        }
                    }

                    File.Delete(settingsPath);
                    File.Move(settingsPath + ".tmp", settingsPath);
                }
                else if (args.Length >= 3 && args[0] == "languages")
                {
                    string languageManagerPath = args[1];
                    string languageXmlPath = Path.Combine(args[2], "English.xml");
                    StringBuilder builder = new StringBuilder();

                    using (FileStream stream = new FileStream(languageXmlPath, FileMode.Open))
                    using (XmlTextReader xml = new XmlTextReader(stream))
                    {
                        try
                        {
                            while (xml.Read())
                            {
                                if (xml.NodeType == XmlNodeType.Element)
                                {
                                    if (xml.LocalName == "Translate")
                                    {
                                        builder.AppendLine(string.Format(
                                            "        public string {0}\r\n" +
                                            "        {{\r\n" +
                                            "            get\r\n" +
                                            "            {{\r\n" +
                                            "                lock (this.ThisLock)\r\n" +
                                            "                {{\r\n" +
                                            "                    return this.Translate(\"{0}\");\r\n" +
                                            "                }}\r\n" +
                                            "            }}\r\n" +
                                            "        }}\r\n",
                                        xml.GetAttribute("Key")));
                                    }
                                }
                                else if (xml.NodeType == XmlNodeType.Whitespace)
                                {
                                    if (xml.Value.StartsWith("\r\n\r\n"))
                                    {
                                        builder.AppendLine("");
                                    }
                                }
                            }
                        }
                        catch (XmlException)
                        {

                        }
                    }

                    using (FileStream inStream = new FileStream(languageManagerPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    using (FileStream outStream = new FileStream(languageManagerPath + ".tmp", FileMode.Create))
                    using (StreamWriter writer = new StreamWriter(outStream, new UTF8Encoding(false)))
                    {
                        bool isRegion = false;
                        bool isRewrite = false;

                        for (; ; )
                        {
                            string line = reader.ReadLine();
                            if (line == null)
                            {
                                break;
                            }

                            if (!isRewrite)
                            {
                                if (line.Contains("#region Property"))
                                {
                                    isRegion = true;
                                }
                                else if (line.Contains("#endregion"))
                                {
                                    writer.Write("        #region Property\r\n\r\n" +
                                        builder.ToString().Trim('\r', '\n') +
                                        "\r\n\r\n");

                                    isRegion = false;
                                    isRewrite = true;
                                }
                            }

                            if (!isRegion)
                            {
                                writer.WriteLine(line);
                            }
                        }
                    }

                    File.Delete(languageManagerPath);
                    File.Move(languageManagerPath + ".tmp", languageManagerPath);

                    Program.LanguageSetting(languageXmlPath);
                }
                else if (args.Length >= 3 && args[0] == "CodeClone")
                {
                    string pathListPath = args[1];
                    string wordListPath = args[2];

                    Dictionary<string, string> pathDic = new Dictionary<string, string>();

                    using (FileStream inStream = new FileStream(pathListPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    {
                        var tempList = new List<string>();

                        for (; ; )
                        {
                            string line = reader.ReadLine();
                            if (line == null) break;

                            tempList.Add(line);

                            if (tempList.Count == 2)
                            {
                                pathDic[tempList[0]] = tempList[1];

                                reader.ReadLine(); //空白読み捨て
                                tempList.Clear();
                            }
                        }
                    }

                    Dictionary<string, string> wordDic = new Dictionary<string, string>();

                    using (FileStream inStream = new FileStream(wordListPath, FileMode.Open))
                    using (StreamReader reader = new StreamReader(inStream))
                    {
                        var tempList = new List<string>();

                        for (; ; )
                        {
                            string line = reader.ReadLine();
                            if (line == null) break;

                            tempList.Add(line);

                            if (tempList.Count == 2)
                            {
                                wordDic[tempList[0]] = tempList[1];

                                reader.ReadLine(); //空白読み捨て
                                tempList.Clear();
                            }
                        }
                    }

                    foreach (var item in pathDic)
                    {
                        var sourcePath = item.Key;
                        var targetPath = item.Value;

                        using (FileStream inStream = new FileStream(sourcePath, FileMode.Open))
                        using (StreamReader reader = new StreamReader(inStream))
                        using (FileStream outStream = new FileStream(targetPath, FileMode.Create))
                        using (StreamWriter writer = new StreamWriter(outStream, new UTF8Encoding(false)))
                        {
                            StringBuilder sb = new StringBuilder(reader.ReadToEnd());

                            foreach (var word in wordDic)
                            {
                                sb.Replace(word.Key, word.Value);
                            }

                            writer.Write(sb.ToString());
                        }
                    }
                }
                else if (args.Length >= 2 && args[0] == "linecount")
                {
                    string basePath = args[1];
                    int count = 0;

                    var list = new List<KeyValuePair<int, string>>();

                    foreach (var path in Program.GetFiles(basePath))
                    {
                        int tcount = 0;
                        using (StreamReader reader = new StreamReader(path))
                        {
                            tcount = reader.ReadToEnd().Count(n => n == '\n');
                        }

                        list.Add(new KeyValuePair<int, string>(tcount, path));
                        count += tcount;
                    }

                    list.Sort((KeyValuePair<int, string> kvp1, KeyValuePair<int, string> kvp2) =>
                    {
                        return kvp1.Key.CompareTo(kvp2.Key);
                    });

                    foreach (var item in list)
                    {
                        var text = item.Value.Substring(basePath.Length).Replace(@"\", "/");
                        Console.WriteLine(string.Format("{0}\t{1}", item.Key, text));
                    }

                    Console.WriteLine(count);
                }
                else if (args.Length >= 3 && args[0] == "run")
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = Path.Combine(Directory.GetCurrentDirectory(), args[1]);
                    startInfo.WorkingDirectory = Path.GetFullPath(args[2]);

                    Process.Start(startInfo);
                }
                else if (args.Length >= 2 && args[0] == "Template")
                {
                    var settings = new List<List<string>>();

                    using (StreamReader reader = new StreamReader(args[1], Encoding.UTF8))
                    {
                        string line;

                        do
                        {
                            var list = new List<string>();

                            while (!string.IsNullOrWhiteSpace(line = reader.ReadLine()))
                            {
                                list.Add(line);
                            }

                            if (list.Count > 0) settings.Add(list);

                        } while (line != null);
                    }

                    foreach (var setting in settings)
                    {
                        if (setting.Count < 2) continue;

                        var sourcePath = setting[0];

                        foreach (var item in setting.Skip(1))
                        {
                            string text;

                            using (StreamReader reader = new StreamReader(sourcePath, Encoding.UTF8))
                            {
                                text = reader.ReadToEnd();
                            }

                            var commands = Decode(item).ToList();
                            if (commands.Count < 2) continue;

                            var targetPath = commands[0];

                            int count = 1;

                            foreach (var item2 in commands.Skip(1))
                            {
                                text = Regex.Replace(text, string.Format(@"<#\s*{0}\s*#>", count++), item2);
                            }

                            using (StreamWriter writer = new StreamWriter(targetPath))
                            {
                                writer.Write(text);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Library.Tool Error", MessageBoxButtons.OK);
                MessageBox.Show(e.StackTrace, "Library.Tool Error", MessageBoxButtons.OK);
            }
        }
Example #26
0
        private static Information GetPortEntryFromService(string services, string serviceType, string gatewayIp, int gatewayPort, int index, TimeSpan timeout)
        {
            if (services == null || !services.Contains(serviceType)) return null;

            try
            {
                services = services.Substring(services.IndexOf(serviceType));

                string controlUrl = _controlUrlRegex.Match(services).Groups["url"].Value;
                string soapBody =
                    "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
                    " <s:Body>" +
                    "  <u:GetGenericPortMappingEntry xmlns:u=\"" + serviceType + "\">" +
                    "   <NewPortMappingIndex>" + index + "</NewPortMappingIndex>" +
                    "  </u:GetGenericPortMappingEntry>" +
                    " </s:Body>" +
                    "</s:Envelope>";
                byte[] body = Encoding.ASCII.GetBytes(soapBody);
                var uri = new Uri(new Uri("http://" + gatewayIp + ":" + gatewayPort.ToString()), controlUrl);

                System.Net.WebRequest wr = System.Net.WebRequest.Create(uri);

                wr.Method = "POST";
                wr.Headers.Add("SOAPAction", "\"" + serviceType + "#GetGenericPortMappingEntry\"");
                wr.ContentType = "text/xml;charset=\"utf-8\"";
                wr.ContentLength = body.Length;
                wr.Timeout = (int)timeout.TotalMilliseconds;

                using (System.IO.Stream stream = wr.GetRequestStream())
                {
                    stream.Write(body, 0, body.Length);
                }

                var contexts = new List<InformationContext>();

                using (WebResponse wres = wr.GetResponse())
                {
                    if (((HttpWebResponse)wres).StatusCode == HttpStatusCode.OK)
                    {
                        using (XmlTextReader xml = new XmlTextReader(wres.GetResponseStream()))
                        {
                            while (xml.Read())
                            {
                                if (xml.NodeType == XmlNodeType.Element)
                                {
                                    if (xml.LocalName == "GetGenericPortMappingEntryResponse")
                                    {
                                        using (var xmlSubtree = xml.ReadSubtree())
                                        {
                                            while (xmlSubtree.Read())
                                            {
                                                if (xmlSubtree.NodeType == XmlNodeType.Element)
                                                {
                                                    contexts.Add(new InformationContext(xmlSubtree.LocalName, xml.ReadString()));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                return new Information(contexts);
            }
            catch (Exception)
            {

            }

            return null;
        }
Example #27
0
        /// <summary>
        /// This method loads the configuration of the given file into the Instance
        /// settings instance.
        /// </summary>
        /// <param name="filename">A <see cref="string"/> with the filename without
        /// path of the settings file to read.</param>
        public void LoadConfigFile(string filename)
        {
            if (File.Exists(fileSettings.SettingsDirectory + Path.DirectorySeparatorChar  + filename))
            {
                XmlReader xmlReader = new XmlTextReader(fileSettings.SettingsDirectory + Path.DirectorySeparatorChar + filename);
                if (xmlReader != null)
                {
                    try
                    {
                        xmlReader.ReadToFollowing(FileSettings.Name);
                        fileSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Processing.Name); // "ProcessingSettings");
                        processingSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Eyestracker.Name);
                        eyestrackerSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Eyetracker.Name);
                        eyetrackerSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Calibration.Name);
                        calibrationSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Camera.Name);
                        cameraSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Network.Name);
                        networkSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Cloud.Name);
                        cloudSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Visualization.Name);
                        visualizationSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(Autotune.Name);
                        autotuneSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        xmlReader.ReadToFollowing(EyeMovement.Name);
                        eyeMovementSettings.LoadConfigFile(xmlReader.ReadSubtree());

                        #region EyeSpark specific code
                        xmlReader.ReadToFollowing(HeadMovement.Name);
                        headMovementSettings.LoadConfigFile(xmlReader.ReadSubtree());
                        #endregion

                        xmlReader.Close();
                    }
                    catch (Exception ex)
                    {
                        xmlReader.Close();
                        Console.WriteLine("Error loading settings: " + ex.Message);
                        // MessageBox.Show("Error loading settings: " + ex.Message);
                        // ErrorLogger.ProcessException(ex, false);
                    }
                }
            }
        }
Example #28
0
        public static double pepXMLReader(string pepxml, string output)
        {
            double totalions_pep = 0;
            int totalions = 0;
            int totalpep = 0;
            Console.WriteLine("reading pepxml file...");
            List<string> list = new List<string>();
            using (XmlTextReader reader = new XmlTextReader(pepxml))
            {
                while (reader.Read())
                {
                    if (reader.NodeType.Equals(XmlNodeType.Element) && reader.Name.Equals("spectrum_query"))
                    {
                        string spectrumNativeID = reader.GetAttribute("spectrumNativeID");
                        string charge = reader.GetAttribute("assumed_charge");
                        if (charge == "3")
                        {
                            //test here
                            //Console.WriteLine("spectrumID= " + spectrumNativeID);
                            XmlReader subReader = reader.ReadSubtree();
                            while (subReader.Read())
                            {
                                if (subReader.NodeType.Equals(XmlNodeType.Element) && subReader.Name.Equals("search_hit"))
                                {
                                    string hitRank = subReader.GetAttribute("hit_rank");
                                    string peptideSeq = subReader.GetAttribute("peptide");
                                    string num_matched_ions = subReader.GetAttribute("num_matched_ions");
                                    string tot_num_ions = subReader.GetAttribute("tot_num_ions");
                                    int total_num_ions = Convert.ToInt16(tot_num_ions);
                                    totalions += total_num_ions;
                                    //test
                                    //Console.WriteLine("hit_rank= " + hitRank);
                                    string mvh = "";
                                    string mzfidelity = "";
                                    string hgt = "";
                                    string rst = "";
                                    XmlReader subReader2 = reader.ReadSubtree();
                                    while (subReader2.Read())
                                    {
                                        if (subReader2.NodeType.Equals(XmlNodeType.Element) && subReader.Name.Equals("search_score"))
                                        {
                                            string name = subReader2.GetAttribute("name");
                                            if (name == "mvh")
                                            {
                                                mvh = subReader2.GetAttribute("value");
                                            }
                                            if (name == "mzFidelity")
                                            {
                                                mzfidelity = subReader2.GetAttribute("value");
                                            }
                                            if (name == "hgt")
                                            {
                                                hgt = subReader2.GetAttribute("value");
                                            }
                                            if (name == "rst")
                                            {
                                                rst = subReader2.GetAttribute("value");
                                                //test
                                                //Console.WriteLine("rst= " + rst);
                                            }
                                        }
                                    }//end of subReader2
                                    totalpep++;
                                    string finalstring = pepxml + "," + num_matched_ions + "," + tot_num_ions + "," + mvh + "," + mzfidelity + "," + hgt + "," + rst;
                                    list.Add(finalstring);
                                }//end of node: search_hit
                            }//sub reader 1
                        }

                    }//end of if(spectruem_querry)
                } //while read pepXML
            }//end of using

            Console.WriteLine("writing csv file...");
            TextWriter tw = new StreamWriter(output);
            tw.WriteLine("pepxml,machion,totions,mvh,mf,hgt,rst");
            foreach (string ss in list)
            {
                tw.WriteLine(ss);
            }
            tw.Flush();
            tw.Close();

            totalions_pep = totalions*1.0/totalpep;
            return totalions_pep;
        }
		private void ParseSemanticDomainFile()
		{
			XmlTextReader reader = null;
			try
			{
				reader = new XmlTextReader(_semanticDomainQuestionsFileName);
				reader.MoveToContent();
				if (!reader.IsStartElement("semantic-domain-questions"))
				{
					//what are we going to do when the file is bad?
					Debug.Fail("Bad file format, expected semantic-domain-questions element");
				}
				//string ws = reader.GetAttribute("lang"); got it from the configuration file

				// should verify that this writing system is in optionslist
				_semanticDomainWritingSystem =
					BasilProject.Project.WritingSystems[WritingSystemIdForNamesAndQuestions];
				string semanticDomainType = reader.GetAttribute("semantic-domain-type");
				// should verify that domain type matches type of optionList in semantic domain field

				reader.ReadToDescendant("semantic-domain");
				while (reader.IsStartElement("semantic-domain"))
				{
					string domainKey = reader.GetAttribute("id");
					List<string> questions = new List<string>();
					XmlReader questionReader = reader.ReadSubtree();
					questionReader.MoveToContent();
					questionReader.ReadToFollowing("question");
					while (questionReader.IsStartElement("question"))
					{
						questions.Add(questionReader.ReadElementString("question").Trim());
					}
					_domainKeys.Add(domainKey);
					if (questions.Count == 0)
					{
						questions.Add(string.Empty);
					}
					_domainQuestions.Add(domainKey, questions);
					reader.ReadToFollowing("semantic-domain");
				}
			}
			catch (XmlException)
			{
				// log this;
			}
			finally
			{
				if (reader != null)
				{
					reader.Close();
				}
			}
		}
        private static void read_engine_file(string ConfigFile, Microservice_Server_Configuration Config, List<Microservice_Endpoint> AllEndpoints, Dictionary<Microservice_VerbMapping, string> EndpointToComponentDictionary, Dictionary<Microservice_VerbMapping, string> EndpointToRestrictionDictionary, Dictionary<string, Microservice_Component> Components, Dictionary<string, Microservice_RestrictionRange> Ranges)
        {
            // Streams used for reading
            Stream readerStream = null;
            XmlTextReader readerXml = null;

            try
            {
                // Open a link to the file
                readerStream = new FileStream(ConfigFile, FileMode.Open, FileAccess.Read);

                // Open a XML reader connected to the file
                readerXml = new XmlTextReader(readerStream);

                while (readerXml.Read())
                {
                    if (readerXml.NodeType == XmlNodeType.Element)
                    {
                        switch (readerXml.Name.ToLower())
                        {
                            case "engine":
                                if (readerXml.MoveToAttribute("ClearAll"))
                                {
                                    if (readerXml.Value.Trim().ToLower() == "true")
                                    {
                                        Config.ClearAll();
                                        AllEndpoints.Clear();
                                        Components.Clear();
                                        Ranges.Clear();
                                        EndpointToComponentDictionary.Clear();
                                        EndpointToRestrictionDictionary.Clear();
                                    }
                                    readerXml.MoveToElement();
                                }
                                read_engine_details(readerXml.ReadSubtree(), Config, AllEndpoints, EndpointToComponentDictionary, EndpointToRestrictionDictionary, Components, Ranges);
                                break;
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                Config.Error = ee.Message;
            }
            finally
            {
                if (readerXml != null)
                {
                    readerXml.Close();
                }
                if (readerStream != null)
                {
                    readerStream.Close();
                }
            }
        }
Example #31
0
        public void LoadLevel(string fileName)
        {
            // TODO TODO TODO TODO TODO TODO TODO TODO
            // TODO use XDocument because XmlTextReader sucks balls

            XmlTextReader reader = new XmlTextReader(fileName);
            reader.ReadToFollowing("world");
            reader = (XmlTextReader)reader.ReadSubtree();

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element &&
                    reader.Name == "area")
                {
                    string isbn = reader.GetAttribute("ISBN");
                }
            }
        }