/// 获取token,如果存在且没过期,则直接取token /// <summary> /// 获取token,如果存在且没过期,则直接取token /// </summary> /// <returns></returns> public static string GetExistAccessToken() { // 读取XML文件中的数据 string filepath = System.Web.HttpContext.Current.Server.MapPath("/XMLToken.xml"); FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader str = new StreamReader(fs, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(str); str.Close(); str.Dispose(); fs.Close(); fs.Dispose(); string Token = xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText; DateTime AccessTokenExpires = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText); //如果token过期,则重新获取token if (DateTime.Now >= AccessTokenExpires) { AccessToken mode = Getaccess(); //将token存到xml文件中,全局缓存 xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText = mode.access_token; DateTime _AccessTokenExpires = DateTime.Now.AddSeconds(mode.expires_in); xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText = _AccessTokenExpires.ToString(); xml.Save(filepath); Token = mode.access_token; } return Token; }
public void FixBindings(string projectFilePath) { XmlDocument xd = new XmlDocument(); xd.PreserveWhitespace = true; xd.Load(projectFilePath); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xd.NameTable); namespaceManager.AddNamespace("b", @"http://schemas.microsoft.com/developer/msbuild/2003"); XmlNode ParentNode = xd.SelectSingleNode(@"/b:Project/b:PropertyGroup[boolean(@Condition) = false]", namespaceManager); Dictionary<string, string> Queries = new Dictionary<string, string>(); Queries.Add("SccProjectName", "//b:SccProjectName"); Queries.Add("SccLocalPath", "//b:SccLocalPath"); Queries.Add("SccAuxPath", "//b:SccAuxPath"); Queries.Add("SccProvider", "//b:SccProvider"); foreach (KeyValuePair<string, string> Pair in Queries) { string Query = Pair.Value; XmlNode Node = null; Node = xd.SelectSingleNode(Query, namespaceManager); if (Node != null || Node.InnerText != "SAK") Node.InnerText = "SAK"; if (Node == null) { XmlElement Element = xd.CreateElement(Pair.Key); Element.InnerText = "SAK"; ParentNode.AppendChild(Element); } } xd.Save(projectFilePath); }
/// <summary> /// Gets Post objects out of XML files, which follow the BlogEngine.NET format. /// </summary> /// <param name = "folderSystemPath">Folder where XML files are located</param> /// <returns>zasz.me.Models.Post objects</returns> public IEnumerable<Post> GetFromFolder(string folderSystemPath) { if (String.IsNullOrEmpty(folderSystemPath)) die("Null Path"); Debug.Assert(folderSystemPath != null, "folderSystemPath != null"); var files = Directory.GetFiles(folderSystemPath); var xmlFiles = (from file in files where file.EndsWith(".xml") select file).ToList(); if (!xmlFiles.Any()) die("No XML Files found"); // ReSharper disable PossibleNullReferenceException foreach (var postFile in xmlFiles) { log("Working on file : " + postFile); var newPost = new Post(); var postDoc = new XmlDocument(); postDoc.Load(postFile); newPost.Title = postDoc.SelectSingleNode("post/title").InnerText; log("Title : " + newPost.Title); newPost.Content = HttpUtility.HtmlDecode(postDoc.SelectSingleNode("post/content").InnerText); newPost.Timestamp = DateTime.Parse(postDoc.SelectSingleNode("post/pubDate").InnerText); newPost.Slug = postDoc.SelectSingleNode("post/slug").InnerText; newPost.Tags = new List<Tag>(); postDoc.SelectNodes("post/tags/tag") .Cast<XmlNode>() .Where(node => !string.IsNullOrEmpty(node.InnerText)) .ForEach( x => newPost.Tags.Add(new Tag(x.InnerText))); yield return newPost; } // ReSharper restore PossibleNullReferenceException }
public static List<CashTransaction> GetCashTransactions(DateTime fromDate, DateTime toDate, string xmlFileName) { List<CashTransaction> cashTransactions = new List<CashTransaction>(); XmlDocument xdoc = new XmlDocument(); xdoc.Load(xmlFileName); XmlNodeList cashNodes = xdoc.SelectNodes("//Cash//Entry"); foreach (XmlNode item in cashNodes) { if ((DateTime.Parse(item.Attributes["PostedDate"].InnerText) >= fromDate) && (DateTime.Parse(item.Attributes["PostedDate"].InnerText) <= toDate)) { var t = new CashTransaction(); t.PostedDate = item.Attributes["PostedDate"].InnerText; t.Id = item.Attributes["Id"].InnerText; t.TransactionType = item.Attributes["TransactionType"].InnerText; t.Amount = ""; t.Amount2 = ""; if (t.TransactionType == "DEPOSIT") t.Amount = item.Attributes["Amount"].InnerText; else t.Amount2 = item.Attributes["Amount"].InnerText; t.LedgerAccount = xdoc.SelectSingleNode("//Refs/refItem[@refCode='" + item.Attributes["LedgerAccount"].InnerText + "']").Attributes["refDescription"].InnerText; if (item.Attributes["LedgerAccount"].InnerText == "DUE") { var personId = xdoc.SelectSingleNode("//Members/Member[@MasonId='" + item.Attributes["PayTo"].InnerText + "']").Attributes["PersonId"].InnerText; var personNode = xdoc.SelectSingleNode("//People/Person[@PersonId='" + personId + "']"); t.PayTo = personNode.Attributes["FirstName"].InnerText + " " + personNode.Attributes["LastName"].InnerText; } else t.PayTo = item.Attributes["PayTo"].InnerText; t.Memo = item.ChildNodes[0].InnerText; cashTransactions.Add(t); } } return cashTransactions; }
public static void InitializeProcessor() { XmlDocument cfg = new XmlDocument(); cfg.Load("remoteconfig.xml"); //*********************Loading External Devices************ XmlNodeList nlist = cfg.SelectNodes("ProcessorConfiguration/ExternalDevice"); IExternalDevicePort[] externaldevices = null; if(nlist.Count>0) { Console.WriteLine("Loading External Devices"); externaldevices = new ExternalDevicePort[nlist.Count]; int tmp2=0; foreach(XmlNode tmp in nlist) { externaldevices[tmp2] = new ExternalDevicePort( tmp.SelectSingleNode("Name").InnerText ,new ExternalDevicePort.Echo(EchoMessage)); externaldevices[tmp2].Initialize(int.Parse( tmp.SelectSingleNode("Port").InnerText)); tmp2++; } } server = new RemoteRequestServer(int.Parse(cfg.SelectSingleNode( "ProcessorConfiguration/Port").InnerText), cfg.SelectSingleNode("ProcessorConfiguration/Name").InnerText,externaldevices); threadstacksize =int.Parse(cfg.SelectSingleNode( "ProcessorConfiguration/ThreadStackSize").InnerText); }
public PollQuestion GetActiveQuestion() { PollQuestion ret = null; //For real-time applications, you can get data from databases like SQL Server string sampleXmlString = SampleData.GetActivePollQuestion(); XmlDocument pollQuestionXmlDoc = new XmlDocument(); pollQuestionXmlDoc.LoadXml(sampleXmlString); XmlElement root = pollQuestionXmlDoc.DocumentElement; XmlNode activeNode = pollQuestionXmlDoc.SelectSingleNode("//PollQuestion/Active"); if (root.Name == "PollQuestion") { ret = new PollQuestion(); ret.ID = pollQuestionXmlDoc.SelectSingleNode("//PollQuestion/ID").InnerText; ret.Question = pollQuestionXmlDoc.SelectSingleNode("//PollQuestion/Question").InnerText; string activeStatus = pollQuestionXmlDoc.SelectSingleNode("//PollQuestion/Active").InnerText; ret.Active = Boolean.Parse(activeStatus); XmlNodeList answerChoices = pollQuestionXmlDoc.SelectNodes("//PollQuestion/AnswerGroup/Answer"); if (answerChoices != null && answerChoices.Count > 0) { ret.AnswerGroup = new List<string>(); foreach (XmlNode answer in answerChoices) { ret.AnswerGroup.Add(answer.InnerText); } } } return ret; }
/// <summary> /// Makes sure the necessary HTTP module is present in the web.config file to support /// device detection and image optimisation. /// </summary> /// <param name="xml">Xml fragment for the system.webServer web.config section</param> /// <returns>True if a change was made, otherwise false.</returns> private static bool FixAddModule(XmlDocument xml) { var changed = false; var module = xml.SelectSingleNode("//modules/add[@type='FiftyOne.Foundation.Mobile.Detection.DetectorModule, FiftyOne.Foundation']") as XmlElement; if (module != null) { // If image optimisation is enabled and the preCondition attribute // is present then it'll need to be removed. if (module.Attributes["preCondition"] != null) { module.Attributes.RemoveNamedItem("preCondition"); changed = true; } // Make sure the module entry is named "Detector". if ("Detector".Equals(module.GetAttribute("name")) == false) { module.Attributes["name"].Value = "Detector"; changed = true; } } else { // The module entry is missing so add a new one. var modules = xml.SelectSingleNode("//modules"); module = xml.CreateElement("add"); module.Attributes.Append(xml.CreateAttribute("name")); module.Attributes["name"].Value = "Detector"; module.Attributes.Append(xml.CreateAttribute("type")); module.Attributes["type"].Value = "FiftyOne.Foundation.Mobile.Detection.DetectorModule, FiftyOne.Foundation"; modules.InsertAfter(module, modules.LastChild); changed = true; } return changed; }
public static TestResults InterpretTestResults(XmlDocument doc) { TestResults results = new TestResults(); XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable); nsm.AddNamespace("n", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"); results.Outcome = doc.SelectSingleNode("n:TestRun/n:ResultSummary", nsm).Attributes["outcome"].Value; results.CountExecuted = int.Parse(doc.SelectSingleNode("n:TestRun/n:ResultSummary/n:Counters", nsm).Attributes["executed"].Value); results.CountPassed = int.Parse(doc.SelectSingleNode("n:TestRun/n:ResultSummary/n:Counters", nsm).Attributes["passed"].Value); results.CountFailed = int.Parse(doc.SelectSingleNode("n:TestRun/n:ResultSummary/n:Counters", nsm).Attributes["failed"].Value); XmlNodeList testresults = doc.SelectNodes("n:TestRun/n:Results/n:UnitTestResult[@outcome='Failed']", nsm); string names = string.Empty; foreach (XmlNode testresult in testresults) { string message = testresult.Attributes["testName"].Value; XmlNode xmlErrorInfoNode = testresult.SelectSingleNode("n:Output/n:ErrorInfo/n:Message", nsm); if (xmlErrorInfoNode != null) { message += ": " + xmlErrorInfoNode.InnerText; results.ResultCode = ExitCode.Failure; } results.FailingTests.Add(message); } return results; }
public UnitContent(XmlDocument document, ContentImporterContext context) { XmlNode unitNode = document["unit"]; Name = unitNode.Attributes["name"].Value; Width = int.Parse(unitNode.Attributes["width"].Value, CultureInfo.InvariantCulture); Height = int.Parse(unitNode.Attributes["height"].Value, CultureInfo.InvariantCulture); XmlNode spritesetNode = document.SelectSingleNode("unit/spriteset"); if (spritesetNode != null) { XmlNode imageNode = document.SelectSingleNode("unit/spriteset/image"); if (imageNode != null) { imagePath = imageNode.Attributes["source"].Value; imageSize = new Vector2( int.Parse(imageNode.Attributes["width"].Value, CultureInfo.InvariantCulture), int.Parse(imageNode.Attributes["height"].Value, CultureInfo.InvariantCulture) ); } } Animations = Animation.animationListFromXmlNodeList(document.SelectNodes("unit/animations/animation"), Width, Height); XmlNode dataNode = document.SelectSingleNode("unit/data"); if (dataNode != null) foreach (XmlNode node in dataNode.ChildNodes) Data[node.Name] = node.InnerXml; }
private void OnlineMenuManagementForm_Activated(object sender, EventArgs e) { string onlineUser = String.Empty; string onlinePassword = String.Empty; string onlineLocation = String.Empty; XmlDocument xmlDoc = new XmlDocument(); string executableName = System.Reflection.Assembly.GetExecutingAssembly().Location; FileInfo executableFileInfo = new FileInfo(executableName); string currentDirectory = executableFileInfo.DirectoryName + "\\Config"; xmlDoc.Load(currentDirectory + "\\CommonConstants.xml"); XmlNode appSettingsNode = xmlDoc.SelectSingleNode("CCommonConstants/OnlineUser"); onlineUser = appSettingsNode.InnerText; appSettingsNode = xmlDoc.SelectSingleNode("CCommonConstants/OnlinePassword"); onlinePassword = appSettingsNode.InnerText; appSettingsNode = xmlDoc.SelectSingleNode("CCommonConstants/online_location"); onlineLocation = appSettingsNode.InnerText; string url = onlineLocation + "/Category/OnlineMenuManagement.aspx?RMSAdmin=" + onlineUser + "$" + onlinePassword; url = "http://www.ibacs.co.uk/"; menumanagementBrowser.Navigate(url); }
public void start() { XmlDocument x = new XmlDocument(); try { x.Load(this.URL); XmlNode root = x.DocumentElement; if (root.Name != "swpi") { throw new XmlException(); } string version = x.SelectSingleNode("descendant::version").InnerText; string downloadURL = x.SelectSingleNode("descendant::URL").InnerText; if (version == null || downloadURL == null) { throw new XmlException(); } if (String.Compare(version, Assembly.GetExecutingAssembly().GetName().Version.ToString()) == 1) { DialogResult r = MessageBox.Show("New version of SwProjectInterface is available to download. Would you like to open download website?", "Update available", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (r == DialogResult.Yes) { Process.Start(downloadURL); } } } catch (Exception e) { //MessageBox.Show(e.Message); } }
/// <summary> /// Initialises the package. /// </summary> /// <param name="pkgdir">the package directory</param> /// <param name="cat">the category this package belongs to</param> private Package(DirectoryInfo pkgdir, Category cat) { _pkgdir = pkgdir; _category = cat; _dists = new List<IDistribution>(Distribution.Enumerate(this)); /* load package info */ FileInfo[] fiarr = pkgdir.GetFiles("metadata.xml"); if (fiarr.Length == 1) { XmlDocument infoxml = new XmlDocument(); infoxml.Load(fiarr[0].FullName); XmlElement elem = (XmlElement)infoxml.SelectSingleNode("//Package/Description"); if (elem != null && !String.IsNullOrWhiteSpace(elem.InnerText)) _description = elem.InnerText; elem = (XmlElement)infoxml.SelectSingleNode("//Package/Homepage"); if (elem != null && !String.IsNullOrWhiteSpace(elem.InnerText)) _homepage = elem.InnerText; elem = (XmlElement)infoxml.SelectSingleNode("//Package/License"); if (elem != null && !String.IsNullOrWhiteSpace(elem.InnerText)) _license = elem.InnerText; } }
public void ReadXml(System.Xml.XmlReader xreader) { MachineValues = new List<DeviceInfo>(); var xml = xreader.ReadOuterXml(); var xdoc = new XmlDocument(); xdoc.LoadXml(xml); var machineNode = xdoc.SelectSingleNode("//machinevalues"); for(int i = 0; i < machineNode.ChildNodes.Count; i += 3) { var di = new DeviceInfo(); var nameNode = machineNode.ChildNodes[i]; var typeNode = machineNode.ChildNodes[i + 1]; var valueNode = machineNode.ChildNodes[i + 2]; di.Name = nameNode.InnerText; di.Type = (DeviceType)int.Parse(typeNode.InnerText); di.Value = valueNode.InnerText; MachineValues.Add(di); } var tokenNode = xdoc.SelectSingleNode("//token"); this.Token = tokenNode.InnerText; }
public static void Init() { engines = new Dictionary<String, Engine>(); String file = "C:\\deluxe\\DMCSystemsManagement\\AirManConfig.xml"; System.Xml.Linq.XDocument _xdoc; XmlDocument xdoc = new XmlDocument(); try { _xdoc = System.Xml.Linq.XDocument.Load(file); xdoc.Load(file); } catch (Exception e) { //System.Console.WriteLine("cant find XML file" + file); throw (e); } var _rp = xdoc.SelectSingleNode("/Meta/Semaphore/Location"); String path = (String)xdoc.SelectSingleNode("/AIRS/Meta/Semaphore/Location").InnerText; var _eles = from _e in _xdoc.Descendants("AIR") where _e.Name == "AIR" select _e; foreach (var item in _eles) { engines.Add((String)item.Attribute("Name"),new Engine((String)item.Attribute("Name"),UInt16.Parse((String)item.Attribute("Id")))); engines[(String)item.Attribute("Name")].RemotePath = "\\\\" + (String)item.Attribute("Hostname") + path; var _chann = from _e in item.Descendants() where _e.Name == "CHANN" select _e; foreach (var chann in _chann) { engines[ (String) item.Attribute("Name")].AddChannel((String) chann.Attribute("Name"),Convert.ToUInt16( chann.Attribute("Id").Value)); } } }
public Model Load(string file, Device device) { XmlDocument document = new XmlDocument(); document.Load(file); XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable); ns.AddNamespace("c", "http://www.collada.org/2005/11/COLLADASchema"); // Read vertex positions var positionsNode = document.SelectSingleNode("/c:COLLADA/c:library_geometries/c:geometry/c:mesh/c:source/c:float_array", ns); var indicesNode = document.SelectSingleNode("/c:COLLADA/c:library_geometries/c:geometry/c:mesh/c:triangles/c:p", ns); var positions = ParseVector3s(positionsNode.InnerText).ToArray(); var indices = ParseInts(indicesNode.InnerText).ToArray(); // Mixing concerns here, but oh well var model = new Model() { VertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, positions), IndexBuffer = Buffer.Create(device, BindFlags.IndexBuffer, indices), IndexCount = indices.Length, VertexPositions = positions, Indices = indices }; return model; }
static Config() { //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ //读取XML配置信息 string fullPath = Utils.GetMapPath("~/xmlconfig/alipay.config"); XmlDocument doc = new XmlDocument(); doc.Load(fullPath); XmlNode _partner = doc.SelectSingleNode(@"Root/partner"); XmlNode _key = doc.SelectSingleNode(@"Root/key"); XmlNode _seller_email = doc.SelectSingleNode(@"Root/seller_email"); XmlNode _return_url = doc.SelectSingleNode(@"Root/return_url"); XmlNode _notify_url = doc.SelectSingleNode(@"Root/notify_url"); //读取站点配置信息 Model.siteconfig model = new BLL.siteconfig().loadConfig(DTKeys.FILE_SITE_XML_CONFING); //合作身份者ID,以2088开头由16位纯数字组成的字符串 partner = _partner.InnerText; //交易安全检验码,由数字和字母组成的32位字符串 key = _key.InnerText; //签约支付宝账号或卖家支付宝帐户 seller_email = _seller_email.InnerText; //页面跳转同步返回页面文件路径 要用 http://格式的完整路径,不允许加?id=123这类自定义参数 return_url = Utils.DelLastChar(model.weburl, "/") + _return_url.InnerText; //服务器通知的页面文件路径 要用 http://格式的完整路径,不允许加?id=123这类自定义参数 notify_url = Utils.DelLastChar(model.weburl, "/") + _notify_url.InnerText; //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ //字符编码格式 目前支持 gbk 或 utf-8 input_charset = "utf-8"; //签名方式 不需修改 sign_type = "MD5"; }
public Feed GetFeed(string url, int priority) { if (string.IsNullOrEmpty(url)) throw new ArgumentException("url"); string request = string.Format("http://{0}/v{1}/feed_id?appkey={2}&format=xml&link={3}&priority={4}", Feed.Host, Feed.Version, appKey, url, priority); string response = processor.GetResponse(request, null); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode feedId = doc.SelectSingleNode("//feed_id"); if (feedId == null) { string message = "Could not get feed"; if (doc.SelectSingleNode("//error") != null) { message += ": " + doc.SelectSingleNode("//error").InnerText; } throw new PostRankException(message); } else { return GetFeed(long.Parse(feedId.InnerText)); } }
public void Load() { if (!File.Exists(_filePath)) return; var document = new XmlDocument(); document.Load(_filePath); var tempBool = false; var tempInt = 0; var node = document.SelectSingleNode(@"/Settings/Maximized"); if (node != null && Boolean.TryParse(node.InnerText, out tempBool)) Maximized = tempBool; node = document.SelectSingleNode(@"/Settings/Top"); if (node != null && Int32.TryParse(node.InnerText, out tempInt)) Top = tempInt; node = document.SelectSingleNode(@"/Settings/Left"); if (node != null && Int32.TryParse(node.InnerText, out tempInt)) Left = tempInt; node = document.SelectSingleNode(@"/Settings/Height"); if (node != null && Int32.TryParse(node.InnerText, out tempInt)) Height = tempInt; node = document.SelectSingleNode(@"/Settings/Width"); if (node != null && Int32.TryParse(node.InnerText, out tempInt)) Width = tempInt; Existed = true; }
public String AnalysisXml(string ReqXml) { string ResXml = string.Empty; string ReqCode = string.Empty; try { System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.LoadXml(ReqXml); //请求指令 ReqCode = xmldoc.SelectSingleNode("JTW91G/MsgData/ReqHeader/ReqCode").InnerText; Trade.CTrade trade = new Trade.CTrade(); string loginid = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/LoginId").InnerText; List<ProductConfig> list = trade.GetProductConfig(loginid); StringBuilder strb = new StringBuilder(); foreach (ProductConfig pcg in list) { strb.Append("<Product>"); strb.AppendFormat("<ProductCode>{0}</ProductCode>", pcg.ProductCode); strb.AppendFormat("<ProductName>{0}</ProductName>", pcg.ProductName); strb.AppendFormat("<GoodsCode>{0}</GoodsCode>", pcg.GoodsCode); strb.AppendFormat("<PriceCode>{0}</PriceCode>", pcg.PriceCode); strb.AppendFormat("<AdjustBase>{0}</AdjustBase>", pcg.AdjustBase); strb.AppendFormat("<AdjustCount>{0}</AdjustCount>", pcg.AdjustCount); strb.AppendFormat("<PriceDot>{0}</PriceDot>", pcg.PriceDot); strb.AppendFormat("<ValueDot>{0}</ValueDot>", pcg.ValueDot); strb.AppendFormat("<SetBase>{0}</SetBase>", pcg.SetBase); strb.AppendFormat("<HoldBase>{0}</HoldBase>", pcg.HoldBase); strb.AppendFormat("<OrdeMoney>{0}</OrdeMoney>", pcg.OrderMoney); strb.AppendFormat("<MaxPrice>{0}</MaxPrice>", pcg.MaxPrice); strb.AppendFormat("<MinPrice>{0}</MinPrice>", pcg.MinPrice); strb.AppendFormat("<MaxTime>{0}</MaxTime>", pcg.MaxTime); strb.AppendFormat("<State>{0}</State>", pcg.State); strb.AppendFormat("<Unit>{0}</Unit>", pcg.Unit); strb.Append("</Product>"); } if (strb.Length > 0) { //响应消息体 string DataBody = string.Format("<DataBody><Products>{0}</Products></DataBody>", strb); ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL004, ResCode.UL004Desc, DataBody); } else { ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL034, ResCode.UL034Desc, string.Format("<DataBody></DataBody>")); } } catch (Exception ex) { com.individual.helper.LogNet4.WriteErr(ex); //业务处理失败 ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL005, ResCode.UL005Desc, string.Format("<DataBody></DataBody>")); } return ResXml; }
protected IList<ManageThemeInfo> LoadThemes(string currentThemeName) { XmlDocument document = new XmlDocument(); IList<ManageThemeInfo> list = new List<ManageThemeInfo>(); string path = HttpContext.Current.Request.PhysicalApplicationPath + HiConfiguration.GetConfig().FilesPath + @"\Templates\vshop"; string[] strArray = Directory.Exists(path) ? Directory.GetDirectories(path) : null; ManageThemeInfo item = null; foreach (string str3 in strArray) { DirectoryInfo info2 = new DirectoryInfo(str3); string str2 = info2.Name.ToLower(CultureInfo.InvariantCulture); if ((str2.Length > 0) && !str2.StartsWith("_")) { foreach (FileInfo info3 in info2.GetFiles("template.xml")) { item = new ManageThemeInfo(); FileStream inStream = info3.OpenRead(); document.Load(inStream); inStream.Close(); item.Name = document.SelectSingleNode("root/Name").InnerText; item.ThemeImgUrl = Globals.ApplicationPath + "/Templates/vshop/" + str2 + "/" + document.SelectSingleNode("root/ImageUrl").InnerText; item.ThemeName = str2; if (string.Compare(item.ThemeName, currentThemeName) == 0) { this.litThemeName.Text = item.ThemeName; } list.Add(item); } } } return list; }
public FileReporter(XmlDocument xmlSettings) { string relativePath = xmlSettings.SelectSingleNode("/ConfigData/ReporterPlugins/TextFileReporter/ReportPath").InnerText; string prefix = xmlSettings.SelectSingleNode("/ConfigData/ReporterPlugins/TextFileReporter/PrefixFilename").InnerText; string datePart = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); if (string.IsNullOrEmpty(relativePath)) this.reportFile = @"c:\" + prefix + "XdeploymentEmergency.log"; else { this.reportFile = relativePath + "\\" + prefix + datePart + ".log"; // TODO use path.combine this.reportFile = System.IO.Path.GetFullPath(this.reportFile); } FileInfo fi = new FileInfo(this.reportFile); this.reportFile = fi.FullName; // TODO check if path to file exists if (fi.Directory.Exists) { // good } else { // bad create one logger.Warn(string.Format("The reporting directory '{0}' doesnt exists. It will be created.",fi.DirectoryName)); fi.Directory.Create(); } }
public List<ReportResult> GetValidationReport(XmlDocument xmlDoc,string strFolderPath) { List<ReportResult> result = new List<ReportResult>(); int intTotalSteps = 0; XmlNode XmlSummaryList = xmlDoc.SelectSingleNode("ReportRoot/Summary"); string strOverallStatus = XmlSummaryList.SelectSingleNode("OverallStatus").InnerText; int intOverAllTotalSteps = int.Parse(XmlSummaryList.SelectSingleNode("TotalSteps").InnerText); XmlNodeList XmlDetailist = xmlDoc.SelectSingleNode("ReportRoot/Detail").ChildNodes; intTotalSteps = XmlDetailist.Count; for (int intNodei = 0; intNodei < intTotalSteps; intNodei++) { string strStepName = XmlDetailist.Item(intNodei).Attributes.Item(0).InnerText; string strStepStatus = XmlDetailist.Item(intNodei).SelectSingleNode("CaseStatus").InnerText; int intTotalCheckpoints=XmlDetailist.Item(intNodei).SelectSingleNode("CheckPoints").SelectNodes("CheckPoint").Count; for (int intItemi = 0; intItemi < intTotalCheckpoints;intItemi++ ) { string strCPStatus = XmlDetailist.Item(intNodei).SelectSingleNode("CheckPoints").SelectNodes("CheckPoint").Item(intItemi).SelectSingleNode("CPStatus").InnerText; string strCPName = XmlDetailist.Item(intNodei).SelectSingleNode("CheckPoints").SelectNodes("CheckPoint").Item(intItemi).SelectSingleNode("CPName").InnerText; string strCPSnapshotRelativePath = XmlDetailist.Item(intNodei).SelectSingleNode("CheckPoints").SelectNodes("CheckPoint").Item(intItemi).SelectSingleNode("CPSnapshot").InnerText; string strScreenShotCheckResult = checkScreenShot(strCPSnapshotRelativePath, strFolderPath); if (strCPStatus != "Pass" || strStepStatus != "Pass" || strScreenShotCheckResult != strCPSnapshotRelativePath + " ScreenShot Validation Successfully") { result.Add(new ReportResult() { strStepNo = (intNodei+1).ToString(), strStepName = strStepName, strStepStatus = strStepStatus, strCPStatus = strCPName+"|"+strCPStatus,strScreenShotCheckResult=strScreenShotCheckResult }); } //check filepath existence } } return result; }
public void CanHandleRequest() { string host = UnitTestHelper.GenerateRandomString(); Config.CreateBlog("The Title Of This Blog", "blah", "None-of-your-biz", host, string.Empty); StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); UnitTestHelper.SetHttpContextWithBlogRequest(host, string.Empty, "/", "Export.aspx", writer); Config.CurrentBlog.Author = "MasterChief"; Config.UpdateConfigData(Config.CurrentBlog); HttpContext.Current.Response.Clear(); BlogMLProvider.Instance().ConnectionString = Config.ConnectionString; BlogMLHttpHandler handler = new BlogMLHttpHandler(); Assert.AreEqual(0, sb.Length); handler.ProcessRequest(HttpContext.Current); string result = sb.ToString(); //For some reason we get 2 weird chars at the beginning during the unit test. //Need to figure out if this is happening in a real export. if(result.IndexOf("<") > 0) result = result.Substring(result.IndexOf("<")); XmlDocument xml = new XmlDocument(); xml.LoadXml(result); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable); nsmgr.AddNamespace("bml", "http://www.blogml.com/2006/09/BlogML"); Assert.AreEqual("The Title Of This Blog", xml.SelectSingleNode("/bml:blog/bml:title", nsmgr).InnerText); Assert.AreEqual("MasterChief", xml.SelectSingleNode("/bml:blog/bml:authors/bml:author/bml:title", nsmgr).InnerText); }
void GetInfo() { // создаем xml-документ XmlDocument xmlDocument = new XmlDocument (); // делаем запрос на получение имени пользователя WebRequest webRequest = WebRequest.Create ("https://api.vk.com/method/users.get.xml?&access_token=" + token); WebResponse webResponse = webRequest.GetResponse (); Stream stream = webResponse.GetResponseStream (); xmlDocument.Load (stream); string name = xmlDocument.SelectSingleNode ("response/user/first_name").InnerText; // делаем запрос на проверку, webRequest = WebRequest.Create ("https://api.vk.com/method/groups.isMember.xml?group_id=20629724&access_token=" + token); webResponse = webRequest.GetResponse (); stream = webResponse.GetResponseStream (); xmlDocument.Load (stream); bool habrvk = (xmlDocument.SelectSingleNode ("response").InnerText =="1"); // выводим диалоговое окно var builder = new AlertDialog.Builder (this); // пользователь состоит в группе "хабрахабр"? if (!habrvk) { builder.SetMessage ("Привет, "+name+"!\r\n\r\nТы не состоишь в группе habrahabr.Не хочешь вступить?"); builder.SetPositiveButton ("Да", (o, e) => { // уточнив, что пользователь желает вступить, отправим запрос webRequest = WebRequest.Create ("https://api.vk.com/method/groups.join.xml?group_id=20629724&access_token=" + token); webResponse = webRequest.GetResponse (); }); builder.SetNegativeButton ("Нет", (o, e) => { }); } else { builder.SetMessage ("Привет, "+name+"!\r\n\r\nОтлично! Ты состоишь в группе habrahabr."); builder.SetPositiveButton ("Ок", (o, e) => { }); } builder.Create().Show(); }
public VideoMsg(XmlDocument xmldoc) : base(xmldoc) { //<xml> //<ToUserName><![CDATA[toUser]]></ToUserName> //<FromUserName><![CDATA[fromUser]]></FromUserName> //<CreateTime>1357290913</CreateTime> //<MsgType><![CDATA[video]]></MsgType> //<MediaId><![CDATA[media_id]]></MediaId> //<ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId> //<MsgId>1234567890123456</MsgId> //</xml> //ToUserName 开发者微信号 //FromUserName 发送方帐号(一个OpenID) //CreateTime 消息创建时间 (整型) //MsgType 视频为video //MediaId 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。 //ThumbMediaId 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。 //MsgId 消息id,64位整型 XmlNode xmlMediaId = xmldoc.SelectSingleNode("/xml/MediaId"); if (xmlMediaId == null) throw new ArgumentNullException("Media_id"); XmlNode xmlThumbMediaId = xmldoc.SelectSingleNode("/xml/ThumbMediaId"); if (xmlThumbMediaId == null) throw new ArgumentNullException("ThumbMediaId"); _mediaId = xmlMediaId.InnerText; _thumbMediaId = xmlThumbMediaId.InnerText; }
public NotificationMail GetNotificationMail(string notificationType) { try { var notifications = new XmlDocument(); notifications.Load(Config.ConfigurationFile); var settings = notifications.SelectSingleNode("//global"); var node = notifications.SelectSingleNode(string.Format("//instant//notification [@name = '{0}']", notificationType)); var details = new XmlDocument(); var cont = details.CreateElement("details"); cont.AppendChild(details.ImportNode(settings, true)); cont.AppendChild(details.ImportNode(node, true)); var detailsChild = details.AppendChild(cont); var notificationMail = new NotificationMail { FromMail = detailsChild.SelectSingleNode("//email").InnerText, FromName = detailsChild.SelectSingleNode("//name").InnerText, Subject = detailsChild.SelectSingleNode("//subject").InnerText, Domain = detailsChild.SelectSingleNode("//domain").InnerText, Body = detailsChild.SelectSingleNode("//body").InnerText }; return notificationMail; } catch (Exception e) { LogHelper.Error<MarkAsSolutionReminder>(string.Format("Couldn't get settings for {0}", notificationType), e); throw; } }
protected BaiduApiException GenerateApiException(string errorString) { BaiduApiException exception = null; string error_code =null; string error_msg = null; if (this.restFormat == RestFormat.Xml) { XmlDocument xml = new XmlDocument(); xml.LoadXml(errorString); XmlNode codeNode = xml.SelectSingleNode("//error_code"); if (codeNode != null) error_code = codeNode.InnerText; XmlNode msgNode = xml.SelectSingleNode("//error_msg"); if (msgNode != null) error_msg = msgNode.InnerText; exception = new BaiduApiException(error_code, error_msg); } else { JavaScriptSerializer js = new JavaScriptSerializer(); exception = js.Deserialize<BaiduApiException>(errorString); } return exception; }
private List<Answer> ParseResponse(string webResponse,string question) { List<Answer> answers = new List<Answer>(); Answer answer = new Answer(); XmlDocument responseXmlDoc = new XmlDocument(); responseXmlDoc.LoadXml(webResponse); XmlNamespaceManager ns = new XmlNamespaceManager(responseXmlDoc.NameTable); ns.AddNamespace("tk", "http://www.trueknowledge.com/ns/kengine"); XmlNode resultNode = responseXmlDoc.SelectSingleNode("//tk:text_result",ns); if (resultNode != null && resultNode.InnerText != "") { answer.question = question; answer.topAnswer = resultNode.InnerText; answer.score = 100; answer.isStarred = true; answer.url = responseXmlDoc.SelectSingleNode("//tk:tk_question_url", ns).InnerText; answer.source = AnswerSource.TrueKnowledge; answer.type = AnswerType.Text; ranker.GetFeatures(answer); answers.Add(answer); } //logger.Info("TrueKnowledge Result Count:{0}", answers.Count); return answers; }
/// <summary> /// Byte Array welches das sichere XML-Dokument enthält /// </summary> /// <param name="Data"></param> public void Load(byte[] Data) { using (var msData = new MemoryStream(Data)) { using (var srData = new StreamReader(msData, Encoding.UTF8)) { var document = new XmlDocument(); document.Load(srData); m_content = document.SelectSingleNode("updateSystemDotNet").SelectSingleNode("Content").InnerText; m_signature = document.SelectSingleNode("updateSystemDotNet").SelectSingleNode("Signature").InnerText; } } //System.Xml.XmlTextReader xR = new System.Xml.XmlTextReader(new System.IO.MemoryStream(Data)); //while (xR.Read()) //{ // if (xR.Name == "Content" && m_content == string.Empty) // { // xR.Read(); // m_content = xR.Value; // } // if (xR.Name == "Signature" && m_signature == string.Empty) // { // xR.Read(); // m_signature = xR.Value; // } //} //xR.Close(); }
public void XmlLoadMethod(string language,out string strTitle,out string strText, out string strElement,out bool flag) { try { flag = false; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "XmlFolder/Language.xml"); XmlNodeList cnTitleList = xmlDocument.SelectSingleNode("root/title/element[@language='" + language + "']").ChildNodes; if (cnTitleList == null) { flag = true; language = "en-us"; } cnTitleList = xmlDocument.SelectSingleNode("root/title/element[@language='" + language + "']").ChildNodes; strTitle = cnTitleList[0].InnerText; XmlNodeList cnTextList = xmlDocument.SelectSingleNode("root/text/element[@language='" + language + "']").ChildNodes; strText = cnTextList[0].InnerText; XmlNodeList cnElementList = xmlDocument.SelectSingleNode("root/comment/element[@language='" + language + "']").ChildNodes; strElement = cnElementList[0].InnerText; } catch (Exception) { strText = string.Empty; strElement = string.Empty; strTitle = string.Empty; flag = true; } }
/// <summary> /// Check the response for any errors it might indicate. Will throw an exception if API response indicates an error. /// Will throw an exception if it has a problem determining success or error. /// </summary> /// <param name="responseXml">the QuickBase response to examine</param> /// <returns>Asyn Call Completed Arguments.</returns> private AsyncCallCompletedEventArgs HandleErrors(string responseXml) { XmlDocument document = new System.Xml.XmlDocument(); document.LoadXml(responseXml); AsyncCallCompletedEventArgs resultArguments = null; XmlNode errCodeNode = document.SelectSingleNode(Utility.UtilityConstants.ERRCODEXPATH); IdsException exception = null; if (errCodeNode == null) { exception = new IdsException(Resources.ErrorCodeMissing); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } int errorCode; if (!int.TryParse(errCodeNode.InnerText, out errorCode)) { exception = new IdsException(string.Format(CultureInfo.InvariantCulture, Resources.ErrorCodeNonNemeric, errorCode)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } if (errorCode == 0) { // 0 indicates success resultArguments = new AsyncCallCompletedEventArgs(responseXml, null); return(resultArguments); } XmlNode errTextNode = document.SelectSingleNode(Utility.UtilityConstants.ERRTEXTXPATH); if (errTextNode == null) { exception = new IdsException(string.Format(CultureInfo.InvariantCulture, Resources.ErrorWithNoText, errorCode)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } string errorText = errTextNode.InnerText; XmlNode errDetailNode = document.SelectSingleNode(Utility.UtilityConstants.ERRDETAILXPATH); string errorDetail = errDetailNode != null ? errDetailNode.InnerText : null; if (!string.IsNullOrEmpty(errorDetail)) { exception = new IdsException(string.Format(CultureInfo.InvariantCulture, Resources.ErrorDetails0, errorText, errorCode, errorDetail)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } exception = new IdsException(string.Format(CultureInfo.InvariantCulture, Resources.ErrorDetails1, errorText, errorCode)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); return(resultArguments); }
protected override void CryptElement(System.Xml.XmlDocument xml, string hmac) { try { string memberCode = xml.SelectSingleNode("//MemberCode").InnerText; XmlNode node = xml.SelectSingleNode("//LoginPassword"); //node.InnerText = CryptHelper.HMAC_MD5(node.InnerText, hmac); node.InnerText = CryptHelper.MD5(memberCode.Trim().ToLower() + "DimooFighter" + node.InnerText.Trim()); } catch { } }
private static System.Xml.XmlDocument MergeSection(System.Xml.XmlDocument oDocFirst, System.Xml.XmlDocument oDocSecond, string sectionName) { XmlNode oNodeWhereInsert = oDocFirst.SelectSingleNode(sectionName); int i = 0; while (oDocSecond.SelectSingleNode(sectionName).ChildNodes.Count != i) { oNodeWhereInsert.AppendChild(oDocFirst.ImportNode(oDocSecond.SelectSingleNode(sectionName).ChildNodes[i], true)); i++; } return(oDocFirst); }
/// <summary> /// /// </summary> /// <param name="xPath"></param> /// <returns></returns> public string SelectSingleNode(string xPath) { XmlNode xmlNode = _xml.SelectSingleNode(xPath); if (xmlNode != null) { return(xmlNode.InnerText); } else { return(""); } }
public String AnalysisXml(string ReqXml) { string ResXml = string.Empty; string ReqCode = string.Empty; try { System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.LoadXml(ReqXml); //请求指令 ReqCode = xmldoc.SelectSingleNode("JTW91G/MsgData/ReqHeader/ReqCode").InnerText; Trade.CTrade trade = new Trade.CTrade(); DelHoldInfo DhInfo = new DelHoldInfo(); DhInfo.LoginID = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/LoginId").InnerText; DhInfo.TradeAccount = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/TradeAccount").InnerText; DhInfo.CurrentTime = Convert.ToDateTime(xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/HoldOrders/HoldOrder/CurrentTime").InnerText); DhInfo.HoldOrderID = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/HoldOrders/HoldOrder/HoldOrderId").InnerText; DhInfo.UserType = 0; //客户端没有传递这个值 内部调用默认赋值0 表示普通用户 DhInfo.ReasonType = "1"; //手动取消 MarDelivery mdy = trade.DelHoldOrder(DhInfo); if (!mdy.Result) { string CodeDesc = ResCode.UL005Desc; string ReturnCode = GssGetCode.GetCode(mdy.ReturnCode, mdy.Desc, ref CodeDesc); ResXml = GssResXml.GetResXml(ReqCode, ReturnCode, CodeDesc, string.Format("<DataBody></DataBody>")); } else { StringBuilder fundinfo = new StringBuilder(); fundinfo.Append("<FundInfo>"); fundinfo.AppendFormat("<Money>{0}</Money>", mdy.MoneyInventory.FdInfo.Money); fundinfo.AppendFormat("<OccMoney>{0}</OccMoney>", mdy.MoneyInventory.FdInfo.OccMoney); fundinfo.AppendFormat("<FrozenMoney>{0}</FrozenMoney>", mdy.MoneyInventory.FdInfo.FrozenMoney); fundinfo.Append("</FundInfo>"); ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL004, ResCode.UL004Desc, string.Format("<DataBody>{0}</DataBody>", fundinfo.ToString())); } } catch (Exception ex) { com.individual.helper.LogNet4.WriteErr(ex); //业务处理失败 ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL005, ResCode.UL005Desc, string.Format("<DataBody></DataBody>")); } return(ResXml); }
private void LoadVersion() { System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); try { xmlDocument.Load(System.Web.HttpContext.Current.Request.MapPath("/Storage/data/app/ios/IosUpgrade.xml")); this.litVersion.Text = xmlDocument.SelectSingleNode("root/Version").InnerText; this.litDescription.Text = xmlDocument.SelectSingleNode("root/Description").InnerText; this.litUpgradeUrl.Text = xmlDocument.SelectSingleNode("root/UpgradeUrl").InnerText; } catch { } }
public void Upgrade(string projectPath, string userSettingsPath, ref System.Xml.XmlDocument projectDocument, ref System.Xml.XmlDocument userSettingsDocument, ref System.Xml.XmlNamespaceManager nsm) { //Add DataTypeReferencedTableMappingSchemaName to each Parameter. foreach (XmlAttribute node in projectDocument.SelectNodes("//*/@DataTypeReferencedTableMappingName", nsm)) { XmlAttribute tableSchemaName = (XmlAttribute)node.SelectSingleNode("//P:TableMapping[@TableName='{0}']/@SchemaName".FormatString(node.Value), nsm); XmlAttribute dataTypeReferencedTableMappingSchemaName = projectDocument.CreateAttribute("DataTypeReferencedTableMappingSchemaName"); dataTypeReferencedTableMappingSchemaName.Value = tableSchemaName.Value; node.OwnerElement.Attributes.Append(dataTypeReferencedTableMappingSchemaName); } //Add ParentTableMappingSchemaName and ReferencedTableMappingSchemaName to each Foreign Key Mapping. foreach (XmlElement node in projectDocument.SelectNodes("//P:ForeignKeyMapping", nsm)) { XmlAttribute parentTableSchemaName = (XmlAttribute)projectDocument.SelectSingleNode("//P:TableMapping[@TableName='{0}']/@SchemaName".FormatString(node.GetAttribute("ParentTableMappingName")), nsm); XmlAttribute referencedTableSchemaName = (XmlAttribute)projectDocument.SelectSingleNode("//P:TableMapping[@TableName='{0}']/@SchemaName".FormatString(node.GetAttribute("ReferencedTableMappingName")), nsm); XmlAttribute parentTableMappingSchemaName = projectDocument.CreateAttribute("ParentTableMappingSchemaName"); XmlAttribute referencedTableMappingSchemaName = projectDocument.CreateAttribute("ReferencedTableMappingSchemaName"); parentTableMappingSchemaName.Value = parentTableSchemaName.Value; referencedTableMappingSchemaName.Value = referencedTableSchemaName.Value; node.Attributes.Append(parentTableMappingSchemaName); node.Attributes.Append(referencedTableMappingSchemaName); } //Add ReferencedTableMappingSchemaName to each Enumeration Mapping. //Rename ReferencedTableName to ReferencedTableMappingName for each Enumeration Mapping foreach (XmlAttribute node in projectDocument.SelectNodes("//P:EnumerationMapping/@ReferencedTableName", nsm)) { XmlAttribute tableSchemaName = (XmlAttribute)projectDocument.SelectSingleNode("//P:TableMapping[@TableName='{0}']/@SchemaName".FormatString(node.Value), nsm); XmlAttribute tableMappingSchemaName = projectDocument.CreateAttribute("ReferencedTableMappingSchemaName"); XmlAttribute tableMappingName = projectDocument.CreateAttribute("ReferencedTableMappingName"); tableMappingSchemaName.Value = tableSchemaName.Value; tableMappingName.Value = node.Value; node.OwnerElement.Attributes.Append(tableMappingSchemaName); node.OwnerElement.Attributes.Append(tableMappingName); node.OwnerElement.Attributes.Remove(node); } //Remove Template.Name attribute. foreach (XmlAttribute node in projectDocument.SelectNodes("//P:Template/@Name", nsm)) { node.OwnerElement.Attributes.Remove(node); } }
public ReportCategory GetReportList(BOAuthentication authModel, string defaultFolderId) { //TODO: Unit test it or Understand refactor it for readability ReportCategory category = new ReportCategory(); XmlDocument docRecv = new System.Xml.XmlDocument(); try { _logMessages.Append("Getting reports list from BO System."); //Get all folders from Root Folder List <string> _lstfolderIds = GetFolders(authModel); //For every folder for (int i = 0; i < _lstfolderIds.Count(); i++) { //Get the list of reports within that folder //TODO: Check with the send param,it should not be null _biRepository.CreateWebRequest(send: null, recv: docRecv, method: "GET", URI: authModel.URI, URIExtension: "/biprws/infostore/" + _lstfolderIds[i], pLogonToken: authModel.LogonToken); XmlNamespaceManager nsmgrGET = new XmlNamespaceManager(docRecv.NameTable); nsmgrGET.AddNamespace("rest", authModel.NameSpace); XmlNodeList nodeList = docRecv.SelectNodes("//rest:attr[@name='type']", nsmgrGET); if (nodeList.Item(0).InnerText.Equals("Folder", StringComparison.OrdinalIgnoreCase)) { ReportCategory parentCat = new ReportCategory() { Name = docRecv.SelectSingleNode("//rest:attr[@name='name']", nsmgrGET).InnerText, InfoStoreId = docRecv.SelectSingleNode("//rest:attr[@name='id']", nsmgrGET).InnerText, Description = docRecv.SelectSingleNode("//rest:attr[@name='description']", nsmgrGET).InnerText, Cuid = docRecv.SelectSingleNode("//rest:attr[@name='cuid']", nsmgrGET).InnerText }; category.ParentCategories.Add(parentCat); //Find sub reports of this report GetChildren(authModel, parentCat); } } _logMessages.Append("Finished Iterating all reports folder"); } catch (Exception ex) { _logMessages.AppendFormat("An Error occurred getting reports list Exception message {0}.", ex.Message); _logger.Info(_logMessages.ToString()); throw; } _logger.Info(_logMessages.ToString()); return(category); }
private void LoadMenu() { string text = (Globals.ApplicationPath + "/Shopadmin/").ToLower(); string text2 = this.Page.Request.Url.AbsolutePath.ToLower(); string xpath = string.Format("Menu/Module/Item/PageLink[@Link='{0}']", text2.Replace(text, "").ToLower()); System.Xml.XmlDocument menuDocument = ShopAdmin.GetMenuDocument(); System.Xml.XmlNode xmlNode = menuDocument.SelectSingleNode(xpath); System.Xml.XmlNode xmlNode2 = null; System.Xml.XmlNode xmlNode3 = null; if (xmlNode != null) { xmlNode2 = xmlNode.ParentNode; xmlNode3 = xmlNode2.ParentNode; } else { xpath = string.Format("Menu/Module/Item[@Link='{0}']", text2.Replace(text, "").ToLower()); xmlNode2 = menuDocument.SelectSingleNode(xpath); if (xmlNode2 != null) { xmlNode3 = xmlNode2.ParentNode; } } System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); System.Xml.XmlNodeList xmlNodeList = menuDocument.SelectNodes("Menu/Module"); foreach (System.Xml.XmlNode xmlNode4 in xmlNodeList) { if (xmlNode4.NodeType == System.Xml.XmlNodeType.Element) { stringBuilder.Append(ShopAdmin.BuildModuleMenu(xmlNode4.Attributes["Title"].Value, xmlNode4.Attributes["Image"].Value, xmlNode4.Attributes["Link"].Value.ToLower(), xmlNode3, text)); stringBuilder.Append(System.Environment.NewLine); } } this.mainMenuHolder.Text = stringBuilder.ToString(); stringBuilder.Remove(0, stringBuilder.Length); if (xmlNode3 != null) { foreach (System.Xml.XmlNode xmlNode5 in xmlNode3.ChildNodes) { if (xmlNode5.NodeType == System.Xml.XmlNodeType.Element) { stringBuilder.Append(ShopAdmin.BuildSubMenu(xmlNode5.Attributes["Title"].Value, xmlNode5.Attributes["Link"].Value.ToLower(), xmlNode2, text)); stringBuilder.Append(System.Environment.NewLine); } } } this.subMenuHolder.Text = stringBuilder.ToString(); }
private static void Test1() { System.Xml.XmlDocument docTEST = new System.Xml.XmlDocument(); docTEST.PreserveWhitespace = true; docTEST.Load(TESTFILEPATH1); XmlNamespaceManager nsMgr = new XmlNamespaceManager(docTEST.NameTable); nsMgr.AddNamespace("spe", "http://schemas.microsoft.com/sharepoint/events"); System.Xml.XmlNode node1 = docTEST.SelectSingleNode("//XmlDocuments/XmlDocument/spe:Receivers/spe:Receiver/spe:Name", nsMgr); System.Xml.XmlNode node2 = docTEST.SelectSingleNode("//XmlDocuments/XmlDocument", nsMgr); //docTEST.Save(TESTFILEPATH1); }
/// <summary> /// 获取结点值 /// </summary> /// <returns></returns> public static string GetNodeValue(string node) { System.Xml.XmlNode _node = ConfigXml.SelectSingleNode(node); string res = ""; if (_node == null) { } else { res = _node.InnerText.ToString(); } return(res); }
/// <summary> /// 读取并缓存规则列表 /// </summary> /// <returns></returns> protected ArrayList GetRuleList() { string cacheKey = ConfigHelper.SitePrefix + "rewriterulelist"; ArrayList ruleList = (ArrayList)HttpContext.Current.Cache.Get(cacheKey); if (ruleList == null) { ruleList = new ArrayList(); string urlFilePath = HttpContext.Current.Server.MapPath(string.Format("{0}common/config/rewrite.config", ConfigHelper.SitePath)); System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); xml.Load(urlFilePath); XmlNode root = xml.SelectSingleNode("rewrite"); foreach (XmlNode n in root.ChildNodes) { if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "item") { RewriterRule rule = new RewriterRule(); rule.LookFor = ConfigHelper.SitePath + n.Attributes["lookfor"].Value; rule.SendTo = ConfigHelper.SitePath + n.Attributes["sendto"].Value; ruleList.Add(rule); } } HttpContext.Current.Cache.Insert(cacheKey, ruleList, new System.Web.Caching.CacheDependency(urlFilePath)); } return(ruleList); }
//<summary> //获取设置值 //</summary> //<param name="strXmlFile">配置文件</param> //<param name="strSection">配置类型</param> //<param name="strConfigKey">配置项</param> //<param name="strDefault">默认值</param> //<returns></returns> public static string GetConfig(string strXmlFile, string strSection, string strConfigKey, string strDefault) { string Ret = string.Empty; try { System.Uri u = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase); string FileName = System.IO.Path.GetDirectoryName(u.LocalPath) + "\\" + strXmlFile; System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument(); XmlDoc.Load(FileName); System.Xml.XmlNode n = XmlDoc.SelectSingleNode("/" + CONFIG_ROOT_NODE + "/" + strSection + "/" + strConfigKey); if (n != null) { Ret = n.InnerText; } else { Ret = strDefault; } } catch (Exception ex) { // throw ex; } return(Ret); }
public XmlNode GetItemGrounp(ProjectItem projectItem, out XmlDocument doc, out bool hasItemGroup) { string projectFileName = projectItem.ContainingProject.FileName; doc = null; hasItemGroup = false; if (File.Exists(projectFileName)) { doc = new System.Xml.XmlDocument(); doc.Load(projectFileName); XmlNode compileNode = doc.SelectSingleNode("/Project/ItemGroup/Compile"); XmlNode itemGroupNode = null; if (compileNode == null) { itemGroupNode = doc.CreateElement("ItemGroup"); doc.DocumentElement.AppendChild(itemGroupNode); } else { itemGroupNode = compileNode.ParentNode; } return(itemGroupNode); } return(null); }
/// <summary> /// 根据Key修改Value /// </summary> /// <param name="key">要修改的Key</param> /// <param name="value">要修改为的值</param> public static void SetValue(string key, string value) { XmlDocument xDoc = new System.Xml.XmlDocument(); if (!FileHelper.IsExistFile(configPath)) { createXml(); } xDoc.Load(configPath); XmlNode xNode = xDoc.SelectSingleNode("//appSettings"); XmlElement xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']"); if (xElem1 != null) { xElem1.SetAttribute("value", value); } else { XmlElement xElem2 = xDoc.CreateElement("add"); xElem2.SetAttribute("key", key); xElem2.SetAttribute("value", value); xNode.AppendChild(xElem2); } xDoc.Save(configPath); }
private void BindHeaderMenu() { string filename = System.Web.HttpContext.Current.Request.MapPath(Globals.ApplicationPath + string.Format("/Templates/sites/" + Hidistro.Membership.Context.HiContext.Current.User.UserId.ToString() + "/{0}/config/HeaderMenu.xml", this.themName)); System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(filename); System.Data.DataTable dataTable = new System.Data.DataTable(); dataTable.Columns.Add("Id", typeof(int)); dataTable.Columns.Add("Title"); dataTable.Columns.Add("DisplaySequence", typeof(int)); dataTable.Columns.Add("Url"); dataTable.Columns.Add("Category"); dataTable.Columns.Add("Visible"); System.Xml.XmlNode xmlNode = xmlDocument.SelectSingleNode("root"); this.txtCategoryNum.Text = xmlNode.Attributes["CategoryNum"].Value; System.Xml.XmlNodeList childNodes = xmlNode.ChildNodes; foreach (System.Xml.XmlNode xmlNode2 in childNodes) { System.Data.DataRow dataRow = dataTable.NewRow(); dataRow["Id"] = int.Parse(xmlNode2.Attributes["Id"].Value); dataRow["Title"] = xmlNode2.Attributes["Title"].Value; dataRow["DisplaySequence"] = int.Parse(xmlNode2.Attributes["DisplaySequence"].Value); dataRow["Category"] = xmlNode2.Attributes["Category"].Value; dataRow["Url"] = xmlNode2.Attributes["Url"].Value; dataRow["Visible"] = xmlNode2.Attributes["Visible"].Value; dataTable.Rows.Add(dataRow); } dataTable.DefaultView.Sort = "DisplaySequence ASC"; this.grdMyHeaderMenu.DataSource = dataTable; this.grdMyHeaderMenu.DataBind(); }
/// <summary> /// 创建处理器 /// </summary> /// <param name="requestXml">请求的xml</param> /// <returns>IHandler对象</returns> public static IHandler CreateHandler(string requestXml) { IHandler handler = null; if (!string.IsNullOrEmpty(requestXml)) { //解析数据 XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(requestXml); XmlNode node = doc.SelectSingleNode("/xml/MsgType"); if (node != null) { XmlCDataSection section = node.FirstChild as XmlCDataSection; if (section != null) { string msgType = section.Value; switch (msgType) { case "text": handler = new TextHandler(requestXml); break; case "event": handler = new EventHandler(requestXml); break; } } } } return(handler); }
protected override void ProcessDataNode(System.Xml.XmlDocument doc, System.Xml.XmlNamespaceManager namespaces) { namespaces.AddNamespace("contact", "urn:ietf:params:xml:ns:contact-1.0"); var children = doc.SelectSingleNode("//contact:creData", namespaces); if (children != null) { XmlNode node; // ContactId node = children.SelectSingleNode("contact:id", namespaces); if (node != null) { ContactId = node.InnerText; } // DateCreated node = children.SelectSingleNode("contact:crDate", namespaces); if (node != null) { DateCreated = node.InnerText; } } }
/// <summary> /// Adds expiration record to the SQLFileCache /// </summary> public static void AddFileExpiration(string Key, ref SQLOptions o) { string strXMLXPath = "/SQLHelper_FileExpirations/File"; string strXMLForeignKeyAttribute = "Key"; System.Xml.XmlDocument doc = GetFileExpirations(ref o); o.WriteToLog("updating expiration file for this value..." + Key); General.Debug.Trace("updating expiration file for this value..." + Key); System.Xml.XmlNode node = doc.SelectSingleNode(strXMLXPath + "[@" + strXMLForeignKeyAttribute + "='" + Key + "']"); if (node == null) { o.WriteToLog("record not found... creating..." + Key); General.Debug.Trace("record not found... creating..." + Key); node = doc.CreateNode(System.Xml.XmlNodeType.Element, "File", ""); node.Attributes.Append(doc.CreateAttribute("Key")); node.Attributes["Key"].Value = Key; node.Attributes.Append(doc.CreateAttribute("ExpirationDate")); node.Attributes["ExpirationDate"].Value = o.Expiration.ToString(); doc.DocumentElement.AppendChild(node); } else { o.WriteToLog("record found... updating..." + Key); General.Debug.Trace("record found... updating..." + Key); node.Attributes["ExpirationDate"].Value = o.Expiration.ToString(); } SaveFileExpirations(doc, ref o); }
/// <summary> /// Returns true if file is expired /// </summary> public static bool FileExpired(string Key, ref SQLOptions o) { string strXMLXPath = "/SQLHelper_FileExpirations/File"; string strXMLForeignKeyAttribute = "Key"; System.Xml.XmlDocument doc = GetFileExpirations(ref o); o.WriteToLog("searching expiration file for this value..." + Key); General.Debug.Trace("searching expiration file for this value..." + Key); System.Xml.XmlNode node = doc.SelectSingleNode(strXMLXPath + "[@" + strXMLForeignKeyAttribute + "='" + Key + "']"); if (node == null) { o.WriteToLog("record not found... " + Key); General.Debug.Trace("record not found... " + Key); return(true); } else { DateTime Expiration = Convert.ToDateTime(node.Attributes["ExpirationDate"].Value); if (DateTime.Now >= Expiration) { o.WriteToLog("file is expired... " + Key); DeleteFileExpiration(Key, ref o); return(true); } else { return(false); } } }
public void loadPodCast(string url) { XmlDocument doc = new XmlDocument(); doc.Load("Feeds.xml"); System.Xml.XmlNodeList rssItems = doc.SelectNodes("ArrayOfRssFeed/RssFeed"); foreach (XmlNode RssFeed in rssItems) { var UrlRss = RssFeed.SelectSingleNode("Url").InnerText; int.TryParse(RssFeed.SelectSingleNode("Updating").InnerText, out int UpdatingRss); var CateRss = RssFeed.SelectSingleNode("Category").InnerText; System.Net.WebRequest myRequest = System.Net.WebRequest.Create(UrlRss); System.Net.WebResponse myResponse = myRequest.GetResponse(); System.IO.Stream rssStream = myResponse.GetResponseStream(); System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument(); rssDoc.Load(rssStream); rssStream.Close(); System.Xml.XmlNode rssName = rssDoc.SelectSingleNode("rss/channel"); var podcastName = rssName.InnerText; System.Xml.XmlNodeList xx = rssDoc.SelectNodes("rss/channel/item"); int antalEpisoder = xx.Count; string frekvens = source.FirstOrDefault(x => x.Value == UpdatingRss).Key; string[] RowPodCast = { antalEpisoder.ToString(), podcastName, frekvens, CateRss, UrlRss }; var listItem = new ListViewItem(RowPodCast); lvPodcast.Items.Add(listItem); } }
// //createDataElement // private static void createDataElement( ref System.Xml.XmlDocument pdoc, string pname, string pvalue, string pcomment) { System.Xml.XmlElement data = pdoc.CreateElement("data"); data.SetAttribute("name", pname); data.SetAttribute("xml:space", "preserve"); System.Xml.XmlElement value = pdoc.CreateElement("value"); value.InnerText = pvalue; data.AppendChild(value); if (!(pcomment == null)) { System.Xml.XmlElement comment = pdoc.CreateElement("comment"); comment.InnerText = pcomment; data.AppendChild(comment); } System.Xml.XmlNode root = pdoc.SelectSingleNode("//root"); System.Xml.XmlNode old_data = root.SelectSingleNode("//data[@name='" + pname + "']"); if (old_data == null) { root.AppendChild(data); } else { root.ReplaceChild(data, old_data); } }
/// <summary> /// 获取远程配置文件 /// </summary> /// <returns>成功返回远程配置文件信息 失败返回null</returns> public System.Xml.XmlDocument GetConfig() { #region 获取配置文件路径 System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(Application.StartupPath + "\\url.xml"); System.Xml.XmlNode node = doc.SelectSingleNode("//dir"); if (node == null) { MessageBox.Show(Language.Msg("url中找dir结点出错!")); } string serverPath = node.InnerText; string configPath = "//Config.xml"; //远程配置文件名 #endregion try { doc.Load(serverPath + configPath); } catch (System.Net.WebException) { } catch (System.IO.FileNotFoundException) { } catch (Exception ex) { MessageBox.Show(Language.Msg("装载Config.xml失败!\n" + ex.Message)); } return(doc); }
private void button1_Click(object sender, EventArgs e) { if (treeProgram.Nodes.Count == 0) { return; } tplDic = new List <string>(); getTreeChecked(treeProgram.Nodes[0]); XmlNode xmlnode = xmlDoc.SelectSingleNode("root/tplItem[@name='" + cbTpl.Text + "']"); xmlnode.RemoveAll(); (xmlnode as XmlElement).SetAttribute("name", cbTpl.Text); //(xmlnode as XmlElement).SetAttribute("ProgramPath", txtClientPath.Text); //(xmlnode as XmlElement).SetAttribute("OutputPath", txtServerPath.Text); foreach (var v in tplDic) { XmlElement xe1 = xmlDoc.CreateElement("Item"); xe1.SetAttribute("path", v.Replace(basepath, "")); //xe1.SetAttribute("checked", v.Value ? "1" : "0"); xmlnode.AppendChild(xe1); } xmlDoc.Save(tplconfig); MessageBox.Show("保存为模板成功!"); }
public void showASpecPodcast(string rss, string xmlCate, string XmlUpdate) { System.Net.WebRequest myRequest = System.Net.WebRequest.Create(rss); System.Net.WebResponse myResponse = myRequest.GetResponse(); System.IO.Stream rssStream = myResponse.GetResponseStream(); System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument(); rssDoc.Load(rssStream); rssStream.Close(); System.Xml.XmlNode rssName = rssDoc.SelectSingleNode("rss/channel"); var podcastName = rssName.InnerText; System.Xml.XmlNodeList xx = rssDoc.SelectNodes("rss/channel/item"); int antalEpisoder = xx.Count; int.TryParse(XmlUpdate, out int XmlUpdateint); string frekvens = source.FirstOrDefault(x => x.Value == XmlUpdateint).Key; string[] RowPodCast = { antalEpisoder.ToString(), podcastName, frekvens, xmlCate, rss }; var listItem = new ListViewItem(RowPodCast); lbEpisode.Items.Clear(); lvPodcast.Items.Add(listItem); }
public ActionResult InsertNotesInformation() { if (!Request.IsAuthenticated) { return(RedirectToAction("LogOn", "Account")); } else { ///Verify if the xml has been updated System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(Server.MapPath("/NoteTypes.xml")); xtr.WhitespaceHandling = System.Xml.WhitespaceHandling.None; System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(xtr); var date = xDoc.SelectSingleNode("// types/date[1]/modified").InnerText; if (DateTime.Parse(date).AddMonths(int.Parse(System.Configuration.ConfigurationManager.AppSettings["NoteTypes"])).ToShortDateString() == DateTime.Now.ToShortDateString()) { Session.Add("createXML", "true"); } if (Request.IsAjaxRequest()) { return(View("_InsertNotes")); } return(View()); } }
public void saveDisplay(string sLocation, string number) { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(sLocation); xmlDoc.SelectSingleNode("QUIZ/Display/Number").InnerText = number; xmlDoc.Save(sLocation); }
//public bool SameCustomField(string customKey, System.Guid customFieldID) //{ // if (m_customFieldsByGUID.ContainsKey(customFieldID.ToString())) // { // if (m_customFieldsByGUID[customFieldID.ToString()] == customKey) // return true; // } // return false; //} /// <summary> /// read the passed in path and file and pull out the classes and fields /// </summary> /// <param name="xmlFileName"></param> /// <returns>true if successfull</returns> public bool ReadLexImportFields(string xmlFileName) { bool success = true; System.Xml.XmlDocument xmlMap = new System.Xml.XmlDocument(); try { xmlMap.Load(xmlFileName); System.Xml.XmlNode abbrSignatures = xmlMap.SelectSingleNode("ImportFields/AbbreviationSignatures"); ReadSignatureNode(abbrSignatures); System.Xml.XmlNodeList classList = xmlMap.SelectNodes("ImportFields/Class"); foreach (System.Xml.XmlNode classNode in classList) { if (!ReadAClassNode(classNode)) { success = false; } } success = Initialize(); // 6/2/08 Now add in any custom fields that are currently defined in the database } catch (System.Xml.XmlException) { // string ErrMsg = "Error: invalid mapping file '" + xmlFileName + "' : " + e.Message; success = false; } return(success); }
/// <summary> /// Xml反序列化为DataTable /// </summary> /// <param name="strXml"></param> /// <returns></returns> public DataTable XMLDeserialize(string strXml) { classLims_NPOI.WriteLog(strXml, ""); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(strXml); XmlNode xn = xmlDoc.SelectSingleNode("complexType"); XmlNodeList xnl = xn.ChildNodes; string sCol = ((XmlElement)xnl[0]).GetAttribute("length"); int nCol = int.Parse(sCol); DataTable dt = new DataTable(); for (int i = 0; i < nCol; i++) { dt.Columns.Add(); } int tmpCol = 0; foreach (XmlNode xnf in xnl) { DataRow dr = dt.NewRow(); tmpCol = 0; XmlElement xe = (XmlElement)xnf; XmlNodeList xnf1 = xe.ChildNodes; foreach (XmlNode xn2 in xnf1) { dr[tmpCol++] = xn2.InnerText; } dt.Rows.Add(dr); } return(dt); }
private void grdHeaderMenu_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e) { if (e.CommandName == "SetYesOrNo") { int rowIndex = ((System.Web.UI.WebControls.GridViewRow)((System.Web.UI.Control)e.CommandSource).NamingContainer).RowIndex; int num = (int)this.grdMyHeaderMenu.DataKeys[rowIndex].Value; string filename = System.Web.HttpContext.Current.Request.MapPath(Globals.ApplicationPath + string.Format("/Templates/sites/" + Hidistro.Membership.Context.HiContext.Current.User.UserId.ToString() + "/{0}/config/HeaderMenu.xml", this.themName)); System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(filename); System.Xml.XmlNodeList childNodes = xmlDocument.SelectSingleNode("root").ChildNodes; foreach (System.Xml.XmlNode xmlNode in childNodes) { if (xmlNode.Attributes["Id"].Value == num.ToString()) { if (xmlNode.Attributes["Visible"].Value == "true") { xmlNode.Attributes["Visible"].Value = "false"; } else { xmlNode.Attributes["Visible"].Value = "true"; } break; } } xmlDocument.Save(filename); this.BindHeaderMenu(); } }