/// <summary> /// Load xml from internet based on firmwareurl, and return softwarelist /// </summary> /// <returns></returns> public List <software> getFWList(string firmwareurl = "") { if (firmwareurl == "") { firmwareurl = this.firmwareurl; } // mirror support L10N.ReplaceMirrorUrl(ref firmwareurl); log.Info("getFWList"); string url = ""; string url2560 = ""; string url2560_2 = ""; string px4 = ""; string px4v2 = ""; string vrbrainv40 = ""; string vrbrainv45 = ""; string vrbrainv50 = ""; string vrbrainv51 = ""; string vrbrainv52 = ""; string vrcorev10 = ""; string vrubrainv51 = ""; string vrubrainv52 = ""; string name = ""; string desc = ""; int k_format_version = 0; softwares.Clear(); software temp = new software(); // this is for mono to a ssl server //ServicePointManager.CertificatePolicy = new NoCheckCertificatePolicy(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( (sender1, certificate, chain, policyErrors) => { return(true); }); updateProgress(-1, Strings.GettingFWList); try { log.Info("url: " + firmwareurl); using (XmlTextReader xmlreader = new XmlTextReader(firmwareurl)) { while (xmlreader.Read()) { xmlreader.MoveToElement(); switch (xmlreader.Name) { case "url": url = xmlreader.ReadString(); break; case "url2560": url2560 = xmlreader.ReadString(); break; case "url2560-2": url2560_2 = xmlreader.ReadString(); break; case "urlpx4": px4 = xmlreader.ReadString(); break; case "urlpx4v2": px4v2 = xmlreader.ReadString(); break; case "urlvrbrainv40": vrbrainv40 = xmlreader.ReadString(); break; case "urlvrbrainv45": vrbrainv45 = xmlreader.ReadString(); break; case "urlvrbrainv50": vrbrainv50 = xmlreader.ReadString(); break; case "urlvrbrainv51": vrbrainv51 = xmlreader.ReadString(); break; case "urlvrbrainv52": vrbrainv52 = xmlreader.ReadString(); break; case "urlvrcorev10": vrcorev10 = xmlreader.ReadString(); break; case "urlvrubrainv51": vrubrainv51 = xmlreader.ReadString(); break; case "urlvrubrainv52": vrubrainv52 = xmlreader.ReadString(); break; case "name": name = xmlreader.ReadString(); break; case "format_version": k_format_version = int.Parse(xmlreader.ReadString()); break; case "desc": desc = xmlreader.ReadString(); break; case "Firmware": if (!name.Equals("") && !desc.Equals("Please Update")) { temp.desc = desc.Trim(); temp.name = name; temp.url = url; temp.url2560 = url2560; temp.url2560_2 = url2560_2; temp.urlpx4v1 = px4; temp.urlpx4v2 = px4v2; temp.urlvrbrainv40 = vrbrainv40; temp.urlvrbrainv45 = vrbrainv45; temp.urlvrbrainv50 = vrbrainv50; temp.urlvrbrainv51 = vrbrainv51; temp.urlvrbrainv52 = vrbrainv52; temp.urlvrcorev10 = vrcorev10; temp.urlvrubrainv51 = vrubrainv51; temp.urlvrubrainv52 = vrubrainv52; temp.k_format_version = k_format_version; try { try { if (!url2560.Contains("github")) { //name = lock (this) { ingetapmversion++; } System.Threading.ThreadPool.QueueUserWorkItem(getAPMVersion, temp); //if (name != "") //temp.name = name; } } catch { } } catch { } // just in case softwares.Add(temp); } url = ""; url2560 = ""; url2560_2 = ""; px4 = ""; px4v2 = ""; vrbrainv40 = ""; vrbrainv45 = ""; vrbrainv50 = ""; vrbrainv51 = ""; vrbrainv52 = ""; vrcorev10 = ""; vrubrainv51 = ""; vrubrainv52 = ""; name = ""; desc = ""; k_format_version = 0; temp = new software(); break; default: break; } } } } catch (Exception ex) { log.Error(ex); //CustomMessageBox.Show("Failed to get Firmware List : " + ex.Message); throw; } while (ingetapmversion > 0) { System.Threading.Thread.Sleep(100); } log.Info("load done"); updateProgress(-1, Strings.ReceivedList); return(softwares); }
List <PointLatLngAlt> getGEAltPath(List <PointLatLngAlt> list) { double alt = 0; double lat = 0; double lng = 0; int pos = 0; List <PointLatLngAlt> answer = new List <PointLatLngAlt>(); //http://code.google.com/apis/maps/documentation/elevation/ //http://maps.google.com/maps/api/elevation/xml string coords = ""; foreach (PointLatLngAlt loc in list) { coords = coords + loc.Lat.ToString(new System.Globalization.CultureInfo("en-US")) + "," + loc.Lng.ToString(new System.Globalization.CultureInfo("en-US")) + "|"; } coords = coords.Remove(coords.Length - 1); if (list.Count <= 2 || coords.Length > (2048 - 256) || distance > 50000) { CustomMessageBox.Show("Too many/few WP's or to Big a Distance " + (distance / 1000) + "km", "Error"); return(answer); } try { using (XmlTextReader xmlreader = new XmlTextReader("http://maps.google.com/maps/api/elevation/xml?path=" + coords + "&samples=" + (distance / 100).ToString(new System.Globalization.CultureInfo("en-US")) + "&sensor=false")) { while (xmlreader.Read()) { xmlreader.MoveToElement(); switch (xmlreader.Name) { case "elevation": alt = double.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); Console.WriteLine("DO it " + lat + " " + lng + " " + alt); PointLatLngAlt loc = new PointLatLngAlt(lat, lng, alt, ""); answer.Add(loc); pos++; break; case "lat": lat = double.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "lng": lng = double.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; default: break; } } } } catch { CustomMessageBox.Show("Error getting GE data", "Error"); } return(answer); }
public static string GetCurs() { try { //загружаем XML документ с сайта центрального банка XmlTextReader reader = new XmlTextReader("http://www.cbr.ru/scripts/XML_daily.asp"); //В эти переменные будем сохранять куски XML //с определенными валютами (Euro, USD) string USDXml = ""; string EuroXML = ""; //Перебираем все узлы в загруженном документе while (reader.Read()) { //Проверяем тип текущего узла switch (reader.NodeType) { //Если этого элемент Valute, то начинаем анализировать атрибуты case XmlNodeType.Element: { if (reader.Name == "Valute") { if (reader.HasAttributes) { //Метод передвигает указатель к следующему атрибуту while (reader.MoveToNextAttribute()) { if (reader.Name == "ID") { //Если значение атрибута равно R01235, то перед нами информация о курсе доллара if (reader.Value == "R01235") { //Возвращаемся к элементу, содержащий текущий узел атрибута reader.MoveToElement(); //Считываем содержимое дочерних узлом USDXml = reader.ReadOuterXml(); } } //Аналогичную процедуру делаем для ЕВРО if (reader.Name == "ID") { if (reader.Value == "R01239") { reader.MoveToElement(); EuroXML = reader.ReadOuterXml(); } } } } } break; } } } //Из выдернутых кусков XML кода создаем новые XML документы XmlDocument usdXmlDocument = new XmlDocument(); usdXmlDocument.LoadXml(USDXml); XmlDocument euroXmlDocument = new XmlDocument(); euroXmlDocument.LoadXml(EuroXML); //Метод возвращает узел, соответствующий выражению XPath XmlNode xmlNode = usdXmlDocument.SelectSingleNode("Valute/Value"); //Считываем значение и конвертируем в decimal. Курс валют получен usdValue = xmlNode.InnerText; xmlNode = euroXmlDocument.SelectSingleNode("Valute/Value"); euroValue = xmlNode.InnerText; }catch (Exception exc) { if (usdValue == null) { usdValue = "Error"; } if (euroValue == null) { euroValue = "Error"; } string Msg; Msg = exc.Message; } return(""); }
private void xmlcamera(bool write, string filename = "cameras.xml") { bool exists = File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename); if (write || !exists) { try { XmlTextWriter xmlwriter = new XmlTextWriter(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename, Encoding.ASCII); xmlwriter.Formatting = Formatting.Indented; xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("Cameras"); foreach (string key in cameras.Keys) { try { if (key == "") { continue; } xmlwriter.WriteStartElement("Camera"); xmlwriter.WriteElementString("name", cameras[key].name); xmlwriter.WriteElementString("flen", cameras[key].focallen.ToString(new System.Globalization.CultureInfo("en-US"))); xmlwriter.WriteElementString("imgh", cameras[key].imageheight.ToString(new System.Globalization.CultureInfo("en-US"))); xmlwriter.WriteElementString("imgw", cameras[key].imagewidth.ToString(new System.Globalization.CultureInfo("en-US"))); xmlwriter.WriteElementString("senh", cameras[key].sensorheight.ToString(new System.Globalization.CultureInfo("en-US"))); xmlwriter.WriteElementString("senw", cameras[key].sensorwidth.ToString(new System.Globalization.CultureInfo("en-US"))); xmlwriter.WriteEndElement(); } catch { } } xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } catch (Exception ex) { CustomMessageBox.Show(ex.ToString()); } } else { try { using (XmlTextReader xmlreader = new XmlTextReader(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename)) { while (xmlreader.Read()) { xmlreader.MoveToElement(); try { switch (xmlreader.Name) { case "Camera": { camerainfo camera = new camerainfo(); while (xmlreader.Read()) { bool dobreak = false; xmlreader.MoveToElement(); switch (xmlreader.Name) { case "name": camera.name = xmlreader.ReadString(); break; case "imgw": camera.imagewidth = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "imgh": camera.imageheight = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "senw": camera.sensorwidth = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "senh": camera.sensorheight = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "flen": camera.focallen = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "Camera": cameras[camera.name] = camera; dobreak = true; break; } if (dobreak) { break; } } string temp = xmlreader.ReadString(); } break; case "Config": break; case "xml": break; default: if (xmlreader.Name == "") // line feeds { break; } //config[xmlreader.Name] = xmlreader.ReadString(); break; } } catch (Exception ee) { Console.WriteLine(ee.Message); } // silent fail on bad entry } } } catch (Exception ex) { Console.WriteLine("Bad Camera File: " + ex.ToString()); } // bad config file // populate list foreach (var camera in cameras.Values) { if (!CMB_camera.Items.Contains(camera.name)) { CMB_camera.Items.Add(camera.name); } } } }
internal static string ChainReferenceAssemblyPath(string targetFrameworkDirectory) { string fullPath = Path.GetFullPath(targetFrameworkDirectory); lock (locker) { chainedReferenceAssemblyPath = chainedReferenceAssemblyPath ?? new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); cachedTargetFrameworkDisplayNames = cachedTargetFrameworkDisplayNames ?? new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); string str2 = null; if (chainedReferenceAssemblyPath.TryGetValue(fullPath, out str2)) { return(str2); } } string path = Path.Combine(Path.Combine(fullPath, "RedistList"), "FrameworkList.xml"); if (!File.Exists(path)) { lock (locker) { chainedReferenceAssemblyPath[fullPath] = null; cachedTargetFrameworkDisplayNames[fullPath] = null; } return(null); } string str5 = null; string str6 = null; try { using (XmlTextReader reader = new XmlTextReader(path)) { while (reader.Read()) { if ((reader.NodeType == XmlNodeType.Element) && string.Equals(reader.Name, "FileList", StringComparison.OrdinalIgnoreCase)) { reader.MoveToFirstAttribute(); do { if (string.Equals(reader.Name, "IncludeFramework", StringComparison.OrdinalIgnoreCase)) { str5 = reader.Value; } else if (string.Equals(reader.Name, "Name", StringComparison.OrdinalIgnoreCase)) { str6 = reader.Value; } }while (reader.MoveToNextAttribute()); reader.MoveToElement(); goto Label_01C3; } } } } catch (XmlException exception) { ErrorUtilities.ThrowInvalidOperation("ToolsLocationHelper.InvalidRedistFile", new object[] { path, exception.Message }); } catch (Exception exception2) { if (ExceptionHandling.NotExpectedException(exception2)) { throw; } ErrorUtilities.ThrowInvalidOperation("ToolsLocationHelper.InvalidRedistFile", new object[] { path, exception2.Message }); } Label_01C3: if (str6 != null) { lock (locker) { cachedTargetFrameworkDisplayNames[fullPath] = str6; } } string fullName = string.Empty; try { if (!string.IsNullOrEmpty(str5)) { fullName = fullPath; fullName = Directory.GetParent(fullName).FullName; fullName = Path.Combine(fullName, str5); fullName = Path.GetFullPath(fullName); if (!Directory.Exists(fullName)) { fullName = null; } } lock (locker) { chainedReferenceAssemblyPath[fullPath] = fullName; } return(fullName); } catch (Exception exception3) { if (ExceptionHandling.IsCriticalException(exception3)) { throw; } ErrorUtilities.ThrowInvalidOperation("ToolsLocationHelper.CouldNotCreateChain", new object[] { fullPath, fullName, exception3.Message }); } return(null); }
private IEnumerable <LocalizedString> Parse(XmlTextReader reader, string xamlPath) { try { while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element || !reader.HasAttributes) { continue; } var in_app_bar = false; if (reader.NamespaceURI.Contains("clr-namespace:Microsoft.Phone.Shell")) { var name = reader.Name.Substring(reader.Prefix.Length + 1); in_app_bar = name == "ApplicationBarIconButton" || name == "ApplicationBarMenuItem"; } var localized_string = new LocalizedString(); var is_binding = false; while (reader.MoveToNextAttribute()) { if (!in_app_bar && !reader.NamespaceURI.Contains("clr-namespace:Vernacular.Xaml")) { continue; } var name = String.IsNullOrEmpty(reader.Prefix) ? reader.Name : reader.Name.Substring(reader.Prefix.Length + 1); switch (name) { case "Text": // only valid when in_app_bar is true case "Catalog.Message": var value = reader.Value; is_binding = IsBinding(value); localized_string.UntranslatedSingularValue = Unescape(value); AddReference(localized_string, reader, xamlPath); break; case "Catalog.PluralMessage": localized_string.UntranslatedPluralValue = Unescape(reader.Value); break; case "Catalog.Comment": localized_string.DeveloperComments = reader.Value; break; case "Catalog.ToolTip": // Here we want to yield a new string directly since // this could be mixed with other Catalog attributes // on the element (e.g. two separate localized strings // could be returned for the element) yield return(AddReference(new LocalizedString { UntranslatedSingularValue = Unescape(reader.Value) }, reader, xamlPath)); break; } } if (localized_string.IsDefined && !is_binding) { yield return(localized_string); } reader.MoveToElement(); } } finally { reader.Close(); } }
private void ReadSection(XmlTextReader reader, string sectionName) { string attName; string nameValue = null; string typeValue = null; string allowLoc = null, allowDef = null; bool requirePermission = false; string requirePer = null; bool allowLocation = true; AllowDefinition allowDefinition = AllowDefinition.Everywhere; while (reader.MoveToNextAttribute()) { attName = reader.Name; if (attName == null) { continue; } if (attName == "allowLocation") { if (allowLoc != null) { ThrowException("Duplicated allowLocation attribute.", reader); } allowLoc = reader.Value; allowLocation = (allowLoc == "true"); if (!allowLocation && allowLoc != "false") { ThrowException("Invalid attribute value", reader); } continue; } if (attName == "requirePermission") { if (requirePer != null) { ThrowException("Duplicated requirePermission attribute.", reader); } requirePer = reader.Value; requirePermission = (requirePer == "true"); if (!requirePermission && requirePer != "false") { ThrowException("Invalid attribute value", reader); } continue; } if (attName == "allowDefinition") { if (allowDef != null) { ThrowException("Duplicated allowDefinition attribute.", reader); } allowDef = reader.Value; try { allowDefinition = (AllowDefinition)Enum.Parse( typeof(AllowDefinition), allowDef); } catch { ThrowException("Invalid attribute value", reader); } continue; } if (attName == "type") { if (typeValue != null) { ThrowException("Duplicated type attribute.", reader); } typeValue = reader.Value; continue; } if (attName == "name") { if (nameValue != null) { ThrowException("Duplicated name attribute.", reader); } nameValue = reader.Value; if (nameValue == "location") { ThrowException("location is a reserved section name", reader); } continue; } ThrowException("Unrecognized attribute.", reader); } if (nameValue == null || typeValue == null) { ThrowException("Required attribute missing", reader); } if (sectionName != null) { nameValue = sectionName + '/' + nameValue; } reader.MoveToElement(); object o = LookForFactory(nameValue); if (o != null && o != removedMark) { ThrowException("Already have a factory for " + nameValue, reader); } SectionData section = new SectionData(nameValue, typeValue, allowLocation, allowDefinition, requirePermission); section.FileName = fileName; factories [nameValue] = section; if (reader.IsEmptyElement) { reader.Skip(); } else { reader.Read(); reader.MoveToContent(); if (reader.NodeType != XmlNodeType.EndElement) { // sub-section inside a section ReadSections(reader, nameValue); } reader.ReadEndElement(); } reader.MoveToContent(); }
public static bool ImportStrategy(string fileName) { FileStream fileStream = null; bool bRet = false; try { int buffSize = 512; byte[] automationData; fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read); XmlTextReader reader = new XmlTextReader(fileStream); reader.MoveToElement(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("Strategy")) { //读Name reader.Read(); reader.MoveToContent(); string name = reader.ReadElementContentAsString(); //读Comment reader.Read(); reader.MoveToContent(); string comment = reader.ReadElementContentAsString(); Strategy strategyToAdd = new Strategy(); //读Event reader.Read(); reader.MoveToContent(); strategyToAdd.Event = (FSEyeEvent)reader.ReadElementContentAsInt(); //读Automation reader.Read(); reader.MoveToContent(); int realLength = 0; automationData = new byte[buffSize]; byte[] tempBuff = new byte[buffSize]; int readCount = reader.ReadElementContentAsBinHex(tempBuff, 0, buffSize); Array.Copy(tempBuff, 0, automationData, realLength, readCount); realLength += readCount; while (tempBuff.Length == readCount) { Array.Resize<byte>(ref automationData, automationData.Length + buffSize); readCount = reader.ReadElementContentAsBinHex(tempBuff, 0, buffSize); Array.Copy(tempBuff, 0, automationData, realLength, readCount); realLength += readCount; } Array.Resize<byte>(ref automationData, realLength); strategyToAdd.Automation = AdminServer.TheInstance.AutomationManager.Load(automationData); //读Enable reader.Read(); reader.MoveToContent(); strategyToAdd.Enabled = reader.ReadElementContentAsInt() == 1 ? true : false; AdminServer.TheInstance.StrategyManager.Add(strategyToAdd, name, comment); } } bRet = true; } catch (Exception) { bRet = false; } finally { if (fileStream != null) fileStream.Close(); } return bRet; }
public static DataTable ShowInfo(string getEDP) { DataTable dt_ProdInfo = new DataTable(); dt_ProdInfo.Columns.AddRange(new DataColumn[7] { new DataColumn("ProdName", typeof(string)), new DataColumn("ProdManufact", typeof(string)), new DataColumn("ProdDesc", typeof(string)), new DataColumn("ProdFinPrice", typeof(string)), new DataColumn("ProdAvailDesc", typeof(string)), new DataColumn("ProdImgURl", typeof(string)) , new DataColumn("ProdBtnTxt", typeof(string)) }); string name = "", manufact = "", desc = "", finalprice = "", availdesc = "", imageurl = "", buttontxt = ""; string URL = "http://afs-sl-pservice01.afservice.org:8080/productservice2/getProductInfo/pcmall?edplist=" + getEDP + "&ignoreCatalog=true"; XmlTextReader reader = new XmlTextReader(URL); reader.WhitespaceHandling = WhitespaceHandling.Significant; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "item") { reader.MoveToElement(); reader.ReadToFollowing("manufacturer"); if (reader.Name == "manufacturer") { manufact = reader.ReadElementString("manufacturer"); } reader.MoveToElement(); reader.ReadToFollowing("name"); if (reader.Name == "name") { name = reader.ReadElementString("name"); } reader.MoveToElement(); if (reader.Name == "description") { desc = reader.ReadElementString("description"); } reader.MoveToElement(); reader.ReadToFollowing("finalPrice"); if (reader.Name == "finalPrice") { finalprice = reader.ReadElementString("finalPrice"); } reader.MoveToElement(); if (reader.Name == "priceButtonDescription") { buttontxt = reader.ReadElementString("priceButtonDescription"); } reader.MoveToElement(); reader.ReadToFollowing("availabilityDescription"); if (reader.Name == "availabilityDescription") { availdesc = reader.ReadElementString("availabilityDescription"); } while (reader.ReadToFollowing("images")) { if (reader.Read()) { if (reader.Name == ("image")) { reader.ReadToFollowing("xlg"); if (reader.Name == "xlg") // { imageurl = reader.ReadElementString("xlg"); break; } } else { imageurl = "http://www.pcm.com/mall/widgetti/images/shared/noImageMed.jpg"; } break; } } dt_ProdInfo.Rows.Add(name, manufact, desc, "$ " + finalprice, availdesc, imageurl, "<i class='fa fa-shopping-cart'></i> " + buttontxt); } } return(dt_ProdInfo); }
public void loadMaterialXml(Material target) { XmlTextReader reader = new XmlTextReader(target.pointer); //target.envMapAlphaBaseTexture = false; gameWindow.log("parsing material: " + target.name); while (reader.Read()) { // parsing data in material tag if (reader.Name == "material" && reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "shader") { target.shader = gameWindow.shaderLoader.getShader(reader.Value); } else if (reader.Name == "ssnshader") { target.ssnshader = gameWindow.shaderLoader.getShader(reader.Value); } else if (reader.Name == "selection") { target.selectionshader = gameWindow.shaderLoader.getShader(reader.Value); } else if (reader.Name == "shadow") { target.shadowshader = gameWindow.shaderLoader.getShader(reader.Value); } else if (reader.Name == "definfo") { target.definfoshader = gameWindow.shaderLoader.getShader(reader.Value); } } gameWindow.log("shader: " + target.shader.name); reader.MoveToElement(); } // parsing textures if (reader.Name == "textures" && reader.HasAttributes) { while (reader.MoveToNextAttribute()) { Texture tmpTex = gameWindow.textureLoader.getTexture(reader.Value); if (reader.Name == "base") { target.setTexture(Material.TexType.baseTexture, tmpTex); } else if (reader.Name == "base2") { target.setTexture(Material.TexType.base2Texture, tmpTex); } else if (reader.Name == "base3") { target.setTexture(Material.TexType.base3Texture, tmpTex); } else if (reader.Name == "normal") { target.setTexture(Material.TexType.normalTexture, tmpTex); } else if (reader.Name == "reflection") { target.setTexture(Material.TexType.reflectionTexture, tmpTex); } else if (reader.Name == "definfo") { target.setTexture(Material.TexType.definfoTexture, tmpTex); } else if (reader.Name == "emit") { target.setTexture(Material.TexType.emitTexture, tmpTex); } } gameWindow.log("base: " + target.getTextureName(Material.TexType.baseTexture)); gameWindow.log("normal: " + target.getTextureName(Material.TexType.normalTexture)); reader.MoveToElement(); } // parsing envmap data if (reader.Name == "envmap") { target.propertys.useEnv = true; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "source") { if (reader.Value == "normalalpha") { target.propertys.envMapAlphaNormalTexture = true; } else if (reader.Value == "basealpha") { target.propertys.envMapAlphaBaseTexture = true; } else { target.setTexture(Material.TexType.envMapTexture, gameWindow.textureLoader.getTexture(reader.Value)); } } else if (reader.Name == "tint") { target.propertys.envMapTint = GenericMethods.VectorFromString(reader.Value); } } reader.MoveToElement(); } } /* -- moved to textures * // parsing specular data * if (reader.Name == "specmap") * { * target.propertys.useSpec = true; * if (reader.HasAttributes) * { * while (reader.MoveToNextAttribute()) * { * if (reader.Name == "source") * { * if (reader.Value == "normalalpha") * target.propertys.specMapAlphaNormalTexture = true; * * else if (reader.Value == "basealpha") * target.propertys.specMapAlphaBaseTexture = true; * * else * target.setTexture(Material.TexType.specMapTexture, gameWindow.textureLoader.getTexture(reader.Value)); * * } * else if (reader.Name == "tint") * { * target.propertys.specMapTint = GenericMethods.VectorFromString(reader.Value); * } * else if (reader.Name == "exp") * { * target.propertys.specExp = GenericMethods.FloatFromString(reader.Value); * } * } * reader.MoveToElement(); * } * } */ // parsing emit data if (reader.Name == "emit") { target.propertys.useEmit = true; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "source") { if (reader.Value == "normalalpha") { target.propertys.emitMapAlphaNormalTexture = true; } else if (reader.Value == "basealpha") { target.propertys.emitMapAlphaBaseTexture = true; } else { target.setTexture(Material.TexType.emitMapTexture, gameWindow.textureLoader.getTexture(reader.Value)); } } else if (reader.Name == "tint") { target.propertys.emitMapTint = GenericMethods.VectorFromString(reader.Value); } } reader.MoveToElement(); } } // parsing transparency data if (reader.Name == "transparency") { target.propertys.useAlpha = true; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "refraction") { target.propertys.refStrength = GenericMethods.FloatFromString(reader.Value); } if (reader.Name == "blur") { target.propertys.blurStrength = GenericMethods.FloatFromString(reader.Value); } if (reader.Name == "fresnel") { target.propertys.fresnelStrength = GenericMethods.FloatFromString(reader.Value); } } reader.MoveToElement(); } } // parsing lighting data if (reader.Name == "lighted") { target.propertys.useLight = true; } // parsing nucull if (reader.Name == "nocull") { target.propertys.noCull = true; } // parsing nucull if (reader.Name == "nodepthmask") { target.propertys.noDepthMask = true; } // parsing additive if (reader.Name == "additive") { target.propertys.additive = true; } // parsing fresnel data if (reader.Name == "fresnel" && reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "exp") { target.propertys.fresnelExp = GenericMethods.FloatFromString(reader.Value); } else if (reader.Name == "strength") { target.propertys.fresnelStr = GenericMethods.FloatFromString(reader.Value); } } reader.MoveToElement(); } target.loaded = true; materials[target.identifier] = target; } }
/// <summary> /// /// </summary> /// <param name="args"> /// XMLReader, filename /// </param> public void Visit(FireMLRoot root, object[] args) { //reader = args[0] as XmlTextReader; //file = args[1] as string; while (reader.Read()) { reader.MoveToContent(); switch (reader.NodeType) { case XmlNodeType.Element: Location location = new Location(file, reader.LineNumber, reader.LinePosition); switch (dic[reader.Name]) { case "MainPlot": if (root.MainPlot != null) { kernel.IssueError(ErrorType.DuplicatedMainPlot, location); continue; } PlotDef plotDef = new PlotDef(); plotDef.Location = location; root.MainPlot = plotDef; //reader.MoveToContent(); plotDef.Accept(this); break; case "SubPlot": reader.MoveToAttribute("name"); string subPlotName = reader.Value; if (root.SubPlotMap.ContainsKey(subPlotName)) { kernel.IssueError(ErrorType.DuplicatedSubPlot, subPlotName, new Location(file, reader.LineNumber, reader.LinePosition)); continue; } PlotDef subPlotDef = new PlotDef(); subPlotDef.Location = location; subPlotDef.Name = subPlotName; root.SubPlotMap.Add(subPlotName, subPlotDef); //reader.MoveToContent(); subPlotDef.Accept(this); break; case "ActionLayer": reader.MoveToAttribute("name"); string layerName = reader.Value; if (root.ActionLayerMap.ContainsKey(layerName)) { kernel.IssueError(ErrorType.DuplicatedActorLayer, layerName, new Location(file, reader.LineNumber, reader.LinePosition)); continue; } ActionLayerDef actionLayerDef = new ActionLayerDef(); actionLayerDef.Location = location; actionLayerDef.Name = layerName; root.ActionLayerMap.Add(layerName, actionLayerDef); //reader.Read(); reader.MoveToElement(); actionLayerDef.Accept(this); break; case "Function": reader.MoveToAttribute("name"); string funcName = reader.Value; if (root.FuncDefMap.ContainsKey(funcName)) { kernel.IssueError(ErrorType.DuplicatedFunction, funcName, new Location(file, reader.LineNumber, reader.LinePosition)); continue; } FunctionDef funcDef = new FunctionDef(); funcDef.Location = location; funcDef.Name = funcName; root.FuncDefMap.Add(funcName, funcDef); //reader.MoveToContent(); funcDef.Accept(this); break; } break; case XmlNodeType.EndElement: reader.Read(); break; } } }
public void Parse() { try { reader.MoveToContent(); while (reader.Read()) { var arg = new ParseEventArg { NodeType = reader.NodeType, Depth = reader.Depth, Name = reader.Name, EmptyElement = reader.IsEmptyElement }; if (reader.HasValue) { arg.Value = reader.Value; } else { arg.Value = null; } if (reader.HasAttributes) { var arr = new Attribute[reader.AttributeCount]; for (var i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); arr[i] = new Attribute { Name = reader.Name, Value = reader.Value, Index = i }; } reader.MoveToElement(); arg.Attributes = new ReadOnlyCollection <Attribute>(arr); } else { arg.Attributes = new ReadOnlyCollection <Attribute>(empty); } OnNode?.Invoke(this, arg); switch (reader.NodeType) { case XmlNodeType.Element: OnElement?.Invoke(this, arg); break; case XmlNodeType.CDATA: OnCData?.Invoke(this, arg); break; case XmlNodeType.Comment: OnComment?.Invoke(this, arg); break; case XmlNodeType.DocumentType: OnDocType?.Invoke(this, arg); break; case XmlNodeType.EndElement: OnEndElement?.Invoke(this, arg); break; case XmlNodeType.EntityReference: OnEntityReferenceUnresolved?.Invoke(this, arg); reader.ResolveEntity(); reader.Read(); arg.Name = reader.Name; arg.Value = reader.Value; arg.Depth = reader.Depth; arg.NodeType = reader.NodeType; OnEntityReference?.Invoke(this, arg); break; case XmlNodeType.ProcessingInstruction: OnProcessingInstruction?.Invoke(this, arg); break; case XmlNodeType.Text: OnText?.Invoke(this, arg); break; } } } catch (XmlException e) { OnException?.Invoke(this, e); } }
public void Parse(string filePath) { try { XmlTextReader reader = new XmlTextReader(filePath); reader.WhitespaceHandling = WhitespaceHandling.None; while (reader.Read()) { if (this.inMathNode == true) { ParseMath(reader); continue; } switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Prefix != String.Empty) { // namespaced element not part of SBML reader.Skip(); } String elementName = reader.LocalName.ToLower(); if (elementName == "notes" || elementName == "annotation") { // not part of the SBML model //reader.Skip(); // need to skip then move back one node reader.Read(); } Hashtable attributes = new Hashtable(); if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); if (reader.Name == "xmlns" && elementName != "math" && elementName != "sbml") { // namespaced node/subtree not part of SBML...unless MathML reader.MoveToElement(); reader.Skip(); } if (reader.Name == "specie") { // horrible leftover from SBML Level 1 attributes.Add("species", reader.Value); } else { attributes.Add(reader.Name.ToLower(), reader.Value); } } } StartElement(elementName, attributes); break; case XmlNodeType.EndElement: EndElement(reader.LocalName.ToLower()); break; // There are many other types of nodes, but // we are not interested in them } } } catch (XmlException e) { Console.WriteLine(e.Message); } }
private void button2_Click(object sender, EventArgs e) { string UMLClassDiagram = "UMLClassDiagram"; string superitem = "superitem"; string UMLAssociation = "UMLAssociation"; string point = "point"; string UMLGeneralization = "UMLGeneralization"; string valueAst = "value=\"*\""; string valueUno = "value=\"1\""; string valueNulo = "value=\"\""; char quitalo = '+'; char quitalo2 = ':'; char quitalo3 = '_'; char quitalo4 = '#'; string line; string NewXml = ""; StreamReader seCargoXml = new StreamReader(textBox1.Text); while ((line = seCargoXml.ReadLine()) != null) { if (line.Contains(UMLClassDiagram) || line.Contains(superitem) || line.Contains(UMLAssociation) || line.Contains(point) || line.Contains(UMLGeneralization) || line.Contains(valueAst) || line.Contains(valueUno) || line.Contains(valueNulo)) { } else { if (line.Contains(quitalo)) { line = line.Replace("+", ""); } if (line.Contains(quitalo2)) { line = line.Replace(":", " "); } if (line.Contains(quitalo3)) { line = line.Replace("_", ""); } if (line.Contains(quitalo4)) { line = line.Replace("#", ""); } NewXml += line; richTextBox1.Text = NewXml; } } seCargoXml.Close(); Console.WriteLine(NewXml); XmlTextReader reader = new XmlTextReader(new StringReader(NewXml)); StringWriter writer = new StringWriter(); while (reader.Read()) { //cadena que almacenará la indentación string indentado = new string('\t', reader.Depth); //evaluando el tipo de nodo switch (reader.NodeType) { //si tipo de nodo es: <?xml version='1.0' encoding='ISO-8859-1'?> case XmlNodeType.XmlDeclaration: //usamos Value para imprimir "xml version='1.0' encoding='ISO-8859-1'" writer.WriteLine("<?{0}?>", reader.Value); break; //if el tipo de nodo es un comentario case XmlNodeType.Comment: writer.WriteLine("{0}<!--{1}-->", indentado, reader.Value); break; //si tipo de nodo es elemento case XmlNodeType.Element: { //y si tiene atributos if (reader.HasAttributes) { //entonces creamos una cadena "atributos" que guardará //los atributos de este nodo. if (reader.LocalName == "UMLClass") { writer.WriteLine("{0}<UMLClass>", indentado); } string atributos = null; string Id = null; for (int i = 0; i < reader.AttributeCount; i++) { //nos movemos para realizar la lectura del atrbiuto de acuerdo al índice. reader.MoveToAttribute(i); //una vez que estamos ubicados en la posición correcta, //leemos el nombre del atributo, como también el valor. if (i == 1 && reader.Name == "value") { Id += reader.Value; writer.WriteLine("{0}<Id>{1}</Id>", indentado, Id); } if (i == 0 && reader.Name != "id" && reader.LocalName != "UMLClass") { atributos += reader.Value; writer.WriteLine("{0}<atributo>{1}</atributo>", indentado, atributos); } } //despues de haber leido los atributos del elemento... //moveremos el puntero al elemento. reader.MoveToElement(); } else { //si la profundidad del nodo es diferente a 2 if (reader.Depth != 2) { writer.WriteLine("{0}<{1}>", indentado, reader.LocalName); } else { writer.Write("{0}<{1}>", indentado, reader.LocalName); } } } break; //if el tipo de nodo es contenido. case XmlNodeType.Text: //imprimimos el contenido. writer.Write(reader.Value); break; //si el tipo de nodo es un elemento final o de cierre. case XmlNodeType.EndElement: //y además, averiguamos si es el que Depth es 2 entonces //no le agregamos la indentación, imprimiendo de esta manera: //<title>XML Programming</title> en vez de <title>XML Programming </title> if (reader.Depth == 2) { writer.WriteLine("</{0}>", reader.LocalName); } else { //con indentación tabPrefix writer.WriteLine("{0}</{1}>", indentado, reader.LocalName); } break; } } //cerramos el reader reader.Close(); //mostrar los resultados. string text = writer.ToString(); Console.Write(text); richTextBox2.Text = writer.ToString(); }
protected override ITableStructure DoGetRowFormat() { if (m_columnNames == null) { m_columnNames = new List <string>(); using (XmlReader xr = new XmlTextReader(GetWorkingFileName())) { xr.MoveToContent(); if (xr.Name != m_rootElementName) { Logging.Warning("Root element has different name"); } xr.Read(); while (xr.NodeType == XmlNodeType.Element) { if (xr.Name == m_rowElementName) { switch (m_storageType) { case XmlDataStorageType.Attribute: for (int i = 0; i < xr.AttributeCount; i++) { xr.MoveToAttribute(i); string name = xr.Name; if (!m_columnNames.Contains(name)) { m_columnNames.Add(name); } } xr.MoveToElement(); xr.Read(); break; case XmlDataStorageType.ColumnNamedElement: xr.Read(); xr.MoveToContent(); while (xr.NodeType == XmlNodeType.Element) { string name = xr.Name; xr.Skip(); if (!m_columnNames.Contains(name)) { m_columnNames.Add(name); } } xr.MoveToContent(); if (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } break; case XmlDataStorageType.InvariantNamedElement: xr.Read(); xr.MoveToContent(); while (xr.NodeType == XmlNodeType.Element) { string name = xr.GetAttribute(m_columnAttributeName); xr.Skip(); if (!m_columnNames.Contains(name)) { m_columnNames.Add(name); } } xr.MoveToContent(); if (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } break; } } else { xr.Skip(); } } } } return(CreateStructure()); }
// This method takes a configData object and creates a config.xml file at // the given path out of it. public bool fileToStruct(string configXMLPath, ConfigData configData) { if (!File.Exists(configXMLPath)) return false; using (XmlTextReader configReader = new XmlTextReader(configXMLPath)) { while (configReader.Read()) { if (configReader.NodeType == XmlNodeType.Element) { // "Global" Attributes string itNameAttr = ""; switch (configReader.Name) { case "ImageTarget": // Parse name from config file itNameAttr = configReader.GetAttribute("name"); if (itNameAttr == null) { Debug.LogWarning("Found ImageTarget without " + "name attribute in " + "config.xml. Image Target " + "will be ignored."); continue; } // Parse itSize from config file Vector2 itSize = Vector2.zero; string[] itSizeAttr = configReader.GetAttribute("size").Split(' '); if (itSizeAttr != null) { if (!QCARUtilities.SizeFromStringArray( out itSize, itSizeAttr)) { Debug.LogWarning("Found illegal itSize " + "attribute for Image " + "Target " + itNameAttr + " in config.xml. " + "Image Target will be " + "ignored."); continue; } } else { Debug.LogWarning("Image Target " + itNameAttr + " is missing a itSize " + "attribut in config.xml. " + "Image Target will be " + "ignored."); continue; } configReader.MoveToElement(); ConfigData.ImageTarget imageTarget = new ConfigData.ImageTarget(); imageTarget.size = itSize; imageTarget.virtualButtons = new List<ConfigData.VirtualButton>(); configData.SetImageTarget(imageTarget, itNameAttr); break; case "VirtualButton": // Parse name from config file string vbNameAttr = configReader.GetAttribute("name"); if (vbNameAttr == null) { Debug.LogWarning("Found VirtualButton " + "without name attribute in " + "config.xml. Virtual Button " + "will be ignored."); continue; } // Parse rectangle from config file Vector4 vbRectangle = Vector4.zero; string[] vbRectangleAttr = configReader.GetAttribute("rectangle").Split(' '); if (vbRectangleAttr != null) { if (!QCARUtilities.RectangleFromStringArray( out vbRectangle, vbRectangleAttr)) { Debug.LogWarning("Found invalid " + "rectangle attribute " + "for Virtual Button " + vbNameAttr + " in config.xml. " + "Virtual Button will " + "be ignored."); continue; } } else { Debug.LogWarning("Virtual Button " + vbNameAttr + " has no rectangle " + "attribute in config.xml. " + "Virtual Button will be " + "ignored."); continue; } // Parse enabled boolean from config file bool vbEnabled = true; string enabledAttr = configReader.GetAttribute("enabled"); if (enabledAttr != null) { if (string.Compare(enabledAttr, "true", true) == 0) { vbEnabled = true; } else if (string.Compare(enabledAttr, "false", true) == 0) { vbEnabled = false; } else { Debug.LogWarning("Found invalid enabled " + "attribute for Virtual " + "Button " + vbNameAttr + " in config.xml. " + "Default setting will " + "be used."); } } // Parse sensitivity from config file VirtualButtonBehaviour.Sensitivity vbSensitivity = VirtualButtonBehaviour.DEFAULT_SENSITIVITY; string vbSensitivityAttr = configReader.GetAttribute("sensitivity"); if (vbSensitivityAttr != null) { if (string.Compare(vbSensitivityAttr, "low", true) == 0) { vbSensitivity = VirtualButtonBehaviour.Sensitivity.LOW; } else if (string.Compare(vbSensitivityAttr, "medium", true) == 0) { vbSensitivity = VirtualButtonBehaviour.Sensitivity.MEDIUM; } else if (string.Compare(vbSensitivityAttr, "high", true) == 0) { vbSensitivity = VirtualButtonBehaviour.Sensitivity.HIGH; } else { Debug.LogWarning("Found illegal " + "sensitivity attribute " + "for Virtual Button " + vbNameAttr + " in config.xml. " + "Default setting will " + "be used."); } } configReader.MoveToElement(); ConfigData.VirtualButton virtualButton = new ConfigData.VirtualButton(); string latestITName = GetLatestITName(configData); virtualButton.name = vbNameAttr; virtualButton.rectangle = vbRectangle; virtualButton.enabled = vbEnabled; virtualButton.sensitivity = vbSensitivity; // Since the XML Reader runs top down we can assume // that the Virtual Button that has been found is // part of the latest Image Target. if (configData.ImageTargetExists(latestITName)) { configData.AddVirtualButton(virtualButton, latestITName); } else { Debug.LogWarning("Image Target with name " + latestITName + " could not be found. " + "Virtual Button " + vbNameAttr + "will not be added."); } break; case "MultiTarget": // Parse name from config file string mtNameAttr = configReader.GetAttribute("name"); if (mtNameAttr == null) { Debug.LogWarning("Found Multi Target without " + "name attribute in " + "config.xml. Multi Target " + "will be ignored."); continue; } configReader.MoveToElement(); ConfigData.MultiTarget multiTarget = new ConfigData.MultiTarget(); multiTarget.parts = new List<ConfigData.MultiTargetPart>(); configData.SetMultiTarget(multiTarget, mtNameAttr); break; case "Part": // Parse name from config file string prtNameAttr = configReader.GetAttribute("name"); if (prtNameAttr == null) { Debug.LogWarning("Found Multi Target Part " + "without name attribute in " + "config.xml. Part will be " + "ignored."); continue; } // Parse translations from config file Vector3 prtTranslation = Vector3.zero; string[] prtTranslationAttr = configReader.GetAttribute("translation").Split(' '); if (prtTranslationAttr != null) { if (!QCARUtilities.TransformFromStringArray( out prtTranslation, prtTranslationAttr)) { Debug.LogWarning("Found illegal " + "transform attribute " + "for Part " + prtNameAttr + " in config.xml. Part " + "will be ignored."); continue; } } else { Debug.LogWarning("Multi Target Part " + prtNameAttr + " has no " + "translation attribute in " + "config.xml. Part will be " + "ignored."); continue; } // Parse rotations from config file Quaternion prtRotation = Quaternion.identity; string[] prtRotationAttr = configReader.GetAttribute("rotation").Split(' '); if (prtRotationAttr != null) { if (!QCARUtilities.OrientationFromStringArray( out prtRotation, prtRotationAttr)) { Debug.LogWarning("Found illegal rotation " + "attribute for Part " + prtNameAttr + " in config.xml. Part " + "will be ignored."); continue; } } else { Debug.LogWarning("Multi Target Part " + prtNameAttr + " has no " + "rotation attribute in " + "config.xml. Part will be " + "ignored."); continue; } configReader.MoveToElement(); ConfigData.MultiTargetPart multiTargetPart = new ConfigData.MultiTargetPart(); string latestMTName = GetLatestMTName(configData); multiTargetPart.name = prtNameAttr; multiTargetPart.rotation = prtRotation; multiTargetPart.translation = prtTranslation; // Since the XML Reader runs top down we can assume // that the Virtual Button that has been found is // part of the latest Image Target. if (configData.MultiTargetExists(latestMTName)) { configData.AddMultiTargetPart(multiTargetPart, latestMTName); } else { Debug.LogWarning("Multi Target with name " + latestMTName + " could not be found. " + "Multi Target Part " + prtNameAttr + "will not be added."); } break; default: break; } } } } return true; }
protected override void DoRead(IDataQueue queue) { try { TableStructure s = CreateStructure(); Dictionary <string, int> colPos = new Dictionary <string, int>(); for (int i = 0; i < m_columnNames.Count; i++) { colPos[m_columnNames[i]] = i; colPos[XmlTool.NormalizeIdentifier(m_columnNames[i])] = i; } using (XmlReader xr = new XmlTextReader(GetWorkingFileName())) { xr.MoveToContent(); if (xr.Name != m_rootElementName) { Logging.Warning("Root element has different name"); } xr.Read(); while (xr.NodeType == XmlNodeType.Element) { // process one row object[] values = new object[m_columnNames.Count]; for (int i = 0; i < values.Length; i++) { values[i] = DBNull.Value; } if (xr.Name == m_rowElementName) { switch (m_storageType) { case XmlDataStorageType.Attribute: for (int i = 0; i < xr.AttributeCount; i++) { xr.MoveToAttribute(i); string name = xr.Name; if (colPos.ContainsKey(name)) { values[colPos[name]] = xr.Value; } } xr.MoveToElement(); xr.Read(); break; case XmlDataStorageType.ColumnNamedElement: xr.Read(); xr.MoveToContent(); while (xr.NodeType == XmlNodeType.Element) { string name = xr.Name; string value = xr.ReadElementContentAs(typeof(string), null).ToString(); if (colPos.ContainsKey(name)) { values[colPos[name]] = value; } } xr.MoveToContent(); if (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } break; case XmlDataStorageType.InvariantNamedElement: xr.Read(); xr.MoveToContent(); while (xr.NodeType == XmlNodeType.Element) { string name = xr.GetAttribute(m_columnAttributeName); string value = xr.ReadElementContentAs(typeof(string), null).ToString(); if (colPos.ContainsKey(name)) { values[colPos[name]] = value; } } xr.MoveToContent(); if (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } break; } } else { xr.Skip(); } queue.PutRecord(new ArrayDataRecord(s, values)); } } } finally { queue.PutEof(); } FinalizeBulkCopy(); }
private void xmlaircraft(string filename = "aircraft.xml") { try { using (XmlTextReader xmlreader = new XmlTextReader(filename)) { while (xmlreader.Read()) { xmlreader.MoveToElement(); try { switch (xmlreader.Name) { case "Vehicle": { aircraftinfo aircraft = new aircraftinfo(); while (xmlreader.Read()) { bool dobreak = false; xmlreader.MoveToElement(); switch (xmlreader.Name) { case "name": aircraft.name = xmlreader.ReadString(); break; case "turn_rad_m": aircraft.turnrad = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "min_alt_m": aircraft.minalt = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "max_alt_m": aircraft.maxalt = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "min_vel_ms": aircraft.minvel = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "max_vel_ms": aircraft.maxvel = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; case "Vehicle": aircrafts[aircraft.name] = aircraft; dobreak = true; break; } if (dobreak) { break; } } string temp = xmlreader.ReadString(); } break; case "xml": break; default: break; } } catch (Exception ee) { Console.WriteLine(ee.Message); } // silent fail on bad entry } } } catch (Exception ex) { Console.WriteLine("Bad Aircraft File: " + ex.ToString()); } // bad config file // populate list foreach (var aircraft in aircrafts.Values) { if (!CMB_aircraft.Items.Contains(aircraft.name)) { CMB_aircraft.Items.Add(aircraft.name); } } }
//public Dictionary<String, String> createDictionary() //{ // Populate the Dictionary! // XDictionaryLoader myDictionaryLoader = new XDictionaryLoader(); // return myDictionaryLoader.ParseXML(); //} /* * public new static XObject consumeXML(Dictionary<String, String> myConfig, string XmlElement, bool bDeep = false) * { * //XDictionaryLoader myDictionaryLoader = new XDictionaryLoader(); * //myDictionaryLoader.Augment(); * // * // Consume XML to create the XComponent object. * // if bDeep is false, then ONLY do this object. * // if bDeep is true, then also do recursive objects. * return new XComponent(); * } * */ public new static XTRMObject consumeXML(Dictionary <String, String> existingConfig, string XmlFragment, int lVariant = 0, bool bDeep = false) { //XDictionaryLoader myDictionaryLoader = new XDictionaryLoader(); //myDictionaryLoader.Augment(); // // Consume XML to create the XComponent object. // if bDeep is false, then ONLY do this object. // if bDeep is true, then also do recursive objects. XmlTextReader reader = null; XmlParserContext context = null; Dictionary <String, String> myConfig = new Dictionary <string, string>(existingConfig); XTRMJob thisJob = new XTRMJob(); try { // Load the reader with the data file and ignore all white space nodes. context = new XmlParserContext(null, null, null, XmlSpace.None); reader = new XmlTextReader(XmlFragment, XmlNodeType.Element, context); reader.WhitespaceHandling = WhitespaceHandling.None; // Parse the file and display each of the nodes. bool bResult = reader.Read(); string outerXML; int lElementType = 0; XDictionaryLoader myDictionaryLoader = new XDictionaryLoader(); Dictionary <String, String> elementAttributes; while (bResult) { bool bProcessed = false; switch (reader.NodeType) { case XmlNodeType.Element: string elementName = reader.Name; switch (elementName.ToUpper()) { case "XTRMTask": // XTRMTask outerXML = reader.ReadOuterXml(); XTRMTask thisTask = (XTRMTask)XTRMTask.consumeXML(myConfig, outerXML, 1, true); thisJob.tasks.Add(thisTask); bProcessed = true; break; } // May wish to get all the attributes here for new elements! if (!bProcessed) { elementAttributes = new Dictionary <String, String>(); if (reader.HasAttributes) { reader.MoveToFirstAttribute(); for (int i = 0; i < reader.AttributeCount; i++) { //reader.GetAttribute(i); elementAttributes.Add(reader.Name, reader.Value); reader.MoveToNextAttribute(); } if (elementAttributes.ContainsKey("Name")) { thisJob.jobName = elementAttributes["Name"]; } if (elementAttributes.ContainsKey("Host")) { thisJob.jobHost = elementAttributes["Host"]; } reader.MoveToElement(); } // Need to see if we are interested in this element! switch (elementName.ToUpper()) { //case "XTRMTask": // XTRMTask // outerXML = reader.ReadOuterXml(); // XTRMTask thisTask = (XTRMTask)XTRMTask.consumeXML(myConfig, outerXML, 1, true); // thisJob.tasks.Add(thisTask); // break; // Reset Dictionary! // XConfig case "BASECONFIG": outerXML = reader.ReadOuterXml(); myDictionaryLoader = new XDictionaryLoader(); myConfig = new Dictionary <string, string>(); myDictionaryLoader.Augment(myConfig, outerXML); break; // Add to the current dictionary! // XConfig case "WITHCONFIG": outerXML = reader.ReadOuterXml(); //myDictionaryLoader = new XDictionaryLoader(); myDictionaryLoader.Augment(myConfig, outerXML); break; default: bResult = reader.Read(); break; } } break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: //writer.WriteProcessingInstruction(reader.Name, reader.Value); bResult = reader.Read(); break; case XmlNodeType.Comment: //writer.WriteComment(reader.Value); bResult = reader.Read(); break; case XmlNodeType.EndElement: //writer.WriteFullEndElement(); bResult = reader.Read(); break; case XmlNodeType.Text: //Console.Write(reader.Value); switch (lElementType) { //case 1: // PARMS //thisTask.parms.Add(reader.Value); default: break; } bResult = reader.Read(); break; default: bResult = reader.Read(); break; } } } catch (Exception ex) { exCount_XML++; XLogger(2320, -1, string.Format("XML={0}; Message={1}", XmlFragment, ex.Message)); } finally { if (reader != null) { reader.Close(); } } thisJob.config = myConfig; return(thisJob); }
internal void Firmware_Load(object sender, EventArgs e) { log.Info("FW load"); string url = ""; string url2560 = ""; string url2560_2 = ""; string name = ""; string desc = ""; int k_format_version = 0; softwares.Clear(); software temp = new software(); // this is for mono to a ssl server //ServicePointManager.CertificatePolicy = new NoCheckCertificatePolicy(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender1, certificate, chain, policyErrors) => { return(true); }); try { log.Info("url: " + firmwareurl); using (XmlTextReader xmlreader = new XmlTextReader(firmwareurl)) { while (xmlreader.Read()) { xmlreader.MoveToElement(); switch (xmlreader.Name) { case "url": url = xmlreader.ReadString(); break; case "url2560": url2560 = xmlreader.ReadString(); break; case "url2560-2": url2560_2 = xmlreader.ReadString(); break; case "name": name = xmlreader.ReadString(); break; case "format_version": k_format_version = int.Parse(xmlreader.ReadString()); break; case "desc": desc = xmlreader.ReadString(); break; case "Firmware": if (!url.Equals("") && !name.Equals("") && !desc.Equals("Please Update")) { temp.desc = desc; temp.name = name; temp.url = url; temp.url2560 = url2560; temp.url2560_2 = url2560_2; temp.k_format_version = k_format_version; try { updateDisplayName(temp); } catch { } // just in case softwares.Add(temp); } url = ""; url2560 = ""; name = ""; desc = ""; k_format_version = 0; temp = new software(); break; default: break; } } } } catch (Exception ex) { log.Error(ex); CustomMessageBox.Show("Failed to get Firmware List : " + ex.Message); } log.Info("FW load done"); }
public int IncludeConfig(string inFile, Dictionary <String, String> myConfig, int lVariant = 0, bool bDeep = false) { // // Consume XML to create the XLator object. // if bDeep is false, then ONLY do this object. // if bDeep is true, then also do recursive objects. int rc = -1; XmlTextReader reader = null; string connectString = XTRMObject.getDictionaryEntry("TaskConnectString"); string outerXML; int lElementType = 0; XDictionaryLoader myDictionaryLoader = new XDictionaryLoader(); Dictionary <String, String> elementAttributes; try { // Load the reader with the data file and ignore all white space nodes. reader = new XmlTextReader(inFile); reader.WhitespaceHandling = WhitespaceHandling.None; // Parse the file and display each of the nodes. bool bResult = reader.Read(); while (bResult) { bool bProcessed = false; switch (reader.NodeType) { case XmlNodeType.Element: string elementName = reader.Name; switch (elementName.ToUpper()) { case "BASECONFIG": outerXML = reader.ReadOuterXml(); myDictionaryLoader = new XDictionaryLoader(); myConfig = myDictionaryLoader.Augment(myConfig, outerXML); bProcessed = true; break; case "WITHCONFIG": outerXML = reader.ReadOuterXml(); myDictionaryLoader.Augment(myConfig, outerXML); bProcessed = true; break; case "EVENTFILTER": outerXML = reader.ReadOuterXml(); XTRMEvent thisFilter = (XTRMEvent)XTRMEvent.consumeXML(myConfig, outerXML, 2, true); eventFilters.Add(thisFilter); bProcessed = true; break; case "XTRMEVENT": outerXML = reader.ReadOuterXml(); XTRMEvent thisEvent = (XTRMEvent)XTRMEvent.consumeXML(myConfig, outerXML, 1, true); events.Add(thisEvent); bProcessed = true; break; case "XTRMWORKFLOW": outerXML = reader.ReadOuterXml(); XTRMWorkFlow thisFlow = (XTRMWorkFlow)XTRMWorkFlow.consumeXML(myConfig, outerXML, 1, true); workflows.Add(thisFlow); bProcessed = true; break; } if (!bProcessed) { // May wish to get all the attributes here for new elements! elementAttributes = new Dictionary <String, String>(); if (reader.HasAttributes) { reader.MoveToFirstAttribute(); for (int i = 0; i < reader.AttributeCount; i++) { elementAttributes.Add(reader.Name, reader.Value); reader.MoveToNextAttribute(); } if (elementAttributes.ContainsKey("Name")) { // Try to instantiate the XEvent Object! name = elementAttributes["Name"]; } reader.MoveToElement(); } // Need to see if we are interested in this element! //string elementName = reader.Name; switch (elementName.ToUpper()) //switch (reader.Name) { case "EVENTFOLDER": lElementType = 1; bResult = reader.Read(); break; case "XTRM": // Advance into Elements! reader.MoveToContent(); bResult = reader.Read(); break; default: bResult = reader.Read(); break; } } break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: bResult = reader.Read(); break; case XmlNodeType.Comment: bResult = reader.Read(); break; case XmlNodeType.EndElement: bResult = reader.Read(); break; case XmlNodeType.Text: switch (lElementType) { case 1: // EventFolder eventFolders.Add(ResolveText(reader.Value, XDictionary)); break; default: break; } bResult = reader.Read(); break; default: bResult = reader.Read(); break; } } } catch (Exception ex) { exCount_XML++; XLogger(2402, -1, string.Format("XLator::IncludeConfig(); ConfigFile={0}; Message={1}", configFile, ex.Message)); } finally { if (reader != null) { reader.Close(); } } return(rc); }
private void ScanFactoriesRecursive(XmlTextReader reader, string configKey) { int depth = reader.Depth; StrictReadToNextElement(reader); while (reader.Depth == depth + 1) { switch (reader.Name) { case "sectionGroup": { // Get the name of the current sectionGroup string tagName = null; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name != "name") { ThrowUnrecognizedAttribute(reader); } tagName = reader.Value; } reader.MoveToElement(); } // sectionGroup name attribute must have a value CheckRequiredAttribute(tagName, "name", reader); // Check the validity of the section name VerifySectionName(tagName, reader); // Add the current sectionGroup to the hashtable and process it string tagKey = TagKey(configKey, tagName); if (HaveFactoryEnum.Section == HaveFactory(tagName)) { throw BuildConfigError("Tag name already defined", reader); } EnsureFactories[tagKey] = GroupSingleton; ScanFactoriesRecursive(reader, tagKey); continue; } case "section": { string tagName = null; string typeName = null; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { switch (reader.Name) { case "name": tagName = reader.Value; break; case "type": typeName = reader.Value; break; case "allowLocation": case "allowDefinition": break; default: ThrowUnrecognizedAttribute(reader); break; } } reader.MoveToElement(); } CheckRequiredAttribute(tagName, "name", reader); CheckRequiredAttribute(typeName, "type", reader); VerifySectionName(tagName, reader); string tagKey = TagKey(configKey, tagName); if (HaveFactory(tagKey) != HaveFactoryEnum.NotFound) { throw BuildConfigError("Tag name already defined", reader); } EnsureFactories[tagKey] = typeName; break; } case "remove": { string tagName = null; // Schema defines that <remove /> elements must have a name attribute // so check to see if we have one and retrieve its value if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name != "name") { ThrowUnrecognizedAttribute(reader); } tagName = reader.Value; } reader.MoveToElement(); } // Enforce schema definition of remove element if (tagName == null) { this.ThrowRequiredAttribute(reader, "name"); } // Does the remove element have a valid name? this.VerifySectionName(tagName, reader); // If so, add it to the hashtable string tagKey = ConfigurationRecord.TagKey(configKey, tagName); if (HaveFactory(tagKey) != HaveFactoryEnum.Section) { throw BuildConfigError("Could not remove section handler", reader); } EnsureFactories[tagName] = RemovedFactorySingleton; break; } case "clear": { // Config schema definition states that clear element has no attributes CheckForUnrecognizedAttributes(reader); // Reset factories hashtable factories = null; factoriesNoInherit = true; break; } default: ThrowUnrecognizedElement(reader); break; } this.StrictReadToNextElement(reader); // Unrecognized children are not allowed if (reader.Depth > depth + 1) { ThrowUnrecognizedElement(reader); } } }
/// <summary> /// Loads the XML. /// </summary> /// <param name="filename"> /// The filename. /// </param> /// <returns> /// A bool value... /// </returns> private bool LoadXml(string filename) { var nt = new NameTable(); var nsm = new XmlNamespaceManager(nt); nsm.AddNamespace(string.Empty, "http://www.w3.org/1999/xhtml"); var context = new XmlParserContext(nt, nsm, string.Empty, XmlSpace.None); var returnValue = false; try { // Create an XmlTextReader using a FileStream. using (Stream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { try { var xtr = new XmlTextReader(fs, XmlNodeType.Document, context) { WhitespaceHandling = WhitespaceHandling.None }; ThemeImage themeImage; var themePart = new ThemePart(); while (!xtr.EOF) { if (xtr.MoveToContent() == XmlNodeType.Element) { switch (xtr.LocalName) { case "Name": this.currentTheme.Name = xtr.ReadString(); break; case "Type": this.currentTheme.Type = xtr.ReadString(); break; case "Css": this.currentTheme.Css = xtr.ReadString(); break; case "MinimizeColor": this.currentTheme.MinimizeColor = xtr.ReadString(); break; case "ThemeImage": themeImage = new ThemeImage(); while (xtr.MoveToNextAttribute()) { switch (xtr.LocalName) { case "Name": themeImage.Name = xtr.Value; break; case "ImageUrl": themeImage.ImageUrl = xtr.Value; break; case "Width": themeImage.Width = double.Parse(xtr.Value); break; case "Height": themeImage.Height = double.Parse(xtr.Value); break; default: break; } } this.currentTheme.ThemeImages.Add(themeImage.Name, themeImage); xtr.MoveToElement(); break; case "ThemePart": themePart = new ThemePart(); while (xtr.MoveToNextAttribute()) { switch (xtr.LocalName) { case "Name": themePart.Name = xtr.Value; break; default: break; } } xtr.MoveToElement(); break; case "HTML": if (themePart.Name.Length != 0) { themePart.Html = xtr.ReadString(); } // Moved here on load instead on retrival. // by Manu var w = string.Concat(this.currentTheme.WebPath, "/"); themePart.Html = themePart.Html.Replace("src='", string.Concat("src='", w)); themePart.Html = themePart.Html.Replace("src=\"", string.Concat("src=\"", w)); themePart.Html = themePart.Html.Replace( "background='", string.Concat("background='", w)); themePart.Html = themePart.Html.Replace( "background=\"", string.Concat("background=\"", w)); this.currentTheme.ThemeParts.Add(themePart.Name, themePart); break; default: // Debug.WriteLine(" - unwanted"); break; } } xtr.Read(); } returnValue = true; } catch (Exception ex) { ErrorHandler.Publish( LogLevel.Error, string.Format("Failed to Load XML Theme : {0} Message was: {1}", filename, ex.Message)); } finally { fs.Close(); } } } catch (Exception ex) { ErrorHandler.Publish( LogLevel.Error, string.Format("Failed to open XML Theme : {0} Message was: {1}", filename, ex.Message)); } return(returnValue); }
static void ReadXML(string file) { DateTime start = DateTime.Now; Build BUILD = new Build(); using (XmlTextReader reader = new XmlTextReader(file)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.HasAttributes) { switch (reader.Name.ToLower()) { case "build": //has this been defined already?... meh BUILD = BuildMain(reader, file); break; case "lzr": //compress and replace section tlzr = BuildSection(reader, "lzr"); BUILD.buildSections.Add(tlzr); break; case "lzi": //compress and insert section tlzi = BuildSection(reader, "lzi"); BUILD.buildSections.Add(tlzi); break; case "rlr": //compress and replace section trlr = BuildSection(reader, "rlr"); BUILD.buildSections.Add(trlr); break; case "rli": //compress and insert section trli = BuildSection(reader, "rli"); BUILD.buildSections.Add(trli); break; case "rep": //overwrite existing data section trep = BuildSection(reader, "rep"); BUILD.buildSections.Add(trep); break; case "ins": //insert data section tins = BuildSection(reader, "ins"); BUILD.buildSections.Add(tins); break; case "bpr": //bitplane conversion, overwrite existing data section tbpr = BuildSection(reader, "bpr"); BUILD.buildSections.Add(tbpr); break; case "bpi": //bitplane conversion, insert data section tbpi = BuildSection(reader, "bpi"); BUILD.buildSections.Add(tbpi); break; case "sbr": // script build replace section tsbr = BuildSection(reader, "sbr"); BUILD.buildSections.Add(tsbr); break; case "sbi": //script build insert section tsbi = BuildSection(reader, "sbi"); BUILD.buildSections.Add(tsbi); break; } reader.MoveToElement(); } } else if (reader.NodeType == XmlNodeType.EndElement) {//closing the element... we will perform the build. if (reader.Name.ToLower() == "build") { Console.WriteLine("Verifying and building..."); RunFullBuild(BUILD); Console.WriteLine("Build Complete. (Total Time: " + GetElapsedTime(start) + ")"); } } } } }
/// <summary> /// Format an Xml element to be written to the config file. /// </summary> /// <param name="xmlElement">the element</param> /// <param name="linePosition">start position of the element</param> /// <param name="indent">indent for each depth</param> /// <param name="skipFirstIndent">skip indent for the first element?</param> /// <returns></returns> internal static string FormatXmlElement(string xmlElement, int linePosition, int indent, bool skipFirstIndent) { XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.Default, Encoding.Unicode); XmlTextReader reader = new XmlTextReader(xmlElement, XmlNodeType.Element, context); StringWriter stringWriter = new StringWriter(new StringBuilder(64), CultureInfo.InvariantCulture); XmlUtilWriter utilWriter = new XmlUtilWriter(stringWriter, false); // append newline before indent? bool newLine = false; // last node visited was text? bool lastWasText = false; // length of the stringbuilder after last indent with newline int sbLengthLastNewLine = 0; while (reader.Read()) { XmlNodeType nodeType = reader.NodeType; int lineWidth; if (lastWasText) { utilWriter.Flush(); lineWidth = sbLengthLastNewLine - ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; } else { lineWidth = 0; } switch (nodeType) { case XmlNodeType.CDATA: case XmlNodeType.Element: case XmlNodeType.EndElement: case XmlNodeType.Comment: // Do not indent if the last node was text - doing so would add whitespace // that is included as part of the text. if (!skipFirstIndent && !lastWasText) { utilWriter.AppendIndent(linePosition, indent, reader.Depth, newLine); if (newLine) { utilWriter.Flush(); sbLengthLastNewLine = ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; } } break; } lastWasText = false; switch (nodeType) { case XmlNodeType.Whitespace: break; case XmlNodeType.SignificantWhitespace: utilWriter.Write(reader.Value); break; case XmlNodeType.CDATA: utilWriter.AppendCData(reader.Value); break; case XmlNodeType.ProcessingInstruction: utilWriter.AppendProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.Comment: utilWriter.AppendComment(reader.Value); break; case XmlNodeType.Text: utilWriter.AppendEscapeTextString(reader.Value); lastWasText = true; break; case XmlNodeType.Element: { // Write "<elem" utilWriter.Write('<'); utilWriter.Write(reader.Name); lineWidth += reader.Name.Length + 2; int c = reader.AttributeCount; for (int i = 0; i < c; i++) { // Add new line if we've exceeded the line width bool writeSpace; if (lineWidth > MaxLineWidth) { utilWriter.AppendIndent(linePosition, indent, reader.Depth - 1, true); lineWidth = indent; writeSpace = false; utilWriter.Flush(); sbLengthLastNewLine = ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; } else { writeSpace = true; } // Write the attribute reader.MoveToNextAttribute(); utilWriter.Flush(); int startLength = ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; if (writeSpace) { utilWriter.AppendSpace(); } utilWriter.Write(reader.Name); utilWriter.Write('='); utilWriter.AppendAttributeValue(reader); utilWriter.Flush(); lineWidth += ((StringWriter)utilWriter.Writer).GetStringBuilder().Length - startLength; } } // position reader back on element reader.MoveToElement(); // write closing tag if (reader.IsEmptyElement) { utilWriter.Write(" />"); } else { utilWriter.Write('>'); } break; case XmlNodeType.EndElement: utilWriter.Write("</"); utilWriter.Write(reader.Name); utilWriter.Write('>'); break; case XmlNodeType.EntityReference: utilWriter.AppendEntityRef(reader.Name); break; // Ignore <?xml and <!DOCTYPE nodes // case XmlNodeType.XmlDeclaration: // case XmlNodeType.DocumentType: } // put each new element on a new line newLine = true; // do not skip any more indents skipFirstIndent = false; } utilWriter.Flush(); string s = ((StringWriter)utilWriter.Writer).ToString(); return(s); }
public static bool Import(TextReader streamReader, IResource rootGroup, bool addToWorkspace, Hashtable namespaces) { bool hasOPML = false; bool lastOutlineIsGroup = false; try { NameTable nt = new NameTable(); // Fill name table if (namespaces != null) { foreach (string key in namespaces.Keys) { nt.Add(key); nt.Add(namespaces[key] as string); } } XmlNamespaceManager nsmgr = new LooseNSManager(nt, namespaces); XmlParserContext ctx = new XmlParserContext(nt, nsmgr, null, XmlSpace.None); string xml = Utils.StreamReaderReadToEnd(streamReader); XmlTextReader reader = new XmlTextReader(xml, XmlNodeType.Document, ctx); try { IResource curGroup = rootGroup; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.LocalName == "opml") { hasOPML = true; } else if (hasOPML && reader.LocalName == "outline") { if (reader.MoveToAttribute("xmlUrl") || reader.MoveToAttribute("xmlurl")) { ProcessFeed(reader, curGroup, addToWorkspace); } else if (reader.MoveToAttribute("text") || reader.MoveToAttribute("title")) { IResource group = FindOrCreateGroup(curGroup, reader.Value); reader.MoveToElement(); if (!reader.IsEmptyElement) { curGroup = group; lastOutlineIsGroup = true; } } } } else if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName == "outline") { if (lastOutlineIsGroup) { curGroup = curGroup.GetLinkProp("Parent"); lastOutlineIsGroup = true; } } } } } finally { reader.Close(); } } finally { streamReader.Close(); } return(hasOPML); }
// This method reads a config.xml file at the given path and fills the // ConfigData object with the data. public bool fileToStruct(string configXMLPath, ConfigData configData) { if (!File.Exists(configXMLPath)) { return(false); } using (XmlTextReader configReader = new XmlTextReader(configXMLPath)) { while (configReader.Read()) { if (configReader.NodeType == XmlNodeType.Element) { // "Global" Attributes string itNameAttr = ""; switch (configReader.Name) { case "ImageTarget": // Parse name from config file itNameAttr = configReader.GetAttribute("name"); if (itNameAttr == null) { Debug.LogWarning("Found ImageTarget without " + "name attribute in " + "config.xml. Image Target " + "will be ignored."); continue; } // Parse itSize from config file Vector2 itSize = Vector2.zero; string[] itSizeAttr = configReader.GetAttribute("size").Split(' '); if (itSizeAttr != null) { if (!QCARUtilities.SizeFromStringArray( out itSize, itSizeAttr)) { Debug.LogWarning("Found illegal itSize " + "attribute for Image " + "Target " + itNameAttr + " in config.xml. " + "Image Target will be " + "ignored."); continue; } } else { Debug.LogWarning("Image Target " + itNameAttr + " is missing a itSize " + "attribut in config.xml. " + "Image Target will be " + "ignored."); continue; } configReader.MoveToElement(); ConfigData.ImageTargetData imageTarget = new ConfigData.ImageTargetData(); imageTarget.size = itSize; imageTarget.virtualButtons = new List <ConfigData.VirtualButtonData>(); configData.SetImageTarget(imageTarget, itNameAttr); break; case "VirtualButton": // Parse name from config file string vbNameAttr = configReader.GetAttribute("name"); if (vbNameAttr == null) { Debug.LogWarning("Found VirtualButton " + "without name attribute in " + "config.xml. Virtual Button " + "will be ignored."); continue; } // Parse rectangle from config file Vector4 vbRectangle = Vector4.zero; string[] vbRectangleAttr = configReader.GetAttribute("rectangle").Split(' '); if (vbRectangleAttr != null) { if (!QCARUtilities.RectangleFromStringArray( out vbRectangle, vbRectangleAttr)) { Debug.LogWarning("Found invalid " + "rectangle attribute " + "for Virtual Button " + vbNameAttr + " in config.xml. " + "Virtual Button will " + "be ignored."); continue; } } else { Debug.LogWarning("Virtual Button " + vbNameAttr + " has no rectangle " + "attribute in config.xml. " + "Virtual Button will be " + "ignored."); continue; } // Parse enabled boolean from config file bool vbEnabled = true; string enabledAttr = configReader.GetAttribute("enabled"); if (enabledAttr != null) { if (string.Compare(enabledAttr, "true", true) == 0) { vbEnabled = true; } else if (string.Compare(enabledAttr, "false", true) == 0) { vbEnabled = false; } else { Debug.LogWarning("Found invalid enabled " + "attribute for Virtual " + "Button " + vbNameAttr + " in config.xml. " + "Default setting will " + "be used."); } } // Parse sensitivity from config file VirtualButton.Sensitivity vbSensitivity = VirtualButton.DEFAULT_SENSITIVITY; string vbSensitivityAttr = configReader.GetAttribute("sensitivity"); if (vbSensitivityAttr != null) { if (string.Compare(vbSensitivityAttr, "low", true) == 0) { vbSensitivity = VirtualButton.Sensitivity.LOW; } else if (string.Compare(vbSensitivityAttr, "medium", true) == 0) { vbSensitivity = VirtualButton.Sensitivity.MEDIUM; } else if (string.Compare(vbSensitivityAttr, "high", true) == 0) { vbSensitivity = VirtualButton.Sensitivity.HIGH; } else { Debug.LogWarning("Found illegal " + "sensitivity attribute " + "for Virtual Button " + vbNameAttr + " in config.xml. " + "Default setting will " + "be used."); } } configReader.MoveToElement(); ConfigData.VirtualButtonData virtualButton = new ConfigData.VirtualButtonData(); string latestITName = GetLatestITName(configData); virtualButton.name = vbNameAttr; virtualButton.rectangle = vbRectangle; virtualButton.enabled = vbEnabled; virtualButton.sensitivity = vbSensitivity; // Since the XML Reader runs top down we can assume // that the Virtual Button that has been found is // part of the latest Image Target. if (configData.ImageTargetExists(latestITName)) { configData.AddVirtualButton(virtualButton, latestITName); } else { Debug.LogWarning("Image Target with name " + latestITName + " could not be found. " + "Virtual Button " + vbNameAttr + "will not be added."); } break; case "MultiTarget": // Parse name from config file string mtNameAttr = configReader.GetAttribute("name"); if (mtNameAttr == null) { Debug.LogWarning("Found Multi Target without " + "name attribute in " + "config.xml. Multi Target " + "will be ignored."); continue; } configReader.MoveToElement(); ConfigData.MultiTargetData multiTarget = new ConfigData.MultiTargetData(); multiTarget.parts = new List <ConfigData.MultiTargetPartData>(); configData.SetMultiTarget(multiTarget, mtNameAttr); break; case "Part": // Parse name from config file string prtNameAttr = configReader.GetAttribute("name"); if (prtNameAttr == null) { Debug.LogWarning("Found Multi Target Part " + "without name attribute in " + "config.xml. Part will be " + "ignored."); continue; } // Parse translations from config file Vector3 prtTranslation = Vector3.zero; string[] prtTranslationAttr = configReader.GetAttribute("translation").Split(' '); if (prtTranslationAttr != null) { if (!QCARUtilities.TransformFromStringArray( out prtTranslation, prtTranslationAttr)) { Debug.LogWarning("Found illegal " + "transform attribute " + "for Part " + prtNameAttr + " in config.xml. Part " + "will be ignored."); continue; } } else { Debug.LogWarning("Multi Target Part " + prtNameAttr + " has no " + "translation attribute in " + "config.xml. Part will be " + "ignored."); continue; } // Parse rotations from config file Quaternion prtRotation = Quaternion.identity; string[] prtRotationAttr = configReader.GetAttribute("rotation").Split(' '); if (prtRotationAttr != null) { if (!QCARUtilities.OrientationFromStringArray( out prtRotation, prtRotationAttr)) { Debug.LogWarning("Found illegal rotation " + "attribute for Part " + prtNameAttr + " in config.xml. Part " + "will be ignored."); continue; } } else { Debug.LogWarning("Multi Target Part " + prtNameAttr + " has no " + "rotation attribute in " + "config.xml. Part will be " + "ignored."); continue; } configReader.MoveToElement(); ConfigData.MultiTargetPartData multiTargetPart = new ConfigData.MultiTargetPartData(); string latestMTName = GetLatestMTName(configData); multiTargetPart.name = prtNameAttr; multiTargetPart.rotation = prtRotation; multiTargetPart.translation = prtTranslation; // Since the XML Reader runs top down we can assume // that the Virtual Button that has been found is // part of the latest Image Target. if (configData.MultiTargetExists(latestMTName)) { configData.AddMultiTargetPart(multiTargetPart, latestMTName); } else { Debug.LogWarning("Multi Target with name " + latestMTName + " could not be found. " + "Multi Target Part " + prtNameAttr + "will not be added."); } break; default: break; } } } } return(true); }
public List <Skeleton> ImportAction(string xmlFilepath) { var xmlReadingState = ReadingXmlState.Skeleton; int currentID = 0; JointType currentJointType = JointType.AnkleRight; XmlTextReader xmlReader = new XmlTextReader(xmlFilepath); while (xmlReader.Read()) { xmlReader.MoveToElement(); if (xmlReader.NodeType != XmlNodeType.EndElement) { #region Managing reading states if (xmlReader.Name != string.Empty) { if (xmlReader.Name == "skeleton") { xmlReadingState = ReadingXmlState.Skeleton; SkeletonCollection.Add(new Skeleton()); } else if (xmlReader.Name == "recordedSampleID") { xmlReadingState = ReadingXmlState.RecordedSampleID; } else if (xmlReader.Name == "x") { xmlReadingState = ReadingXmlState.x; } else if (xmlReader.Name == "y") { xmlReadingState = ReadingXmlState.y; } else if (xmlReader.Name == "z") { xmlReadingState = ReadingXmlState.z; } else { foreach (var joint in Enum.GetValues(typeof(JointType))) { if (xmlReader.Name == joint.ToString()) { currentJointType = (JointType)Enum.Parse(typeof(JointType), joint.ToString()); } xmlReadingState = ReadingXmlState.Joint; } } #endregion } else if (xmlReader.Value != "\r\n" && xmlReader.Value != string.Empty) { switch (xmlReadingState) { case ReadingXmlState.x: int x = 0; int.TryParse(xmlReader.Value, out x); SkeletonPoint pointX; CopyAllPositionAtributes(out pointX, currentID, currentJointType); pointX.X = x; var jointX = SkeletonCollection[currentID].Joints[currentJointType]; jointX.Position = pointX; SkeletonCollection[currentID].Joints[currentJointType] = jointX; break; case ReadingXmlState.y: int y = 0; int.TryParse(xmlReader.Value, out y); SkeletonPoint pointY; CopyAllPositionAtributes(out pointY, currentID, currentJointType); pointY.Y = y; var jointY = SkeletonCollection[currentID].Joints[currentJointType]; jointY.Position = pointY; SkeletonCollection[currentID].Joints[currentJointType] = jointY; break; case ReadingXmlState.z: int z = 0; int.TryParse(xmlReader.Value, out z); SkeletonPoint pointZ; CopyAllPositionAtributes(out pointZ, currentID, currentJointType); pointZ.Z = z; var jointZ = SkeletonCollection[currentID].Joints[currentJointType]; jointZ.Position = pointZ; SkeletonCollection[currentID].Joints[currentJointType] = jointZ; break; case ReadingXmlState.Joint: //nothing, just waiting for the angles data break; case ReadingXmlState.RecordedSampleID: int.TryParse(xmlReader.Value.ToString(), out currentID); break; case ReadingXmlState.Skeleton: //recordedAction.Add(new Skeleton()); break; } } } } return(SkeletonCollection); }
private static ItemCollection ParseComplexType_SequenceChoice(XmlTextReader X) { bool done = false; ItemCollection RetVal; string elementName = X.LocalName; DText p = new DText(); p.ATTRMARK = ":"; if (X.LocalName == "choice") { RetVal = new Choice(); } else { RetVal = new Sequence(); } if (X.HasAttributes) { for (int i = 0; i < X.AttributeCount; i++) { X.MoveToAttribute(i); switch (X.LocalName) { case "minOccurs": RetVal.MinOccurs = X.Value; break; case "maxOccurs": RetVal.MaxOccurs = X.Value; break; } } X.MoveToElement(); } X.Read(); do { switch (X.NodeType) { case XmlNodeType.Element: switch (X.LocalName) { case "group": if (X.HasAttributes) { for (int i = 0; i < X.AttributeCount; i++) { X.MoveToAttribute(i); switch (X.LocalName) { case "ref": break; } } X.MoveToElement(); } break; case "sequence": case "choice": RetVal.AddCollection(ParseComplexType_SequenceChoice(X)); break; case "element": RetVal.AddContentItem(new Element()); if (X.HasAttributes) { for (int i = 0; i < X.AttributeCount; i++) { X.MoveToAttribute(i); switch (X.LocalName) { case "name": RetVal.CurrentItem.Name = X.Value; break; case "type": p[0] = X.Value; if (p.DCOUNT() == 1) { RetVal.CurrentItem.Type = X.Value; RetVal.CurrentItem.TypeNS = X.LookupNamespace(""); } else { RetVal.CurrentItem.Type = p[2]; RetVal.CurrentItem.TypeNS = X.LookupNamespace(p[1]); } break; case "minOccurs": RetVal.CurrentItem.MinOccurs = X.Value; break; case "maxOccurs": RetVal.CurrentItem.MaxOccurs = X.Value; break; } } X.MoveToElement(); } break; case "attribute": break; } break; case XmlNodeType.EndElement: if (X.LocalName == elementName) { done = true; } break; case XmlNodeType.Text: break; } }while(!done && X.Read()); return(RetVal); }
public List <DrawingObject> Unserialize(string path) { List <DrawingObject> DrawingObject = new List <DrawingObject>(); Edge line = null; string startVertex = null, endVertex = null; int StartPointX = 0, StartPointY = 0, EndPointX = 0, EndPointY = 0; string id = null; string tipe = null, nama = null, jenisRelasiAsal = null, jenisRelasiTujuan = null; XmlTextReader reader = new XmlTextReader(path); reader.MoveToContent(); try { if (reader.Name.Equals("diagram")) { while (reader.Read()) { if (reader.Name.Equals("relation")) { Boolean flag = true; reader.MoveToFirstAttribute(); id = reader.Value; reader.MoveToNextAttribute(); StartPointX = Int32.Parse(reader.Value); reader.MoveToNextAttribute(); StartPointY = Int32.Parse(reader.Value); reader.MoveToNextAttribute(); EndPointX = Int32.Parse(reader.Value); reader.MoveToNextAttribute(); EndPointY = Int32.Parse(reader.Value); reader.MoveToNextAttribute(); startVertex = reader.Value; reader.MoveToNextAttribute(); endVertex = reader.Value; reader.MoveToNextAttribute(); tipe = reader.Value; reader.MoveToElement(); while (reader.Read() && flag) { reader.MoveToContent(); flag = true; if (reader.Name.Equals("nama")) { nama = reader.Value; } else if (reader.Name.Equals("jenisRelasiAsal")) { jenisRelasiAsal = reader.Value; } else if (reader.Name.Equals("jenisRelasiTujuan")) { jenisRelasiTujuan = reader.Value; } else if (reader.Name.Equals("relation")) { flag = false; } } if (id != null && tipe.Equals("Directed Association")) { Console.WriteLine("StartVertex: " + startVertex); Console.WriteLine("EndVertex: " + endVertex); Point start = new Point(StartPointX, StartPointY); Point end = new Point(EndPointX, EndPointY); Console.WriteLine("Directed Association : " + id); DirectedAssociationLine tempLine = new DirectedAssociationLine(start, end); tempLine.ID = new Guid(id); tempLine.idStartVertex = startVertex; tempLine.idEndVertex = endVertex; tempLine.relationStart = jenisRelasiAsal; tempLine.relationEnd = jenisRelasiTujuan; DrawingObject.Add(tempLine); } } } } } catch (Exception ex) { Console.WriteLine("Error Unserialize Association: " + ex); } reader.Close(); return(DrawingObject); }
private static UPnPComplexType ParseComplexType(XmlTextReader X, UPnPComplexType RetVal) { string elementName = X.LocalName; int count = 0; bool done = false; DText P = new DText(); P.ATTRMARK = ":"; RetVal.AddContainer(new GenericContainer()); do { switch (X.NodeType) { case XmlNodeType.Element: switch (X.LocalName) { case "complexType": case "group": ++count; if (X.HasAttributes) { for (int i = 0; i < X.AttributeCount; i++) { X.MoveToAttribute(i); if (X.Name == "name") { P[0] = X.Value; if (P.DCOUNT() == 1) { RetVal.LocalName = X.Value; RetVal.NameSpace = X.LookupNamespace(""); } else { RetVal.LocalName = P[2]; RetVal.NameSpace = X.LookupNamespace(P[1]); } } else if (X.Name == "ref") { // NOP } } X.MoveToElement(); } break; case "sequence": case "choice": RetVal.CurrentContainer.AddCollection(ParseComplexType_SequenceChoice(X)); //ParseComplexType_Sequence(X,RetVal); break; case "complexContent": RetVal.AddContainer(new ComplexContent()); break; case "simpleContent": RetVal.AddContainer(new SimpleContent()); break; case "restriction": Restriction r = new Restriction(); if (RetVal.CurrentContainer.GetType() == typeof(ComplexContent)) { ((ComplexContent)RetVal.CurrentContainer).RestExt = r; } else if (RetVal.CurrentContainer.GetType() == typeof(SimpleContent)) { ((SimpleContent)RetVal.CurrentContainer).RestExt = r; } if (X.HasAttributes) { for (int i = 0; i < X.AttributeCount; i++) { X.MoveToAttribute(i); if (X.Name == "base") { P[0] = X.Value; if (P.DCOUNT() == 1) { r.baseType = X.Value; r.baseTypeNS = X.LookupNamespace(""); } else { r.baseType = P[2]; r.baseTypeNS = X.LookupNamespace(P[1]); } } } X.MoveToElement(); } break; } break; case XmlNodeType.EndElement: if (X.LocalName == elementName) { --count; if (count == 0) { done = true; } } break; case XmlNodeType.Text: break; } }while(!done && X.Read()); return(RetVal); }
/// <summary> /// Reads attributes of the current xaml element and converts /// them into appropriate html attributes or css styles. /// </summary> /// <param name="xamlReader"> /// XmlTextReader which is expected to be at XmlNodeType.Element /// (opening element tag) position. /// The reader will remain at the same level after function complete. /// </param> /// <param name="htmlWriter"> /// XmlTextWriter for output html, which is expected to be in /// after WriteStartElement state. /// </param> /// <param name="inlineStyle"> /// String builder for collecting css properties for inline STYLE attribute. /// </param> private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); // Clear string builder for the inline style inlineStyle.Remove(0, inlineStyle.Length); if (!xamlReader.HasAttributes) { return; } bool borderSet = false; while (xamlReader.MoveToNextAttribute()) { string css = null; switch (xamlReader.Name) { // Character fomatting properties // ------------------------------ case "Background": css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "FontFamily": css = "font-family:" + xamlReader.Value + ";"; break; case "FontStyle": css = "font-style:" + xamlReader.Value.ToLower() + ";"; break; case "FontWeight": css = "font-weight:" + xamlReader.Value.ToLower() + ";"; break; case "FontStretch": break; case "FontSize": css = "font-size:" + xamlReader.Value + ";"; break; case "Foreground": css = "color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "TextDecorations": css = "text-decoration:underline;"; break; case "TextEffects": break; case "Emphasis": break; case "StandardLigatures": break; case "Variants": break; case "Capitals": break; case "Fraction": break; // Paragraph formatting properties // ------------------------------- case "Padding": css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "Margin": css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "BorderThickness": css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";"; borderSet = true; break; case "BorderBrush": css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";"; borderSet = true; break; case "LineHeight": break; case "TextIndent": css = "text-indent:" + xamlReader.Value + ";"; break; case "TextAlignment": css = "text-align:" + xamlReader.Value + ";"; break; case "IsKeptTogether": break; case "IsKeptWithNext": break; case "ColumnBreakBefore": break; case "PageBreakBefore": break; case "FlowDirection": break; // Table attributes // ---------------- case "Width": css = "width:" + xamlReader.Value + ";"; break; case "ColumnSpan": htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value); break; case "RowSpan": htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value); break; } if (css != null) { inlineStyle.Append(css); } } if (borderSet) { inlineStyle.Append("border-style:solid;mso-element:para-border-div;"); } // Return the xamlReader back to element level xamlReader.MoveToElement(); Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Executes the task. /// </summary> /// ------------------------------------------------------------------------------------ public override bool Execute() { Log.LogMessage(MessageImportance.Normal, "RegFree processing {0}", Path.GetFileName(Executable)); StringCollection dllPaths = GetFilesFrom(Dlls); if (dllPaths.Count == 0) { string ext = Path.GetExtension(Executable); if (ext != null && ext.Equals(".dll", StringComparison.InvariantCultureIgnoreCase)) { dllPaths.Add(Executable); } } string manifestFile = string.IsNullOrEmpty(Output) ? Executable + ".manifest" : Output; try { var doc = new XmlDocument { PreserveWhitespace = true }; using (XmlReader reader = new XmlTextReader(manifestFile)) { if (reader.MoveToElement()) { doc.ReadNode(reader); } } // Register all DLLs temporarily using (var regHelper = new RegHelper(Log, Platform)) { regHelper.RedirectRegistry(!UserIsAdmin); var creator = new RegFreeCreator(doc, Log); var filesToRemove = dllPaths.Cast <string>().Where(fileName => !File.Exists(fileName)).ToList(); foreach (var file in filesToRemove) { dllPaths.Remove(file); } foreach (string fileName in dllPaths) { Log.LogMessage(MessageImportance.Low, "\tRegistering library {0}", Path.GetFileName(fileName)); try { regHelper.Register(fileName, true, false); } catch (Exception e) { Log.LogMessage(MessageImportance.High, "Failed to register library {0}", fileName); Log.LogMessage(MessageImportance.High, e.StackTrace); } } string assemblyName = Path.GetFileNameWithoutExtension(manifestFile); Debug.Assert(assemblyName != null); // The C++ test programs won't run if an assemblyIdentity element exists. //if (assemblyName.StartsWith("test")) // assemblyName = null; string assemblyVersion = null; try { assemblyVersion = FileVersionInfo.GetVersionInfo(Executable).FileVersion; } catch { // just ignore } if (string.IsNullOrEmpty(assemblyVersion)) { assemblyVersion = "1.0.0.0"; } XmlElement root = creator.CreateExeInfo(assemblyName, assemblyVersion, Platform); foreach (string fileName in dllPaths) { if (NoTypeLib.Count(f => f.ItemSpec == fileName) != 0) { continue; } Log.LogMessage(MessageImportance.Low, "\tProcessing library {0}", Path.GetFileName(fileName)); creator.ProcessTypeLibrary(root, fileName); } creator.ProcessClasses(root); creator.ProcessInterfaces(root); foreach (string fragmentName in GetFilesFrom(Fragments)) { Log.LogMessage(MessageImportance.Low, "\tAdding fragment {0}", Path.GetFileName(fragmentName)); creator.AddFragment(root, fragmentName); } foreach (string fragmentName in GetFilesFrom(AsIs)) { Log.LogMessage(MessageImportance.Low, "\tAdding as-is fragment {0}", Path.GetFileName(fragmentName)); creator.AddAsIs(root, fragmentName); } foreach (string assemblyFileName in GetFilesFrom(DependentAssemblies)) { Log.LogMessage(MessageImportance.Low, "\tAdding dependent assembly {0}", Path.GetFileName(assemblyFileName)); creator.AddDependentAssembly(root, assemblyFileName); } var settings = new XmlWriterSettings { OmitXmlDeclaration = false, NewLineOnAttributes = false, NewLineChars = Environment.NewLine, Indent = true, IndentChars = "\t" }; using (XmlWriter writer = XmlWriter.Create(manifestFile, settings)) { doc.WriteContentTo(writer); } // Unregister DLLs if (Unregister) { foreach (string fileName in dllPaths) { Log.LogMessage(MessageImportance.Low, "\tUnregistering library {0}", Path.GetFileName(fileName)); regHelper.Unregister(fileName, true); } } } } catch (Exception e) { Log.LogErrorFromException(e, true, true, null); return(false); } return(true); }
double getGEAlt(double lat, double lng) { double alt = 0; //http://maps.google.com/maps/api/elevation/xml try { using (XmlTextReader xmlreader = new XmlTextReader("http://maps.google.com/maps/api/elevation/xml?locations=" + lat.ToString(new System.Globalization.CultureInfo("en-US")) + "," + lng.ToString(new System.Globalization.CultureInfo("en-US")) + "&sensor=true")) { while (xmlreader.Read()) { xmlreader.MoveToElement(); switch (xmlreader.Name) { case "elevation": alt = double.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US")); break; default: break; } } } } catch { } return alt * MainV2.comPort.MAV.cs.multiplierdist; }
public static bool ImportScheduledTask(string fileName) { FileStream fileStream = null; bool bRet = false; try { int buffSize = 512; byte[] taskData; fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read); XmlTextReader reader = new XmlTextReader(fileStream); reader.MoveToElement(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("Task")) { //读Name reader.Read(); reader.MoveToContent(); string name = reader.ReadElementContentAsString(); //读Comment reader.Read(); reader.MoveToContent(); string comment = reader.ReadElementContentAsString(); //读Data reader.Read(); reader.MoveToContent(); int realLength = 0; taskData = new byte[buffSize]; byte[] tempBuff = new byte[buffSize]; int readCount = reader.ReadElementContentAsBinHex(tempBuff, 0, buffSize); Array.Copy(tempBuff, 0, taskData, realLength, readCount); realLength += readCount; while (tempBuff.Length == readCount) { Array.Resize<byte>(ref taskData, taskData.Length + buffSize); readCount = reader.ReadElementContentAsBinHex(tempBuff, 0, buffSize); Array.Copy(tempBuff, 0, taskData, realLength, readCount); realLength += readCount; } Array.Resize<byte>(ref taskData, realLength); MemoryStream taskDataStream = new MemoryStream(taskData); IFormatter formatter = new BinaryFormatter(); IScheduledTask task = (IScheduledTask)formatter.Deserialize(taskDataStream); AdminServer.TheInstance.ScheduledTaskManager.Add(task, name, comment); } } bRet = true; } catch (Exception) { bRet = false; } finally { if (fileStream != null) fileStream.Close(); } return bRet; }