public static double GetNewVersionNumberOfDzenClient() { XmlDocument doc = new XmlDocument(); doc.Load("Configuration.xml"); double temp = Convert.ToDouble(doc.GetElementById("dzenclient")); return temp; }
/* List<Edit> edits; //everything is stored by edits public List<Edit> Edits { get { return edits; } set { edits = value; } } */ //Records when an edit has occured and what the edit was //The above structures contain the most updated version of the synthesis /* <localid>rc1</localid> <name>benzaldehyde</name> <refid>aldehyde</refid> <molweight>106.12</molweight> <state>solid</state> <density temp="20">null</density> <islimiting>true</islimiting> <mols unit="mmol">57</mols> <mass unit="g">6</mass> <volume>null</volume> * */ public static Synthesis ReadFile(string filename) { XmlDocument doc = new XmlDocument(); doc.Load(filename); XmlNode header = doc.GetElementById("header"); XmlNodeList editHeader = doc.GetElementsByTagName("editheader"); XmlNodeList reactantNodeList = doc.GetElementsByTagName("reactant"); XmlNodeList reagentNodeList = doc.GetElementsByTagName("reagent"); XmlNodeList productNodeList = doc.GetElementsByTagName("product"); ObservableCollection<Compound> reactants = ReadBlock(reactantNodeList, COMPOUND_TYPES.Reactant); ObservableCollection<Compound> reagents = ReadBlock(reagentNodeList, COMPOUND_TYPES.Reagent); ObservableCollection<Compound> products = ReadBlock(productNodeList, COMPOUND_TYPES.Product); string synthName = GetSynthesisName(editHeader); int projectID = GetSynthesisProjectID(editHeader); SynthesisInfo previousStep = GetPreviousStep(editHeader); SynthesisInfo nextStep = GetNextStep(editHeader); string procedureText = GetProcedureText(editHeader); Synthesis synth = new Synthesis(reactants, reagents, products, synthName, projectID, previousStep, nextStep, procedureText); ReadMolData(doc, synth.AllCompounds); return synth; }
public virtual Object get() { XmlDocument doc = new XmlDocument(); doc.Load("Storage.xml"); XmlElement xmlElement = doc.GetElementById(guid.ToString()); return xmlElement; }
public virtual FilterGraph readFilterGraph(XmlDocument doc) { FilterGraph result = null; if (doc != null) { result = decodeFilterGraph(doc.GetElementById("graph"), null); } return result; }
static void Main() { string filePath = @"..\..\ch11\booklist.xml"; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(filePath); XmlElement element = xmlDocument.GetElementById("b2"); String title = element.FirstChild.FirstChild.Value; Console.WriteLine(title); }
public override bool MoveToId(string id) { XmlElement eltNew = document.GetElementById(id); if (eltNew == null) { return(false); } node = eltNew; return(true); }
public Boolean lookup() { XmlDocument doc = new XmlDocument(); doc.Load("Storage.xml"); if(doc.GetElementById(guid.ToString()) == null){ return false; } else{ return true; } }
public override void add(Guid memberID) { XmlDocument doc = new XmlDocument(); doc.Load("Storage.xml"); XmlNode xmlElement = doc.GetElementById(memberID.ToString()); XmlNode x = xmlElement.FirstChild; XmlElement newBoat = doc.CreateElement(myGuid.ToString()); newBoat.SetAttribute(length.ToString(), type.ToString()); x.AppendChild(newBoat); }
// ReadFile function calls Check functions // and then reads file and writes it to the target list public override void ReadFile(string filepath) { if (CheckFile(filepath)) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(filepath, readerSettings)) { // The load the document DOM XmlDocument document = new XmlDocument(); document.Load(reader); // Grab the first node XmlNode mainNode = document.FirstChild; mainNode = mainNode.NextSibling; XmlElement element = document.GetElementById("Targets"); // Then get the list of nodes containing the data we want. XmlNodeList nodes = mainNode.ChildNodes; //.ChildNodes; int targetCount = 0; foreach (XmlNode node in nodes) { targetCount++; bool isFriend = Convert.ToBoolean(node.Attributes["isFriend"].Value); double yPos = Convert.ToDouble(node.Attributes["yPos"].Value); double xPos = Convert.ToDouble(node.Attributes["xPos"].Value); double zPos = Convert.ToDouble(node.Attributes["zPos"].Value); string Name = Convert.ToString(node.Attributes["Name"].Value); XmlAttribute attribute = node.Attributes[0]; list.Add("Target " + targetCount); list.Add("x = " + xPos); list.Add("y = " + yPos); list.Add("z = " + zPos); list.Add("Friend = " + isFriend); list.Add("Name = " + Name); list.Add("\n"); } } } }
public void Sort_Nodes_Benchmark_New() { var xmlContent = GetXmlContent(1); var xml = new XmlDocument(); xml.LoadXml(xmlContent); var original = xml.GetElementById(1173.ToString()); Assert.IsNotNull(original); long totalTime = 0; var watch = new Stopwatch(); var iterations = 10000; for (var i = 0; i < iterations; i++) { //don't measure the time for clone! var parentNode = (XmlElement)original.Clone(); watch.Start(); XmlHelper.SortNodes( parentNode, "./* [@id]", element => element.Attribute("id") != null, element => element.AttributeValue<int>("sortOrder")); watch.Stop(); totalTime += watch.ElapsedMilliseconds; watch.Reset(); //do assertions just to make sure it is working properly. var currSort = 0; foreach (var child in parentNode.SelectNodes("./* [@id]").Cast<XmlNode>()) { Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value)); currSort++; } //ensure the parent node's properties still exist first Assert.AreEqual("content", parentNode.ChildNodes[0].Name); Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name); //then the child nodes should come straight after Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null); } Debug.WriteLine("Total time for " + iterations + " iterations is " + totalTime); }
/// <summary> /// /// 根据课程替换、删除相应的字符 /// </summary> /// <param name="classtype"></param> public static void characterReplace(string classtype, ref Word.Document document) { object missing = System.Reflection.Missing.Value; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(System.Windows.Forms.Application.StartupPath+"/FilterTemplate.xml"); XmlNode xmlnode = xmldoc.GetElementById(classtype); //xmldoc.SelectSingleNode("//Template"); XmlNodeList xmll = xmlnode.ChildNodes; for (int i = 0; i < xmll.Count; i++) { XmlNode xn = xmll[i]; object text = xn.SelectSingleNode("Replace").InnerText; object replacewith = xn.SelectSingleNode("ReplaceFor").InnerText; object replace=WdReplace.wdReplaceAll; object btrue = true; document.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置 Word.Find find = document.Content.Find;// mainContent1.WordBrowers.document.Content.Find; //find.MatchSoundsLike =ref btrue; bool b = find.Execute(ref text, ref missing, ref missing, ref btrue, ref missing, ref missing, ref missing, ref missing, ref missing, ref replacewith, ref replace, ref missing, ref missing, ref missing, ref missing); } }
private static SubjectStructure subjectPreStructure; //= new SubjectStructure(subjectPre, 1, minisubjectPreStructure); #endregion Fields #region Constructors public MatchArray(string id) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(Application.StartupPath + "/SpotTemplate.xml"); //配置共有信息 //配置对应学科 XmlElement xmlnode = xmldoc.GetElementById(id); //xmldoc.SelectSingleNode("//Template"); XmlNode matchSpaceNumnode = xmlnode.SelectSingleNode("matchSpaceNum"); XmlNode matchSpaceNum2node = xmlnode.SelectSingleNode("matchSpaceNum2"); XmlNode matchSelectOptionnode = xmlnode.SelectSingleNode("matchSelectOption"); XmlNode matchSelectOption2node = xmlnode.SelectSingleNode("matchSelectOption2"); matchSpaceNum = matchSpaceNumnode.InnerText; matchSpaceNum2 = matchSpaceNum2node.InnerText; matchSelectOption = matchSelectOptionnode.InnerText; matchSelectOption2 = matchSelectOption2node.InnerText; XmlNode xmlbigSubjectPre = xmlnode.SelectSingleNode("bigSubjectPre"); bigSubjectPre = xmlbigSubjectPre.InnerText.Split(','); XmlNode xmlanswer = xmlnode.SelectSingleNode("answer"); answer = xmlanswer.InnerText.Split(','); XmlNode xmlSubjectStructure = xmlnode.SelectSingleNode("SubjectStructure"); subjectPreStructure = InitSubjectStructure(xmlSubjectStructure); }
public static string GetLngStringValue(XmlDocument XMLDoc, string key) { //TODO phase out its usage (DIUI, DA, DX) and rename it to GetLanguageString (overloaded) string RetVal = string.Empty; XmlElement Element; ; try { key = key.ToUpper(); Element = XMLDoc.GetElementById(key); if (Element != null) { RetVal = Element.Attributes["value"].Value; } } catch (Exception) { RetVal = key; } return RetVal; }
public virtual XmlElement GetIdElement (XmlDocument document, string idValue) { if ((document == null) || (idValue == null)) return null; // this works only if there's a DTD or XSD available to define the ID XmlElement xel = document.GetElementById (idValue); if (xel == null) { // search an "undefined" ID xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']"); } return xel; }
// // public virtual methods // // This describes how the application wants to associate id references to elements public virtual XmlElement GetIdElement (XmlDocument document, string idValue) { if (document == null) return null; XmlElement elem = null; // Get the element with idValue elem = document.GetElementById(idValue); if (elem != null) return elem; elem = document.SelectSingleNode("//*[@Id=\"" + idValue + "\"]") as XmlElement; if (elem != null) return elem; elem = document.SelectSingleNode("//*[@id=\"" + idValue + "\"]") as XmlElement; if (elem != null) return elem; elem = document.SelectSingleNode("//*[@ID=\"" + idValue + "\"]") as XmlElement; return elem; }
/// <summary> /// Validates for valid language file name convention and valid xml content of language file. /// For validation of naming convention of language file name in isolation, use DevInfo.Lib.DI_LibBAL.NamingConvention.DIFileNameChecker.IsValidLanguageFileName /// </summary> /// <returns></returns> public static bool IsValidLanguageFile(string languageFilePath) { bool RetVal = false; //-- Check for valid argument and file existance if (!string.IsNullOrEmpty(languageFilePath) && File.Exists(languageFilePath)) { //-- Check for valid language file name convention if (DevInfo.Lib.DI_LibBAL.NamingConvention.DIFileNameChecker.IsValidLanguageFileName(Path.GetFileName(languageFilePath))) { try { //-- Try loading xml file XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(languageFilePath); //-- Try to fetch a value against LANGUAGE_NAME name key XmlElement xmlElement = xmlDocument.GetElementById("LANGUAGE_NAME"); //-- If some valid value is returned, then its a valid language xml content //-- This check may be made more exhaustive if desired. if (xmlElement != null) { if (!string.IsNullOrEmpty(xmlElement.Attributes["value"].Value)) { RetVal = true; } } } catch (Exception) { RetVal = false; } } } return RetVal; }
public static bool RemPassWd(string name,string passwd) { try { XmlDocument doc = new XmlDocument(); doc.Load(@"user.xml"); XmlElement node = doc.GetElementById("user"); XmlNode nameNode = (XmlNode)doc.GetElementById("username"); XmlNode passWdNode = (XmlNode)doc.GetElementById("passwd"); nameNode.InnerText = name; passWdNode.InnerText = passwd; //node.AppendChild(nameNode); //node.AppendChild(passWdNode); //doc.DocumentElement.InsertAfter(node, doc.DocumentElement.LastChild); doc.Save(@"user.xml"); } catch (Exception exp) { return false; } return true; }
public static bool saveCheck(string str) { try { XmlDocument doc = new XmlDocument(); doc.Load(@"user.xml"); XmlElement node = doc.GetElementById("user"); XmlNode check = (XmlNode)doc.GetElementById("check"); check.InnerText = str; //node.AppendChild(check); //doc.DocumentElement.InsertAfter(node, doc.DocumentElement.LastChild); doc.Save(@"user.xml"); } catch (Exception exp) { return false; } return true; }
UnifiedResponse IServiceProvider.Search(string query) { string url = GetExecutionUrl(query); var response = new UnifiedResponse(); string xresp = Http.getText(url); if (string.IsNullOrEmpty(xresp)) { response.Success = false; response.Error = "No http response from Last.fm API"; return response; } var doc = new XmlDocument(); doc.LoadXml(xresp); XmlNode error = doc.GetElementById("error"); if (error != null) { response.Success = false; response.Error = string.Format( "Last.fm API returns error #{0}: {1}", error.Attributes["code"], error.InnerXml ); return response; } var nsmanager = new XmlNamespaceManager(doc.NameTable); nsmanager.AddNamespace("opensearch", "http://a9.com/-/spec/opensearch/1.1/"); var countnode = doc.SelectSingleNode("/lfm/results/opensearch:totalResults", nsmanager); response.ResultsCount = countnode == null ? 0 : Convert.ToInt32(countnode.InnerXml); var results = doc.GetElementsByTagName("album"); foreach (XmlNode result in results) { var r = new Result(); r.Request = query; r.Artist = result["artist"] == null ? string.Empty : result["artist"].InnerText; r.Album = result["name"] == null ? string.Empty : result["name"] .InnerText; XmlNode urlnode = null; if ((urlnode = result.SelectSingleNode("descendant::image[@size='mega']")) != null) { r.Width = r.Height = 500; } else if ((urlnode = result.SelectSingleNode("descendant::image[@size='extralarge']")) != null) { r.Width = r.Height = 300; } else if((urlnode = result.SelectSingleNode("descendant::image[@size='large']")) != null) { r.Width = r.Height = 174; } if (urlnode != null) { r.Url = r.Thumb = urlnode.InnerXml; } response.Results.Add(r); } return response; }
public virtual XmlElement GetIdElement(XmlDocument document, string idValue) { if (document == null) { return null; } XmlElement elementById = document.GetElementById(idValue); if (elementById != null) { return elementById; } elementById = document.SelectSingleNode("//*[@Id=\"" + idValue + "\"]") as XmlElement; if (elementById != null) { return elementById; } elementById = document.SelectSingleNode("//*[@id=\"" + idValue + "\"]") as XmlElement; if (elementById != null) { return elementById; } return (document.SelectSingleNode("//*[@ID=\"" + idValue + "\"]") as XmlElement); }
private void addMacroXmlNode(XmlDocument umbracoXML, XmlDocument macroXML, String macroPropertyAlias, String macroPropertyType, String macroPropertyValue) { XmlNode macroXmlNode = macroXML.CreateNode(XmlNodeType.Element, macroPropertyAlias, string.Empty); var x = new XmlDocument(); int currentID = -1; // If no value is passed, then use the current pageID as value if (macroPropertyValue == string.Empty) { var umbPage = (page)HttpContext.Current.Items["umbPageObject"]; if (umbPage == null) return; currentID = umbPage.PageID; } HttpContext.Current.Trace.Write("umbracoMacro", "Xslt node adding search start (" + macroPropertyAlias + ",'" + macroPropertyValue + "')"); switch (macroPropertyType) { case "contentTree": XmlAttribute nodeID = macroXML.CreateAttribute("nodeID"); if (macroPropertyValue != string.Empty) nodeID.Value = macroPropertyValue; else nodeID.Value = currentID.ToString(); macroXmlNode.Attributes.SetNamedItem(nodeID); // Get subs try { macroXmlNode.AppendChild(macroXML.ImportNode(umbracoXML.GetElementById(nodeID.Value), true)); } catch { break; } break; case "contentCurrent": x.LoadXml("<nodes/>"); XmlNode currentNode; if (macroPropertyValue != string.Empty) currentNode = macroXML.ImportNode(umbracoXML.GetElementById(macroPropertyValue), true); else currentNode = macroXML.ImportNode(umbracoXML.GetElementById(currentID.ToString()), true); // remove all sub content nodes foreach (XmlNode n in currentNode.SelectNodes("./node")) currentNode.RemoveChild(n); macroXmlNode.AppendChild(currentNode); break; case "contentSubs": x.LoadXml("<nodes/>"); if (macroPropertyValue != string.Empty) x.FirstChild.AppendChild(x.ImportNode(umbracoXML.GetElementById(macroPropertyValue), true)); else x.FirstChild.AppendChild(x.ImportNode(umbracoXML.GetElementById(currentID.ToString()), true)); macroXmlNode.InnerXml = transformMacroXML(x, "macroGetSubs.xsl"); break; case "contentAll": x.ImportNode(umbracoXML.DocumentElement.LastChild, true); break; case "contentRandom": XmlNode source = umbracoXML.GetElementById(macroPropertyValue); if (source != null) { XmlNodeList sourceList = source.SelectNodes("node"); if (sourceList.Count > 0) { int rndNumber; Random r = library.GetRandom(); lock (r) { rndNumber = r.Next(sourceList.Count); } XmlNode node = macroXML.ImportNode(sourceList[rndNumber], true); // remove all sub content nodes foreach (XmlNode n in node.SelectNodes("./node")) node.RemoveChild(n); macroXmlNode.AppendChild(node); break; } else HttpContext.Current.Trace.Warn("umbracoMacro", "Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); } else HttpContext.Current.Trace.Warn("umbracoMacro", "Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); break; case "mediaCurrent": var c = new Content(int.Parse(macroPropertyValue)); macroXmlNode.AppendChild(macroXML.ImportNode(c.ToXml(content.Instance.XmlContent, false), true)); break; default: macroXmlNode.InnerText = HttpContext.Current.Server.HtmlDecode(macroPropertyValue); break; } macroXML.FirstChild.AppendChild(macroXmlNode); }
public Response(HttpWebResponse response) { System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US"); Tracks = new List<Track>(); for (int i = 0; i < response.Headers.Count; i++) { KeyValuePair<string, string> header = new KeyValuePair<string, string>(response.Headers.GetKey(i), response.Headers.Get(i)); switch (header.Key) { case "Status": this.Status = header.Value; if(header.Value.StartsWith("200")) { this.Success = true; } else { this.Success = false; } break; default: // any other response we are not interested... break; } } XmlDocument xmlDoc = new XmlDocument(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); response.Close(); xmlDoc.LoadXml(result); } XmlNodeList rootList = xmlDoc.GetElementsByTagName("lfm"); XmlNode rootElement = rootList[0]; if (true) { if (rootElement.Attributes["status"].Value.ToLower() == "ok") { ErrorCode = 0; Success = true; ErrorText = ""; XmlNodeList allTracks = xmlDoc.GetElementsByTagName("track"); foreach (XmlNode currentNode in allTracks) { Track track = new Track(); try { if(currentNode.Attributes["nowplaying"].Value == "true") { track.NowPlaying = true; } } catch {} foreach(XmlNode subNode in currentNode) { switch(subNode.Name) { case "artist": track.Artist = subNode.InnerText; break; case "name": track.Name = subNode.InnerText; break; case "album": track.Album = subNode.InnerText; break; case "url": track.Link = subNode.InnerText; break; case "image": switch (subNode.Attributes["size"].Value) { case "small": track.AlbumArtSmall = subNode.InnerText; break; case "medium": track.AlbumArtMedium = subNode.InnerText; break; case "large": track.AlbumArtLarge = subNode.InnerText; break; case "extralarge": track.AlbumArtExtraLarge = subNode.InnerText; break; } break; default: // ignoring break; } } if (track.NowPlaying) { NowPlaying = track; } else { if (LastPlayed == null) { LastPlayed = track; } } Tracks.Add(track); } } else { XmlElement errorElement = xmlDoc.GetElementById("error"); ErrorCode = Convert.ToInt32(errorElement.Attributes["code"].Value); ErrorText = errorElement.Value; Success = false; } } else { Success = false; ErrorCode = 999; ErrorText = "Invalid response from last.fm"; } }
public void delete() { XmlDocument doc = new XmlDocument(); doc.Load("Storage.xml"); XmlElement xmlElement = doc.GetElementById(guid.ToString()); }
public void SetUp() { int next; int pitalicaCount; XmlDocument xmlDoc = new XmlDocument(); if (File.Exists(absolutePath)) { xmlDoc.Load(absolutePath); pitalicaCount = xmlDoc.ChildNodes[2].ChildNodes.Count; for (int i = 0, j = 0; i < BrojPitanja * 4; i++, j++) { DateTime curTime = DateTime.Now; Random randPit = new Random(curTime.Millisecond); next = randPit.Next(1, pitalicaCount); while (pitanjaPostavljena.Contains(next)) { next = randPit.Next(1, pitalicaCount); } pitanjaPostavljena.Add(next); XmlElement curr = xmlDoc.GetElementById(next.ToString()); XmlNode tempNode = curr.GetElementsByTagName("Pitanje")[0]; svaPitanja[i] = tempNode.InnerText; tempNode = curr.GetElementsByTagName("OdgovorA")[0]; svaPitanja[++i] = tempNode.InnerText; if (tempNode.Attributes["Tocan"].InnerText.Equals("Da")) tocniOdgovori[j] = 'A'; tempNode = curr.GetElementsByTagName("OdgovorB")[0]; svaPitanja[++i] = tempNode.InnerText; if (tempNode.Attributes["Tocan"].InnerText.Equals("Da")) tocniOdgovori[j] = 'B'; tempNode = curr.GetElementsByTagName("OdgovorC")[0]; svaPitanja[++i] = tempNode.InnerText; if (tempNode.Attributes["Tocan"].InnerText.Equals("Da")) tocniOdgovori[j] = 'C'; } } else MessageBox.Show(absolutePath.ToString()); init(); }
static SpiderController() { xmlDoc = new XmlDocument(); xmlDoc.Load("SpiderConfig.xml"); MaxDepth = Int32.Parse(xmlDoc.GetElementById("MaximumDepth").InnerText); MaxThreads = Int32.Parse(xmlDoc.GetElementById("MaximumThreads").InnerText); UseLogging = Boolean.Parse(xmlDoc.GetElementById("UseLogging").InnerText); UseWhiteList = Boolean.Parse(xmlDoc.GetElementById("UseWhiteList").InnerText); MinThreadIdleTime = Int32.Parse(xmlDoc.GetElementById("MinThreadIdleTime").InnerText); MaxThreadIdleTime = Int32.Parse(xmlDoc.GetElementById("MaxThreadIdleTime").InnerText); DownloadFolder = xmlDoc.GetElementById("DownloadFolder").InnerText; LogFolder = xmlDoc.GetElementById("LogFolder").InnerText; ExcludedFileTypes = xmlDoc.GetElementById("ExcludedFileTypes").InnerText.Split('|').ToList<string>(); ExcludedDomains = xmlDoc.GetElementById("ExcludedDomains").InnerText.Split(new char[]{',',' ', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); WhiteListedDomains = xmlDoc.GetElementById("WhiteListedDomains").InnerText.Split(new char[] { ',', ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); FileTypesToDownload = xmlDoc.GetElementById("FileTypesToDownload").InnerText.Split('|').ToList<string>(); SeedURLs = xmlDoc.GetElementById("SeedURLs").InnerText.Split(new char[] { ',', ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); }
public void Sort_Nodes() { var xmlContent = GetXmlContent(1); var xml = new XmlDocument(); xml.LoadXml(xmlContent); var original = xml.GetElementById(1173.ToString()); Assert.IsNotNull(original); var parentNode = (XmlElement)original.Clone(); XmlHelper.SortNodes( parentNode, "./* [@id]", element => element.Attribute("id") != null, element => element.AttributeValue<int>("sortOrder")); //do assertions just to make sure it is working properly. var currSort = 0; foreach (var child in parentNode.SelectNodes("./* [@id]").Cast<XmlNode>()) { Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value)); currSort++; } //ensure the parent node's properties still exist first Assert.AreEqual("content", parentNode.ChildNodes[0].Name); Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name); //then the child nodes should come straight after Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null); }
public requestHandler(XmlDocument umbracoContent, String url) { HttpContext.Current.Trace.Write("request handler", "current url '" + url + "'"); bool getByID = false; string currentDomain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; // obsoleted //if (!_urlNameInitialized) // InitializeUrlName(); // The url exists in cache, and the domain doesn't exists (which makes it ok to do a cache look up on the url alone) // TODO: NH: Remove the flag for friendlyxmlschema when real schema is implemented // as the friendlyxmlschema doesn't have any identifier keys we can't do a lookup // based on ID yet. if (_processedRequests.ContainsKey(url) && !Domain.Exists(currentDomain)) { getByID = true; _pageXPathQuery = _processedRequests[url].ToString(); } // The url including the domain exists in cache else if (_processedRequests.ContainsKey(currentDomain + url)) { getByID = true; _pageXPathQuery = _processedRequests[currentDomain + url].ToString(); } // The url isn't cached else { if (url == "") { url = ""; _pageXPathQuery = CreateXPathQuery(url, true); // Never cache roots _doNotCache = true; } else { // If url is an integer, then asume it's the ID of the page if (url[0] == '/') url = url.Substring(1, url.Length - 1); int result; if (int.TryParse(url, out result)) { _pageXPathQuery = url; getByID = true; } else { if (!string.IsNullOrEmpty(url)) { _pageXPathQuery = CreateXPathQuery(url, true); } else { _pageXPathQuery = Document.GetRootDocuments()[0].Id.ToString(); getByID = true; } } } } HttpContext.Current.Trace.Write("umbracoRequestHandler", string.Format("Just before xPath query ({0}, '{1}')", getByID, _pageXPathQuery)); if (getByID) currentPage = umbracoContent.GetElementById(_pageXPathQuery.Trim()); else { HttpContext.Current.Trace.Write("umbracoRequestHandler", "pageXPathQueryStart: '" + pageXPathQueryStart + "'"); currentPage = umbracoContent.SelectSingleNode(pageXPathQueryStart + _pageXPathQuery); if (currentPage == null) { // If no node found, then try with a relative page query currentPage = umbracoContent.SelectSingleNode("/" + _pageXPathQuery); } // Add to url cache if (currentPage != null && !_doNotCache) { string prefixUrl = ""; if (Domain.Exists(currentDomain)) prefixUrl = currentDomain; if (url.Substring(0, 1) != "/") url = "/" + url; lock (locker) { if (!_processedRequests.ContainsKey(prefixUrl + url)) _processedRequests.Add(prefixUrl + url, currentPage.Attributes.GetNamedItem("id").Value); } HttpContext.Current.Trace.Write("umbracoRequestHandler", "Adding to cache... ('" + prefixUrl + url + "')"); } } if (currentPage == null) { // No node found, try custom url handlers defined in /config/404handlers.config if (_customHandlers == null) { _customHandlers = new XmlDocument(); _customHandlers.Load( IOHelper.MapPath( SystemFiles.NotFoundhandlersConfig ) ); } foreach (XmlNode notFoundHandler in _customHandlers.DocumentElement.SelectNodes("notFound")) { // Load handler string _chAssembly = notFoundHandler.Attributes.GetNamedItem("assembly").Value; string _chType = notFoundHandler.Attributes.GetNamedItem("type").Value; // check for namespace string _chNameSpace = _chAssembly; if (notFoundHandler.Attributes.GetNamedItem("namespace") != null) _chNameSpace = notFoundHandler.Attributes.GetNamedItem("namespace").Value; try { // Reflect to execute and check whether the type is umbraco.main.IFormhandler HttpContext.Current.Trace.Write("notFoundHandler", string.Format("Trying NotFoundHandler '{0}.{1}'...", _chAssembly, _chType)); Assembly assembly = Assembly.LoadFrom( IOHelper.MapPath( SystemDirectories.Bin + "/" + _chAssembly + ".dll")); Type type = assembly.GetType(_chNameSpace + "." + _chType); INotFoundHandler typeInstance = Activator.CreateInstance(type) as INotFoundHandler; if (typeInstance != null) { typeInstance.Execute(url); if (typeInstance.redirectID > 0) { int redirectID = typeInstance.redirectID; currentPage = umbracoContent.GetElementById(redirectID.ToString()); HttpContext.Current.Trace.Write("notFoundHandler", string.Format("NotFoundHandler '{0}.{1} found node matching {2} with id: {3}", _chAssembly, _chType, url, redirectID)); // check for caching if (typeInstance.CacheUrl) { if (url.Substring(0, 1) != "/") url = "/" + url; string prefixUrl = string.Empty; if (Domain.Exists(currentDomain)) prefixUrl = currentDomain; if (url.Substring(0, 1) != "/") url = "/" + url; lock (locker) { if (!_processedRequests.ContainsKey(prefixUrl + url)) _processedRequests.Add(prefixUrl + url, currentPage.Attributes.GetNamedItem("id").Value); } HttpContext.Current.Trace.Write("notFoundHandler", string.Format("Added to cache '{0}', '{1}'...", url, redirectID)); } break; } } } catch (Exception e) { HttpContext.Current.Trace.Warn("notFoundHandler", "Error implementing notfoundHandler '" + _chAssembly + "." + _chType + "'", e); } } } HttpContext.Current.Trace.Write("umbracoRequestHandler", "After xPath query"); // Check for internal redirects if (currentPage != null) { XmlNode internalRedirect = currentPage.SelectSingleNode(UmbracoSettings.UseLegacyXmlSchema ? "data [@alias = 'umbracoInternalRedirectId']" : "umbracoInternalRedirectId"); if (internalRedirect != null && internalRedirect.FirstChild != null && !String.IsNullOrEmpty(internalRedirect.FirstChild.Value)) { HttpContext.Current.Trace.Write("internalRedirection", "Found internal redirect id via umbracoInternalRedirectId property alias"); int internalRedirectId = 0; if (int.TryParse(internalRedirect.FirstChild.Value, out internalRedirectId) && internalRedirectId > 0) { currentPage = umbracoContent.GetElementById( internalRedirectId.ToString()); HttpContext.Current.Trace.Write("internalRedirection", "Redirecting to " + internalRedirect.FirstChild.Value); } else HttpContext.Current.Trace.Warn("internalRedirection", "The redirect id is not an integer: " + internalRedirect.FirstChild.Value); } } // Check access HttpContext.Current.Trace.Write("umbracoRequestHandler", "Access checking started"); if (currentPage != null) { int id = int.Parse(currentPage.Attributes.GetNamedItem("id").Value); string path = currentPage.Attributes.GetNamedItem("path").Value; if (Access.IsProtected(id, path)) { HttpContext.Current.Trace.Write("umbracoRequestHandler", "Page protected"); var user = System.Web.Security.Membership.GetUser(); if (user == null || !library.IsLoggedOn()) { HttpContext.Current.Trace.Write("umbracoRequestHandler", "Not logged in - redirecting to login page..."); currentPage = umbracoContent.GetElementById(Access.GetLoginPage(path).ToString()); } else { if (user != null && !Access.HasAccces(id, user.ProviderUserKey)) { HttpContext.Current.Trace.Write("umbracoRequestHandler", "Member has not access - redirecting to error page..."); currentPage = content.Instance.XmlContent.GetElementById(Access.GetErrorPage(path).ToString()); } } } else HttpContext.Current.Trace.Write("umbracoRequestHandler", "Page not protected"); } HttpContext.Current.Trace.Write("umbracoRequestHandler", "Access checking ended"); }
public bool LoadAllMapConfig(XmlDocument xmldoc, ZzhaControlLibrary.ZzhaMapGis mapgis) { //MapGis.ClearAllStation(); //MapGis.ClearAllStatic(); XmlNode MapNode = xmldoc.SelectSingleNode("//Map"); if (MapNode.Attributes.Count == 0) { MessageBox.Show("全图范围尚未配置,请先配置全图范围后再模拟全图", "提示", MessageBoxButtons.OK); return false; } //mapgis.MapFilePath = Application.StartupPath + MapNode.InnerText; try { DataTable dt = dpicbll.GetBackPicByFileID(MapNode.InnerText); byte[] buffer = (byte[])dt.Rows[0][0]; Graphics.Config.FileChanger fc = new KJ128NMainRun.Graphics.Config.FileChanger(); if (!System.IO.Directory.Exists(Application.StartupPath + "\\MapGis\\DMap")) { System.IO.Directory.CreateDirectory(Application.StartupPath + "\\MapGis\\DMap"); } fc.CreateFile(Application.StartupPath + "\\MapGis\\DMap\\" + dt.Rows[0][1].ToString(), buffer); mapgis.MapFilePath = Application.StartupPath + "\\MapGis\\DMap\\" + dt.Rows[0][1].ToString(); System.IO.File.Delete(Application.StartupPath + "\\MapGis\\DMap\\" + dt.Rows[0][1].ToString()); } catch (Exception ex) { MessageBox.Show("无法识别的图片!", "提示", MessageBoxButtons.OK); return false; } mapgis.MinWidth = int.Parse(MapNode.Attributes["MinWidth"].InnerText); mapgis.MaxWidth = int.Parse(MapNode.Attributes["MaxWidth"].InnerText); XmlNode DivRoot = xmldoc.SelectSingleNode("//Divs"); foreach (XmlNode divnode in DivRoot) { mapgis.AddDiv(divnode.InnerText, int.Parse(divnode.Attributes["MinWidth"].InnerText), int.Parse(divnode.Attributes["MaxWidth"].InnerText)); } //加到DIV结束 XmlNode StaticRoot = xmldoc.SelectSingleNode("//Statics"); if (StaticRoot != null && StaticRoot.ChildNodes.Count > 0) { foreach (XmlNode staticnode in StaticRoot.ChildNodes) { float x = float.Parse(staticnode.ChildNodes[2].InnerText); float y = float.Parse(staticnode.ChildNodes[3].InnerText); string filepath =staticnode.ChildNodes[1].InnerText; string divname = staticnode.ChildNodes[0].InnerText; int width = int.Parse(staticnode.ChildNodes[4].InnerText); int height = int.Parse(staticnode.ChildNodes[5].InnerText); string name = staticnode.ChildNodes[6].InnerText; string key = staticnode.ChildNodes[7].InnerText; ZzhaControlLibrary.StaticType type = ZzhaControlLibrary.StaticType.ImageAndWord; string fontname = staticnode.ChildNodes[9].Attributes[0].InnerText; float size = float.Parse(staticnode.ChildNodes[9].Attributes[1].InnerText); FontStyle fontstyle = (FontStyle)Enum.Parse(typeof(FontStyle), staticnode.ChildNodes[9].Attributes[2].InnerText); Color FontColor = Color.FromArgb(int.Parse(staticnode.ChildNodes[9].InnerText)); System.Drawing.Font staticFont = new Font(fontname, size, fontstyle); if (staticnode.ChildNodes[8].InnerText == "Image") { type = ZzhaControlLibrary.StaticType.Image; mapgis.AddStaticObj(x, y, new Bitmap(Application.StartupPath + filepath), divname, width, height, filepath, name, key, type, staticFont, FontColor); } if (staticnode.ChildNodes[8].InnerText == "ImageAndWord") { type = ZzhaControlLibrary.StaticType.ImageAndWord; mapgis.AddStaticObj(x, y, new Bitmap(Application.StartupPath + filepath), divname, width, height, filepath, name, key, type, staticFont, FontColor); } if (staticnode.ChildNodes[8].InnerText == "Word") { type = ZzhaControlLibrary.StaticType.Word; mapgis.AddStaticObj(x, y, name, key, divname, staticFont, FontColor); } } } XmlNode StationRoot = xmldoc.SelectSingleNode("//Stations"); if (StationRoot != null && StationRoot.ChildNodes.Count > 0) { DataTable stationinfodt = new Graphics_StationInfoBLL().GetStationInfo(); if (stationinfodt != null && stationinfodt.Rows.Count > 0) { try { for (int i = 0; i < stationinfodt.Rows.Count; i++) { string stationID = stationinfodt.Rows[i][0].ToString() + "." + stationinfodt.Rows[i][1].ToString(); string stationName = stationinfodt.Rows[i][2].ToString(); float stationheadx = float.Parse(stationinfodt.Rows[i][3].ToString()); float stationheady = float.Parse(stationinfodt.Rows[i][4].ToString()); string stationstate = stationinfodt.Rows[i][5].ToString(); XmlNode stationnode = xmldoc.GetElementById(stationName); if (stationnode != null) { string stationdivname = stationnode.InnerText; if (stationstate == "正常" || stationstate == "未初始化") mapgis.AddStation(stationheadx, stationheady, stationName, stationID, "正常", new Bitmap(Application.StartupPath + "\\MapGis\\ShineImage\\Signal.gif"), stationdivname); if (stationstate == "故障") mapgis.AddStation(stationheadx, stationheady, stationName, stationID, stationstate, new Bitmap(Application.StartupPath + "\\MapGis\\ShineImage\\No-Signal.gif"), stationdivname); if (stationstate == "休眠") mapgis.AddStation(stationheadx, stationheady, stationName, stationID, stationstate, new Bitmap(Application.StartupPath + "\\MapGis\\ShineImage\\Station.GIF"), stationdivname); } } mapgis.FalshStations(); } catch (Exception ex) { MessageBox.Show("图形系统中部分图片已经不存在", "提示", MessageBoxButtons.OK); return false; } } } mapgis.FlashAll(); return true; }
// add elements to the <macro> root node, corresponding to parameters private void AddMacroXmlNode(XmlDocument umbracoXml, XmlDocument macroXml, string macroPropertyAlias, string macroPropertyType, string macroPropertyValue) { XmlNode macroXmlNode = macroXml.CreateNode(XmlNodeType.Element, macroPropertyAlias, string.Empty); var x = new XmlDocument(); // if no value is passed, then use the current "pageID" as value var contentId = macroPropertyValue == string.Empty ? UmbracoContext.Current.PageId.ToString() : macroPropertyValue; TraceInfo("umbracoMacro", "Xslt node adding search start (" + macroPropertyAlias + ",'" + macroPropertyValue + "')"); switch (macroPropertyType) { case "contentTree": var nodeId = macroXml.CreateAttribute("nodeID"); nodeId.Value = contentId; macroXmlNode.Attributes.SetNamedItem(nodeId); // Get subs try { macroXmlNode.AppendChild(macroXml.ImportNode(umbracoXml.GetElementById(contentId), true)); } catch { } break; case "contentCurrent": var importNode = macroPropertyValue == string.Empty ? umbracoXml.GetElementById(contentId) : umbracoXml.GetElementById(macroPropertyValue); var currentNode = macroXml.ImportNode(importNode, true); // remove all sub content nodes foreach (XmlNode n in currentNode.SelectNodes("node|*[@isDoc]")) currentNode.RemoveChild(n); macroXmlNode.AppendChild(currentNode); break; case "contentSubs": // disable that one, it does not work anyway... //x.LoadXml("<nodes/>"); //x.FirstChild.AppendChild(x.ImportNode(umbracoXml.GetElementById(contentId), true)); //macroXmlNode.InnerXml = TransformMacroXml(x, "macroGetSubs.xsl"); break; case "contentAll": macroXmlNode.AppendChild(macroXml.ImportNode(umbracoXml.DocumentElement, true)); break; case "contentRandom": XmlNode source = umbracoXml.GetElementById(contentId); if (source != null) { var sourceList = source.SelectNodes("node|*[@isDoc]"); if (sourceList.Count > 0) { int rndNumber; var r = library.GetRandom(); lock (r) { rndNumber = r.Next(sourceList.Count); } var node = macroXml.ImportNode(sourceList[rndNumber], true); // remove all sub content nodes foreach (XmlNode n in node.SelectNodes("node|*[@isDoc]")) node.RemoveChild(n); macroXmlNode.AppendChild(node); } else TraceWarn("umbracoMacro", "Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); } else TraceWarn("umbracoMacro", "Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); break; case "mediaCurrent": var c = new Content(int.Parse(macroPropertyValue)); macroXmlNode.AppendChild(macroXml.ImportNode(c.ToXml(umbraco.content.Instance.XmlContent, false), true)); break; default: macroXmlNode.InnerText = HttpContext.Current.Server.HtmlDecode(macroPropertyValue); break; } macroXml.FirstChild.AppendChild(macroXmlNode); }
public static XmlDocument AppendDocumentXml(int id, int level, int parentId, XmlNode docNode, XmlDocument xmlContentCopy) { // Find the document in the xml cache XmlNode x = xmlContentCopy.GetElementById(id.ToString()); // if the document is not there already then it's a new document // we must make sure that its document type exists in the schema var xmlContentCopy2 = xmlContentCopy; if (x == null && !UmbracoSettings.UseLegacyXmlSchema) { xmlContentCopy = ValidateSchema(docNode.Name, xmlContentCopy); if (xmlContentCopy != xmlContentCopy2) docNode = xmlContentCopy.ImportNode(docNode, true); } // Find the parent (used for sortering and maybe creation of new node) XmlNode parentNode; if (level == 1) parentNode = xmlContentCopy.DocumentElement; else parentNode = xmlContentCopy.GetElementById(parentId.ToString()); if (parentNode != null) { if (x == null) { x = docNode; parentNode.AppendChild(x); } else TransferValuesFromDocumentXmlToPublishedXml(docNode, x); // TODO: Update with new schema! string xpath = UmbracoSettings.UseLegacyXmlSchema ? "./node" : "./* [@id]"; XmlNodeList childNodes = parentNode.SelectNodes(xpath); // Maybe sort the nodes if the added node has a lower sortorder than the last if (childNodes.Count > 0) { int siblingSortOrder = int.Parse(childNodes[childNodes.Count - 1].Attributes.GetNamedItem("sortOrder").Value); int currentSortOrder = int.Parse(x.Attributes.GetNamedItem("sortOrder").Value); if (childNodes.Count > 1 && siblingSortOrder > currentSortOrder) { SortNodes(ref parentNode); } } } return xmlContentCopy; }
private static XmlNode GetInitalXML() { var xmlPath = ConfigurationManager.AppSettings["XMLPath"]; var xmlStartFile = ConfigurationManager.AppSettings["XMLStartupFile"]; var xmlFileName = Path.Combine(xmlPath, xmlStartFile); var doc = new XmlDocument(); doc.Load(xmlFileName); var root = doc.GetElementById("FSMStatus"); return root; }