protected void Page_Load(object sender, EventArgs e) { AWSAuthConnection conn = new AWSAuthConnection(accessKey, secretKey); XmlTextReader r = new XmlTextReader(Request.InputStream); r.MoveToContent(); string xml = r.ReadOuterXml(); XmlDocument documentToSave = new XmlDocument(); documentToSave.LoadXml(xml); SortedList metadata = new SortedList(); metadata.Add("title", bucket); metadata.Add("Content-Type", "application/xml"); S3Object titledObject = new S3Object(documentToSave.OuterXml, metadata); SortedList headers = new SortedList(); headers.Add("Content-Type", "application/xml"); headers.Add("x-amz-acl", "public-read"); conn.put(bucket, documentKey, titledObject, headers); Response.Write("saved: " + documentToSave.OuterXml); }
private void rss_update(object sender, EventArgs e) { int i; string title; int toggler = 1; try { led_line = ""; reader = new XmlTextReader(url); using(reader) { reader.Read(); reader.MoveToContent(); i = 0; while(!reader.EOF) { while(!reader.EOF && reader.Name != "item") reader.Read(); while(!reader.EOF && reader.Name != "title") reader.Read(); if(!reader.EOF) { title = reader.ReadString(); titles[i++] = title; led_line += title+ " "; if(toggler == 1) led_line += "%r"; else led_line += "%g"; toggler ^= 1; } } num_titles = i; } } catch(Exception) { return; } }
private void buttonItem11_Click(object sender, EventArgs e) { { string downloadUrl = "http://www.mediafire.com/xzombeast#1,1"; Version newVersion = null; string aboutUpdate = ""; string xmlUrl = "http://www.absolutelygrim.x10.bz/updates/update.xml"; XmlTextReader reader = null; try { reader = new XmlTextReader(xmlUrl); reader.MoveToContent(); string elementName = ""; if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "appinfo")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "version": newVersion = new Version(reader.Value); break; case "link": downloadUrl = reader.Value; break; case "about": aboutUpdate = reader.Value; break; } } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); Environment.Exit(1); } finally { if (reader != null) { reader.Close(); } } Version applicationVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (applicationVersion.CompareTo(newVersion) < 0) { string str = String.Format("New version found!\nYour version: {0}.\nNewest version: {1}. \nAdded in this version: {2}. ", applicationVersion, newVersion, aboutUpdate); if (DialogResult.No != MessageBox.Show(str + "\nWould you like to download this update?", "Check for updates", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { try { System.Diagnostics.Process.Start("http://www.mediafire.com/xzombeast#1,1"); System.Diagnostics.Process.Start("http://www.absolutelygrim.x10.bz/updates"); } catch { } return; } else { ; } } else { MessageBox.Show("Your version: " + applicationVersion + " is up to date.", "Check for Updates", MessageBoxButtons.OK, MessageBoxIcon.None); } } }
public static void CheckForUpdates() { if (HasInternetConnection) { try { var releasePageUrl = ""; Version newVersion = null; const string versionConfig = "https://raw.github.com/Codeusa/Borderless-Gaming/master/version.xml"; var reader = new XmlTextReader(versionConfig); reader.MoveToContent(); var elementName = ""; try { if (reader.NodeType == XmlNodeType.Element && reader.Name == "borderlessgaming") { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: elementName = reader.Name; break; default: if (reader.NodeType == XmlNodeType.Text && reader.HasValue) { switch (elementName) { case "version": newVersion = new Version(reader.Value); break; case "url": releasePageUrl = reader.Value; break; } } break; } } } } catch (Exception) { MessageBox.Show(Resources.ErrorUpdates, Resources.ErrorHeader, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { reader.Close(); } var applicationVersion = Assembly.GetEntryAssembly().GetName().Version; if (applicationVersion.CompareTo(newVersion) < 0) { if (MessageBox.Show(Resources.InfoUpdateAvailable, Resources.InfoUpdatesHeader, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { GotoSite(releasePageUrl); } } } catch { } } }
private void updatecheck_Click(object sender, EventArgs e) { var downloadUrl = ""; Version newVersion = null; var aboutUpdate = ""; var xmlUrl = "https://www.flamewall.net/ucs/system.xml"; XmlTextReader reader = null; try { reader = new XmlTextReader(xmlUrl); reader.MoveToContent(); var elementName = ""; if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "appinfo")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == XmlNodeType.Text) && reader.HasValue) { switch (elementName) { case "version": newVersion = new Version(reader.Value); break; case "url": downloadUrl = reader.Value; break; case "about": aboutUpdate = reader.Value; break; } } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (reader != null) { reader.Close(); } } var applicationVersion = Assembly.GetExecutingAssembly().GetName().Version; if (applicationVersion.CompareTo(newVersion) < 0) { StatusLabel.Text = "Status : New version available!"; var str = string.Format( "New version found!\nYour version: {0}.\nNewest version: {1}. \nAdded in this version: {2}. ", applicationVersion, newVersion, aboutUpdate); if (DialogResult.No != MessageBox.Show(str + "\nWould you like to download this update?", "Check for updates", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { try { Process.Start(downloadUrl); } catch (Exception ex) { Console.WriteLine(ex); } } } else { MessageBox.Show("Your version: " + applicationVersion + " is up to date.", "Check for Updates", MessageBoxButtons.OK, MessageBoxIcon.None); } }
/// <summary> /// Deserialize /// </summary> /// <param name="name"></param> /// <param name="q"></param> /// <param name="tr"></param> /// <returns></returns> internal static EdgeMx Deserialize( string name, Query q, XmlTextReader tr) { Enum iEnum = null; EdgeMx e = new EdgeMx(); if (XmlUtil.GetEnumAttribute(tr, "ShowLabels", typeof(ShowLabels), ref iEnum)) { e.ShowLabels = (ShowLabels)iEnum; } if (XmlUtil.GetEnumAttribute(tr, "SummarizationType", typeof(SummarizationType), ref iEnum)) { e.SummarizationType = (SummarizationType)iEnum; } XmlUtil.GetBoolAttribute(tr, "IncludeEdgeVertex", ref e.IncludeEdgeVertex); while (true) // loop through elements of network { tr.Read(); tr.MoveToContent(); if (Lex.Eq(tr.Name, name + "Column")) { e.QueryColumn = ResultsViewProps.DeserializeQueryColumn(q, tr); tr.Read(); tr.MoveToContent(); } else if (Lex.Eq(tr.Name, "Color")) { e.Color = ColorDimension.Deserialize("Color", q, tr); tr.Read(); tr.MoveToContent(); } else if (Lex.Eq(tr.Name, "Width")) { e.Width = SizeDimension.Deserialize("Width", q, tr); tr.Read(); tr.MoveToContent(); } else if (Lex.Eq(tr.Name, "TooltipFields")) { e.TooltipFields = TooltipDimensionDef.Deserialize("TooltipFields", q, tr); //tr.Read(); tr.MoveToContent(); } else if (tr.NodeType == XmlNodeType.EndElement && // end of props Lex.Eq(tr.Name, name)) { break; } else { throw new Exception("Unexpected element: " + tr.Name); } } return(e); }
/// <summary> /// Deserialize /// </summary> /// <param name="q"></param> /// <param name="tr"></param> /// <param name="view"></param> /// <returns></returns> public static bool Deserialize( Query q, XmlTextReader tr, ResultsViewProps view) { Enum iEnum = null; bool b1 = false; string txt = ""; int i1 = -1; double d1 = -1; if (!Lex.Eq(tr.Name, "NetworkProperties")) { return(false); } //if (view.NetworkProperties == null) // view.NetworkProperties = new NetworkProperties(); //NetworkProperties p = view.NetworkProperties; if (XmlUtil.GetEnumAttribute(tr, "GraphDirectedness", typeof(GraphDirectedness), ref iEnum)) { p.GraphDirectedness = (GraphDirectedness)iEnum; } LayoutSettingsMx s = p.LayoutSettings; // layout settings if (XmlUtil.GetEnumAttribute(tr, "LayoutType", typeof(LayoutType), ref iEnum)) { s.LayoutType = (LayoutType)iEnum; } if (XmlUtil.GetEnumAttribute(tr, "LayoutStyle", typeof(LayoutStyle), ref iEnum)) { s.LayoutStyle = (LayoutStyle)iEnum; } XmlUtil.GetDoubleAttribute(tr, "GroupRectanglePenWidth", ref s.GroupRectanglePenWidth); if (XmlUtil.GetEnumAttribute(tr, "IntergroupEdgeStyle", typeof(IntergroupEdgeStyle), ref iEnum)) { s.IntergroupEdgeStyle = (IntergroupEdgeStyle)iEnum; } XmlUtil.GetBoolAttribute(tr, "ImproveLayoutOfGroups", ref s.ImproveLayoutOfGroups); XmlUtil.GetIntAttribute(tr, "MaximumVerticesPerBin", ref s.MaximumVerticesPerBin); XmlUtil.GetIntAttribute(tr, "BinLength", ref s.BinLength); XmlUtil.GetFloatAttribute(tr, "FruchtermanReingoldC", ref s.FruchtermanReingoldC); XmlUtil.GetIntAttribute(tr, "FruchtermanReingoldIterations", ref s.FruchtermanReingoldIterations); XmlUtil.GetIntAttribute(tr, "Margin", ref s.Margin); if (XmlUtil.GetEnumAttribute(tr, "VertexGroupMethod", typeof(VertexGroupMethodMx), ref iEnum)) { p.VertexGroupMethod = (VertexGroupMethodMx)iEnum; } XmlUtil.GetBoolAttribute(tr, "GroupingDisabled", ref p.GroupingDisabled); XmlUtil.GetDoubleAttribute(tr, "GraphScale", ref p.GraphScale); if (tr.IsEmptyElement) { return(true); // return if no elements } while (true) // loop through elements of network { tr.Read(); tr.MoveToContent(); if (Lex.Eq(tr.Name, "Vertex1")) { p.Vertex1 = VertexMx.Deserialize("Vertex1", q, tr); } else if (Lex.Eq(tr.Name, "Vertex2")) { p.Vertex2 = VertexMx.Deserialize("Vertex2", q, tr); } else if (Lex.Eq(tr.Name, "Edge")) { p.Edge = EdgeMx.Deserialize("Edge", q, tr); } else if (Lex.Eq(tr.Name, "GroupByQc")) { p.GroupByQc = ResultsViewProps.DeserializeQueryColumn(q, tr); tr.Read(); tr.MoveToContent(); } else if (tr.NodeType == XmlNodeType.EndElement && // end of props Lex.Eq(tr.Name, "NetworkProperties")) { break; } else { throw new Exception("Unexpected element: " + tr.Name); } } return(true); }
public static CamConfigData[] LoadSettings(string vsSettingsFile) { List<CamConfigData> data = new List<CamConfigData>(); // check file existance if (File.Exists(vsSettingsFile)) { // VsSplasher.Status = "Load setting..."; FileStream fs = null; XmlTextReader xmlIn = null; // open file fs = new FileStream(vsSettingsFile, FileMode.Open, FileAccess.Read); // create XML reader xmlIn = new XmlTextReader(fs); xmlIn.WhitespaceHandling = WhitespaceHandling.None; xmlIn.MoveToContent(); // check for main node if (xmlIn.Name != "Cameras") throw new ApplicationException(""); xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) xmlIn.Read(); CamConfigData obj; while (xmlIn.Name == "Camera") { obj = new CamConfigData(); obj.id = Convert.ToInt32(xmlIn.GetAttribute("id")); obj.name = xmlIn.GetAttribute("name"); obj.desc = xmlIn.GetAttribute("desc"); obj.run = Convert.ToBoolean(xmlIn.GetAttribute("run")); obj.analyse = Convert.ToBoolean(xmlIn.GetAttribute("analyse")); obj.record = Convert.ToBoolean(xmlIn.GetAttribute("record")); obj.events = Convert.ToBoolean(xmlIn.GetAttribute("event")); obj.data = Convert.ToBoolean(xmlIn.GetAttribute("data")); obj.provider = xmlIn.GetAttribute("provider"); obj.source = xmlIn.GetAttribute("source"); obj.analyzer = xmlIn.GetAttribute("analyzer"); obj.ThresholdAlpha = Convert.ToInt32(xmlIn.GetAttribute("ThresholdAlpha")); obj.ThresholdSigma = Convert.ToInt32(xmlIn.GetAttribute("ThresholdSigma")); obj.endcoder = xmlIn.GetAttribute("encoder"); obj.ImageWidth = Convert.ToInt32(xmlIn.GetAttribute("ImageWidth")); obj.ImageHeight = Convert.ToInt32(xmlIn.GetAttribute("ImageHeight")); obj.CodecsName = xmlIn.GetAttribute("CodecsName"); obj.Quality = Convert.ToInt32(xmlIn.GetAttribute("Quality")); data.Add(obj); xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) xmlIn.Read(); } // close file xmlIn.Close(); fs.Close(); return data.ToArray(); } else { return data.ToArray(); } }
private void ReadSectionGroup(XmlTextReader reader, string configSection) { if (!reader.MoveToNextAttribute()) { ThrowException("sectionGroup must have a 'name' attribute.", reader); } string value = null; do { if (reader.Name == "name") { if (value != null) { ThrowException("Duplicate 'name' attribute.", reader); } value = reader.Value; } else #if NET_2_0 if (reader.Name != "type") #endif { ThrowException("Unrecognized attribute.", reader); } }while (reader.MoveToNextAttribute()); if (value == null) { ThrowException("No 'name' attribute.", reader); } if (value == "location") { ThrowException("location is a reserved section name", reader); } if (configSection != null) { value = configSection + '/' + value; } object o = LookForFactory(value); if (o != null && o != removedMark && o != groupMark) { ThrowException("Already have a factory for " + value, reader); } factories [value] = groupMark; if (reader.IsEmptyElement) { reader.Skip(); reader.MoveToContent(); } else { reader.Read(); reader.MoveToContent(); if (reader.NodeType != XmlNodeType.EndElement) { ReadSections(reader, value); } reader.ReadEndElement(); reader.MoveToContent(); } }
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(); }
// Load application's configration public bool Load( ) { isSuccessfullyLoaded = false; lock ( baseConfigFileName ) { // check file existance if (File.Exists(configFileName)) { FileStream fs = null; XmlTextReader xmlIn = null; try { // open file fs = new FileStream(configFileName, FileMode.Open); // create XML reader xmlIn = new XmlTextReader(fs); xmlIn.WhitespaceHandling = WhitespaceHandling.None; xmlIn.MoveToContent( ); // check main node if (xmlIn.Name != mainTag) { throw new ApplicationException( ); } // move to next node xmlIn.Read( ); while (true) { // ignore anything if it is not under main tag while ((xmlIn.Depth > 1) || ( (xmlIn.Depth == 1) && (xmlIn.NodeType != XmlNodeType.Element))) { xmlIn.Read( ); } // break if end element is reached if (xmlIn.Depth == 0) { break; } int tagStartLineNummber = xmlIn.LineNumber; switch (xmlIn.Name) { case optionsTag: LoadOptions(xmlIn); break; } // read to the next node, if loader did not move any further if (xmlIn.LineNumber == tagStartLineNummber) { xmlIn.Read( ); } } isSuccessfullyLoaded = true; // ignore the rest } catch { } finally { if (xmlIn != null) { xmlIn.Close( ); } } } } return(isSuccessfullyLoaded); }
private void okButton_Click(object sender, EventArgs e) { /* * <?xml version="1.0" encoding = "utf-8"?> * <powersdr> * <version>2.8.0.28</version> * <url>http://ke9ns.com/flexpage.html/</url> * </powersdr> */ string downloadUrl = ""; Version newVersion = null; string xmlUrl = "http://ke9ns.com/update.xml"; XmlTextReader reader = null; try { Debug.WriteLine("HERE0"); reader = new XmlTextReader(xmlUrl); Debug.WriteLine("HERE1"); reader.MoveToContent(); string elementName = ""; Debug.WriteLine("HERE2"); if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "powersdr")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "version": newVersion = new Version(reader.Value); break; case "url": downloadUrl = reader.Value; break; } } } } } } catch (Exception e1) { if (reader != null) { reader.Close(); } MessageBox.Show("Failed to get update information. " + e1, "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { if (reader != null) { reader.Close(); } } Version appVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; // ke9ns this is your current installed version if (appVersion.CompareTo(newVersion) < 0) { DialogResult dr = MessageBox.Show( "Version " + newVersion.Major + "." + newVersion.Minor + "." + newVersion.Build + "." + newVersion.Revision + " of ke9ns PowerSDR is available for download, would you like to download it?", "This is Your currently installed version: " + appVersion.Major + "." + appVersion.Minor + "." + appVersion.Build + "." + appVersion.Revision, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) { return; } else if (dr == DialogResult.Yes) { System.Diagnostics.Process.Start(downloadUrl); } } else { MessageBox.Show("PowerSDR ke9ns Version: " + appVersion.Major + "." + appVersion.Minor + "." + appVersion.Build + "." + appVersion.Revision + " is up to date!", "No need to Update", MessageBoxButtons.OK, MessageBoxIcon.Information); } } // okButton_Click
private bool getVersionFromWebsite() { try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; // Provide the XmlTextReader with the URL of our xml document XmlTextReader reader = new XmlTextReader(ConstantsAndEnums.APP_VERSION_URL); // Simply (and easily) skip the junk at the beginning reader.MoveToContent(); // internal - as the XmlTextReader moves only forward, we save current xml element name // in elementName variable. When we parse a text node, we refer to elementName to check // what was the node name string elementName = ""; // We check if the xml starts with a proper "ourfancyapp" element node if ((reader.NodeType == XmlNodeType.Element)) // && (reader.Name == "oricexplorer")) { while (reader.Read()) { // When we find an element node, we remember its name if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { // for text nodes... if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { // We check what the name of the node was switch (elementName) { case "version": // Thats why we keep the version info in xxx.xxx.xxx.xxx format // the Version class does the parsing for us newVersion = new Version(reader.Value); break; case "url": websiteURL = reader.Value; break; case "details": //updateDetails = reader.Value; break; } } } } } reader.Close(); } catch (FileNotFoundException ex) { string message = ex.Message; infoBoxDetails.Text = "Version check has failed.\n\nUpdate file was not found on server."; return(false); } catch (Exception ex) { infoBoxDetails.Text = string.Format("Version check has failed.\n\n{0}.", ex.Message); return(false); } return(true); }
/// <summary> /// Create a content layout file for the conceptual topics /// </summary> private void CreateContentLayoutFile() { string filename = Path.Combine(base.ProjectFolder, "ContentLayout.content"); XmlTextReader reader = null; XmlWriterSettings settings = new XmlWriterSettings(); XmlWriter writer = null; int topicsAdded = 0; try { settings.Indent = true; settings.CloseOutput = true; writer = XmlWriter.Create(filename, settings); writer.WriteStartDocument(); writer.WriteStartElement("Topics"); reader = new XmlTextReader(new StreamReader(topicLayoutFilename)); reader.MoveToContent(); while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "topics" && !reader.IsEmptyElement) { while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "topic") { this.ConvertTopic(reader, writer); topicsAdded++; } reader.Read(); } } reader.Read(); } writer.WriteEndElement(); // </Topics> writer.WriteEndDocument(); } catch (Exception ex) { throw new BuilderException("CVT0006", String.Format( CultureInfo.CurrentCulture, "Error converting " + "content layout file ({0}):\r\n{1}", topicLayoutFilename, ex.Message), ex); } finally { if (reader != null) { reader.Close(); } if (writer != null) { writer.Close(); } } if (topicsAdded != 0) { project.AddFileToProject(filename, filename); } else { this.CreateDefaultContentLayoutFile(); } }
public override void EmiteNF(string file) { XmlTextReader reader = new XmlTextReader(file); reader.WhitespaceHandling = WhitespaceHandling.None; reader.MoveToContent(); XmlDocument oXml = new XmlDocument(); oXml.Load(reader); Array result = service.EnvNfe(XmlDocumentUtilities.GetValue <string>(oXml, "prf"), XmlDocumentUtilities.GetValue <string>(oXml, "usr"), XmlDocumentUtilities.GetValue <string>(oXml, "ctr"), XmlDocumentUtilities.GetValue <string>(oXml, "cnpj"), XmlDocumentUtilities.GetValue <string>(oXml, "cnpjn"), XmlDocumentUtilities.GetValue <string>(oXml, "ie"), XmlDocumentUtilities.GetValue <string>(oXml, "im"), XmlDocumentUtilities.GetValue <string>(oXml, "lgr"), XmlDocumentUtilities.GetValue <string>(oXml, "num"), XmlDocumentUtilities.GetValue <string>(oXml, "cpl"), XmlDocumentUtilities.GetValue <string>(oXml, "bai"), XmlDocumentUtilities.GetValue <string>(oXml, "cid"), XmlDocumentUtilities.GetValue <string>(oXml, "est"), XmlDocumentUtilities.GetValue <string>(oXml, "cep"), XmlDocumentUtilities.GetValue <string>(oXml, "fon"), XmlDocumentUtilities.GetValue <string>(oXml, "mail"), XmlDocumentUtilities.GetValue <string>(oXml, "dat"), XmlDocumentUtilities.GetValue <string>(oXml, "f1n"), XmlDocumentUtilities.GetValue <string>(oXml, "f1d"), XmlDocumentUtilities.GetValue <string>(oXml, "f1v"), XmlDocumentUtilities.GetValue <string>(oXml, "f2n"), XmlDocumentUtilities.GetValue <string>(oXml, "f2d"), XmlDocumentUtilities.GetValue <string>(oXml, "f2v"), XmlDocumentUtilities.GetValue <string>(oXml, "f3n"), XmlDocumentUtilities.GetValue <string>(oXml, "f3d"), XmlDocumentUtilities.GetValue <string>(oXml, "f3v"), XmlDocumentUtilities.GetValue <string>(oXml, "f4n"), XmlDocumentUtilities.GetValue <string>(oXml, "f4d"), XmlDocumentUtilities.GetValue <string>(oXml, "f4v"), XmlDocumentUtilities.GetValue <string>(oXml, "f5n"), XmlDocumentUtilities.GetValue <string>(oXml, "f5d"), XmlDocumentUtilities.GetValue <string>(oXml, "f5v"), XmlDocumentUtilities.GetValue <string>(oXml, "f6n"), XmlDocumentUtilities.GetValue <string>(oXml, "f6d"), XmlDocumentUtilities.GetValue <string>(oXml, "f6v"), XmlDocumentUtilities.GetValue <string>(oXml, "item1"), XmlDocumentUtilities.GetValue <string>(oXml, "item2"), XmlDocumentUtilities.GetValue <string>(oXml, "item3"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq1"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq2"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq3"), XmlDocumentUtilities.GetValue <string>(oXml, "val1"), XmlDocumentUtilities.GetValue <string>(oXml, "val2"), XmlDocumentUtilities.GetValue <string>(oXml, "val3"), XmlDocumentUtilities.GetValue <string>(oXml, "loc"), XmlDocumentUtilities.GetValue <string>(oXml, "ret"), XmlDocumentUtilities.GetValue <string>(oXml, "txt"), XmlDocumentUtilities.GetValue <string>(oXml, "val"), XmlDocumentUtilities.GetValue <string>(oXml, "valtrib"), XmlDocumentUtilities.GetValue <string>(oXml, "iss"), XmlDocumentUtilities.GetValue <string>(oXml, "issret"), XmlDocumentUtilities.GetValue <string>(oXml, "desci"), XmlDocumentUtilities.GetValue <string>(oXml, "desco"), XmlDocumentUtilities.GetValue <string>(oXml, "binss"), XmlDocumentUtilities.GetValue <string>(oXml, "birrf"), XmlDocumentUtilities.GetValue <string>(oXml, "bcsll"), XmlDocumentUtilities.GetValue <string>(oXml, "bpis"), XmlDocumentUtilities.GetValue <string>(oXml, "bcofins"), XmlDocumentUtilities.GetValue <string>(oXml, "ainss"), XmlDocumentUtilities.GetValue <string>(oXml, "airrf"), XmlDocumentUtilities.GetValue <string>(oXml, "acsll"), XmlDocumentUtilities.GetValue <string>(oXml, "apis"), XmlDocumentUtilities.GetValue <string>(oXml, "acofins"), XmlDocumentUtilities.GetValue <string>(oXml, "inss"), XmlDocumentUtilities.GetValue <string>(oXml, "irrf"), XmlDocumentUtilities.GetValue <string>(oXml, "csll"), XmlDocumentUtilities.GetValue <string>(oXml, "pis"), XmlDocumentUtilities.GetValue <string>(oXml, "cofins"), XmlDocumentUtilities.GetValue <string>(oXml, "item4"), XmlDocumentUtilities.GetValue <string>(oXml, "item5"), XmlDocumentUtilities.GetValue <string>(oXml, "item6"), XmlDocumentUtilities.GetValue <string>(oXml, "item7"), XmlDocumentUtilities.GetValue <string>(oXml, "item8"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq4"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq5"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq6"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq7"), XmlDocumentUtilities.GetValue <string>(oXml, "aliq8"), XmlDocumentUtilities.GetValue <string>(oXml, "val4"), XmlDocumentUtilities.GetValue <string>(oXml, "val5"), XmlDocumentUtilities.GetValue <string>(oXml, "val6"), XmlDocumentUtilities.GetValue <string>(oXml, "val7"), XmlDocumentUtilities.GetValue <string>(oXml, "val8"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser1"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser2"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser3"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser4"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser5"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser6"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser7"), XmlDocumentUtilities.GetValue <string>(oXml, "iteser8"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser1"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser2"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser3"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser4"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser5"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser6"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser7"), XmlDocumentUtilities.GetValue <string>(oXml, "alqser8"), XmlDocumentUtilities.GetValue <string>(oXml, "valser1"), XmlDocumentUtilities.GetValue <string>(oXml, "valser2"), XmlDocumentUtilities.GetValue <string>(oXml, "valser3"), XmlDocumentUtilities.GetValue <string>(oXml, "valser4"), XmlDocumentUtilities.GetValue <string>(oXml, "valser5"), XmlDocumentUtilities.GetValue <string>(oXml, "valser6"), XmlDocumentUtilities.GetValue <string>(oXml, "valser7"), XmlDocumentUtilities.GetValue <string>(oXml, "valser8")); string strResult = base.CreateXML(result); /// WANDREY: como não tem consulta a lote, a extensao do retorno deve seguir o padrao ou já retorna como -loterps.xml????????????????????? GerarRetorno(file, strResult, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).RetornoXML); //.LoteRps); }
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; }
/// <summary> /// Checks for application update /// </summary> private void CheckVersion() { string xmlURL = "https://raw.githubusercontent.com/liinko/FFXIVTexToolsWeb/master/version.xml"; string changeLog = ""; string siteURL = ""; Version v = null; try { using (XmlTextReader reader = new XmlTextReader(xmlURL)) { reader.MoveToContent(); string elementName = ""; if (reader.NodeType == XmlNodeType.Element && reader.Name == "FFXIVTexTools2") { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if (reader.NodeType == XmlNodeType.Text && reader.HasValue) { switch (elementName) { case "version": v = new Version(reader.Value); break; case "url": siteURL = reader.Value; break; case "log": changeLog = reader.Value; break; } } } } } } var ver = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion; var curVersion = new Version(ver); if (curVersion.CompareTo(v) < 0) { Update up = new Update(); up.Message = "Version: " + v.ToString().Substring(0, 5) + "\n\nChange Log:\n" + changeLog + "\n\nPlease visit the website to download the update."; up.Show(); } } catch (Exception ex) { FlexibleMessageBox.Show("There was an issue checking for updates. \n" + ex.Message, "Updater Error " + Info.appVersion, MessageBoxButtons.OK, MessageBoxIcon.None); } }
// pseudo SAX reader public static void xmlparse(string fname) { XmlReader reader = new XmlTextReader(fname); string line; urls = new ArrayList(); int cnt = 0; // http://msdn.microsoft.com/en-us/library/1z92b1d4.aspx // http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.readsubtree.aspx while (reader.Read()) { if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "formvals") { XmlReader inner = reader.ReadSubtree(); StringDictionary myCol = new StringDictionary(); while (inner.Read()) { if (inner.MoveToContent() == XmlNodeType.Element && inner.Name == "input") { inner.MoveToFirstAttribute(); // to avoid dependency on the attribute order, key them by the attribute name // amended with the unique count of the current input element. myCol.Add(String.Format("{0}-{1}", inner.Name, cnt.ToString()), inner.Value); inner.MoveToNextAttribute(); myCol.Add(String.Format("{0}-{1}", inner.Name, cnt.ToString()), inner.Value); cnt++; } DictionaryEntry[] myArr = new DictionaryEntry[myCol.Count]; myCol.CopyTo(myArr, 0); for (int i = 0; i < myArr.Length; i++) { try{ string inputNameRegExp = @"name\-(?<input>\d+)"; MatchCollection myMatchCollection = Regex.Matches(myArr[i].Key.ToString(), inputNameRegExp ); foreach (Match myMatch in myMatchCollection) { string pos = myMatch.Groups["input"].Value.ToString(); // do not use StringDictionary for final formvals or you have your keyc converted to lower case. formvals.Add(myCol[String.Format("name-{0}", pos)], myCol[String.Format("value-{0}", pos)]); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } myCol.Clear(); } foreach ( KeyValuePair<string, string> kvp in formvals ) Console.WriteLine("formvals[ {0} ] = {1}", kvp.Key, kvp.Value); inner.Close(); } if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "url") { line = reader.ReadString(); urls.Add(line); Console.WriteLine(line); } } }
// Check for updates void checkForUpdates() { DebugLog("Checking for updates..."); string downloadUrl = ""; string aboutUpdate = ""; string xmlUrl = updateURL; Version newVersion = null; XmlTextReader reader = null; Version applicationVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; try { reader = new XmlTextReader(xmlUrl); reader.MoveToContent(); string elementName = ""; if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "appinfo")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "version": newVersion = new Version(reader.Value); DebugLog("Current version: " + applicationVersion.Build); DebugLog("New version: " + newVersion); break; case "url": downloadUrl = reader.Value; DebugLog("Download URL: " + downloadUrl); break; case "about": aboutUpdate = reader.Value; DebugLog("About: " + aboutUpdate); break; } } } } } } catch (Exception ex) { DebugLog("Error: " + ex.Message); MessageBox.Show(ex.Message); Environment.Exit(1); } finally { if (reader != null) { reader.Close(); } } if (newVersion > applicationVersion) { string str = String.Format( "There is a new version available.\n" + "Your version: {0}.\n" + "Newest version: {1}.\n\n" + "Changes in new version: \n{2}. ", applicationVersion, newVersion, aboutUpdate); DebugLog("A new version is available, prompting for update..."); if (DialogResult.No != MessageBox.Show(str + "\nWould you like to download this update?", "Check for updates", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { try { DebugLog("Trying to update to new version..."); Process.Start(downloadUrl); } catch (Exception e) { DebugLog("Update failed: " + e); MessageBox.Show("The update was unsuccessful. Try again later.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } return; } } else { DebugLog("Application version checked and is up-to-date"); } }
public static bool ExportItemPost(string ServerVersion, string sItemId, string sFile) { bool bSuccess = false; string sResponseText = string.Empty; System.Net.HttpWebRequest oHttpWebRequest = null; EwsProxyFactory.CreateHttpWebRequest(ref oHttpWebRequest); oHttpWebRequest.Headers.Add("client-request-id", Guid.NewGuid().ToString()); oHttpWebRequest.Headers.Add("return-client-request-id: ", "true"); // Build request body... string EwsRequest = TemplateEwsRequests.ExportItems; EwsRequest = EwsRequest.Replace("##RequestServerVersion##", ServerVersion); EwsRequest = EwsRequest.Replace("##ItemId##", sItemId); try { // Use request to do POST to EWS so we get back the data for the item to export. byte[] bytes = Encoding.UTF8.GetBytes(EwsRequest); oHttpWebRequest.ContentLength = bytes.Length; using (Stream requestStream = oHttpWebRequest.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); requestStream.Flush(); requestStream.Close(); } // Get response HttpWebResponse oHttpWebResponse = (HttpWebResponse)oHttpWebRequest.GetResponse(); StreamReader oStreadReader = new StreamReader(oHttpWebResponse.GetResponseStream()); sResponseText = oStreadReader.ReadToEnd(); // OK? if (oHttpWebResponse.StatusCode == HttpStatusCode.OK) { int BUFFER_SIZE = 1024; int iReadBytes = 0; XmlDocument oDoc = new XmlDocument(); XmlNamespaceManager namespaces = new XmlNamespaceManager(oDoc.NameTable); namespaces.AddNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages"); try { oDoc.LoadXml(sResponseText); //try //{ XmlNode oData = oDoc.SelectSingleNode("//m:Data", namespaces); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message.ToString() + "\r\n\r\n" + "Response: \r\n" + sResponseText, "Error"); //} // Write base 64 encoded text Data XML string into a binary base 64 text/XML file BinaryWriter oBinaryWriter = new BinaryWriter(File.Open(sFile, FileMode.Create)); StringReader oStringReader = new StringReader(oData.OuterXml); XmlTextReader oXmlTextReader = new XmlTextReader(oStringReader); oXmlTextReader.MoveToContent(); byte[] buffer = new byte[BUFFER_SIZE]; do { iReadBytes = oXmlTextReader.ReadBase64(buffer, 0, BUFFER_SIZE); oBinaryWriter.Write(buffer, 0, iReadBytes); }while (iReadBytes >= BUFFER_SIZE); oXmlTextReader.Close(); oBinaryWriter.Flush(); oBinaryWriter.Close(); bSuccess = true; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString() + "\r\n\r\n" + "Response: \r\n" + sResponseText, "Error"); } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Error"); } finally { } return(bSuccess); }
public void Load() { XmlTextReader reader = new XmlTextReader(projectPath); string activeConfigName = null; ProjectConfig currentConfig = null; try { reader.MoveToContent(); if (reader.NodeType != XmlNodeType.Element || reader.Name != "NUnitProject") { throw new ProjectFormatException( "Invalid project format: <NUnitProject> expected.", reader.LineNumber, reader.LinePosition); } while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "Settings": if (reader.NodeType == XmlNodeType.Element) { activeConfigName = reader.GetAttribute("activeconfig"); string autoConfig = reader.GetAttribute("autoconfig"); if (autoConfig != null) { this.AutoConfig = autoConfig.ToLower() == "true"; } if (this.AutoConfig) { activeConfigName = NUnitConfiguration.BuildConfiguration; } string appbase = reader.GetAttribute("appbase"); if (appbase != null) { this.BasePath = appbase; } string processModel = reader.GetAttribute("processModel"); if (processModel != null) { this.ProcessModel = (ProcessModel)Enum.Parse(typeof(ProcessModel), processModel); } string domainUsage = reader.GetAttribute("domainUsage"); if (domainUsage != null) { this.DomainUsage = (DomainUsage)Enum.Parse(typeof(DomainUsage), domainUsage); } } break; case "Config": if (reader.NodeType == XmlNodeType.Element) { string configName = reader.GetAttribute("name"); currentConfig = new ProjectConfig(configName); currentConfig.BasePath = reader.GetAttribute("appbase"); currentConfig.ConfigurationFile = reader.GetAttribute("configfile"); string binpath = reader.GetAttribute("binpath"); currentConfig.PrivateBinPath = binpath; string type = reader.GetAttribute("binpathtype"); if (type == null) { if (binpath == null) { currentConfig.BinPathType = BinPathType.Auto; } else { currentConfig.BinPathType = BinPathType.Manual; } } else { currentConfig.BinPathType = (BinPathType)Enum.Parse(typeof(BinPathType), type, true); } string runtime = reader.GetAttribute("runtimeFramework"); if (runtime != null) { currentConfig.RuntimeFramework = RuntimeFramework.Parse(runtime); } Configs.Add(currentConfig); if (configName == activeConfigName) { activeConfig = currentConfig; } } else if (reader.NodeType == XmlNodeType.EndElement) { currentConfig = null; } break; case "assembly": if (reader.NodeType == XmlNodeType.Element && currentConfig != null) { string path = reader.GetAttribute("path"); currentConfig.Assemblies.Add( Path.Combine(currentConfig.BasePath, path)); } break; default: break; } } } this.IsDirty = false; this.reloadRequired = false; } catch (FileNotFoundException) { throw; } catch (XmlException e) { throw new ProjectFormatException( string.Format("Invalid project format: {0}", e.Message), e.LineNumber, e.LinePosition); } catch (Exception e) { throw new ProjectFormatException( string.Format("Invalid project format: {0} Line {1}, Position {2}", e.Message, reader.LineNumber, reader.LinePosition), reader.LineNumber, reader.LinePosition); } finally { reader.Close(); } }
/// <summary> /// Deserialize /// </summary> /// <param name="vertexName"></param> /// <param name="q"></param> /// <param name="tr"></param> /// <returns></returns> internal static VertexMx Deserialize( string name, Query q, XmlTextReader tr) { Enum iEnum = null; VertexMx v = new VertexMx(); if (XmlUtil.GetEnumAttribute(tr, "ShowLabels", typeof(ShowLabels), ref iEnum)) { v.ShowLabels = (ShowLabels)iEnum; } while (true) // loop through elements of network { tr.Read(); tr.MoveToContent(); if (Lex.Eq(tr.Name, name + "Column")) { v.QueryColumn = ResultsViewProps.DeserializeQueryColumn(q, tr); //tr.Read(); tr.MoveToContent(); } else if (Lex.Eq(tr.Name, "Color")) { v.Color = ColorDimension.Deserialize("Color", q, tr); //tr.Read(); tr.MoveToContent(); } else if (Lex.Eq(tr.Name, "Size")) { v.Size = SizeDimension.Deserialize("Size", q, tr); //tr.Read(); tr.MoveToContent(); } else if (Lex.Eq(tr.Name, "Shape")) { v.Shape = ShapeDimension.Deserialize("Shape", q, tr); //tr.Read(); tr.MoveToContent(); } else if (Lex.Eq(tr.Name, "TooltipFields")) { v.TooltipFields = TooltipDimensionDef.Deserialize("TooltipFields", q, tr); //tr.Read(); tr.MoveToContent(); } else if (tr.NodeType == XmlNodeType.EndElement && // end of props Lex.Eq(tr.Name, name)) { break; } else { throw new Exception("Unexpected element: " + tr.Name); } } return(v); }
// Load application settings public bool LoadSettings() { bool ret = false; // check file existance if (File.Exists(settingsFile)) { FileStream fs = null; XmlTextReader xmlIn = null; try { // open file fs = new FileStream(settingsFile, FileMode.Open); // create XML reader xmlIn = new XmlTextReader(fs); xmlIn.WhitespaceHandling = WhitespaceHandling.None; xmlIn.MoveToContent(); // check for main node if (xmlIn.Name != "CameraViewer") { throw new ApplicationException(""); } // move to next node xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) { xmlIn.Read(); } // check for main window node if (xmlIn.Name != "MainWindow") { throw new ApplicationException(""); } // read main window position int x = Convert.ToInt32(xmlIn.GetAttribute("x")); int y = Convert.ToInt32(xmlIn.GetAttribute("y")); int width = Convert.ToInt32(xmlIn.GetAttribute("width")); int height = Convert.ToInt32(xmlIn.GetAttribute("height")); // move to next node xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) { xmlIn.Read(); } // check for view node if (xmlIn.Name != "View") { throw new ApplicationException(""); } showCameraBar = Convert.ToBoolean(xmlIn.GetAttribute("cameraBar")); cameraBarWidth = Convert.ToInt32(xmlIn.GetAttribute("cameraBarWidth")); mainWindowLocation = new Point(x, y); mainWindowSize = new Size(width, height); ret = true; } // catch any exceptions catch (Exception) { } finally { if (xmlIn != null) { xmlIn.Close(); } } } return(ret); }
public static void LoadFromXml(DockPanel dockPanel, Stream stream, DeserializeDockContent deserializeContent, bool closeStream) { if (dockPanel.Contents.Count != 0) { throw new InvalidOperationException(Strings.DockPanel_LoadFromXml_AlreadyInitialized); } DockPanelStruct dockPanelStruct; ContentStruct[] contents; PaneStruct[] panes; DockWindowStruct[] dockWindows; FloatWindowStruct[] floatWindows; using (var xmlIn = new XmlTextReader(stream) { WhitespaceHandling = WhitespaceHandling.None }) { xmlIn.MoveToContent(); while (!xmlIn.Name.Equals("DockPanel")) { if (!MoveToNextElement(xmlIn)) { throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); } } string formatVersion = xmlIn.GetAttribute("FormatVersion"); if (!IsFormatVersionValid(formatVersion)) { throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidFormatVersion); } dockPanelStruct = new DockPanelStruct(); dockPanelStruct.DockLeftPortion = Convert.ToDouble(xmlIn.GetAttribute("DockLeftPortion"), CultureInfo.InvariantCulture); dockPanelStruct.DockRightPortion = Convert.ToDouble(xmlIn.GetAttribute("DockRightPortion"), CultureInfo.InvariantCulture); dockPanelStruct.DockTopPortion = Convert.ToDouble(xmlIn.GetAttribute("DockTopPortion"), CultureInfo.InvariantCulture); dockPanelStruct.DockBottomPortion = Convert.ToDouble(xmlIn.GetAttribute("DockBottomPortion"), CultureInfo.InvariantCulture); dockPanelStruct.IndexActiveDocumentPane = Convert.ToInt32(xmlIn.GetAttribute("ActiveDocumentPane"), CultureInfo.InvariantCulture); dockPanelStruct.IndexActivePane = Convert.ToInt32(xmlIn.GetAttribute("ActivePane"), CultureInfo.InvariantCulture); // Load Contents MoveToNextElement(xmlIn); if (xmlIn.Name != "Contents") { throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); } contents = LoadContents(xmlIn); // Load Panes if (xmlIn.Name != "Panes") { throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); } panes = LoadPanes(xmlIn); // Load DockWindows if (xmlIn.Name != "DockWindows") { throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); } dockWindows = LoadDockWindows(xmlIn, dockPanel); // Load FloatWindows if (xmlIn.Name != "FloatWindows") { throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); } floatWindows = LoadFloatWindows(xmlIn); if (closeStream) { xmlIn.Close(); } } dockPanel.SuspendLayout(true); dockPanel.DockLeftPortion = dockPanelStruct.DockLeftPortion; dockPanel.DockRightPortion = dockPanelStruct.DockRightPortion; dockPanel.DockTopPortion = dockPanelStruct.DockTopPortion; dockPanel.DockBottomPortion = dockPanelStruct.DockBottomPortion; // Set DockWindow ZOrders int prevMaxDockWindowZOrder = int.MaxValue; for (int i = 0; i < dockWindows.Length; i++) { int maxDockWindowZOrder = -1; int index = -1; for (int j = 0; j < dockWindows.Length; j++) { if (dockWindows[j].ZOrderIndex > maxDockWindowZOrder && dockWindows[j].ZOrderIndex < prevMaxDockWindowZOrder) { maxDockWindowZOrder = dockWindows[j].ZOrderIndex; index = j; } } dockPanel.DockWindows[dockWindows[index].DockState].BringToFront(); prevMaxDockWindowZOrder = maxDockWindowZOrder; } // Create Contents for (int i = 0; i < contents.Length; i++) { IDockContent content = deserializeContent(contents[i].PersistString); if (content == null) { content = new DummyContent(); } content.DockHandler.DockPanel = dockPanel; content.DockHandler.AutoHidePortion = contents[i].AutoHidePortion; content.DockHandler.IsHidden = true; content.DockHandler.IsFloat = contents[i].IsFloat; } // Create panes for (int i = 0; i < panes.Length; i++) { DockPane pane = null; for (int j = 0; j < panes[i].IndexContents.Length; j++) { IDockContent content = dockPanel.Contents[panes[i].IndexContents[j]]; if (j == 0) { pane = dockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(content, panes[i].DockState, false); } else if (panes[i].DockState == DockState.Float) { content.DockHandler.FloatPane = pane; } else { content.DockHandler.PanelPane = pane; } } } // Assign Panes to DockWindows for (int i = 0; i < dockWindows.Length; i++) { for (int j = 0; j < dockWindows[i].NestedPanes.Length; j++) { DockWindow dw = dockPanel.DockWindows[dockWindows[i].DockState]; int indexPane = dockWindows[i].NestedPanes[j].IndexPane; DockPane pane = dockPanel.Panes[indexPane]; int indexPrevPane = dockWindows[i].NestedPanes[j].IndexPrevPane; DockPane prevPane = (indexPrevPane == -1) ? dw.NestedPanes.GetDefaultPreviousPane(pane) : dockPanel.Panes[indexPrevPane]; DockAlignment alignment = dockWindows[i].NestedPanes[j].Alignment; double proportion = dockWindows[i].NestedPanes[j].Proportion; pane.DockTo(dw, prevPane, alignment, proportion); if (panes[indexPane].DockState == dw.DockState) { panes[indexPane].ZOrderIndex = dockWindows[i].ZOrderIndex; } } } // Create float windows for (int i = 0; i < floatWindows.Length; i++) { FloatWindow fw = null; for (int j = 0; j < floatWindows[i].NestedPanes.Length; j++) { int indexPane = floatWindows[i].NestedPanes[j].IndexPane; DockPane pane = dockPanel.Panes[indexPane]; if (j == 0) { fw = dockPanel.Theme.Extender.FloatWindowFactory.CreateFloatWindow(dockPanel, pane, floatWindows[i].Bounds); } else { int indexPrevPane = floatWindows[i].NestedPanes[j].IndexPrevPane; DockPane prevPane = indexPrevPane == -1 ? null : dockPanel.Panes[indexPrevPane]; DockAlignment alignment = floatWindows[i].NestedPanes[j].Alignment; double proportion = floatWindows[i].NestedPanes[j].Proportion; pane.DockTo(fw, prevPane, alignment, proportion); } if (panes[indexPane].DockState == fw.DockState) { panes[indexPane].ZOrderIndex = floatWindows[i].ZOrderIndex; } } } // sort IDockContent by its Pane's ZOrder int[] sortedContents = null; if (contents.Length > 0) { sortedContents = new int[contents.Length]; for (int i = 0; i < contents.Length; i++) { sortedContents[i] = i; } int lastDocument = contents.Length; for (int i = 0; i < contents.Length - 1; i++) { for (int j = i + 1; j < contents.Length; j++) { DockPane pane1 = dockPanel.Contents[sortedContents[i]].DockHandler.Pane; int ZOrderIndex1 = pane1 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane1)].ZOrderIndex; DockPane pane2 = dockPanel.Contents[sortedContents[j]].DockHandler.Pane; int ZOrderIndex2 = pane2 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane2)].ZOrderIndex; if (ZOrderIndex1 > ZOrderIndex2) { int temp = sortedContents[i]; sortedContents[i] = sortedContents[j]; sortedContents[j] = temp; } } } } // show non-document IDockContent first to avoid screen flickers for (int i = 0; i < contents.Length; i++) { IDockContent content = dockPanel.Contents[sortedContents[i]]; if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState != DockState.Document) { content.DockHandler.SuspendAutoHidePortionUpdates = true; content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden; content.DockHandler.SuspendAutoHidePortionUpdates = false; } } // after all non-document IDockContent, show document IDockContent for (int i = 0; i < contents.Length; i++) { IDockContent content = dockPanel.Contents[sortedContents[i]]; if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState == DockState.Document) { content.DockHandler.SuspendAutoHidePortionUpdates = true; content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden; content.DockHandler.SuspendAutoHidePortionUpdates = false; } } for (int i = 0; i < panes.Length; i++) { dockPanel.Panes[i].ActiveContent = panes[i].IndexActiveContent == -1 ? null : dockPanel.Contents[panes[i].IndexActiveContent]; } if (dockPanelStruct.IndexActiveDocumentPane >= 0 && dockPanel.Panes.Count > dockPanelStruct.IndexActiveDocumentPane) { dockPanel.Panes[dockPanelStruct.IndexActiveDocumentPane].Activate(); } if (dockPanelStruct.IndexActivePane >= 0 && dockPanel.Panes.Count > dockPanelStruct.IndexActivePane) { dockPanel.Panes[dockPanelStruct.IndexActivePane].Activate(); } for (int i = dockPanel.Contents.Count - 1; i >= 0; i--) { if (dockPanel.Contents[i] is DummyContent) { dockPanel.Contents[i].DockHandler.Form.Close(); } } dockPanel.ResumeLayout(true, true); }
static Version NewVersion() { Version newVersion = null; string url = ""; XmlTextReader reader = null; try { string xmlURL = MobileConfiguration.Configuration.Settings["URLCheckVersion"].ToString(); if (ExistUrl(xmlURL)) { reader = new XmlTextReader(xmlURL); reader.MoveToContent(); string elementName = ""; if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "ourfancyapp")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "scanner_version": newVersion = new Version(reader.Value); break; case "url": url = reader.Value; break; default: break; } } } } } } else { MessageBox.Show("The System Can't Check for Update Program", "Warning"); newVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); newVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; } finally { if (reader != null) { reader.Close(); } } return(newVersion); }
public static ONOid ValidateTicket(double dtdVersion, string ticket, string clientName) { try { string lServerName = ""; string lClientName = ""; ONOid lAgentOid; ONDateTime lTimeStamp; ONNat lValidity; #region Open xml string lTicket = UncipherTicket(ticket); XmlTextReader lXMLReader = new XmlTextReader(new StringReader(lTicket)); lXMLReader.WhitespaceHandling = WhitespaceHandling.None; lXMLReader.MoveToContent(); #endregion #region Load information lXMLReader.ReadStartElement("ONTicket"); // Server name lServerName = lXMLReader.ReadElementString("Server"); // Client name lClientName = lXMLReader.ReadElementString("Client"); // Agent oid object[] lParam = new object[2]; lParam[0] = lXMLReader; lParam[1] = dtdVersion; lXMLReader.ReadStartElement("Agent"); string lAgentClass = lXMLReader.GetAttribute("Class"); lAgentOid = ONContext.InvoqueMethod(ONContext.GetType_XML(lAgentClass), "XML2ON", lParam) as ONOid; lXMLReader.ReadEndElement(); // Agent // TimeStamp lTimeStamp = ONXmlDateTime.XML2ON(lXMLReader, dtdVersion, "Timestamp"); // Validity lValidity = ONXmlNat.XML2ON(lXMLReader, dtdVersion, "Validity"); lXMLReader.ReadEndElement(); // ONTicket #endregion #region Validate information // Server name if (lServerName != mServerName) { throw new ONAgentValidationException(null); } // Client name if (lClientName != clientName) { throw new ONAgentValidationException(null); } // Agent oid if (ONSecureControl.SecureServer) { if (lAgentOid == null) { throw new ONAgentValidationException(null); } } // TimeStamp if (ONStdFunctions.datetimeAfter(lTimeStamp, ONStdFunctions.systemDateTime())) { throw new ONAgentValidationException(null); } if (new ONBool(mValidity > 0) && (ONStdFunctions.datetimeBefore(ONStdFunctions.dateTimeAdd(new ONString("s"), lValidity, lTimeStamp), ONStdFunctions.systemDateTime()))) { throw new ONAgentValidationException(null); } // Validity if (new ONBool(mValidity > 0) && (lValidity != new ONNat(mValidity))) { throw new ONAgentValidationException(null); } #endregion #region Close xml lXMLReader.Close(); #endregion return(lAgentOid); } catch (ONAgentValidationException) { throw; } catch { throw new ONAgentValidationException(null); } }
public void Load() { XmlTextReader reader = new XmlTextReader(projectPath); string activeConfigName = null; ProjectConfig currentConfig = null; try { reader.MoveToContent(); if (reader.NodeType != XmlNodeType.Element || reader.Name != "NUnitProject") { throw new ProjectFormatException( "Invalid project format: <NUnitProject> expected.", reader.LineNumber, reader.LinePosition); } while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "Settings": if (reader.NodeType == XmlNodeType.Element) { activeConfigName = reader.GetAttribute("activeconfig"); if (activeConfigName == "NUnitAutoConfig") { #if DEBUG if (Environment.Version.Major == 2) { activeConfigName = "Debug2005"; } else { activeConfigName = "Debug"; } #else if (Environment.Version.Major == 2) { activeConfigName = "Release2005"; } else { activeConfigName = "Release"; } #endif } string appbase = reader.GetAttribute("appbase"); if (appbase != null) { this.BasePath = appbase; } } break; case "Config": if (reader.NodeType == XmlNodeType.Element) { string configName = reader.GetAttribute("name"); currentConfig = new ProjectConfig(configName); currentConfig.BasePath = reader.GetAttribute("appbase"); currentConfig.ConfigurationFile = reader.GetAttribute("configfile"); string binpath = reader.GetAttribute("binpath"); currentConfig.PrivateBinPath = binpath; string type = reader.GetAttribute("binpathtype"); if (type == null) { if (binpath == null) { currentConfig.BinPathType = BinPathType.Auto; } else { currentConfig.BinPathType = BinPathType.Manual; } } else { currentConfig.BinPathType = (BinPathType)Enum.Parse(typeof(BinPathType), type, true); } Configs.Add(currentConfig); if (configName == activeConfigName) { activeConfig = currentConfig; } } else if (reader.NodeType == XmlNodeType.EndElement) { currentConfig = null; } break; case "assembly": if (reader.NodeType == XmlNodeType.Element && currentConfig != null) { string path = reader.GetAttribute("path"); currentConfig.Assemblies.Add( Path.Combine(currentConfig.BasePath, path)); } break; default: break; } } } this.IsDirty = false; } catch (FileNotFoundException) { throw; } catch (XmlException e) { throw new ProjectFormatException( string.Format("Invalid project format: {0}", e.Message), e.LineNumber, e.LinePosition); } catch (Exception e) { throw new ProjectFormatException( string.Format("Invalid project format: {0} Line {1}, Position {2}", e.Message, reader.LineNumber, reader.LinePosition), reader.LineNumber, reader.LinePosition); } finally { reader.Close(); } }
public int ParseConfig(string configFile, bool bDeep = false) { // // Consume XML to create the XFSEntity objects. // if bDeep is false, then ONLY do this object. // if bDeep is true, then also do recursive objects. XmlTextReader reader = null; int rc = -1; string connectString = XTRMObject.getDictionaryEntry("TaskConnectString"); string outerXML; int lElementType = 0; XDictionaryLoader myDictionaryLoader = new XDictionaryLoader(); Dictionary <String, String> elementAttributes; entities.Clear(); try { // Load the reader with the data file and ignore all white space nodes. reader = new XmlTextReader(configFile); 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 "XFSENTITY": outerXML = reader.ReadOuterXml(); XTRMFSEntity thisEntity = (XTRMFSEntity)XTRMFSEntity.consumeXML(outerXML, 1, true); entities.Add(thisEntity); 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++) { //reader.GetAttribute(i); elementAttributes.Add(reader.Name, reader.Value); reader.MoveToNextAttribute(); } if (elementAttributes.ContainsKey("Tag")) { agentTag = elementAttributes["Tag"]; } if (elementAttributes.ContainsKey("Source")) { agentSource = elementAttributes["Source"]; } if (elementAttributes.ContainsKey("User")) { agentUser = elementAttributes["User"]; } if (elementAttributes.ContainsKey("EventPath")) { agentEventPath = elementAttributes["EventPath"]; } reader.MoveToElement(); } // Need to see if we are interested in this element! //string elementName = reader.Name; switch (elementName.ToUpper()) { case "XFILEAGENTCONFIG": // Advance into Elements! reader.MoveToContent(); bResult = reader.Read(); 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) { default: break; } bResult = reader.Read(); break; default: bResult = reader.Read(); break; } } } catch (Exception ex) { exCount_XML++; XLogger(2400, -1, string.Format("XTRMFileAgent::parseConfig(); ConfigFile={0}; Message={1}", configFile, ex.Message)); } finally { if (reader != null) { reader.Close(); } } return(rc); }
public string LatestVersionScanner(string currentV) { string lastestV = null; XmlTextReader reader = null; try { string xmlURL = Server.MapPath(".") + "\\UpdateFile\\app_version.xml"; if (File.Exists(xmlURL)) { reader = new XmlTextReader(xmlURL); reader.MoveToContent(); string elementName = ""; if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "ourfancyapp")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "scanner_version": lastestV = reader.Value; break; default: break; } } } } } } else { lastestV = currentV; } } catch (Exception ex) { lastestV = currentV; } finally { if (reader != null) { reader.Close(); } } return(lastestV); }
/// <summary> /// Reads a Paratext .ssf file and imports selected configuration items into our own Options object. /// </summary> /// <param name="projectOptions">Options object to update with data in the Paratext .ssf file.</param> /// <param name="ssfFileName">Full path to the Paratext .ssf file to update.</param> public void ReadParatextSsf(Options projectOptions, string ssfFileName) { string elementName, setting; try { if (!File.Exists(ssfFileName)) { return; } XmlTextReader ssf = new XmlTextReader(ssfFileName); ssf.WhitespaceHandling = WhitespaceHandling.Significant; ssf.MoveToContent(); while (ssf.Read()) { if ((ssf.NodeType == XmlNodeType.Element) && (ssf.Name != "ScriptureText")) { if (!ssf.IsEmptyElement) { elementName = ssf.Name; ssf.Read(); // Get content of element if ((ssf.NodeType == XmlNodeType.Text) && (!String.IsNullOrEmpty(ssf.Value))) { setting = ssf.Value; switch (elementName) { case "Encoding": if (setting != "65001") { Logit.WriteLine("Warning: Paratext encoding is not Unicode UTF-8 (" + setting + ") in " + ssfFileName); } break; case "EthnologueCode": if (projectOptions.languageId.Length < 3) { projectOptions.languageId = setting; } break; case "RangeIndicator": // verse range separator projectOptions.rangeSeparator = setting; break; case "SequenceIndicator": projectOptions.multiRefSameChapterSeparator = setting; break; case "ChapterVerseSeparator": projectOptions.CVSeparator = setting; break; case "ChapterRangeSeparator": projectOptions.multiRefDifferentChapterSeparator = setting; break; case "BookSequenceSeparator": projectOptions.BookSequenceSeparator = setting; break; case "ChapterNumberSeparator": projectOptions.ChapterNumberSeparator = setting; break; case "BookSourceForMarkerXt": projectOptions.BookSourceForMarkerXt = setting; break; case "BookSourceForMarkerR": projectOptions.BookSourceForMarkerR = setting; break; case "Guid": projectOptions.paratextGuid = setting; break; } } } } } ssf.Close(); projectOptions.Write(); } catch (Exception ex) { Logit.WriteError("Error reading Paratext options file " + ssfFileName + ": " + ex.Message); Logit.WriteError(ex.StackTrace); } }
public bool LoadSettings(string vsSettingsFile) { // check file existance if (File.Exists(vsSettingsFile)) { // VsSplasher.Status = "Load setting..."; FileStream fs = null; XmlTextReader xmlIn = null; // open file fs = new FileStream(vsSettingsFile, FileMode.Open,FileAccess.Read); // create XML reader xmlIn = new XmlTextReader(fs); xmlIn.WhitespaceHandling = WhitespaceHandling.None; xmlIn.MoveToContent(); // check for main node if (xmlIn.Name != "appSettings") throw new ApplicationException(""); xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) xmlIn.Read(); while (xmlIn.Name == "add") { data.Add(xmlIn.GetAttribute("key"), xmlIn.GetAttribute("value")); xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) xmlIn.Read(); } // close file xmlIn.Close(); fs.Close(); return true; } else { return false; } }
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; }
//bool disabled = true; public static Update CheckUpdate() { Update update = new Update(); string xmlUrl = "http://earleys.be/downloads/GTAMP3Randomizer/update.xml"; XmlTextReader reader = null; try { reader = new XmlTextReader(xmlUrl); reader.MoveToContent(); string elementName = ""; if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "appinfo")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "version": update.Version = new Version(reader.Value); break; case "url": update.Url = reader.Value; break; case "about": update.About = reader.Value; break; case "mandatoryversion": update.Mandatory = new Version(reader.Value); break; } } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (reader != null) { reader.Close(); } } return(update); }
public void parseXML(string strPath) { try { XmlTextReader reader = new XmlTextReader (strPath); reader.Read (); Console.WriteLine ("--- Dateianfang ---"); Console.WriteLine (reader.ReadToEnd ()); Console.WriteLine ("--- Dateiende -----"); Console.WriteLine (reader.NodeType); // It prints "XmlDeclaration" reader.MoveToContent (); Console.WriteLine (reader.NodeType); // It prints "Element" Console.WriteLine (reader.Name); // "rss" Console.WriteLine (reader.GetAttribute ("version")); // Maybe "0.92" // proceed content until we reach "item" element while (!reader.EOF && reader.Name != "item") reader.Read (); reader.Read (); // Move from "item" to "title" while (reader.NodeType == XmlNodeType.Whitespace) reader.Read (); Console.WriteLine ("Title : " + reader.ReadString ()); reader.Read (); // from "</title>" to whitespace reader.Read (); // from whitespace to <link> Console.WriteLine ("Link : " + reader.ReadString ()); reader.Read (); // from "</link>" to whitespace reader.Read (); // from whitespace to <pubDate> Console.WriteLine ("Date : " + reader.ReadString ()); reader.Read (); // from "</pubDate>" to whitespace reader.Read (); // from whitespace to <description> Console.WriteLine ("Description : " + reader.ReadString ()); } // Datei nicht gefunden catch (FileNotFoundException ex) { Console.WriteLine (ex.Message); } // Verzeichnis existiert nicht catch (DirectoryNotFoundException ex) { Console.WriteLine (ex.Message); } // Pfadangabe war 'null' catch (ArgumentNullException ex) { Console.WriteLine (ex.Message); } // Pfadangabe war leer ("") catch (ArgumentException ex) { Console.WriteLine (ex.Message); } // allgemeine Exception catch (Exception ex) { Console.WriteLine (ex.Message); } }
//XmlTextReader "crawling style" reader fits better the purpose than a "read it all at once" XDocument public static string XmlToPlainText(this string xmlDoc, bool isReflectionDocument = false, bool ignoreExceptionsInfo = false) { //var root.XElement.Parse("<root>" + entity.Documentation.Xml.Text + "</root>"); var sections = new List <string>(); var b = new StringBuilder(); try { using (var reader = new XmlTextReader(new StringReader("<root>" + xmlDoc + "</root>"))) { string lastElementName = null; bool exceptionsStarted = false; reader.XmlResolver = null; while (reader.Read()) { var nodeType = reader.NodeType; switch (nodeType) { case XmlNodeType.Text: if (lastElementName == "summary") { b.Insert(0, reader.Value.Shrink()); } else { if (exceptionsStarted) { b.Append(" "); } if (lastElementName == "code") { b.Append(reader.Value); //need to preserve all formatting (line breaks and indents) } else { //if (reflectionDocument) // b.Append(reader.Value.NormalizeLines()); //need to preserve line breaks but not indents //else b.Append(reader.Value.Shrink()); } } break; case XmlNodeType.Element: { bool silentElement = false; switch (reader.Name) { case "filterpriority": reader.Skip(); break; case "root": case "summary": case "c": silentElement = true; break; case "paramref": silentElement = true; b.Append(reader.GetAttribute("name")); break; case "param": silentElement = true; b.AppendLine(); b.Append(reader.GetAttribute("name") + ": "); break; case "para": silentElement = true; b.AppendLine(); break; case "remarks": b.AppendLine(); b.Append("Remarks: "); break; case "returns": silentElement = true; b.AppendLine(); b.Append("Returns: "); break; case "exception": { if (!exceptionsStarted) { b.AppendLine(); sections.Add(b.ToString().Trim()); b.Length = 0; if (!ignoreExceptionsInfo) { b.AppendLine("Exceptions: "); } } exceptionsStarted = true; if (!ignoreExceptionsInfo && !reader.IsEmptyElement) { bool printExInfo = false; if (printExInfo) { b.Append(" " + reader.GetCrefAttribute() + ": "); } else { b.Append(" " + reader.GetCrefAttribute()); reader.Skip(); } } break; } case "see": silentElement = true; if (reader.IsEmptyElement) { b.Append(reader.GetCrefAttribute()); } else { reader.MoveToContent(); if (reader.HasValue) { b.Append(reader.Value); } else { b.Append(reader.GetCrefAttribute()); } } break; } if (!silentElement) { b.AppendLine(); } lastElementName = reader.Name; break; } case XmlNodeType.EndElement: { if (reader.Name == "summary") { b.AppendLine(); sections.Add(b.ToString().Trim()); b.Length = 0; } else if (reader.Name == "returns") { b.AppendLine(); sections.Add(b.ToString().Trim()); b.Length = 0; } break; } } } } sections.Add(b.ToString().Trim()); string sectionSeparator = (isReflectionDocument ? "\r\n--------------------------\r\n" : "\r\n\r\n"); return(string.Join(sectionSeparator, sections.Where(x => !string.IsNullOrEmpty(x)).ToArray())); } catch (XmlException) { return(xmlDoc); } }
public static List<UrlMapSet> LoadSets() { List<UrlMapSet> sets = new List<UrlMapSet>(); using (XmlReader reader = new XmlTextReader(new StreamReader(HttpContext.Current.Server.MapPath("~/Config/FileSets.xml")))) { reader.MoveToContent(); while (reader.Read()) { if ("set" == reader.Name) { string setName = reader.GetAttribute("name"); UrlMapSet UrlMapSet = new UrlMapSet(); UrlMapSet.Name = setName; while (reader.Read()) { if ("url" == reader.Name) { string urlName = reader.GetAttribute("name"); string url = reader.ReadElementContentAsString(); UrlMapSet.Urls.Add(new UrlMap(urlName, url)); } else if ("set" == reader.Name) break; } sets.Add(UrlMapSet); } } } return sets; }
public static string XmlDocumentationToText(string xmlDoc) { System.Diagnostics.Debug.WriteLine(xmlDoc); StringBuilder b = new StringBuilder(); try { using (XmlTextReader reader = new XmlTextReader(new StringReader("<root>" + xmlDoc + "</root>"))) { reader.XmlResolver = null; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Text: b.Append(reader.Value); break; case XmlNodeType.Element: switch (reader.Name) { case "filterpriority": reader.Skip(); break; case "returns": b.AppendLine(); b.Append("Returns: "); break; case "param": b.AppendLine(); b.Append(reader.GetAttribute("name") + ": "); break; case "remarks": b.AppendLine(); b.Append("Remarks: "); break; case "see": if (reader.IsEmptyElement) { b.Append(reader.GetAttribute("cref")); } else { reader.MoveToContent(); if (reader.HasValue) { b.Append(reader.Value); } else { b.Append(reader.GetAttribute("cref")); } } break; } break; } } } return(b.ToString()); } catch (XmlException) { return(xmlDoc); } }
public override void FromXmlString(string xmlString) { StringReader input = new StringReader(xmlString); XmlTextReader xmlTextReader = new XmlTextReader(input); this.class14_0 = (this.class14_1 = (this.class14_2 = (this.class14_3 = (this.class14_4 = (this.class14_5 = (this.class14_6 = (this.class14_7 = null))))))); while (true) { XmlNodeType xmlNodeType = xmlTextReader.MoveToContent(); XmlNodeType xmlNodeType2 = xmlNodeType; switch (xmlNodeType2) { case XmlNodeType.None: return; case XmlNodeType.Element: { string name = xmlTextReader.Name; if (!this.method_15(xmlTextReader, name, "Modulus", ref this.class14_0) && !this.method_15(xmlTextReader, name, "Exponent", ref this.class14_1) && !this.method_15(xmlTextReader, name, "P", ref this.class14_2) && !this.method_15(xmlTextReader, name, "Q", ref this.class14_3) && !this.method_15(xmlTextReader, name, "DP", ref this.class14_4) && !this.method_15(xmlTextReader, name, "DQ", ref this.class14_5) && !this.method_15(xmlTextReader, name, "InverseQ", ref this.class14_6) && !this.method_15(xmlTextReader, name, "D", ref this.class14_7)) { xmlTextReader.ReadString(); } break; } default: if (xmlNodeType2 != XmlNodeType.EndElement) { goto Block_9; } xmlTextReader.ReadEndElement(); break; } } Block_9: throw new ArgumentException(); }
private void LoadLanguage(string locale) { var languageResource = $"{Environment.CurrentDirectory}\\Languages\\{locale}.xml"; XmlTextReader languageReader = new XmlTextReader(languageResource); languageReader.MoveToContent(); string elementName = ""; if ((languageReader.NodeType == XmlNodeType.Element) && (languageReader.Name == "Locale")) { while (languageReader.Read()) { if (languageReader.NodeType == XmlNodeType.Element) { elementName = languageReader.Name; } else { if ((languageReader.NodeType == XmlNodeType.Text) && (languageReader.HasValue)) { switch (elementName) { case "Title": this.Text = languageReader.Value; break; case "File": this.fileToolStripMenuItem.Text = languageReader.Value; break; case "Open": this.openToolStripMenuItem.Text = languageReader.Value; break; case "Save": this.saveToolStripMenuItem.Text = languageReader.Value; break; case "Edit": this.editToolStripMenuItem.Text = languageReader.Value; break; case "Cut": this.cutToolStripMenuItem.Text = languageReader.Value; break; case "Copy": this.copyToolStripMenuItem.Text = languageReader.Value; break; case "Paste": this.pasteToolStripMenuItem.Text = languageReader.Value; break; case "Options": this.toolsToolStripMenuItem.Text = languageReader.Value; break; case "Language": this.customizeToolStripMenuItem.Text = languageReader.Value; break; } } } } } }
private Dictionary<string, string> parseXML(string XML) { if (XML == string.Empty) return new Dictionary<string, string>(); // Catch empty response Dictionary<string, string> parameters = new Dictionary<string, string>(); XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(XML)); reader.MoveToContent(); while (reader.Read()) { reader.MoveToContent(); parameters.Add(reader.Name,reader.ReadInnerXml().ToString()); } return parameters; }
void Deserialize_inner(Stream inStream, ISoapMessage soapMessage) { ArrayList headers = null; xmlReader = new XmlTextReader(inStream); xmlReader.WhitespaceHandling = WhitespaceHandling.None; mapper = new SoapTypeMapper(_binder); try { // SOAP-ENV:Envelope xmlReader.MoveToContent(); xmlReader.ReadStartElement(); xmlReader.MoveToContent(); // Read headers while (!(xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Body" && xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace)) { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Header" && xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace) { if (headers == null) { headers = new ArrayList(); } DeserializeHeaders(headers); } else { xmlReader.Skip(); } xmlReader.MoveToContent(); } // SOAP-ENV:Body xmlReader.ReadStartElement(); xmlReader.MoveToContent(); // The root object if (soapMessage != null) { if (DeserializeMessage(soapMessage)) { _topObjectId = NextAvailableId; RegisterObject(_topObjectId, soapMessage, null, 0, null, null); } xmlReader.MoveToContent(); if (headers != null) { soapMessage.Headers = (Header[])headers.ToArray(typeof(Header)); } } while (xmlReader.NodeType != XmlNodeType.EndElement) { Deserialize(); } // SOAP-ENV:Body xmlReader.ReadEndElement(); xmlReader.MoveToContent(); // SOAP-ENV:Envelope xmlReader.ReadEndElement(); } finally { if (xmlReader != null) { xmlReader.Close(); } } }