protected void DL_SubjectArealist_ItemDatabound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { ListViewDataItem ditem = (ListViewDataItem)e.Item; //data reader System.Data.DataRowView item = (System.Data.DataRowView)ditem.DataItem; Literal myfavicons = (Literal)ditem.FindControl("myfavicons"); HyperLink SubjectAreaTitle = (HyperLink)ditem.FindControl("SubjectAreaTitle"); Literal Description = (Literal)ditem.FindControl("Description"); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(item["content_html"].ToString()); string ShortDescription = commonfunctions.getFieldValue(XMLDoc, "ShortDescription", "/SubjectAreas"); string Name = commonfunctions.getFieldValue(XMLDoc, "Name", "/SubjectAreas"); long saId = long.Parse(item["content_id"].ToString()); Description.Text = ShortDescription; myfavicons.Text = commonfunctions.getMyFavIcons(saId.ToString(), "2", Title, "0"); SubjectAreaTitle.Text = Name; SubjectAreaTitle.NavigateUrl = commonfunctions.getQuickLink(saId); ; } }
static public string Request_POST(string rooturl, string param) { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(rooturl); Encoding encoding = Encoding.UTF8; byte[] bs = Encoding.ASCII.GetBytes(param); string responseData = String.Empty; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = bs.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { responseData = reader.ReadToEnd().ToString(); } } XmlDocument doc = new XmlDocument(); doc.LoadXml(responseData); XmlElement root = doc.DocumentElement; return root.InnerText; }
public void GetData() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(LevelStats.text); StartCoroutine(LoadLevelStats(xmlDoc)); }
public void MakeList() { XmlDocument xmlDoc = new XmlDocument(); // xmlDoc is the new xml document. xmlDoc.LoadXml(ELEData.text); // load the file. XmlNodeList EleList = xmlDoc.GetElementsByTagName("storeElement"); // array of the level nodes. GameObject eleGO; StoreElement strElmnt; int i = 0; foreach (XmlNode eleInfo in EleList) { int pfI = int.Parse(eleInfo.Attributes["storeType"].Value); eleGO = (GameObject)Instantiate(ELEPrefab[pfI]); if(pfI==0){ Text txtEl = eleGO.GetComponent<Text>(); txtEl.text = LanguageManager.current.getText(eleInfo.Attributes["name"].Value); }else if(pfI==1){ strElmnt = eleGO.GetComponent<StoreElement>(); int toolIndex = int.Parse(eleInfo.Attributes["imageIndex"].Value); strElmnt.init( eleInfo.Attributes["id"].Value, i, LanguageManager.current.getText(eleInfo.Attributes["name"].Value), LanguageManager.current.getSentance(eleInfo.Attributes["desc"].Value,"20"), (ToolType)toolIndex, ElEImages[toolIndex], (eleInfo.Attributes["upgrades"] != null) ); elmentList.Add(strElmnt); } eleGO.transform.SetParent(gridGroup.transform); eleGO.transform.localScale = Vector3.one; } }
public static void SetCountriesName(string language) { Debug.Log("countries....." + language); TextAsset textAsset = (TextAsset) Resources.Load("countries"); var xml = new XmlDocument (); xml.LoadXml (textAsset.text); Countries = new Hashtable(); AppCountries = new SortedList(); try{ var element = xml.DocumentElement[language]; if (element != null) { var elemEnum = element.GetEnumerator(); while (elemEnum.MoveNext()) { var xmlItem = (XmlElement)elemEnum.Current; Countries.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText); AppCountries.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText); } } else { Debug.LogError("The specified language does not exist: " + language); } } catch (Exception ex) { Debug.Log("Language:SetCountryName()" + ex.ToString()); } }
public static void GetAttributesOnCDataNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a><![CDATA[test data]]></a>"); Assert.Null(xmlDocument.DocumentElement.FirstChild.Attributes); }
protected void DL_newslist_ItemDatabound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { ListViewDataItem ditem = (ListViewDataItem)e.Item; //data reader System.Data.DataRowView item = (System.Data.DataRowView)ditem.DataItem; HyperLink NewsTitle = (HyperLink)ditem.FindControl("NewsTitle"); Literal NewsDate = (Literal)ditem.FindControl("NewsDate"); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(item["content_html"].ToString()); string HeadLine = commonfunctions.getFieldValue(XMLDoc, "Headline", "/News"); string Date = commonfunctions.getFieldValue(XMLDoc, "Date", "/News"); string Teaser = commonfunctions.getFieldValue(XMLDoc, "Teaser", "/News"); DateTime DateShown = Convert.ToDateTime(Date); long newsId = long.Parse(item["content_id"].ToString()); NewsDate.Text = DateShown.ToString("MMMM dd, yyyy"); NewsTitle.Text = HeadLine; NewsTitle.NavigateUrl = commonfunctions.getQuickLink(newsId); ; } }
public static void GetAttributesOnCommentNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a><!-- comment --></a>"); Assert.Null(xmlDocument.DocumentElement.FirstChild.Attributes); }
public static void GetAttributesOnTextNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a>text node</a>"); Assert.Null(xmlDocument.DocumentElement.FirstChild.Attributes); }
public static void GetAttributesOnAttribute() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a attr1='test' />"); Assert.Null(xmlDocument.DocumentElement.Attributes[0].Attributes); }
public static void GetAttributesOnProcessingInstruction() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a><?PI pi_info?></a>"); Assert.Null(xmlDocument.DocumentElement.FirstChild.Attributes); }
public static AEAnimationData ParceAnimationData(string data) { XmlDocument doc = new XmlDocument(); doc.LoadXml(data); AEAnimationData animation = new AEAnimationData (); XmlNode anim = doc.SelectSingleNode("after_affect_animation_doc"); XmlNode meta = anim.SelectSingleNode("meta"); animation.frameDuration = GetFloat (meta, "frameDuration"); animation.totalFrames = GetInt (meta, "totalFrames"); animation.duration = GetFloat (meta, "duration"); frameDuration = animation.frameDuration; XmlNode composition = anim.SelectSingleNode("composition"); animation.composition = ParseComposition (composition); XmlNode sub_items = anim.SelectSingleNode("sub_items"); XmlNodeList usedCompositions = sub_items.SelectNodes("composition"); foreach (XmlNode c in usedCompositions) { animation.addComposition(ParseComposition (c)); } return animation; }
/// <summary> /// 从 body 字符串中解析,成功返回 true,否则 false /// </summary> /// <param name="str">body字符串</param> /// <param name="command">出参,对应 command 属性</param> /// <param name="cmd_node">出参,对应整个 cmd 节点</param> /// <param name="mcu_jid">出参,mcu jid</param> /// <param name="mcu_cid">出参,mcu cid</param> /// <returns></returns> public static bool parse(string str, out string command, out XmlElement cmd_node, out string mcu_jid, out int mcu_cid) { command = null; cmd_node = null; mcu_cid = 0; mcu_jid = null; try { XmlDocument doc = new XmlDocument(); doc.LoadXml(str); XmlElement node_zonekey = doc.DocumentElement; if (node_zonekey.Name == "zonekey") { XmlNode node_app = node_zonekey.Attributes.GetNamedItem("app"); if (node_app != null && node_app.NodeType == XmlNodeType.Attribute && ((XmlAttribute)node_app).Value == "record_livingcast_service") { // 找到 cmd 节点,和 mcu 节点 XmlNodeList cmds = doc.SelectNodes("/zonekey/cmd"); XmlNodeList mcus = doc.SelectNodes("/zonekey/mcu"); if (cmds.Count >= 1 && mcus.Count >= 1) { cmd_node = (XmlElement)cmds[0]; XmlElement mcu_node = (XmlElement)mcus[0]; XmlNode attr_command = cmd_node.Attributes.GetNamedItem("command"); if (attr_command != null) { command = attr_command.Value; int state = 0; foreach (XmlNode cn in mcu_node.ChildNodes) { if (cn.Name == "jid") { mcu_jid = cn.InnerText; state |= 1; } else if (cn.Name == "cid") { mcu_cid = int.Parse(cn.InnerText); state |= 2; } } return state == 3; // 拥有 mcu_jid, mcu_cid } } } } return false; } catch { return false; } }
public static void Main(string[] arg) { if (arg.Length < 1) throw new ArgumentException("Must pass one or two command line arguments."); StringWriter sw = new StringWriter(); string s; while ((s = Console.ReadLine()) != null) { sw.WriteLine(s); } XmlDocument d = new XmlDocument(); d.LoadXml(sw.ToString()); object ret; if (arg.Length == 1) { ret = d.CreateNavigator().Evaluate(arg[0]); } else if (arg.Length == 2 && arg[0] == "-expr") { ret = d.CreateNavigator().Evaluate(arg[1]); } else if (arg.Length == 2 && arg[0] == "-node") { ret = d.SelectSingleNode(arg[1]); } else { throw new ArgumentException("Bad command line arguments."); } if (ret is XPathNodeIterator) { XPathNodeIterator iter = (XPathNodeIterator)ret; while (iter.MoveNext()) { Console.WriteLine(iter.Current); } } else if (ret is XmlNode) { Console.WriteLine(((XmlNode)ret).InnerXml); } else { Console.WriteLine(ret); } }
/// <summary> /// upload image and get task's id</summary> /// <param name="data"> byte[], image of document</param> /// <returns> returns UrlData with URL (empty in case of failure) and Status of operation)</returns> public async Task<string> PostImage(byte[] data) { var client = new HttpClient(); setAuthentication(client); string id = ""; client.BaseAddress = new Uri("http://cloud.ocrsdk.com/processMRZ"); try { var response = await client.PostAsync(client.BaseAddress, new ByteArrayContent(data)); response.EnsureSuccessStatusCode(); //Console.WriteLine(response.StatusCode); ///response.isStatusCode != ... ) var result = await response.Content.ReadAsStringAsync(); XmlDocument doc = new XmlDocument(); doc.LoadXml(result); id = doc.SelectSingleNode("/response/task/@id").Value; } catch (Exception exception) { //Console.WriteLine("CAUGHT EXCEPTION:"); //Console.WriteLine(exception); return ""; } return id; }
public static void GetOneAttribute() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem1 child1=\"\" child2=\"duu\" child3=\"e1;e2;\" child4=\"a1\" child5=\"goody\"> text node two e1; text node three </elem1>"); Assert.Equal("duu", xmlDocument.DocumentElement.GetAttribute("child2")); }
public static void WrongNamespace() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem1 child1=\"\" child2=\"duu\" child3=\"e1;e2;\" child4=\"a1\" child5=\"goody\"> text node two e1; text node three </elem1>"); Assert.Equal(string.Empty, xmlDocument.DocumentElement.GetAttribute("child1", "ns2")); }
private static String ParseResponse(string response) { XmlDocument doc = null; XslCompiledTransform myXslTransform = null; TextWriter sw = null; string result; try { doc = new XmlDocument(); ; myXslTransform = new XslCompiledTransform(); sw = new StringWriter(); doc.LoadXml(response); myXslTransform.Load(new XmlTextReader(new StringReader(Resources.Resource.xml2json))); JavaScriptSerializer serializer = new JavaScriptSerializer(); myXslTransform.Transform(doc, null, sw); result = sw.ToString(); } catch { result = System.Web.Configuration.WebConfigurationManager.AppSettings["errorParsingOrLoading"]; logger.Error(result); } finally { sw.Close(); } return result; }
/// <summary> /// Convert XML to TextBox. /// </summary> /// <param name="mXML">XML document</param> public string ConvertXML(string mXML) { if (DataHelper.GetNotEmpty(mXML, "") == "") { return ""; } StringBuilder mToReturn = new StringBuilder(); XmlDocument mXMLDocument = new XmlDocument(); mXMLDocument.LoadXml(mXML); XmlNodeList NodeList = mXMLDocument.DocumentElement.GetElementsByTagName("column"); int i = 0; foreach (XmlNode node in NodeList) { if (i > 0) { mToReturn.Append(";"); } mToReturn.Append(XmlHelper.GetXmlAttributeValue(node.Attributes["name"], "")); i++; } return mToReturn.ToString(); }
//List<Dictionary<string,string>> pictures = new List<Dictionary<string,string>>(); //Dictionary<string,string> obj; IEnumerator Start() { //Load XML data from a URL //string url = "http://vvtest.ucoz.com/picturesReal.xml"; string url = "http://85.255.65.168/XML/pictureInformation.xml"; //For now all comes from Ucoz FTP, because real server is not running. Bellow link for server WWW www = new WWW(url); //Load the data and yield (wait) till it's ready before we continue executing the rest of this method. yield return www; if (www.error == null) { //Sucessfully loaded the XML Debug.Log("Loaded following XML " + www.data); //Create a new XML document out of the loaded data XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(www.data); XmlNodeList levelsList = xmlDoc.GetElementsByTagName("picture"); // array of the level nodes. XmlNodeList linkList = xmlDoc.GetElementsByTagName("links"); // array of the level nodes. int mPictureIdentificator = theRealPicture - 1; } else {//Error Debug.Log("ERROR: " + www.error); } }
public static bool ParsePListFile(string xmlFile, ref Hashtable plist) { /* if (!File.Exists(xmlFile)) { Debug.LogError("File doesn't exist: " + xmlFile); return false; } StreamReader sr = new StreamReader(xmlFile); string txt = sr.ReadToEnd(); sr.Close(); */ string txt = xmlFile; XmlDocument xml = new XmlDocument(); xml.XmlResolver = null; //Disable schema/DTD validation, it's not implemented for Unity. xml.LoadXml(txt); XmlNode plistNode = xml.LastChild; if (!plistNode.Name.Equals("plist")) { Debug.LogError("plist file missing <plist> nodes." + xmlFile); return false; } string plistVers = plistNode.Attributes["version"].Value; if (plistVers == null || !plistVers.Equals(SUPPORTED_VERSION)) { Debug.LogError("This is an unsupported plist version: " + plistVers + ". Required version:a " + SUPPORTED_VERSION); return false; } XmlNode dictNode = plistNode.FirstChild; if (!dictNode.Name.Equals("dict")) { Debug.LogError("Missing root dict from plist file: " + xmlFile); return false; } return LoadDictFromPlistNode(dictNode, ref plist); }
public static void DocumentNodeTypeTest() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a />"); Assert.Equal(XmlNodeType.Document, xmlDocument.NodeType); }
public static void ElementWithNoChildTwoAttributes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top attr1='test1' attr2='test2' />"); Assert.Null(xmlDocument.DocumentElement.FirstChild); }
//导入数据库 protected void btnImportData_Click(object sender, EventArgs e) { string xml = txtData.Value.Trim(); if (string.IsNullOrEmpty(xml)) { Common.MessageBox.Show(this, "文本框为空!"); return; } try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); //加载XML文档 XmlNode root = xmlDoc.SelectSingleNode("//config"); InsertTableData(xmlDoc, "webconfig"); InsertTableData(xmlDoc, "dictionary"); InsertTableData(xmlDoc, "channel"); InsertTableData(xmlDoc, "ad"); InsertTableData(xmlDoc, "adtype"); Common.MessageBox.Show(this, "成功导入数据库!"); } catch (Exception ex) { Common.MessageBox.Show(this, ex.Message); } }
private void GetUpdateList(string updateKey) { WebClient client = new WebClient(); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; string response; try { response = client.UploadString("http://infinity-code.com/products_update/checkupdates.php", "k=" + WWW.EscapeURL(updateKey) + "&v=" + OnlineMaps.version + "&c=" + (int)channel); } catch { return; } XmlDocument document = new XmlDocument(); document.LoadXml(response); XmlNode firstChild = document.FirstChild; updates = new List<OnlineMapsUpdateItem>(); foreach (XmlNode node in firstChild.ChildNodes) updates.Add(new OnlineMapsUpdateItem(node)); }
public static String getConfigItem(String id) { String s_return = ""; if (tools.configXML == null || id.Equals("reLoad")) { tools.dbType = null; tools.configXML = null; String path = tools.webPath + "\\config.xml"; TextReader fr = new StreamReader(path); String strLine = fr.ReadLine(); String xml = ""; while (strLine != null) { xml += strLine; strLine = fr.ReadLine(); } configXML = new XmlDocument(); configXML.LoadXml(xml); tools.dbType = tools.getConfigItem("DB_TYPE"); } XmlElement e = configXML.GetElementById(id); s_return = e.InnerText; return s_return; }
public static string LoadDataString(string s) { XmlDocument doc = new XmlDocument (); doc.LoadXml (s); return doc.OuterXml; }
string extractTextFromHTML(string html, ref string?color) { // the text to return string res = ""; // text is stored in html inside the .mcf // html basically is xml so... parse it as xml XmlDocument doc = new XmlDocument(); doc?.LoadXml(html); // get the node that contains span objects for each line of text XmlNode node = doc?.SelectSingleNode("html/body/table/tr/td"); if (node == null) { Log.Error("Text node not found. Stopping text parsing."); return(""); } // extract text from each <span> and store in single string with newline character string styleInfo = ""; foreach (XmlNode p in node.ChildNodes) { XmlNode span = p.SelectSingleNode("span"); res += span?.InnerText + "\n"; // if span exists... add text + newline styleInfo = getAttributeStr(span, "style"); } if (color != null && styleInfo.Contains("color:")) { string[] t = styleInfo.Split("color:"); string colorhex = t.Last().Split(";").First(); color = colorhex.Insert(1, "ff"); } // return all lines return(res); }
public override string ToText(Subtitle subtitle, string title) { if (Configuration.Settings.General.CurrentFrameRate > 26) { FrameRate = 30; } else { FrameRate = 25; } string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + Environment.NewLine + "<!DOCTYPE fcpxml>" + Environment.NewLine + Environment.NewLine + "<fcpxml version=\"1.3\">" + Environment.NewLine + " <project name=\"Subtitle Edit subtitle\" uid=\"C1E80D31-57D4-4E6C-84F6-86A75DCB7A54\" eventID=\"B5C98F73-1D7E-4205-AEF3-1485842EB191\" location=\"file://localhost/Volumes/Macintosh%20HD/Final%20Cut%20Projects/Yma%20Sumac/Yma%20LIVE%20in%20Moscow/\" >" + Environment.NewLine + " <resources>" + Environment.NewLine + " <format id=\"r1\" name=\"FFVideoFormatDV720x480i5994\" frameDuration=\"2002/60000s\" fieldOrder=\"lower first\" width=\"720\" height=\"480\" paspH=\"10\" paspV=\"11\"/>" + Environment.NewLine + " <projectRef id=\"r2\" name=\"Yma DVD\" uid=\"B5C98F73-1D7E-4205-AEF3-1485842EB191\"/>" + Environment.NewLine + " <asset id=\"r3\" name=\"Live In Moscow MERGED-quicktime\" uid=\"E2951D8A4091478C718D981E70B29220\" projectRef=\"r2\" src=\"file://localhost/Volumes/Macintosh%20HD/Final%20Cut%20Events/Yma%20DVD/Original%20Media/Live%20In%20Moscow%20MERGED-quicktime.mov\" start=\"0s\" duration=\"128865737/30000s\" hasVideo=\"1\"/>" + Environment.NewLine + " <format id=\"r4\" name=\"FFVideoFormatRateUndefined\" width=\"640\" height=\"480\"/>" + Environment.NewLine + " <asset id=\"r5\" name=\"Moscow opening credit frame 2\" uid=\"492B77C679B1EEDA87E214703CD9B236\" projectRef=\"r2\" src=\"file://localhost/Volumes/Macintosh%20HD/Final%20Cut%20Events/Yma%20DVD/Original%20Media/Moscow%20opening%20credit%20frame%202.png\" start=\"0s\" duration=\"0s\" hasVideo=\"1\"/>" + Environment.NewLine + " <effect id=\"r6\" name=\"Custom\" uid=\".../Titles.localized/Build In:Out.localized/Custom.localized/Custom.moti\"/>" + Environment.NewLine + " </resources>" + Environment.NewLine + " <sequence duration=\"10282752480/2400000s\" format=\"r1\" tcStart=\"0s\" tcFormat=\"NDF\" audioLayout=\"stereo\" audioRate=\"48k\">" + Environment.NewLine + " <spine>" + Environment.NewLine + " </spine>" + Environment.NewLine + " </sequence>" + Environment.NewLine + " </project>" + Environment.NewLine + "</fcpxml>"; string xmlClipStructure = " <video lane=\"6\" offset=\"4130126/60000s\" ref=\"r4\" name=\"Basic Subtitle\" duration=\"288288/60000s\" start=\"216003788/60000s\">" + Environment.NewLine + " <param name=\"Text\" key=\"9999/999166889/999166904/2/369\" value=\"\"/>" + Environment.NewLine + " </video>"; var xml = new XmlDocument(); xml.LoadXml(xmlStructure); XmlNode videoNode = xml.DocumentElement.SelectSingleNode("project/sequence/spine"); int number = 1; foreach (Paragraph p in subtitle.Paragraphs) { XmlNode clip = xml.CreateElement("clip"); clip.InnerXml = xmlClipStructure; var attr = xml.CreateAttribute("name"); attr.Value = title; clip.Attributes.Append(attr); attr = xml.CreateAttribute("duration"); //attr.Value = "9529520/2400000s"; attr.Value = Convert.ToInt64(p.Duration.TotalSeconds * 2400000) + "/2400000s"; clip.Attributes.Append(attr); attr = xml.CreateAttribute("start"); //attr.Value = "1201200/2400000s"; attr.Value = Convert.ToInt64(p.StartTime.TotalSeconds * 2400000) + "/2400000s"; clip.Attributes.Append(attr); attr = xml.CreateAttribute("audioStart"); attr.Value = "0s"; clip.Attributes.Append(attr); attr = xml.CreateAttribute("audioDuration"); attr.Value = Convert.ToInt64(p.Duration.TotalSeconds * 2400000) + "/2400000s"; clip.Attributes.Append(attr); attr = xml.CreateAttribute("tcFormat"); attr.Value = "NDF"; clip.Attributes.Append(attr); XmlNode titleNode = clip.SelectSingleNode("video"); titleNode.Attributes["offset"].Value = Convert.ToInt64(p.StartTime.TotalSeconds * 60000) + "/60000s"; titleNode.Attributes["name"].Value = Utilities.RemoveHtmlTags(p.Text); titleNode.Attributes["duration"].Value = Convert.ToInt64(p.Duration.TotalSeconds * 60000) + "/60000s"; titleNode.Attributes["start"].Value = Convert.ToInt64(p.StartTime.TotalSeconds * 60000) + "/60000s"; XmlNode param = clip.SelectSingleNode("video/param"); param.Attributes["value"].InnerText = Utilities.RemoveHtmlTags(p.Text); videoNode.AppendChild(clip); number++; } string xmlAsText = ToUtf8XmlString(xml); xmlAsText = xmlAsText.Replace("fcpxml[]", "fcpxml"); xmlAsText = xmlAsText.Replace("fcpxml []", "fcpxml"); return(xmlAsText); }
private void LoadLogicClassRecord(string strName) { NFIClass xLogicClass = GetElement(strName); if (null != xLogicClass) { XmlDocument xmldoc = new XmlDocument(); string strLogicPath = mstrPath + xLogicClass.GetPath(); if (RuntimePlatform.Android == Application.platform || RuntimePlatform.IPhonePlayer == Application.platform) { strLogicPath = strLogicPath.Replace(".xml", ""); TextAsset textAsset = (TextAsset)Resources.Load(strLogicPath); xmldoc.LoadXml(textAsset.text); } else { try { xmldoc.Load(strLogicPath); } catch (Exception e) { Debug.LogFormat("Load Config Error {0}", e.ToString()); } } XmlNode xRoot = xmldoc.SelectSingleNode("XML"); XmlNode xNodePropertys = xRoot.SelectSingleNode("Records"); if (null != xNodePropertys) { XmlNodeList xNodeList = xNodePropertys.SelectNodes("Record"); if (null != xNodeList) { for (int i = 0; i < xNodeList.Count; ++i) { XmlNode xRecordNode = xNodeList.Item(i); string strID = xRecordNode.Attributes["Id"].Value; string strRow = xRecordNode.Attributes["Row"].Value; string strUpload = xRecordNode.Attributes["Upload"].Value; bool bUpload = strUpload.Equals("1"); NFDataList xValue = new NFDataList(); NFDataList xTag = new NFDataList(); XmlNodeList xTagNodeList = xRecordNode.SelectNodes("Col"); for (int j = 0; j < xTagNodeList.Count; ++j) { XmlNode xColTagNode = xTagNodeList.Item(j); XmlAttribute strTagID = xColTagNode.Attributes["Tag"]; XmlAttribute strTagType = xColTagNode.Attributes["Type"]; xTag.AddString(strTagID.Value); switch (strTagType.Value) { case "int": { xValue.AddInt(0); } break; case "float": { xValue.AddFloat(0.0); } break; case "string": { xValue.AddString(""); } break; case "object": { xValue.AddObject(new NFGUID(0, 0)); } break; case "vector2": { xValue.AddVector2(NFVector2.Zero()); } break; case "vector3": { xValue.AddVector3(NFVector3.Zero()); } break; default: break; } } NFIRecord xRecord = xLogicClass.GetRecordManager().AddRecord(strID, int.Parse(strRow), xValue, xTag); xRecord.SetUpload(bUpload); } } } } }
public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName) { _errorCount = 0; var sb = new StringBuilder(); lines.ForEach(line => sb.AppendLine(line)); var xml = new XmlDocument { XmlResolver = null }; xml.LoadXml(sb.ToString().Replace(" & ", " & ").Replace("Q&A", "Q&A").RemoveControlCharactersButWhiteSpace().Trim()); var nsmgr = new XmlNamespaceManager(xml.NameTable); nsmgr.AddNamespace("ttaf1", xml.DocumentElement.NamespaceURI); var div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr); if (div == null) div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild; var styleDic = new Dictionary<string, string>(); foreach (XmlNode node in xml.DocumentElement.SelectNodes("//ttaf1:style", nsmgr)) { if (node.Attributes["tts:fontStyle"] != null && node.Attributes["xml:id"] != null) { styleDic.Add(node.Attributes["xml:id"].Value, node.Attributes["tts:fontStyle"].Value); } } bool couldBeFrames = true; bool couldBeMillisecondsWithMissingLastDigit = true; foreach (XmlNode node in div.ChildNodes) { try { var pText = new StringBuilder(); foreach (XmlNode innerNode in node.ChildNodes) { switch (innerNode.Name.Replace("tt:", string.Empty)) { case "br": pText.AppendLine(); break; case "span": bool italic = false; if (innerNode.Attributes["style"] != null && styleDic.ContainsKey(innerNode.Attributes["style"].Value)) { if (styleDic[innerNode.Attributes["style"].Value].Contains("italic")) { italic = true; pText.Append("<i>"); } } if (!italic && innerNode.Attributes != null) { var fs = innerNode.Attributes.GetNamedItem("tts:fontStyle"); if (fs != null && fs.Value == "italic") { italic = true; pText.Append("<i>"); } } if (innerNode.HasChildNodes) { foreach (XmlNode innerInnerNode in innerNode.ChildNodes) { if (innerInnerNode.Name == "br" || innerInnerNode.Name == "tt:br") { pText.AppendLine(); } else { pText.Append(innerInnerNode.InnerText); } } } else { pText.Append(innerNode.InnerText); } if (italic) pText.Append("</i>"); break; case "i": pText.Append("<i>" + innerNode.InnerText + "</i>"); break; case "b": pText.Append("<b>" + innerNode.InnerText + "</b>"); break; default: pText.Append(innerNode.InnerText); break; } } string start = null; string end = null; string dur = null; foreach (XmlAttribute attr in node.Attributes) { if (attr.Name.EndsWith("begin", StringComparison.Ordinal)) start = attr.InnerText; else if (attr.Name.EndsWith("end", StringComparison.Ordinal)) end = attr.InnerText; else if (attr.Name.EndsWith("duration", StringComparison.Ordinal)) dur = attr.InnerText; } string text = pText.ToString(); text = text.Replace(Environment.NewLine + "</i>", "</i>" + Environment.NewLine); text = text.Replace("<i></i>", string.Empty).Trim(); if (!string.IsNullOrEmpty(end)) { if (end.Length != 11 || end.Substring(8, 1) != ":" || start == null || start.Length != 11 || start.Substring(8, 1) != ":") { couldBeFrames = false; } if (couldBeMillisecondsWithMissingLastDigit && (end.Length != 11 || start == null || start.Length != 11 || end.Substring(8, 1) != "." || start.Substring(8, 1) != ".")) { couldBeMillisecondsWithMissingLastDigit = false; } double dBegin, dEnd; if (!start.Contains(':') && Utilities.CountTagInText(start, '.') == 1 && !end.Contains(':') && Utilities.CountTagInText(end, '.') == 1 && double.TryParse(start, NumberStyles.Float, CultureInfo.InvariantCulture, out dBegin) && double.TryParse(end, NumberStyles.Float, CultureInfo.InvariantCulture, out dEnd)) { subtitle.Paragraphs.Add(new Paragraph(text, dBegin * TimeCode.BaseUnit, dEnd * TimeCode.BaseUnit)); } else { if (start.Length == 8 && start[2] == ':' && start[5] == ':' && end.Length == 8 && end[2] == ':' && end[5] == ':') { var p = new Paragraph(); var parts = start.Split(SplitCharColon); p.StartTime = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0); parts = end.Split(SplitCharColon); p.EndTime = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0); p.Text = text; subtitle.Paragraphs.Add(p); } else { subtitle.Paragraphs.Add(new Paragraph(TimedText10.GetTimeCode(start, false), TimedText10.GetTimeCode(end, false), text)); } } } else if (!string.IsNullOrEmpty(dur)) { if (dur.Length != 11 || dur.Substring(8, 1) != ":" || start == null || start.Length != 11 || start.Substring(8, 1) != ":") { couldBeFrames = false; } if (couldBeMillisecondsWithMissingLastDigit && (dur.Length != 11 || start == null || start.Length != 11 || dur.Substring(8, 1) != "." || start.Substring(8, 1) != ".")) { couldBeMillisecondsWithMissingLastDigit = false; } TimeCode duration = TimedText10.GetTimeCode(dur, false); TimeCode startTime = TimedText10.GetTimeCode(start, false); var endTime = new TimeCode(startTime.TotalMilliseconds + duration.TotalMilliseconds); subtitle.Paragraphs.Add(new Paragraph(startTime, endTime, text)); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); _errorCount++; } } subtitle.RemoveEmptyLines(); if (couldBeFrames) { bool all30OrBelow = true; foreach (Paragraph p in subtitle.Paragraphs) { if (p.StartTime.Milliseconds > 30 || p.EndTime.Milliseconds > 30) { all30OrBelow = false; break; } } if (all30OrBelow) { foreach (Paragraph p in subtitle.Paragraphs) { p.StartTime.Milliseconds = SubtitleFormat.FramesToMillisecondsMax999(p.StartTime.Milliseconds); p.EndTime.Milliseconds = SubtitleFormat.FramesToMillisecondsMax999(p.EndTime.Milliseconds); } } } else if (couldBeMillisecondsWithMissingLastDigit && Configuration.Settings.SubtitleSettings.TimedText10TimeCodeFormatSource != "hh:mm:ss.ms-two-digits") { foreach (Paragraph p in subtitle.Paragraphs) { p.StartTime.Milliseconds *= 10; p.EndTime.Milliseconds *= 10; } } subtitle.Renumber(); }
private string WrapInSoapMessage(string stsResponse, string relyingPartyIdentifier) { XmlDocument samlAssertion = new XmlDocument(); samlAssertion.PreserveWhitespace = true; samlAssertion.LoadXml(stsResponse); //Select the book node with the matching attribute value. String notBefore = samlAssertion.DocumentElement.FirstChild.Attributes["NotBefore"].Value; String notOnOrAfter = samlAssertion.DocumentElement.FirstChild.Attributes["NotOnOrAfter"].Value; XmlDocument soapMessage = new XmlDocument(); XmlElement soapEnvelope = soapMessage.CreateElement("t", "RequestSecurityTokenResponse", "http://schemas.xmlsoap.org/ws/2005/02/trust"); soapMessage.AppendChild(soapEnvelope); XmlElement lifeTime = soapMessage.CreateElement("t", "Lifetime", soapMessage.DocumentElement.NamespaceURI); soapEnvelope.AppendChild(lifeTime); XmlElement created = soapMessage.CreateElement("wsu", "Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); XmlText createdValue = soapMessage.CreateTextNode(notBefore); created.AppendChild(createdValue); lifeTime.AppendChild(created); XmlElement expires = soapMessage.CreateElement("wsu", "Expires", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); XmlText expiresValue = soapMessage.CreateTextNode(notOnOrAfter); expires.AppendChild(expiresValue); lifeTime.AppendChild(expires); XmlElement appliesTo = soapMessage.CreateElement("wsp", "AppliesTo", "http://schemas.xmlsoap.org/ws/2004/09/policy"); soapEnvelope.AppendChild(appliesTo); XmlElement endPointReference = soapMessage.CreateElement("wsa", "EndpointReference", "http://www.w3.org/2005/08/addressing"); appliesTo.AppendChild(endPointReference); XmlElement address = soapMessage.CreateElement("wsa", "Address", endPointReference.NamespaceURI); XmlText addressValue = soapMessage.CreateTextNode(relyingPartyIdentifier); address.AppendChild(addressValue); endPointReference.AppendChild(address); XmlElement requestedSecurityToken = soapMessage.CreateElement("t", "RequestedSecurityToken", soapMessage.DocumentElement.NamespaceURI); XmlNode samlToken = soapMessage.ImportNode(samlAssertion.DocumentElement, true); requestedSecurityToken.AppendChild(samlToken); soapEnvelope.AppendChild(requestedSecurityToken); XmlElement tokenType = soapMessage.CreateElement("t", "TokenType", soapMessage.DocumentElement.NamespaceURI); XmlText tokenTypeValue = soapMessage.CreateTextNode("urn:oasis:names:tc:SAML:1.0:assertion"); tokenType.AppendChild(tokenTypeValue); soapEnvelope.AppendChild(tokenType); XmlElement requestType = soapMessage.CreateElement("t", "RequestType", soapMessage.DocumentElement.NamespaceURI); XmlText requestTypeValue = soapMessage.CreateTextNode("http://schemas.xmlsoap.org/ws/2005/02/trust/Issue"); requestType.AppendChild(requestTypeValue); soapEnvelope.AppendChild(requestType); XmlElement keyType = soapMessage.CreateElement("t", "KeyType", soapMessage.DocumentElement.NamespaceURI); XmlText keyTypeValue = soapMessage.CreateTextNode("http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey"); keyType.AppendChild(keyTypeValue); soapEnvelope.AppendChild(keyType); return(soapMessage.OuterXml); }
public ActionResult LatestAlbums() { if (Sitecore.Context.Item == null) { return(null); } var dataSourceId = Sitecore.Context.Item.ID.ToString(); Assert.IsNotNullOrEmpty(dataSourceId, "dataSourceId is null or empty"); var item = Sitecore.Context.Database.GetItem(dataSourceId); if (item == null) { return(null); } LatestAlbums latestAlbums = new LatestAlbums(); //Event Links - DropTree Field with Child Items //ReferenceField artistRoot = item.Fields[Templates.LatestAlbums.Fields.LatestAlbumsList]; List <Artist> artistAlbumList = new List <Artist>(); MultilistField latestAlbumsListField = item.Fields[Templates.LatestAlbums.Fields.LatestAlbumsList]; Item[] latestAlbumArtistItems = latestAlbumsListField.GetItems(); //foreach (Item i in artistRoot.TargetItem.Children) if (latestAlbumArtistItems != null && latestAlbumArtistItems.Count() > 0) { foreach (Item i in latestAlbumArtistItems) { Artist artist = new Artist(); Item artistItem = Sitecore.Context.Database.GetItem(i.ID); artist.ArtistName = artistItem.Fields[Templates.Artist.Fields.ArtistName.ToString()].Value; artist.ArtistTitle = artistItem.Fields[Templates.Artist.Fields.ArtistTitle.ToString()].Value; artist.ArtistDescription = artistItem.Fields[Templates.Artist.Fields.ArtistDescription.ToString()].Value; LinkField artistTwitterLink = artistItem.Fields[Templates.Artist.Fields.ArtistTwitterUrl]; artist.ArtistTwitterUrl = artistTwitterLink.Url; LinkField artistLinkedInLink = artistItem.Fields[Templates.Artist.Fields.ArtistLinkedInUrl]; artist.ArtistLinkedInUrl = artistLinkedInLink.Url; LinkField artistWebsiteLink = artistItem.Fields[Templates.Artist.Fields.ArtistWebsiteUrl]; artist.ArtistWebsiteUrl = artistWebsiteLink.Url; ImageField artistImage = artistItem.Fields[Templates.Artist.Fields.ArtistImage]; XmlDocument doc = new XmlDocument(); //doc.LoadXml("<image stylelabs-content-id=\"29865\" thumbnailsrc=\"https://cmp-connector-400-r147.stylelabsqa.com/api/gateway/29865/thumbnail\" src=\"https://cmp-connector-400-r147.stylelabsqa.com/api/public/content/19c8d2004811433d931cc13c1d0b138a?v=638d2b04\" mediaid=\"\" stylelabs-content-type=\"Image\" alt=\"can-of-coke.jpg\" height=\"879\" width=\"1200\" />"); doc.LoadXml(artistImage.Value); XmlElement root = doc.DocumentElement; string src = root.Attributes["src"] != null? root.Attributes["src"].Value: string.Empty; if (!string.IsNullOrEmpty(src)) { artist.ArtistImageUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(artistImage.MediaItem); } else { artist.ArtistImageUrl = src; } artist.ArtistImageAlt = artistImage.Alt; artistAlbumList.Add(artist); } } //Featured Artists List - TreeList Field //MultilistField latestAlbumsListField = item.Fields[Templates.LatestAlbums.Fields.LatestAlbumsList]; //Item[] latestAlbumArtistItems = latestAlbumsListField.GetItems(); // if (latestAlbumArtistItems != null && latestAlbumArtistItems.Count() > 0) //{ // foreach (Item i in latestAlbumArtistItems) // { // Artist artist = new Artist(); // Item artistItem = Sitecore.Context.Database.GetItem(i.ID); // artist.ArtistName = artistItem.Fields[Templates.Artist.Fields.ArtistName.ToString()].Value; // artist.ArtistTitle = artistItem.Fields[Templates.Artist.Fields.ArtistTitle.ToString()].Value; // artist.ArtistDescription = artistItem.Fields[Templates.Artist.Fields.ArtistDescription.ToString()].Value; // LinkField artistTwitterLink = artistItem.Fields[Templates.Artist.Fields.ArtistTwitterUrl]; // artist.ArtistTwitterUrl = artistTwitterLink.Url; // LinkField artistLinkedInLink = artistItem.Fields[Templates.Artist.Fields.ArtistLinkedInUrl]; // artist.ArtistLinkedInUrl = artistLinkedInLink.Url; // LinkField artistWebsiteLink = artistItem.Fields[Templates.Artist.Fields.ArtistWebsiteUrl]; // artist.ArtistWebsiteUrl = artistWebsiteLink.Url; // ImageField artistImage = artistItem.Fields[Templates.Artist.Fields.ArtistImage]; // artist.ArtistImageUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(artistImage.MediaItem); // artist.ArtistImageAlt = artistImage.Alt; // artistAlbumList.Add(artist); // } //} latestAlbums.LatestAlbumsList = artistAlbumList; return(View(latestAlbums)); }
private void updatecheck() { string URLString = ""; string XMLResult = ""; //string VehicleString; bool m_updateavailable = false; bool m_version_toohigh = false; bool _info = false; Version maxversion = new Version("1.0.0.0"); File.Delete(Apppath + "\\input.xml"); File.Delete(Apppath + "\\Notes.xml"); try { if (m_customer.Length > 0) { URLString = "http://trionic.mobixs.eu/vagedcsuite/version.xml"; XMLResult = GetPageHTML(URLString, 10); using (StreamWriter xmlfile = new StreamWriter(Apppath + "\\input.xml", false, System.Text.Encoding.ASCII, 2048)) { xmlfile.Write(XMLResult); xmlfile.Close(); } URLString = "http://trionic.mobixs.eu/vagedcsuite/Notes.xml"; XMLResult = GetPageHTML(URLString, 10); using (StreamWriter xmlfile = new StreamWriter(Apppath + "\\Notes.xml", false, System.Text.Encoding.ASCII, 2048)) { xmlfile.Write(XMLResult); xmlfile.Close(); } } XmlDocument doc; try { doc = new XmlDocument(); doc.LoadXml(FileToString(Apppath + "\\input.xml")); // Add any other properties that would be useful to store //foreach ( System.Xml.XmlNodeList Nodes; Nodes = doc.GetElementsByTagName("vagedcsuite"); foreach (System.Xml.XmlNode Item in Nodes) { System.Xml.XmlAttributeCollection XMLColl; XMLColl = Item.Attributes; foreach (System.Xml.XmlAttribute myAttr in XMLColl) { if (myAttr.Name == "version") { Version v = new Version(myAttr.Value); if (v > m_currentversion) { if (v > maxversion) { maxversion = v; } m_updateavailable = true; PumpString("Available version: " + myAttr.Value, false, false, new Version(), false, Apppath + "\\Notes.xml"); } else if (v.Major < m_currentversion.Major || (v.Major == m_currentversion.Major && v.Minor < m_currentversion.Minor) || (v.Major == m_currentversion.Major && v.Minor == m_currentversion.Minor && v.Build < m_currentversion.Build)) { // mmm .. gebruiker draait een versie die hoger is dan dat is vrijgegeven... if (v > maxversion) { maxversion = v; } m_updateavailable = false; m_version_toohigh = true; } } else if (myAttr.Name == "info") { try { _info = Convert.ToBoolean(myAttr.Value); } catch (Exception sendIE) { Console.WriteLine(sendIE.Message); } } } } } catch (Exception E) { PumpString(E.Message, false, false, new Version(), false, ""); } if (m_updateavailable) { //Console.WriteLine("An update is available: " + maxversion.ToString()); PumpString("A newer version is available: " + maxversion.ToString(), m_updateavailable, m_version_toohigh, maxversion, _info, Apppath + "\\Notes.xml"); m_NewVersion = maxversion; } else if (m_version_toohigh) { PumpString("Versionnumber is too high: " + maxversion.ToString(), m_updateavailable, m_version_toohigh, maxversion, _info, Apppath + "\\Notes.xml"); m_NewVersion = maxversion; } else { PumpString("No new version(s) found...", false, false, new Version(), _info, Apppath + "\\Notes.xml"); } } catch (Exception tuE) { PumpString(tuE.Message, false, false, new Version(), _info, ""); } }
public void SetUp() { var xml = @" <appSettings> <add key='EntitySettings.DefaultUserCalendar' value='M-F 9-5'/> <add key='AttachmentSettings.MaximumFileSizeKB' value='10240'/> <add key='DatabaseSettings.ConnectionString' value='DbConnectionString' /> <add key='DatabaseSettings.Dialect' value='NHibernate.Dialect.MsSql2005Dialect' /> <add key='DatabaseSettings.Driver' value='NHibernate.Driver.SqlClientDriver' /> <add key='DatabaseSettings.Provider' value='NHibernate.Connection.DriverConnectionProvider' /> <add key='DatabaseSettings.ProxyFactory' value='NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle' /> <add key='DatabaseSettings.ShowSql' value='false' /> <add key='DatabaseSettings.UseOuterJoin' value='True' /> <add key='DatabaseSettings.GenerateStatistics' value='true'/> <add key='EmailEngineSettings.AdministratorEmail' value='*****@*****.**'/> <add key='EmailEngineSettings.PollingFrequency' value='15'/> <add key='EmailSettings.IncomingEmailCaseIdentifierPattern' value='About(\s*Case)?\s*(?<Identifier>[\d\-]+)'/> <add key='EmailSettings.LogEmailReplyToAddress' value='*****@*****.**'/> <add key='EmailSettings.OutgoingDefaultFromEmail' value='*****@*****.**'/> <add key='EmailSettings.OutgoingEmailSubjectPrefix' value='About Case'/> <add key='EmailSettings.SmtpEnableSsl' value='false'/> <add key='EmailSettings.SmtpHostAddress' value='127.0.0.1'/> <add key='EmailSettings.SmtpPort' value='25'/> <add key='EmailSettings.UseSmtpCredentials' value='false'/> <add key='IntegratedAuthenticationSettings.DefaultSite' value='Default Site'/> <add key='IntegratedAuthenticationSettings.InternalSiteType' value='Internal'/> <add key='LocalizationSettings.PrependCultureOnMissing' value='true'/> <add key='PollingServiceSettings.FrequencyInSeconds' value='5' /> <add key='SearchSettings.IndexFilesPath' value='A thingie'/> <add key='SearchSettings.LuceneParams' value='(+domain:case +({0})) OR (+domain:solution -status:expired +({0})) OR (+domain:externalfile +({0}))'/> <add key='SearchSettings.NumberOfIndexChangesBeforeOptimization' value='500'/> <add key='SearchSettings.LuceneMaximumClauseCount' value='1024'/> <add key='SearchSettings.SelfServiceLuceneParams' value='+domain:solution +public:true +status:published +({0})'/> <add key='WebsiteSettings.MaxNotificationDisplayCount' value='10'/> <add key='WebsiteSettings.PublicReportFrameUrlBase' value='http://localhost/DovetailCRM.Reports/reportlist.aspx' /> <add key='WebsiteSettings.PublicReportListUrl' value='http://localhost/DovetailCRM.Reports/reports.axd'/> <add key='WebsiteSettings.PublicReportWidgetUrlBase' value='http://localhost/DovetailCRM.Reports/DashboardReportViewer.aspx'/> <add key='WebsiteSettings.PublicMobileUrlBase' value='http://localhost/mobile' /> <add key='WebsiteSettings.PublicUrlBase' value='http://localhost/DovetailCRM/' /> <add key='WebsiteSettings.DiagnosticsEnabled' value='true' /> <add key='WebsiteSettings.CustomViewPath' value='Overrides' /> <add key='WebsiteSettings.AnonymousAccessFileExtensions' value='gif, png, jpg, css, js, htm, html' /> </appSettings> ".Replace("'", "\""); var document = new XmlDocument(); document.LoadXml(xml); theSettings = new XmlSettingsData(document.DocumentElement); }
private void CrearDataSource() { try { //this.sqlConnection2.ConnectionString = this.ReportParameters["@Conexion"].Value.ToString(); ////Transfer the ReportParameter value to the parameter of the select command //this.sqlDataAdapter1.SelectCommand.Parameters["@Id_Emp"].Value = this.ReportParameters["@Id_Emp"].Value; //this.sqlDataAdapter1.SelectCommand.Parameters["@Id_Cd"].Value = this.ReportParameters["@Id_Cd"].Value; //this.sqlDataAdapter1.SelectCommand.Parameters["@Id_Ord"].Value = this.ReportParameters["@Id_Ord"].Value; // -------------------------------------------- // Generar source a partir del XML de factura // -------------------------------------------- if (this.source.Columns.Count == 0) { this.source.Columns.Add("Id_Prd", typeof(string)); this.source.Columns.Add("Prd_Descripcion", typeof(string)); this.source.Columns.Add("Prd_Unidad", typeof(string)); this.source.Columns.Add("Prd_Cantidad", typeof(string)); this.source.Columns.Add("Prd_PrecioUnitario", typeof(string)); this.source.Columns.Add("Prd_Importe", typeof(string)); } XmlDocument doc = new XmlDocument(); doc.LoadXml(this.ReportParameters["@FacturaXML"].Value.ToString()); //XmlNode nodoPage = doc.SelectSingleNode("//Page"); //string height = nodoPage.Attributes["height"].Value; //string width = nodoPage.Attributes["width"].Value; this.source.Rows.Clear(); XmlNodeList nodosProductos = doc.SelectNodes("//Concepto"); foreach (XmlNode producto in nodosProductos) { //XmlNode producto = xn.SelectSingleNode("Concepto"); if (producto.Attributes.Count > 0) { DataRow row = this.source.NewRow(); row["Id_Prd"] = producto.Attributes["noIdentificacion"].Value; row["Prd_Descripcion"] = producto.Attributes["descripcion"].Value; row["Prd_Unidad"] = "LT"; // producto.Attributes["cantidad"].Value; row["Prd_Cantidad"] = producto.Attributes["cantidad"].Value; row["Prd_PrecioUnitario"] = producto.Attributes["valorUnitario"].Value; row["Prd_Importe"] = producto.Attributes["importe"].Value; this.source.Rows.Add(row); } } // --------------------------------------------------------------------------------------------- // Si se asigno correctamente el origen de datos, se actualiza el estatus de la factura // --------------------------------------------------------------------------------------------- //actualiza estatus de factura a Impreso (I) int verificador = 0; Factura factura = new Factura(); factura.Id_Emp = Convert.ToInt32(this.ReportParameters["Id_Emp"].Value); factura.Id_Cd = Convert.ToInt32(this.ReportParameters["Id_Cd"].Value); factura.Id_Fac = Convert.ToInt32(this.ReportParameters["Id_Fac"].Value); factura.Fac_Estatus = "I"; new CN_CapFactura().ModificarFactura_Estatus(factura, this.ReportParameters["Conexion"].Value.ToString(), ref verificador); } catch (Exception ex) { throw ex; } }
// ... private string GenerateResponse(ref HttpContext context, XmlDocument xDoc) { // Initial log. string requestUri = context.Request.Path.ToString() + "/" + context.Request.QueryString.ToString(); var odsHeader = context.Request.Headers.FirstOrDefault(item => item.Key == "X-PICASO-ODS"); int logId = InitialLog(context.Request.Method, requestUri, context.Request.ContentType, context.Request.Headers, odsHeader.Value); //var stopWatch = new Stopwatch(); //stopWatch.Start(); var rpcClient = new RpcClient(); //string rpcQueue = GetODSQueueName(context.Request); //if (string.IsNullOrEmpty(rpcQueue)) // return null; string rpcQueue = "rpc_queue"; var response = rpcClient.Call(rpcQueue, xDoc.OuterXml); rpcClient.Close(); int statusCode = -1; string contentType = string.Empty; string message = string.Empty; XmlDocument incomingDoc = new XmlDocument(); try { incomingDoc.LoadXml(response); // Update log //stopWatch.Stop(); context.Response.Headers.Clear(); if (incomingDoc.SelectSingleNode("//ContentType") != null) { context.Response.ContentType = contentType = incomingDoc.SelectSingleNode("//ContentType").InnerText; } XmlNode statusCodeNode = incomingDoc.SelectSingleNode("//StatusCode"); if (statusCodeNode != null) { int.TryParse(statusCodeNode.InnerText, out statusCode); } XmlNode bodyNode = incomingDoc.SelectSingleNode("//Body"); //if(bodyNode != null) // UpdateLog(logId, contentType, statusCodeNode, bodyNode, null); //else // UpdateLog(logId, contentType, statusCodeNode, null, null); //Set up Cookies //XmlNodeList xCookies = incomingDoc.SelectNodes("//cookies/cookie"); //foreach (XmlNode xCookie in xCookies) //{ // context.Response.Cookies.Append(xCookie.SelectSingleNode(".//key").InnerText, xCookie.SelectSingleNode(".//value").InnerText); //} XmlNodeList xHeaders = incomingDoc.SelectNodes("//headers/header"); foreach (XmlNode xHeader in xHeaders) { string key = xHeader.SelectSingleNode(".//key").InnerText; string value = xHeader.SelectSingleNode(".//value").InnerText; if (key == "Cookie" || key == "Content-Type" || key == "Content-Length" || key == "Accept-Encoding") { ; } // Picaso based custom headers else if (key == "X-PICASO-RequesterUPID" || key == "X-PICASO-RequesteeUPID" || key == "X-PICASO-ODS") { context.Response.Headers.Add(key, value); } //else //{ // //if (key == "Host") // // value = domain; // context.Response.Headers.Add(key, value); //} } string body = string.Empty; if (incomingDoc.SelectSingleNode("//Body") != null) { if (contentType != "text/html") { body = incomingDoc.SelectSingleNode("//Body").InnerText; } else if (incomingDoc.SelectSingleNode("//Body").InnerText.Contains("blocked for security reasons")) { message = "Blocked for security reasons"; context.Response.Headers.Add("Content-Type", "application/json"); dynamic errorBody = new JObject(); errorBody.Result = "AR"; errorBody.Message = message; body = JsonConvert.SerializeObject(errorBody); } } if (statusCode == 500) { dynamic bodyObj = JsonConvert.DeserializeObject(body); UpdateLog(logId, statusCode, bodyObj.errorMessage, bodyObj.innerexception); } else if (statusCode == 201 || statusCode == 400 || statusCode == 401 || statusCode == 501 || statusCode == 502) { UpdateLog(logId, statusCode, body, null); } else { UpdateLog(logId, statusCode, message, null); } context.Response.StatusCode = statusCode; return(body); } catch (Exception e) { Console.WriteLine("JsonMiddlewareHandler | GenerateResponse | Exception: " + e.Message); UpdateLog(logId, statusCode, e.Message, e.InnerException.ToString()); return(e.Message); } }
private void LoadLogicClassProperty(string strName) { NFIClass xLogicClass = GetElement(strName); if (null != xLogicClass) { XmlDocument xmldoc = new XmlDocument(); string strLogicPath = mstrPath + xLogicClass.GetPath(); if (RuntimePlatform.Android == Application.platform || RuntimePlatform.IPhonePlayer == Application.platform) { strLogicPath = strLogicPath.Replace(".xml", ""); TextAsset textAsset = (TextAsset)Resources.Load(strLogicPath); xmldoc.LoadXml(textAsset.text); } else { try { xmldoc.Load(strLogicPath); } catch (Exception e) { Debug.LogFormat("Load Config Error {0}", e.ToString()); } } XmlNode xRoot = xmldoc.SelectSingleNode("XML"); XmlNode xNodePropertys = xRoot.SelectSingleNode("Propertys"); XmlNodeList xNodeList = xNodePropertys.SelectNodes("Property"); for (int i = 0; i < xNodeList.Count; ++i) { XmlNode xPropertyNode = xNodeList.Item(i); XmlAttribute strID = xPropertyNode.Attributes["Id"]; XmlAttribute strType = xPropertyNode.Attributes["Type"]; XmlAttribute strUpload = xPropertyNode.Attributes["Upload"]; bool bUpload = strUpload.Value.Equals("1"); switch (strType.Value) { case "int": { NFDataList xValue = new NFDataList(); xValue.AddInt(0); NFIProperty xProperty = xLogicClass.GetPropertyManager().AddProperty(strID.Value, xValue); xProperty.SetUpload(bUpload); } break; case "float": { NFDataList xValue = new NFDataList(); xValue.AddFloat(0.0); NFIProperty xProperty = xLogicClass.GetPropertyManager().AddProperty(strID.Value, xValue); xProperty.SetUpload(bUpload); } break; case "string": { NFDataList xValue = new NFDataList(); xValue.AddString(""); NFIProperty xProperty = xLogicClass.GetPropertyManager().AddProperty(strID.Value, xValue); xProperty.SetUpload(bUpload); } break; case "object": { NFDataList xValue = new NFDataList(); xValue.AddObject(new NFGUID(0, 0)); NFIProperty xProperty = xLogicClass.GetPropertyManager().AddProperty(strID.Value, xValue); xProperty.SetUpload(bUpload); } break; default: break; } } } }
public Attendee Build(string xmlString) { this.Validate(xmlString); var toReturn = new Attendee(this.Context); var doc = new XmlDocument(); doc.LoadXml(xmlString); toReturn.Id = TryGetElementIntValue("id", doc); toReturn.EventId = TryGetElementIntValue("event_id", doc); toReturn.TicketId = TryGetElementNullableIntValue("ticket_id", doc); toReturn.Quantity = TryGetElementNullableIntValue("quantity", doc); toReturn.Currency = TryGetElementValue("currency", doc); toReturn.AmountPaid = TryGetElementNullableFloatValue("amount_paid", doc); toReturn.Barcode = TryGetElementValue("barcode", doc); toReturn.OrderId = TryGetElementNullableIntValue("order_id", doc); toReturn.OrderType = TryGetElementValue("order_type", doc); toReturn.Created = TryGetElementDateTimeValue("created", doc); toReturn.Modified = TryGetElementDateTimeValue("modified", doc); toReturn.EventDate = TryGetElementDateTimeValue("event_date", doc); toReturn.Discount = TryGetElementValue("discount", doc); toReturn.Notes = TryGetElementValue("notes", doc); toReturn.Email = TryGetElementValue("email", doc); toReturn.Prefix = TryGetElementValue("prefix", doc); toReturn.FirstName = TryGetElementValue("first_name", doc); toReturn.LastName = TryGetElementValue("last_name", doc); toReturn.Suffix = TryGetElementValue("suffix", doc); toReturn.HomeAddress = TryGetElementValue("home_address", doc); toReturn.HomeAddress2 = TryGetElementValue("home_address_2", doc); toReturn.HomeCity = TryGetElementValue("home_city", doc); toReturn.HomePostalCode = TryGetElementValue("home_postal_code", doc); toReturn.HomeRegion = TryGetElementValue("home_region", doc); toReturn.HomeCountry = TryGetElementValue("home_country", doc); toReturn.HomeCountryCode = TryGetElementValue("home_country_code", doc); toReturn.HomePhone = TryGetElementValue("home_phone", doc); toReturn.CellPhone = TryGetElementValue("cell_phone", doc); toReturn.ShipAddress = TryGetElementValue("ship_address", doc); toReturn.ShipAddress2 = TryGetElementValue("ship_address_2", doc); toReturn.ShipCity = TryGetElementValue("ship_city", doc); toReturn.ShipPostalCode = TryGetElementValue("ship_postal_code", doc); toReturn.ShipRegion = TryGetElementValue("ship_region", doc); toReturn.ShipCountry = TryGetElementValue("ship_country", doc); toReturn.ShipCountryCode = TryGetElementValue("ship_country_code", doc); toReturn.WorkAddress = TryGetElementValue("work_address", doc); toReturn.WorkAddress2 = TryGetElementValue("work_address_2", doc); toReturn.WorkCity = TryGetElementValue("work_city", doc); toReturn.WorkPostalCode = TryGetElementValue("work_postal_code", doc); toReturn.WorkRegion = TryGetElementValue("work_region", doc); toReturn.WorkCountry = TryGetElementValue("work_country", doc); toReturn.WorkCountryCode = TryGetElementValue("work_country_code", doc); toReturn.WorkPhone = TryGetElementValue("work_phone", doc); toReturn.JobTitle = TryGetElementValue("job_title", doc); toReturn.Company = TryGetElementValue("company", doc); toReturn.Website = TryGetElementValue("website", doc); toReturn.Blog = TryGetElementValue("blog", doc); toReturn.BirthDate = TryGetElementDateTimeValue("birth_date", doc); toReturn.Age = TryGetElementNullableIntValue("age", doc); string gender = TryGetElementValue("gender", doc); if (!String.IsNullOrEmpty(gender)) { toReturn.Gender = (AttendeeGender)Enum.Parse(typeof(AttendeeGender), gender); } return(toReturn); }
public XmlDocument MLLoadTreeXML(string editFormatUrl, bool ismenu, int PortalID, int source, string codes, string parentCat, string Locale) { DataTable dt = null; if (source == 0) { dt = LoadTree(ismenu, PortalID,""); } else if (source == 1) { dt = LoadTreeByCode(ismenu, PortalID, codes); } else if (source == 2) { dt = LoadTreeByParents(ismenu, PortalID, parentCat); } XmlDocument doc = new XmlDocument(); doc.LoadXml("<categories></categories>"); XmlElement root = doc.DocumentElement; for (int i = 0; i < dt.Rows.Count; i++) { XmlElement category = doc.CreateElement("category"); int tabid = Convert.ToInt32(dt.Rows[i]["DesktopListID"]); string link = DotNetNuke.Common.Globals.NavigateURL(tabid, "", "categoryid/" + dt.Rows[i]["CatID"].ToString()); if (dt.Rows[i]["NewsID"].ToString() != "0") { tabid = Convert.ToInt32(dt.Rows[i]["DesktopViewID"]); link = DotNetNuke.Common.Globals.NavigateURL(tabid, "", "id/" + dt.Rows[i]["NewsID"].ToString()); } string url_edit = editFormatUrl.Replace("@@catid", dt.Rows[i]["CatID"].ToString()); DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "ImgLevel1", DotNetNuke.Common.Globals.ApplicationPath + "/images/action_right.gif"); DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "ImgLevel2", DotNetNuke.Common.Globals.ApplicationPath + "/images/edit.gif"); DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "OrderNumber", dt.Rows[i]["OrderNumber"].ToString()); MLCategoryInfo fMLCat = MLCategoryController.GetCategory(dt.Rows[i]["CatID"].ToString(), Locale, false); if (fMLCat != null) { if (fMLCat.MLCatName != null) { DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "CatName", fMLCat.MLCatName.StringTextOrFallBack); } else { DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "CatName", fMLCat.CatName); } } else { DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "CatName", dt.Rows[i]["CatName"].ToString()); } DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "Level", dt.Rows[i]["Level"].ToString()); string indent = ""; int level = int.Parse(dt.Rows[i]["Level"].ToString()); for (int j = 1; j < level; j++) { indent += HttpContext.Current.Server.HtmlDecode(" "); } DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "Indent", indent); DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "CatCode", dt.Rows[i]["CatCode"].ToString()); DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "PortalID", dt.Rows[i]["PortalID"].ToString()); DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "link", link); DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "url_edit", url_edit); if (i % 2 == 1) DotNetNuke.NewsProvider.Utils.AddNode(doc, category, "odd", "true"); root.AppendChild(category); } return doc; }
// https://dejanstojanovic.net/aspnet/2018/june/loading-rsa-key-pair-from-pem-files-in-net-core-with-c/ public static RSA FromXmlFile(string xmlFilePath) { RSAParameters parameters = new RSAParameters(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(File.ReadAllText(xmlFilePath)); if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue")) { foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { switch (node.Name) { case "Modulus": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.Modulus = Convert.FromBase64String(node.InnerText); } break; case "Exponent": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.Exponent = Convert.FromBase64String(node.InnerText); } break; case "P": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.P = Convert.FromBase64String(node.InnerText); } break; case "Q": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.Q = Convert.FromBase64String(node.InnerText); } break; case "DP": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.DP = Convert.FromBase64String(node.InnerText); } break; case "DQ": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.DQ = Convert.FromBase64String(node.InnerText); } break; case "InverseQ": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.InverseQ = Convert.FromBase64String(node.InnerText); } break; case "D": if (!string.IsNullOrEmpty(node.InnerText)) { parameters.D = Convert.FromBase64String(node.InnerText); } break; } } } else { throw new Exception("Invalid XML RSA key."); } return(RSA.Create(parameters)); }
/// <summary> /// Loads the section. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="sectionName">Name of the section.</param> /// <returns></returns> private static XmlNode LoadSection(string fileName, string sectionName) { if (string.IsNullOrWhiteSpace(fileName)) { return(null); } var xmlData = _xmlDefault; var attemps = 5; while (true) { try { using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var tr = new StreamReader(fs)) { Thread.Sleep(10); xmlData = tr.ReadToEnd(); if (string.IsNullOrWhiteSpace(xmlData)) { xmlData = _xmlDefault; } break; } } } catch (FileNotFoundException) { xmlData = _xmlDefault; break; } catch (IOException) { attemps--; if (attemps < 0) { throw; } Thread.Sleep(100); } catch (Exception) { throw; } } var xDoc = new XmlDocument() { PreserveWhitespace = true }; xDoc.LoadXml(xmlData); return(xDoc.SelectSingleNode(sectionName)); }
protected void btnIngresar_Click(object sender, EventArgs e) { try { if (txtIngresoRut.Text == "") { return; } Formatos objFor = new Formatos(); string crut = ""; string pasww; Validaciones objValida = new Validaciones(); string RutValidado = objValida.ValidaRut(txtIngresoRut.Text); txtIngresoRut.Text = RutValidado; Session["RutFormateado"] = RutValidado; if (RutValidado == "n") { Response.Write("<script>alert('Rut no valido')</script>"); txtIngresoRut.Text = ""; } else { crut = objFor.QuitaFormatoRut(txtIngresoRut.Text); txtIngresoRut.Text = Session["RutFormateado"].ToString(); pasww = txtPasword.Text; string strXmlAutentica; //<ParametrosIn Rut="1106757" Paswword="1111" /> //11067573 strXmlAutentica = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; strXmlAutentica = "<ParametrosIn Rut=\"" + crut + "\" Password=\"" + pasww + "\" />"; //localhost.Service objService = new localhost.Service(); //string XmlAutentica = objService.AutenticaUsuario(crut, pasww); Service objService = new Service(); Encripta objEnc = new Encripta(); string rutencr = objEnc.Encrit(pasww); string XmlAutentica = objService.AutenticaUsuario(crut, pasww); //string XmlAutentica = "<ParametrosOut><Autorizacion cCodigo=\"0\" Mensaje=\"Autorizado\"/><Perfiles><Perfil cPerfil=\"1\" tPetfil=\"Socio\"/><Perfil cPerfil=\"2\" tPetfil=\"Ahorrante\"/></Perfiles></ParametrosOut>"; txtPasword.Text = XmlAutentica; //////////////////////// XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(XmlAutentica); string strMensaje = ""; string strcCodigo = ""; XmlNodeList lista = xDoc.GetElementsByTagName("Autorizacion"); // XmlNodeList lista = ((XmlElement)personas[0]).GetElementsByTagName("Producto"); foreach (XmlElement nodo in lista) { strcCodigo = nodo.GetAttribute("cCodigo"); strMensaje = nodo.GetAttribute("Mensaje"); //cCodigo = 1 "aceptado 2 Rechazado } //////////////////////// string prueba = strcCodigo; if (strcCodigo == "0") { //Response.Write("<script>alert('Socio existe')</script>"); //carga variables de session string strXmlPersonas = objService.TraePersonas(Int32.Parse(crut)); xDoc.LoadXml(strXmlPersonas); string idCliente = ""; string NombreCompleto = ""; string NumeroControl = ""; XmlNodeList lista2 = xDoc.GetElementsByTagName("Persona"); XmlNodeList lista3 = ((XmlElement)lista2[0]).GetElementsByTagName("DatosPersonales"); foreach (XmlElement nodo in lista3) { XmlNodeList idCliente2 = nodo.GetElementsByTagName("IdCliente"); idCliente = idCliente2[0].InnerText; XmlNodeList objNombre = nodo.GetElementsByTagName("NombreCompleto"); NombreCompleto = objNombre[0].InnerText; XmlNodeList objControl = nodo.GetElementsByTagName("cControl"); NumeroControl = objControl[0].InnerText; } //Response.Write (NumeroControl); //cargado Session["RutFormateado"]; Session["NombreCompleto"] = NombreCompleto; Session["IdCliente"] = idCliente; Session["PaginaActiva"] = "1"; Session["CargaPagina"] = "1"; //fin carga //if (Int32.Parse(NumeroControl) == 1) // Response.Redirect("CambioPasword.aspx"); Response.Redirect("CargaSaldos.aspx?crut=" + crut); //Response.Redirect("FondoInicio.aspx?crut=" + crut); } else { // Response.Write("<script Language=\"javascript\" runat=\"server\">alert('Socio no existe');window.location.href='http://" + Session["IpServidor"].ToString() +"/sitiowebandescoop/default.aspx';</script>"); Response.Write("<script>alert('Usuario Incorrecto');window.location='default.aspx';</script>"); //Page.ClientScript.RegisterStartupScript(this.GetType(), "", "MensageTransaccionRuta('Usuario Incorrecto','default.aspx');", true); return; } txtIngresoRut.Text = ""; txtPasword.Text = ""; txtPasword.Focus(); } } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message.Normalize().Replace("'", "") + "');window.location='default.aspx';</script>"); } }
private void GetXML_DoWork(object sender, DoWorkEventArgs e) { try { XmlDocument doc = new XmlDocument(); WebClient wc = new WebClient(); string creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(":" + password)); wc.Headers[HttpRequestHeader.Authorization] = "Basic " + creds; doc.LoadXml(wc.DownloadString(url)); wc.Dispose(); XmlNode rootNode = doc.SelectSingleNode("root"); XmlNode infoNode = rootNode.SelectSingleNode("information"); XmlNode categoryNode = infoNode.SelectNodes("category")[0]; foundAlbum = false; foundTitle = false; foundArtist = false; foundGenre = false; foreach (XmlNode temp in categoryNode.SelectNodes("info")) { if (temp.Attributes["name"].Value == "album") { Song.Album = temp.InnerText; foundAlbum = true; } if (temp.Attributes["name"].Value == "title") { Song.Title = temp.InnerText; foundTitle = true; } if (temp.Attributes["name"].Value == "artist") { Song.Artist = temp.InnerText; foundArtist = true; } if (temp.Attributes["name"].Value == "genre") { Song.Genre = temp.InnerText; foundGenre = true; } } if (!foundAlbum) { Song.Album = "Unknown"; } if (!foundTitle) { Song.Title = "Unknown"; } if (!foundArtist) { Song.Artist = "Unknown"; } if (!foundGenre) { Song.Genre = "Unknown"; } fileText = GetText(); if (oldFileText != fileText) { string spaces = ""; for (int i = fileText.Length; i < 83; i++) { spaces += " "; } File.WriteAllText(saveFileFullName, fileText + spaces); } oldFileText = fileText; doc = null; rootNode = null; categoryNode = null; } catch (Exception ex) { mainWindowCallbacks.ShowMessage("ERROR IN GETTING INFORMATION", "The following error has ocurred: " + ex.Message.ToString(), false); isRunning = false; runXMLWorker.Enabled = false; btnStartStopText = "Start"; } }
// 当月消费的磁贴 public static void TileNotificate(float cost, float budget, float percentage) { string source = "ms-appx:///Assets/"; // 根据当月消费占预算的比例设置背景颜色 if (percentage < 0.5) { source += "green.png"; } else if (percentage < 0.8) { source += "orange.png"; } else { source += "red.png"; } percentage *= 100; string content = $@" <tile> <visual> <binding template='TileMedium'> <text hint-style='subtitle'>本月:</text> <image src='{source}' placement='background'/> <text hint-style='captionSubtle'>已消费:{cost}</text> <text hint-style='captionSubtle'>消费占比:{percentage}%</text> </binding> <binding template='TileWide'> <text hint-style='subtitle'>本月消费:</text> <image src='{source}' placement='background'/> <text hint-style='bodySubtle' hint-align='center'>已消费:{cost}</text> <text hint-style='bodySubtle' hint-align='center'>预算:{budget}</text> <text hint-style='bodySubtle' hint-align='center'>消费占比:{percentage}%</text> </binding> <binding template='TileLarge'> <text hint-style='subtitle'>本月消费:</text> <image src='{source}' placement='background'/> <text hint-style='bodySubtle' hint-align='center'>已消费:{cost}</text> <text hint-style='bodySubtle' hint-align='center'>预算:{budget}</text> <text hint-style='bodySubtle' hint-align='center'>消费占比:{percentage}%</text> </binding> <binding template='TileSmall'> <image src='{source}' placement='background'/> <text hint-style='captionSubtle'>{cost}</text> <text hint-style='captionSubtle'>{percentage}%</text> </binding> </visual> </tile>"; // Load the string into an XmlDocument XmlDocument doc = new XmlDocument(); doc.LoadXml(content); // Then create the tile notification var notification = new TileNotification(doc); TileUpdateManager.CreateTileUpdaterForApplication().Update(notification); }
public static void SetupNOAA(FlexCelReport reportStart, string CityName, string DataPath, bool UseOfflineData, Dictionary <string, LatLong> Cities) { LatLong CityCoords; GetCity(Cities, CityName, out CityCoords); reportStart.SetValue("Date", DateTime.Now); string forecasts; DateTime dtStart = DateTime.Now; if (UseOfflineData) { using (StreamReader fs = new StreamReader(Path.Combine(DataPath, "OfflineData.xml"))) { forecasts = fs.ReadToEnd(); } } else { ndfdXML nd = new ndfdXML(); forecasts = nd.NDFDgen(CityCoords.Latitude, CityCoords.Longitude, productType.glance, dtStart, dtStart.AddDays(7), unitType.m, new weatherParametersType()); #if (SAVEOFFLINEDATA) using (StreamWriter sw = new StreamWriter(Path.Combine(DataPath, "OfflineData.xml"))) { sw.Write(forecasts); } #endif } if (String.IsNullOrEmpty(forecasts)) { throw new Exception("Can't find the place " + CityName); } DataSet ds = new DataSet(); //Load the data into a dataset. On this web service, we cannot just call DataSet.ReadXml as the data is not on the correct format. XmlDocument xmlDoc = new XmlDocument(); { xmlDoc.LoadXml(forecasts); XmlNodeList HighList = xmlDoc.SelectNodes("/dwml/data/parameters/temperature[@type='maximum']/value/text()"); XmlNodeList LowList = xmlDoc.SelectNodes("/dwml/data/parameters/temperature[@type='minimum']/value/text()"); XmlNodeList IconList = xmlDoc.SelectNodes("/dwml/data/parameters/conditions-icon/icon-link/text()"); DataTable WeatherTable = ds.Tables.Add("Weather"); WeatherTable.Columns.Add("Day", typeof(DateTime)); WeatherTable.Columns.Add("Low", typeof(double)); WeatherTable.Columns.Add("High", typeof(double)); WeatherTable.Columns.Add("Icon", typeof(byte[])); for (int i = 0; i < Math.Min(Math.Min(HighList.Count, LowList.Count), IconList.Count); i++) { WeatherTable.Rows.Add(new object[] { dtStart.AddDays(i), Convert.ToDouble(LowList[i].Value), Convert.ToDouble(HighList[i].Value), LoadIcon(IconList[i].Value, UseOfflineData, DataPath) }); } } reportStart.AddTable(ds, TDisposeMode.DisposeAfterRun); reportStart.SetValue("Latitude", CityCoords.Latitude); reportStart.SetValue("Longitude", CityCoords.Longitude); reportStart.SetValue("Place", CityName); }
protected void Page_Load(object sender, EventArgs e) { if (Session["AppLocation"] == null || Session.Count == 0 || Session["AppUserID"].ToString() == "") { IQCareMsgBox.Show("SessionExpired", this); Response.Redirect("~/frmlogin.aspx", true); } XmlDocument xmlDoc = null; // Get the ID of the action if (base.Session["PRINT_REPORT_ID"] != null) { try { strReport_ID = base.Session["PRINT_REPORT_ID"].ToString(); datefrom = Convert.ToDateTime(base.Session["REPOR_DATE_RANGE_FROM"]); dateTo = Convert.ToDateTime(base.Session["REPOR_DATE_RANGE_TO"]); cd4CutOff = Convert.ToInt32(base.Session["REPORT_CD4_CUTOFF"]); theReports.RunReport(Convert.ToInt16(strReport_ID), datefrom, dateTo, cd4CutOff); xmlDoc = new XmlDocument(); xmlDoc.LoadXml(theReports.GetReportData()); // XmlSchemaInference inference = new XmlSchemaInference(); // MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlDoc.OuterXml.ToString())); //XmlTextReader reader = new XmlTextReader(stream); //XmlSchemaSet schemaSet = inference.InferSchema(reader); ////XmlSchema schema = // IEnumerator en = schemaSet.Schemas().GetEnumerator(); // en.MoveNext(); // XmlSchema schema = (XmlSchema)en.Current; // FileStream file = new FileStream(Server.MapPath("new.xsd"), FileMode.Create, FileAccess.ReadWrite); // XmlTextWriter xwriter = new XmlTextWriter(file, new UTF8Encoding()); // xwriter.Formatting = Formatting.Indented; // schema.Write(xwriter); xslDoc = new XmlDocument(); xslDoc.LoadXml(theReports.ReportXslTemplate); // xslDoc.Save(Server.MapPath("\\" + strReport_ID.ToString() + "xsl.xml")); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xslDoc.NameTable); nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform"); XPathNavigator xslNav = xslDoc.CreateNavigator(); XslCompiledTransform trans = new XslCompiledTransform(); Response.Clear(); Response.ContentType = "text/html; charset=windows-1252"; XsltSettings xslSessings = new XsltSettings(); xslSessings.EnableScript = true; trans.Load(xslNav, xslSessings, new XmlUrlResolver()); trans.Transform(xmlDoc.CreateNavigator(), null, Response.OutputStream); Response.Flush(); } catch (Exception exp) { MsgBuilder theBuilder = new MsgBuilder(); theBuilder.DataElements["MessageText"] = "Please verify the IQTools connection. Please make sure you have IQTools configured properly."; IQCareMsgBox.Show("#C1", theBuilder, this); } } else { return; } }
internal void InitializeMetadata(string epubFolder, string opfPath, string opfXml) { var contentFolder = Path.GetFileName(Path.GetDirectoryName(opfPath)); _opfDocument = new XmlDocument(); _opfDocument.PreserveWhitespace = true; _opfDocument.LoadXml(opfXml); _opfNsmgr = new XmlNamespaceManager(_opfDocument.NameTable); _opfNsmgr.AddNamespace("o", "http://www.idpf.org/2007/opf"); _opfNsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/"); var identifierItem = _opfDocument.SelectSingleNode("/o:package/o:metadata/dc:identifier", _opfNsmgr); Identifier = identifierItem.InnerText; var titleItem = _opfDocument.SelectSingleNode("/o:package/o:metadata/dc:title", _opfNsmgr); Title = titleItem.InnerText; var langItem = _opfDocument.SelectSingleNode("/o:package/o:metadata/dc:language", _opfNsmgr); LanguageCode = langItem.InnerText; var modifiedItem = _opfDocument.SelectSingleNode("/o:package/o:metadata/o:meta[@property='dcterms:modified']", _opfNsmgr); Modified = DateTime.Parse(modifiedItem.InnerText); var descriptionItem = _opfDocument.SelectSingleNode("/o:package/o:metadata/dc:description", _opfNsmgr); if (descriptionItem != null) { Description = descriptionItem.InnerText; } var creatorItems = _opfDocument.SelectNodes("/o:package/o:metadata/dc:creator", _opfNsmgr); foreach (var node in creatorItems) { var creator = node as XmlElement; var id = creator.GetAttribute("id"); var refinementNode = _opfDocument.SelectSingleNode("/o:package/o:metadata/o:meta[@refines='#" + id + "' and @property='role' and @scheme='marc:relators']", _opfNsmgr); if (refinementNode == null || refinementNode.InnerText == "aut") { Authors.Add(creator.InnerText); } else { OtherCreators.Add(creator.InnerText); } } var contributorItems = _opfDocument.SelectNodes("/o:package/o:metadata/dc:contributor", _opfNsmgr); foreach (var node in contributorItems) { var contributor = node as XmlElement; var id = contributor.GetAttribute("id"); var refinementNode = _opfDocument.SelectSingleNode("/o:package/o:metadata/o:meta[@refines='#" + id + "' and @property='role' and @scheme='marc:relators']", _opfNsmgr); if (refinementNode == null || refinementNode.InnerText == "ill") { Illustrators.Add(contributor.InnerText); } else { OtherContributors.Add(contributor.InnerText); } } var chapterItems = _opfDocument.SelectNodes("/o:package/o:manifest/o:item[@media-type='application/xhtml+xml' and @id!='toc' and @id!='nav']", _opfNsmgr); foreach (var node in chapterItems) { var chapter = node as XmlElement; var href = chapter.GetAttribute("href"); PageFiles.Add(Path.Combine(epubFolder, contentFolder, href)); } var imageItems = _opfDocument.SelectNodes("/o:package/o:manifest/o:item[starts-with(@media-type,'image/')]", _opfNsmgr); foreach (var node in imageItems) { var image = node as XmlElement; var href = image.GetAttribute("href"); ImageFiles.Add(Path.Combine(epubFolder, contentFolder, href)); } }
public void TC01_DeleteStripDoc_DeleteDoc() { String strTestCaseNo = "Delete_TC001"; PropertiesCollection.test = PropertiesCollection.extent.CreateTest("TC01_DeleteStripDoc_DeleteDoc"); Object[] ObjDBResponse = new object[7]; //Fetching data from My SQL Database var connection = new ConnectToMySQL_Fetch_TestData(); var testData = connection.Select(strtblname, strTestCaseNo, strTestType); //Connecting to application database and retrieving the current count of documents attached to the strip string strConnectionString = "Data Source=" + ConfigurationManager.AppSettings["SQLServerDataSource"] + ";Initial Catalog=" + ConfigurationManager.AppSettings["SQLServerInitialCatalog"] + ";Integrated Security=" + ConfigurationManager.AppSettings["SQLServerIntegratedSecurity"] + ';'; SqlConnection myConnection = new SqlConnection(strConnectionString); myConnection.Open(); IRestResponse response = DeleteRestRequest(strTestCaseNo); var doc = new XmlDocument(); doc.LoadXml(response.Content); SqlDataReader reader = null; String query; SqlCommand command; //Retrieving & printing the Response code int intRespCode = Get_StatusCode(response); try { Console.WriteLine("intResponse: " + intRespCode); Assert.AreEqual(intRespCode, 200); PropertiesCollection.test.Log(Status.Pass, "Status Response is 200 OK"); } catch { PropertiesCollection.test.Log(Status.Fail, "Status Response is not 200 OK"); } if (intRespCode == 200) { Object[] dbResponse = new object[7]; query = "select count(*) from dbo.tblstripreport where StripReportID = '" + testData[3] + "'"; command = new SqlCommand(query, myConnection); reader = command.ExecuteReader(); try { Assert.AreEqual(query, 0); PropertiesCollection.test.Log(Status.Pass, "Strip Document has been deleted from the Database"); } catch { PropertiesCollection.test.Log(Status.Fail, "Strip Document has not been deleted from the Database"); } try { Assert.AreEqual(doc.GetElementsByTagName("Code")[0].InnerText, "FP004"); PropertiesCollection.test.Log(Status.Pass, "Validation of the Code has passed"); } catch { PropertiesCollection.test.Log(Status.Fail, "Validation of the Code has failed"); } } }
public void HandleErrors_XML_MethodTest() { string xml = "<some></some>"; XmlDocument respXML = new XmlDocument(); respXML.LoadXml(xml); try { IntuitErrorHandler.HandleErrors(xml); } catch (IdsException ex) { if (ex != null && ex.Message != "API response without Error code element.") { Assert.Fail(ex.ToString()); } } xml = "<errcode>401</errcode>"; respXML.LoadXml(xml); try { IntuitErrorHandler.HandleErrors(respXML); } catch (IdsException ex) { if (ex != null && ex.Message != "Error 401") { Assert.Fail(ex.ToString()); } } xml = "<errcode>0</errcode>"; respXML.LoadXml(xml); IntuitErrorHandler.HandleErrors(respXML); xml = "<errcode>failure</errcode>"; respXML.LoadXml(xml); try { IntuitErrorHandler.HandleErrors(respXML); } catch (IdsException ex) { if (ex != null && ex.Message != "Error code \"0\" not numeric!") { Assert.Fail(ex.ToString()); } } xml = "<error><errcode>401</errcode><errtext>there is an error</errtext></error>"; respXML.LoadXml(xml); try { IntuitErrorHandler.HandleErrors(respXML); } catch (IdsException ex) { if (ex != null && ex.Message != "there is an error (Error 401)") { Assert.Fail(ex.ToString()); } } xml = "<error><errcode>401</errcode><errtext>there is an error</errtext><errdetail>error detail</errdetail></error>"; respXML.LoadXml(xml); try { IntuitErrorHandler.HandleErrors(respXML); } catch (IdsException ex) { if (ex != null && ex.Message != "there is an error (Error 401, Detail: error detail)") { Assert.Fail(ex.ToString()); } } }
/// <summary> /// Add an attribute metadata /// </summary> /// <param name="amd">Attribute metadata</param> /// <param name="sheet">Worksheet where to write</param> public void AddAttribute(AttributeMetadata amd, ExcelWorksheet sheet) { var y = 1; if (!attributesHeaderAdded) { InsertAttributeHeader(sheet, lineNumber, y); attributesHeaderAdded = true; } lineNumber++; sheet.Cells[lineNumber, y].Value = (amd.LogicalName); y++; sheet.Cells[lineNumber, y].Value = (amd.SchemaName); y++; var amdDisplayName = amd.DisplayName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode); sheet.Cells[lineNumber, y].Value = (amd.DisplayName.LocalizedLabels.Count == 0 ? "N/A" : amdDisplayName != null ? amdDisplayName.Label : ""); y++; if (amd.AttributeType != null) { sheet.Cells[lineNumber, y].Value = (amd.AttributeType.Value.ToString()); } y++; var amdDescription = amd.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode); sheet.Cells[lineNumber, y].Value = (amd.Description.LocalizedLabels.Count == 0 ? "N/A" : amdDescription != null ? amdDescription.Label : ""); y++; sheet.Cells[lineNumber, y].Value = ((amd.IsCustomAttribute != null && amd.IsCustomAttribute.Value).ToString(CultureInfo.InvariantCulture)); y++; if (settings.AddRequiredLevelInformation) { sheet.Cells[lineNumber, y].Value = (amd.RequiredLevel.Value.ToString()); y++; } if (settings.AddValidForAdvancedFind) { sheet.Cells[lineNumber, y].Value = (amd.IsValidForAdvancedFind.Value.ToString(CultureInfo.InvariantCulture)); y++; } if (settings.AddAuditInformation) { sheet.Cells[lineNumber, y].Value = (amd.IsAuditEnabled.Value.ToString(CultureInfo.InvariantCulture)); y++; } if (settings.AddFieldSecureInformation) { sheet.Cells[lineNumber, y].Value = ((amd.IsSecured != null && amd.IsSecured.Value).ToString(CultureInfo.InvariantCulture)); y++; } if (settings.AddFormLocation) { var entity = settings.EntitiesToProceed.FirstOrDefault(e => e.Name == amd.EntityLogicalName); if (entity != null) { foreach (var form in entity.FormsDefinitions.Where(fd => entity.Forms.Contains(fd.Id) || entity.Forms.Count == 0)) { var formName = form.GetAttributeValue <string>("name"); var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(form["formxml"].ToString()); var controlNode = xmlDocument.SelectSingleNode("//control[@datafieldname='" + amd.LogicalName + "']"); if (controlNode != null) { XmlNodeList sectionNodes = controlNode.SelectNodes("ancestor::section"); XmlNodeList headerNodes = controlNode.SelectNodes("ancestor::header"); XmlNodeList footerNodes = controlNode.SelectNodes("ancestor::footer"); if (sectionNodes.Count > 0) { if (sectionNodes[0].SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']") != null) { var sectionName = sectionNodes[0].SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']").Attributes["description"].Value; XmlNode tabNode = sectionNodes[0].SelectNodes("ancestor::tab")[0]; if (tabNode != null && tabNode.SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']") != null) { var tabName = tabNode.SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']").Attributes["description"].Value; if (sheet.Cells[lineNumber, y].Value != null) { sheet.Cells[lineNumber, y].Value = sheet.Cells[lineNumber, y].Value + "\r\n" + string.Format("{0}/{1}/{2}", formName, tabName, sectionName); } else { sheet.Cells[lineNumber, y].Value = string.Format("{0}/{1}/{2}", formName, tabName, sectionName); } } } } else if (headerNodes.Count > 0) { if (sheet.Cells[lineNumber, y].Value != null) { sheet.Cells[lineNumber, y].Value = sheet.Cells[lineNumber, y].Value + "\r\n" + string.Format("{0}/Header", formName); } else { sheet.Cells[lineNumber, y].Value = string.Format("{0}/Header", formName); } } else if (footerNodes.Count > 0) { if (sheet.Cells[lineNumber, y].Value != null) { sheet.Cells[lineNumber, y].Value = sheet.Cells[lineNumber, y].Value + "\r\n" + string.Format("{0}/Footer", formName); } else { sheet.Cells[lineNumber, y].Value = string.Format("{0}/Footer", formName); } } } } } sheet.Column(y).PageBreak = true; y++; } sheet.Column(y).PageBreak = true; AddAdditionalData(lineNumber, y, amd, sheet); }
protected void Page_Load(object sender, EventArgs e) { BLLJIMP.BllOrder bllOrder = new BLLJIMP.BllOrder(); BLLJIMP.BLLUser bllUser = new BLLJIMP.BLLUser(""); Dictionary <string, string> dicAll = bllOrder.GetRequestParameter(); if (dicAll.Count > 0)//判断是否有带返回参数 { Notify notify = new Notify(); bool verifyResult = notify.VerifyNotify(dicAll, dicAll["sign"]); if (verifyResult)//验证成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //请在这里加上商户的业务逻辑程序代码 //——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表 //解密(如果是RSA签名需要解密,如果是MD5签名则下面一行清注释掉) //sPara = aliNotify.Decrypt(sPara); //XML解析notify_data数据 try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(dicAll["notify_data"]); xmlDoc.Save(string.Format("C:\\Alipay\\notify{0}.xml", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); //商户订单号 string outTradeNo = xmlDoc.SelectSingleNode("/notify/out_trade_no").InnerText; //支付宝交易号 string tradeNo = xmlDoc.SelectSingleNode("/notify/trade_no").InnerText; //交易状态 string tradeStatus = xmlDoc.SelectSingleNode("/notify/trade_status").InnerText; var orderPay = bllOrder.GetOrderPay(outTradeNo); if (tradeStatus == "TRADE_FINISHED") { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 //注意: //该种交易状态只在两种情况下出现 //1、开通了普通即时到账,买家付款成功后。 //2、开通了高级即时到账,从该笔交易成功时间算起,过了签约时的可退款时限(如:三个月以内可退款、一年以内可退款等)后。 if (orderPay.Status.Equals(0)) //只有未付款状态 { if (orderPay.Type.Equals("1")) //投票充值 { ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction(); try { UserInfo userInfo = bllUser.GetUserInfo(orderPay.UserId); if (userInfo.AvailableVoteCount == null) { userInfo.AvailableVoteCount = 0; } userInfo.AvailableVoteCount += int.Parse(orderPay.Ex1); orderPay.Status = 1; orderPay.Trade_No = tradeNo; if (!bllOrder.Update(orderPay, tran)) { tran.Rollback(); Response.Write("fail"); } if (bllUser.Update(userInfo, string.Format(" AvailableVoteCount={0}", userInfo.AvailableVoteCount), string.Format(" AutoID={0}", userInfo.AutoID), tran) < 1) { tran.Rollback(); Response.Write("fail"); } tran.Commit(); Response.Write("success"); //请不要修改或删除 } catch (Exception ex) { tran.Rollback(); Response.Write("fail"); } } else { } } Response.Write("success"); //请不要修改或删除 } else if (tradeStatus == "TRADE_SUCCESS") { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 //注意: //该种交易状态只在一种情况下出现——开通了高级即时到账,买家付款成功后。 if (orderPay.Status.Equals(0)) //只有未付款状态 { if (orderPay.Type.Equals(1)) //投票充值 { ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZCBLLEngine.BLLTransaction(); try { UserInfo userInfo = bllUser.GetUserInfo(orderPay.UserId); if (userInfo.AvailableVoteCount == null) { userInfo.AvailableVoteCount = 0; } userInfo.AvailableVoteCount += int.Parse(orderPay.Ex1); orderPay.Status = 1; orderPay.Trade_No = tradeNo; if (!bllOrder.Update(orderPay, tran)) { tran.Rollback(); Response.Write("fail"); } if (bllUser.Update(userInfo, string.Format(" AvailableVoteCount={0}", userInfo.AvailableVoteCount), string.Format(" AutoID={0}", userInfo.AutoID), tran) < 1) { tran.Rollback(); Response.Write("fail"); } tran.Commit(); Response.Write("success"); //请不要修改或删除 } catch (Exception Ex) { tran.Rollback(); Response.Write("fail"); } } else { } } Response.Write("success"); //请不要修改或删除 } else { Response.Write(tradeStatus); } } catch (Exception Ex) { Response.Write("fail"); } //——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— ///////////////////////////////////////////////////////////////////////////////////////////////////////////// } else//验证失败 { Response.Write("fail"); } } else { Response.Write("无通知参数"); } }
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { labelPleaseWait.Text = string.Empty; if (e.Error != null) { MessageBox.Show(string.Format(_language.UnableToDownloadPluginListX, e.Error.Message)); if (e.Error.InnerException != null) { MessageBox.Show(e.Error.InnerException.Source + ": " + e.Error.InnerException.Message + Environment.NewLine + Environment.NewLine + e.Error.InnerException.StackTrace); } return; } _updateAllListUrls = new List <string>(); _updateAllListNames = new List <string>(); listViewGetPlugins.BeginUpdate(); try { _pluginDoc.LoadXml(e.Result); string[] arr = _pluginDoc.DocumentElement.SelectSingleNode("SubtitleEditVersion").InnerText.Split(new[] { '.', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); double requiredVersion = Convert.ToDouble(arr[0] + "." + arr[1], CultureInfo.InvariantCulture); string[] versionInfo = Utilities.AssemblyVersion.Split('.'); double currentVersion = Convert.ToDouble(versionInfo[0] + "." + versionInfo[1], CultureInfo.InvariantCulture); if (currentVersion < requiredVersion) { MessageBox.Show(_language.NewVersionOfSubtitleEditRequired); DialogResult = DialogResult.Cancel; return; } foreach (XmlNode node in _pluginDoc.DocumentElement.SelectNodes("Plugin")) { var item = new ListViewItem(node.SelectSingleNode("Name").InnerText.Trim('.')); item.SubItems.Add(node.SelectSingleNode("Description").InnerText); item.SubItems.Add(node.SelectSingleNode("Version").InnerText); item.SubItems.Add(node.SelectSingleNode("Date").InnerText); listViewGetPlugins.Items.Add(item); foreach (ListViewItem installed in listViewInstalledPlugins.Items) { var installedVer = Convert.ToDouble(installed.SubItems[2].Text.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "."), CultureInfo.InvariantCulture); var currentVer = Convert.ToDouble(node.SelectSingleNode("Version").InnerText.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "."), CultureInfo.InvariantCulture); if (string.Compare(installed.Text, node.SelectSingleNode("Name").InnerText.Trim('.'), StringComparison.OrdinalIgnoreCase) == 0 && installedVer < currentVer) { //item.BackColor = Color.LightGreen; installed.BackColor = Color.LightPink; installed.SubItems[1].Text = _language.UpdateAvailable + " " + installed.SubItems[1].Text; buttonUpdateAll.Visible = true; _updateAllListUrls.Add(node.SelectSingleNode("Url").InnerText); _updateAllListNames.Add(node.SelectSingleNode("Name").InnerText); } } } } catch (Exception exception) { MessageBox.Show(string.Format(_language.UnableToDownloadPluginListX, exception.Source + ": " + exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace)); } listViewGetPlugins.EndUpdate(); if (_updateAllListUrls.Count > 0) { buttonUpdateAll.BackColor = Color.LightGreen; if (Configuration.Settings.Language.PluginsGet.UpdateAllX != null) { buttonUpdateAll.Text = string.Format(Configuration.Settings.Language.PluginsGet.UpdateAllX, _updateAllListUrls.Count); } else { buttonUpdateAll.Text = Configuration.Settings.Language.PluginsGet.UpdateAll; } buttonUpdateAll.Visible = true; } }
public void Generate(IOrganizationService service) { ExcelWorksheet summarySheet = null; if (settings.AddEntitiesSummary) { summaryLineNumber = 1; summarySheet = AddWorkSheet("Entities list"); } int totalEntities = settings.EntitiesToProceed.Count; int processed = 0; foreach (var entity in settings.EntitiesToProceed.OrderBy(e => e.Name)) { ReportProgress(processed * 100 / totalEntities, string.Format("Processing entity '{0}'...", entity.Name)); var emd = emdCache.FirstOrDefault(x => x.LogicalName == entity.Name); if (emd == null) { var reRequest = new RetrieveEntityRequest { LogicalName = entity.Name, EntityFilters = EntityFilters.Entity | EntityFilters.Attributes }; var reResponse = (RetrieveEntityResponse)service.Execute(reRequest); emdCache.Add(reResponse.EntityMetadata); emd = reResponse.EntityMetadata; } if (settings.AddEntitiesSummary) { AddEntityMetadataInLine(emd, summarySheet); } lineNumber = 1; var emdDisplayNameLabel = emd.DisplayName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode); var sheet = AddWorkSheet(emdDisplayNameLabel == null ? "N/A" : emdDisplayNameLabel.Label, emd.SchemaName); if (!settings.AddEntitiesSummary) { AddEntityMetadata(emd, sheet); } if (settings.AddFormLocation) { currentEntityForms = MetadataHelper.RetrieveEntityFormList(emd.LogicalName, service); } List <AttributeMetadata> amds = new List <AttributeMetadata>(); switch (settings.AttributesSelection) { case AttributeSelectionOption.AllAttributes: amds = emd.Attributes.ToList(); break; case AttributeSelectionOption.AttributesOptionSet: amds = emd.Attributes.Where( x => x.AttributeType != null && (x.AttributeType.Value == AttributeTypeCode.Boolean || x.AttributeType.Value == AttributeTypeCode.Picklist || x.AttributeType.Value == AttributeTypeCode.State || x.AttributeType.Value == AttributeTypeCode.Status)).ToList(); break; case AttributeSelectionOption.AttributeManualySelected: amds = emd.Attributes.Where( x => settings.EntitiesToProceed.FirstOrDefault(y => y.Name == emd.LogicalName).Attributes.Contains( x.LogicalName)).ToList(); break; case AttributeSelectionOption.AttributesOnForm: // If no forms selected, we search attributes in all forms if (entity.Forms.Count == 0) { foreach (var form in entity.FormsDefinitions) { var tempStringDoc = form.GetAttributeValue <string>("formxml"); var tempDoc = new XmlDocument(); tempDoc.LoadXml(tempStringDoc); amds.AddRange(emd.Attributes.Where(x => tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") != null)); } } else { // else we parse selected forms foreach (var formId in entity.Forms) { var form = entity.FormsDefinitions.FirstOrDefault(f => f.Id == formId); var tempStringDoc = form.GetAttributeValue <string>("formxml"); var tempDoc = new XmlDocument(); tempDoc.LoadXml(tempStringDoc); amds.AddRange(emd.Attributes.Where(x => tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") != null)); } } break; case AttributeSelectionOption.AttributesNotOnForm: // If no forms selected, we search attributes in all forms if (entity.Forms.Count == 0) { foreach (var form in entity.FormsDefinitions) { var tempStringDoc = form.GetAttributeValue <string>("formxml"); var tempDoc = new XmlDocument(); tempDoc.LoadXml(tempStringDoc); amds.AddRange(emd.Attributes.Where(x => tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") == null)); } } else { // else we parse selected forms foreach (var formId in entity.Forms) { var form = entity.FormsDefinitions.FirstOrDefault(f => f.Id == formId); var tempStringDoc = form.GetAttributeValue <string>("formxml"); var tempDoc = new XmlDocument(); tempDoc.LoadXml(tempStringDoc); amds.AddRange(emd.Attributes.Where(x => tempDoc.SelectSingleNode("//control[@datafieldname='" + x.LogicalName + "']") == null)); } } break; } if (settings.Prefixes != null && settings.Prefixes.Count > 0) { var filteredAmds = new List <AttributeMetadata>(); foreach (var prefix in settings.Prefixes) { filteredAmds.AddRange(amds.Where(a => a.LogicalName.StartsWith(prefix) /*|| a.IsCustomAttribute.Value == false*/)); } amds = filteredAmds; } if (amds.Any()) { foreach (var amd in amds.Distinct(new AttributeMetadataComparer()).OrderBy(a => a.LogicalName)) { AddAttribute(emd.Attributes.FirstOrDefault(x => x.LogicalName == amd.LogicalName), sheet); } } else { Write("no attributes to display", sheet, 1, !settings.AddEntitiesSummary ? 10 : 1); } sheet.Cells[sheet.Dimension.Address].AutoFitColumns(); processed++; } if (settings.AddEntitiesSummary) { summarySheet.Cells[summarySheet.Dimension.Address].AutoFitColumns(); } SaveDocument(settings.FilePath); }
public override string ToText(Subtitle subtitle, string title) { string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<tt xmlns=\"http://www.w3.org/2006/10/ttaf1\" xmlns:ttp=\"http://www.w3.org/2006/10/ttaf1#parameter\" ttp:timeBase=\"media\" xmlns:tts=\"http://www.w3.org/2006/10/ttaf1#style\" xml:lang=\"en\" xmlns:ttm=\"http://www.w3.org/2006/10/ttaf1#metadata\">" + Environment.NewLine + " <head>" + Environment.NewLine + " <metadata>" + Environment.NewLine + " <ttm:title></ttm:title>" + Environment.NewLine + " </metadata>" + Environment.NewLine + " <styling>" + Environment.NewLine + " <style id=\"s0\" tts:backgroundColor=\"black\" tts:fontStyle=\"normal\" tts:fontSize=\"16\" tts:fontFamily=\"sansSerif\" tts:color=\"white\" />" + Environment.NewLine + " </styling>" + Environment.NewLine + " </head>" + Environment.NewLine + " <body tts:textAlign=\"center\" style=\"s0\">" + Environment.NewLine + " <div />" + Environment.NewLine + " </body>" + Environment.NewLine + "</tt>"; var xml = new XmlDocument(); xml.LoadXml(xmlStructure); var nsmgr = new XmlNamespaceManager(xml.NameTable); nsmgr.AddNamespace("ttaf1", "http://www.w3.org/2006/10/ttaf1"); nsmgr.AddNamespace("ttp", "http://www.w3.org/2006/10/ttaf1#parameter"); nsmgr.AddNamespace("tts", "http://www.w3.org/2006/10/ttaf1#style"); nsmgr.AddNamespace("ttm", "http://www.w3.org/2006/10/ttaf1#metadata"); XmlNode titleNode = xml.DocumentElement.SelectSingleNode("//ttaf1:head", nsmgr).FirstChild.FirstChild; titleNode.InnerText = title; XmlNode div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr); if (div == null) div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild; int no = 0; foreach (Paragraph p in subtitle.Paragraphs) { XmlNode paragraph = xml.CreateElement("p", "http://www.w3.org/2006/10/ttaf1"); string text = p.Text.Replace(Environment.NewLine, "\n").Replace("\n", "@iNEWLINE__"); text = HtmlUtil.RemoveHtmlTags(text); paragraph.InnerText = text; paragraph.InnerXml = paragraph.InnerXml.Replace("@iNEWLINE__", "<br />"); XmlAttribute start = xml.CreateAttribute("begin"); start.InnerText = ConvertToTimeString(p.StartTime); paragraph.Attributes.Append(start); XmlAttribute id = xml.CreateAttribute("id"); id.InnerText = "p" + no; paragraph.Attributes.Append(id); XmlAttribute end = xml.CreateAttribute("end"); end.InnerText = ConvertToTimeString(p.EndTime); paragraph.Attributes.Append(end); div.AppendChild(paragraph); no++; } string s = ToUtf8XmlString(xml); s = s.Replace(" xmlns=\"\"", string.Empty); return s; }
public void Load(string file) { using (FileStream fs = File.OpenRead(file)) { var buf = new byte[1024]; int nread, i; if ((nread = fs.Read(buf, 0, buf.Length)) <= 0) { return; } if (ByteOrderMark.TryParse(buf, nread, out bom)) { i = bom.Length; } else { i = 0; } do { // Read to the first newline to figure out which line endings this file is using while (i < nread) { if (buf[i] == '\r') { newLine = "\r\n"; break; } else if (buf[i] == '\n') { newLine = "\n"; break; } i++; } if (newLine == null) { if ((nread = fs.Read(buf, 0, buf.Length)) <= 0) { newLine = "\n"; break; } i = 0; } } while (newLine == null); // Check for a blank line at the end endsWithEmptyLine = fs.Seek(-1, SeekOrigin.End) > 0 && fs.ReadByte() == '\n'; } // Load the XML document doc = new XmlDocument(); doc.PreserveWhitespace = false; // HACK: XmlStreamReader will fail if the file is encoded in UTF-8 but has <?xml version="1.0" encoding="utf-16"?> // To work around this, we load the XML content into a string and use XmlDocument.LoadXml() instead. string xml = File.ReadAllText(file); doc.LoadXml(xml); }
public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName) { _errorCount = 0; FrameRate = Configuration.Settings.General.CurrentFrameRate; var sb = new StringBuilder(); lines.ForEach(line => sb.AppendLine(line)); string x = sb.ToString(); if (!x.Contains("<fcpxml version=\"1.3\"") && !x.Contains("<fcpxml version=\"1.2\"")) { return; } var xml = new XmlDocument(); try { xml.XmlResolver = null; xml.LoadXml(x.Trim()); foreach (XmlNode node in xml.SelectNodes("//project/sequence/spine/clip/video/param[@name='Text']")) { try { string text = node.Attributes["value"].InnerText; Paragraph p = new Paragraph(); p.Text = text.Trim(); p.StartTime = DecodeTime(node.ParentNode.Attributes["offset"]); p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + DecodeTime(node.ParentNode.Attributes["duration"]).TotalMilliseconds; subtitle.Paragraphs.Add(p); } catch { _errorCount++; } } if (subtitle.Paragraphs.Count == 0) { foreach (XmlNode node in xml.SelectNodes("//project/sequence/spine/clip/title/text")) { try { string text = node.ParentNode.InnerText; Paragraph p = new Paragraph(); p.Text = text.Trim(); p.StartTime = DecodeTime(node.ParentNode.Attributes["offset"]); p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + DecodeTime(node.ParentNode.Attributes["duration"]).TotalMilliseconds; bool add = true; if (subtitle.Paragraphs.Count > 0) { var prev = subtitle.Paragraphs[subtitle.Paragraphs.Count - 1]; if (prev.Text == p.Text && prev.StartTime.TotalMilliseconds == p.StartTime.TotalMilliseconds) { add = false; } } if (add) { subtitle.Paragraphs.Add(p); } } catch { _errorCount++; } } } subtitle.Renumber(1); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.Message); _errorCount = 1; return; } }
public static void ElementWithNoChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top />"); Assert.Null(xmlDocument.DocumentElement.FirstChild); }
IEnumerator LoadConfig() { Debug.Log("WeaveAppLoader -> LoadConfig()"); XmlDocument config = new XmlDocument(); if(_filePath == "") { // Load from Resources Debug.Log("Loading From Resources"); TextAsset textAsset = (TextAsset)Resources.Load("config/weave_config"); config.LoadXml(textAsset.text); } else { string url = _filePath + "config/weave_config.xml"; WWW www = new WWW(url); yield return www; if(www.error == null) { Debug.Log("Loading weave_config.xml from filePath"); string xml = www.text; config.LoadXml(xml); } else { Debug.Log("Error: " +www.error +" - loading from resources"); TextAsset textAsset = (TextAsset)Resources.Load("config/weave_config.xml"); config.LoadXml(textAsset.text); } } DataModel.Instance.Config = config; StartCoroutine(LoadPeople()); }
public void xmltranslate(string url, string queryString) { HttpRequest Request = HttpContext.Current.Request; string callback = Request["callback"]; HttpContext.Current.Response.ContentType = "application/json;charset=utf-8"; HttpResponse Response = HttpContext.Current.Response; // string url = "http://www.tianditu.com/query.shtml?"; // string queryString = "postStr={'orig':'116.35506,39.92277','dest':'116.39751,39.90854','mid':'116.36506,39.91277;116.37506,39.92077','style':'0'}&type=search"; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString); httpWebRequest.ContentType="text/xml"; httpWebRequest.Method="GET"; HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close(); streamReader.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(responseContent); string json = JsonConvert.SerializeXmlNode(doc); //return json; Response.Write(callback + "(" + json + ")"); ; Response.End(); }