/// <summary> /// Load a new shader /// </summary> /// <param name="vertexShader">The vertexshader.</param> /// <param name="fragmentShader">The fragmentshader</param> public static Shader Load(StringReader vertexShader, StringReader fragmentShader) { var shader = new Shader(); string vertexShaderCode = vertexShader.ReadToEnd(); string fragmentShaderCode = fragmentShader.ReadToEnd(); if (string.IsNullOrEmpty(vertexShaderCode) && string.IsNullOrEmpty(fragmentShaderCode)) { throw new InvalidOperationException("Both vertex and fragement shader code are empty."); } if (string.IsNullOrEmpty(vertexShaderCode) == false) { shader.AttachShaderCode(vertexShaderCode, ShaderType.VertexShader); } if (string.IsNullOrEmpty(fragmentShaderCode) == false) { shader.AttachShaderCode(fragmentShaderCode, ShaderType.FragmentShader); } shader.Build(); return shader; }
public static string GetFileAsString(string file) { using (StringReader reader = new StringReader(file)) { return reader.ReadToEnd(); } }
static void Main(string[] args) { StringWriter w = new StringWriter(); w.WriteLine("Sing a song of {0} pence", 6); string s = "A pocket full of rye"; w.Write(s); w.Write(w.NewLine); w.Write(string.Format(4 + " and " + 20 + " blackbirds")); w.Write(new StringBuilder(" baked in a pie")); w.WriteLine(); Console.WriteLine(w); StringBuilder sb = w.GetStringBuilder(); int i = sb.Length; sb.Append("The birds began to sing"); sb.Insert(i, "when the pie was opened\n"); sb.AppendFormat("\nWasn't that a {0} to set before the king", "dainty dish"); Console.WriteLine(w); Console.WriteLine(); StringReader r = new StringReader(w.ToString()); string t = r.ReadLine(); Console.WriteLine(t); Console.Write((char)r.Read()); char[] ca = new char[37]; r.Read(ca, 0, 19); Console.Write(ca); Console.WriteLine(r.ReadToEnd()); r.Close(); w.Close(); Console.ReadLine(); }
/// <summary> /// Initializes a new instance of Template with specified StringReader containing template text. /// </summary> /// <param name="reader">StringReader containing template text.</param> public Template(StringReader reader) { if(reader == null) throw new ArgumentNullException("reader"); this.data = reader.ReadToEnd(); }
public static string ExtractQuery(string fileName, TextWriter errorlogger) { try { string data = File.ReadAllText(fileName); XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.None); Stream xmlFragment = new MemoryStream(Encoding.UTF8.GetBytes(data)); XmlTextReader reader = new XmlTextReader(xmlFragment, XmlNodeType.Element, context); reader.MoveToContent(); if (reader.NodeType == XmlNodeType.Text) { return data; } XmlReader reader2 = reader.ReadSubtree(); StringBuilder output = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(output)) { writer.WriteNode(reader2, true); } StringReader reader3 = new StringReader(data); for (int i = 0; i < reader.LineNumber; i++) { reader3.ReadLine(); } return reader3.ReadToEnd().Trim(); } catch (Exception ex) { errorlogger.WriteLine(ex.Message); errorlogger.WriteLine(ex.StackTrace); } return string.Format("//Error loading the file - {0} .The the linq file might be a linqpad expression which is not supported in the viewer currently." ,fileName); }
public override string getText() { if (text != null && text.Length > 0) return text; if (file_read) return null; file_read = true; String uiroot = MainProgram.theApplication.getUIRoot(); Debug.Assert(uiroot != null); if (uiroot.ToCharArray()[uiroot.Length-1] != '/') uiroot += "/"; if (Parent == null || Parent.Name == null) return null; uiroot += "/ui/" + Parent.Name; try { TextReader tr = new StringReader(uiroot); text = tr.ReadToEnd(); } catch (Exception e) { return null; } return text; }
public void Build(ScriptInfo script) { using (TextReader reader = new StringReader(script.Code)) { string line; while ((line = reader.ReadLine()) != null) { MatchCollection matches = _regex.Matches(line); if (matches.Count == 1) { Match match = matches[0]; string family = match.Groups["family"].Value; string name = match.Groups["name"].Value; BuildDependency(script, family, name); } else { while (line == "|") { line = reader.ReadLine(); } break; } } script.Code = string.Format("{1}{0}{2}{0}", Environment.NewLine, line, reader.ReadToEnd()); } }
private IEnumerable<FeedItem> ExtractFeedItemsFromSyndicationString(string value) { var items = new List<FeedItem>(); using (StringReader stringReader = new StringReader(value)) { string content = stringReader.ReadToEnd(); content = content.Replace("-0001 00:00:00 +0000", string.Format("{0} 00:00:00 +0000", DateTime.Now.Year)); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(content); using (XmlReader reader = XmlReader.Create(new MemoryStream(bytes))) { SyndicationFeed feed = SyndicationFeed.Load(reader); foreach (SyndicationItem item in feed.Items) { try { items.Add(new FeedItem() { Title = htmlConverter.Convert(item.Title.Text), Summary = htmlConverter.Convert(item.Summary.Text), Url = item.Links[0].Uri, PublishedDate = item.PublishDate.DateTime.AddHours(5).ToLocalTime(), // adjust for EST IsNew = true }); } catch (Exception) { // ignore individual errors } } } } return items; }
/// <summary> /// 单独展示时解析XML /// </summary> /// <param name="fileInfo"></param> /// <returns></returns> public static List <SingleCurtain> SingleReadInfo(string fileInfo) { List <SingleCurtain> LoadList = new List <SingleCurtain>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); //stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["stylor_list"].ChildNodes) { SingleCurtain newExcel = new SingleCurtain(); //newExcel.IsModel = bool.Parse(item["IsModel"].InnerText); //newExcel.Description = item["Description"].InnerText; newExcel.TextureUrl = item.Attributes["stylor_file_url"].Value; newExcel.Stylor_code = item.Attributes["stylor_code"].Value; newExcel.Name = item.Attributes["stylor_name"].Value; //newExcel.Curtain_kind = item.Attributes["prod_kind"].Value; LoadList.Add(newExcel); } return(LoadList); }
/// <summary> /// Parsea el Header del XML para obtener la info /// </summary> /// <returns>Estructura con la info del nivel</returns> private LevelInfo ParseHeader() { // Variable contenedora de la info var levelInfo = new LevelInfo(); // Parsea el XML using (var stringReader = new System.IO.StringReader(_XMLsource.text)) { var xml = XDocument.Parse(stringReader.ReadToEnd()); levelInfo.Version = xml.Root.Element("Version").Value; levelInfo.LevelName = xml.Root.Element("Data").Element("Name").Value; levelInfo.Difficulty = int.Parse(xml.Root.Element("Data").Element("Difficulty").Value); levelInfo.GoldScore = float.Parse(xml.Root.Element("Data").Element("GoldScore").Value); levelInfo.SilverScore = float.Parse(xml.Root.Element("Data").Element("SilverScore").Value); levelInfo.BronzeScore = float.Parse(xml.Root.Element("Data").Element("BronzeScore").Value); levelInfo.Rewinds = int.Parse(xml.Root.Element("Data").Element("Rewinds").Value); levelInfo.Size = new IntVector3( int.Parse(xml.Root.Element("Data").Element("Size").Element("X").Value), int.Parse(xml.Root.Element("Data").Element("Size").Element("Y").Value), int.Parse(xml.Root.Element("Data").Element("Size").Element("Z").Value) ); } return(levelInfo); }
public static void StringReaderWithEmptyString() { // [] Check vanilla construction //----------------------------------------------------------- StringReader sr = new StringReader(string.Empty); Assert.Equal(string.Empty, sr.ReadToEnd()); }
public static List <StyleInfo> ReadStyleXML(int HouseID, int SceneID, string fileInfo) { List <StyleInfo> LoadList = new List <StyleInfo>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { StyleInfo newData = new StyleInfo(); newData.HouseID = int.Parse(item["House"].InnerText); if (newData.HouseID == HouseID) { newData.SceneID = int.Parse(item["Scene"].InnerText); if (newData.SceneID == SceneID) { newData.URL = item["URL"].InnerText; newData.IconUrl = item["Icon"].InnerText; newData.description = item["Description"].InnerText; LoadList.Add(newData); } } } return(LoadList); }
public override void WriteLine(string format, params object[] arg) { base.WriteLine(format, arg); TextReader stringReader = new StringReader(this.ToString()); String[] s = stringReader.ReadToEnd().Split(Environment.NewLine.ToCharArray()); //for (int i = 0; i < s.Length; i++) if (s[i].Trim().Length > 0) xbs_messages.addDebugMessage(" @ UPnP log: " + s[i].Trim()); }
public async Task<object> GetAsync(string key, Type type) { var encrypted = await m_inner.GetAsync(key, typeof(Encrypted)) as Encrypted; if (encrypted == null) { return null; } try { string decryptedValue = m_cryptographer.Decrypt(m_encryptionKey, encrypted); using (var reader = new StringReader(decryptedValue)) { if (type == typeof(string)) { return reader.ReadToEnd(); } return HealthVaultClient.Serializer.Deserialize(reader, type, null); } } catch (Exception) { return null; } }
/// <summary> /// 解析整体XML /// </summary> /// <param name="fileInfo"></param> /// <returns></returns> public static List <AssetInfo> ReadAllAsset(string fileInfo) { List <AssetInfo> LoadList = new List <AssetInfo>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); //stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["prod_list"].ChildNodes) { AssetInfo myasset = new AssetInfo(); myasset.Icon = item.Attributes["prod_pic_url"].Value; myasset.isModle = true; myasset.Name = item.Attributes["prod_name"].Value; myasset.ProdId = item.Attributes["prod_id"].Value; LoadList.Add(myasset); } //AssetInfo my = new AssetInfo(); //my.Icon = "quanbu2_2"; //my.DefaultTexture = "Texture"; //my.isModle = false; //LoadList.Add(my); return(LoadList); }
/// <summary> /// Converts a string to a number (used by parseFloat). /// </summary> /// <param name="input"> The string to convert. </param> /// <returns> The result of parsing the string as a number. </returns> internal static double ParseFloat(string input) { var reader = new System.IO.StringReader(input); // Skip whitespace and line terminators. while (IsWhiteSpaceOrLineTerminator(reader.Peek())) { reader.Read(); } // The number can start with a plus or minus sign. bool negative = false; int firstChar = reader.Read(); switch (firstChar) { case '-': negative = true; firstChar = reader.Read(); break; case '+': firstChar = reader.Read(); break; } // Infinity or -Infinity are also valid. if (firstChar == 'I') { var nfinityString = reader.ReadToEnd(); if (nfinityString == null) { throw new InvalidOperationException("Reader returned null."); } if (nfinityString.StartsWith("nfinity", StringComparison.Ordinal)) { return(negative ? double.NegativeInfinity : double.PositiveInfinity); } } // Empty strings return NaN. if ((firstChar < '0' || firstChar > '9') && firstChar != '.') { return(double.NaN); } // Parse the number. NumberParser.ParseCoreStatus status; var result = NumberParser.ParseCore(reader, (char)firstChar, out status, false, false); // Handle various error cases. if (status == ParseCoreStatus.NoDigits) { return(double.NaN); } return(negative ? -result : result); }
public static void StringReaderWithGenericString() { // [] Another vanilla construction //----------------------------------------------------------- StringReader sr = new StringReader("Hello\0World"); Assert.Equal("Hello\0World", sr.ReadToEnd()); }
public void ReadFromShouldConsumeTheCorrectNumberOfSyllablesFromTheInput() { var input = new StringReader("out of the water out of itself"); var line = new Line(5); line.ReadFrom(input); Assert.AreEqual("out of the water", line.ToString()); Assert.AreEqual("out of itself", input.ReadToEnd()); }
public async void readLineFromDatasetFile() { try { DatabaseContext context = new DatabaseContext(); IFileSystem fileSystem = FileSystem.Current; IFolder rootFolder = fileSystem.LocalStorage; IFile movFile = await rootFolder.GetFileAsync("movementDataset.txt"); string newFileText; string line; string fileText = await movFile.ReadAllTextAsync(); using (System.IO.StringReader reader = new System.IO.StringReader(fileText)) { line = reader.ReadLine(); //System.Diagnostics.Debug.WriteLine("READ from file pulse " + line); newFileText = reader.ReadToEnd(); } movFile.WriteAllTextAsync(newFileText); MovementJson obj = Newtonsoft.Json.JsonConvert.DeserializeObject <MovementJson>(line); int index = 1; if (!context.Movement.Any()) { index = 1; } else { Pohyb tmp = context.Movement.FirstOrDefault(t => t.PohybId == context.Movement.Max(x => x.PohybId)); index = tmp.PohybId; index++; } Pohyb POH = new Pohyb { PohybId = index, TimeStamp = obj.timestamp.ToString(), Xhodnota = obj.x * 10, Yhodnota = obj.y * 10 }; context.Movement.Add(POH); System.Diagnostics.Debug.WriteLine("****** VLOZENIE MOVEMENT DO DB: " + POH.PohybId + " " + POH.Xhodnota + " " + POH.Yhodnota + " " + POH.TimeStamp); context.SaveChanges(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Citanie movement suboru zo zariadenia: " + nameof(LoadPulse) + e.ToString()); } }
private char[] ReadAsciiData() { string raw = ReadTextFile("Problem59.txt", true); using (StringReader reader = new StringReader(raw)) { string line = reader.ReadToEnd(); return line.Split(',').Select(x => Convert.ToChar(Int32.Parse(x))).ToArray(); } }
public async void readLineFromDatasetFile() { try { DatabaseContext context = new DatabaseContext(); IFileSystem fileSystem = FileSystem.Current; IFolder rootFolder = fileSystem.LocalStorage; IFile tempFile = await rootFolder.GetFileAsync("pulseDataset.txt"); string newFileText; string line; string fileText = await tempFile.ReadAllTextAsync(); using (System.IO.StringReader reader = new System.IO.StringReader(fileText)) { line = reader.ReadLine(); //System.Diagnostics.Debug.WriteLine("READ from file pulse " + line); newFileText = reader.ReadToEnd(); } tempFile.WriteAllTextAsync(newFileText); DatasetJson obj = Newtonsoft.Json.JsonConvert.DeserializeObject <DatasetJson>(line); int index = 1; if (!context.Pulse.Any()) { index = 1; } else { Tep tmp = context.Pulse.FirstOrDefault(t => t.TepId == context.Pulse.Max(x => x.TepId)); index = tmp.TepId; index++; } Tep tep = new Tep { TepId = index, //TimeStamp = obj.header.creation_date_time.ToString(), TimeStamp = obj.timestamp.ToString(), Hodnota = obj.value }; context.Pulse.Add(tep); //System.Diagnostics.Debug.WriteLine("****** VLOZENIE TEPU DO DB: " + tep.TepId + " " + tep.Hodnota + " " + tep.TimeStamp); context.SaveChanges(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Citanie pulz suboru zo zariadenia: " + nameof(LoadPulse) + e.ToString()); } }
private string cleanXmlResponseString(string response) { // get rid of UTF-8 BOM System.IO.StringReader stringReader = new System.IO.StringReader(response); stringReader.Read(); // skip BOM System.Xml.XmlReader.Create(stringReader); string loadableXmlResponse = stringReader.ReadToEnd(); return(loadableXmlResponse); }
public LoadFailedPluginViewModel(LoadFailedPluginData data) { this.Metadata = data.Metadata ?? new BlacklistedAssembly { Name = Path.GetFileName(data.FilePath) } as object; using (var reader = new StringReader(data.Message)) { this.Message = reader.ReadLine(); this.Exception = reader.ReadToEnd(); } }
public static void fillTree(string xml, TreeView tree) { XmlDocument xmlDocument = new XmlDocument(); System.IO.StringReader stringReader = new System.IO.StringReader(xml); stringReader.Read(); xmlDocument.LoadXml(stringReader.ReadToEnd()); xmlHelper.ConvertXmlNodeToTreeNode(xmlDocument, tree.Nodes); tree.Nodes[0].ExpandAll(); }
private static IEnumerable<HyphenatorPattern> ReadPatterns(XElement source) { if (source == null) yield break; using (var reader = new StringReader(source.Value)) { foreach (var word in WhiteSpaceRegex.Split((reader.ReadToEnd() ?? "").Trim())) { yield return new HyphenatorPattern(word); } } }
/// <summary> /// Echo the text back unchanged. /// </summary> /// <param name="stringreader">Reader for the incoming string</param> /// <param name="stringwriter">Writer for the outgoing string</param> /// <param name="encoding">The encodigng for the outgoing string (ignored)</param> public void Encode(StringReader stringreader, StringWriter stringwriter, System.Text.Encoding encoding) { try { stringwriter.Write(stringreader.ReadToEnd()); } catch(Exception e) { throw new Exception("Error writing during Encoding" + e.Message); } }
protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) { string modifiedXml = Visualizer.ShowModal_LoadXmlFromString(objectProvider.GetObject().ToString(), objectProvider.IsObjectReplaceable, true); if (Visualizer.ReplaceObject()) { StringReader sr = new StringReader(modifiedXml); objectProvider.ReplaceObject(sr.ReadToEnd()); sr.Close(); } }
public static void VerifyLines(IList<string> expectedLines, string text) { var textReader = new StringReader(text); for (int iLine = 0; iLine < expectedLines.Count; iLine++) { var actualLine = textReader.ReadLine(); Assert.AreEqual(expectedLines[iLine], actualLine, "Mismatch on line {0}", iLine); } var endText = textReader.ReadToEnd(); Assert.AreEqual("", endText); }
/// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABFN_Group Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // group = "(" *c-wsp alternation *c-wsp ")" if (reader.Peek() != '(') { throw new ParseException("Invalid ABNF 'group' value '" + reader.ReadToEnd() + "'."); } // Eat "(". reader.Read(); // TODO: *c-wsp ABFN_Group retVal = new ABFN_Group(); // We reached end of stream, no closing ")". if (reader.Peek() == -1) { throw new ParseException("Invalid ABNF 'group' value '" + reader.ReadToEnd() + "'."); } retVal.m_pAlternation = ABNF_Alternation.Parse(reader); // We don't have closing ")". if (reader.Peek() != ')') { throw new ParseException("Invalid ABNF 'group' value '" + reader.ReadToEnd() + "'."); } else { reader.Read(); } return retVal; }
/// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABNF_Option Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // option = "[" *c-wsp alternation *c-wsp "]" if (reader.Peek() != '[') { throw new ParseException("Invalid ABNF 'option' value '" + reader.ReadToEnd() + "'."); } // Eat "[". reader.Read(); // TODO: *c-wsp ABNF_Option retVal = new ABNF_Option(); // We reached end of stream, no closing "]". if (reader.Peek() == -1) { throw new ParseException("Invalid ABNF 'option' value '" + reader.ReadToEnd() + "'."); } retVal.m_pAlternation = ABNF_Alternation.Parse(reader); // We don't have closing ")". if (reader.Peek() != ']') { throw new ParseException("Invalid ABNF 'option' value '" + reader.ReadToEnd() + "'."); } else { reader.Read(); } return retVal; }
public static byte [] GetNetworkDeviceState() { string data = null; using (StringReader reader = new StringReader(XMLs.NetworkDeviceState)) { data = reader.ReadToEnd(); } System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding(); return encoding.GetBytes(data); }
public async void readFileByLines() { try { DatabaseContext context = new DatabaseContext(); IFileSystem fileSystem = FileSystem.Current; IFolder rootFolder = fileSystem.LocalStorage; IFile tempFile = await rootFolder.GetFileAsync("temperatureData.txt"); string newFileText; string line; string fileText = await tempFile.ReadAllTextAsync(); using (System.IO.StringReader reader = new System.IO.StringReader(fileText)) { line = reader.ReadLine(); System.Diagnostics.Debug.WriteLine("temperature " + line); newFileText = reader.ReadToEnd(); } tempFile.WriteAllTextAsync(newFileText); Json obj = Newtonsoft.Json.JsonConvert.DeserializeObject <Json>(line); int index = 1; if (!context.Temperature.Any()) { index = 1; } else { Teplota tmp = context.Temperature.FirstOrDefault(t => t.TeplotaId == context.Temperature.Max(x => x.TeplotaId)); index = tmp.TeplotaId; index++; } Teplota teplota = new Teplota { TeplotaId = index++, //TimeStamp = obj.header.creation_date_time.ToString(), TimeStamp = DateTime.Now.ToString(), Hodnota = obj.body.body_temperature.value }; context.Temperature.Add(teplota); context.SaveChanges(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("citanie teplotneho suboru zo zariadenia: " + e.ToString()); } }
/// <summary> /// Creates a new instance of the MailMessage class from a string /// containing raw RFC822/MIME mail message data. /// </summary> /// <param name="text">A string containing the mail message data to /// create the MailMessage instance from.</param> /// <returns>An initialized instance of the MailMessage class.</returns> /// <remarks>This is used when fetching entire messages instead /// of the partial-fetch mechanism because it saves redundant /// round-trips to the server.</remarks> internal static MailMessage FromMIME822(string text) { StringReader reader = new StringReader(text); StringBuilder header = new StringBuilder(); string line; while(!String.IsNullOrEmpty(line = reader.ReadLine())) header.AppendLine(line); MailMessage m = FromHeader(header.ToString()); MIMEPart[] parts = ParseMailBody(reader.ReadToEnd(), m.Headers); foreach (MIMEPart p in parts) m.AddBodypart(BodypartFromMIME(p), p.body); return m; }
public NameSpaceExpression(string namespaceName, string namespaceContent) { _namespaceName = namespaceName; StringReader stringReader = new StringReader(namespaceContent); string line = stringReader.ReadLine(); if (string.IsNullOrWhiteSpace(line)) { Debug.WriteLine("WMC.Service: First line after namespace is empty"); } else { line = line.Trim(); string[] tokens = line.Split(' '); if (tokens.Length != 2) { Debug.WriteLine("WMC.Service: Line: " + line + " (after namespace) do no have 2 tokens seprated by space"); return; } if (tokens[0] == "c") { _classExpression = new InternalClassExpression(tokens[1], stringReader.ReadToEnd()); } else if (tokens[0] == "pc") { _classExpression = new PublicClassExpression(tokens[1], stringReader.ReadToEnd()); } if (_classExpression == null) { throw new ArgumentException("WMC.Service: Line: " + line + " (after namespace) is not class definition"); } } }
static void Main(string[] args) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); sw.Write("Hello, "); sw.Write("World!"); sw.Close(); StringReader sr = new StringReader(sb.ToString()); Console.WriteLine(sr.ReadToEnd()); sr.Close(); }
public void Scan(System.IO.StringReader sr) { input = new StringReader(sr.ReadToEnd().ToString() + "\n\n"); scannerThread = new Thread(doScan); scannerThread.Start(); while (scannerThread.IsAlive) { ; } if (failed) { throw new Exception("Newline in constant"); } }
/// <summary> /// Parses a data uri /// </summary> public static BinaryBlob Parse(string dataUri) { var blob = new BinaryBlob(); var reader = new StringReader(dataUri); // data:[<MIME-type>][;charset=<encoding>][;base64],<data> reader.Expect("data:"); blob.ContentType = reader.ReadUntil(ch => ch == ';').Trim(); reader.Read(); reader.Expect("base64,"); blob.Data = Convert.FromBase64String(reader.ReadToEnd()); return blob; }
public Evaluator(string expression) { if (String.IsNullOrWhiteSpace(expression)) { throw new ArgumentException("Expression is null or whitespaces"); } StringReader stringReader = new StringReader(expression); string firstLine = stringReader.ReadLine(); if (string.IsNullOrWhiteSpace(firstLine)) { throw new ArgumentException("Expression do not have any line ended with new line"); } string[] tokens = firstLine.Split(' '); if (tokens.Length != 2) { throw new ArgumentException("Tokens are not equal to 2"); } switch (tokens[0]) { case "c": _expression = new InternalClassExpression(tokens[1], stringReader.ReadToEnd()); break; case "pc": _expression = new PublicClassExpression(tokens[1], stringReader.ReadToEnd()); break; case "ns": _expression = new NameSpaceExpression(tokens[1], stringReader.ReadToEnd()); break; } if (_expression == null) { throw new ArgumentException("Expression do not stats with namespace nor class declaration"); } }
/// <summary> /// 场景Xml /// </summary> /// <param name="windowID"></param> /// <param name="fileInfo"></param> /// <returns></returns> public static List <SceneManager> ReadSceneXml(string windowID, string fileInfo) { //Camera.main.GetComponent<AssetManager>().textshow.text += " 555555555555555 " + fileInfo; List <SceneManager> scene = new List <SceneManager>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); //stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; if (Xmlroot["room_list"] != null) { foreach (XmlNode item in Xmlroot["room_list"].ChildNodes) { if (item.Attributes["scene_id"].Value == windowID) { SceneManager manager = new SceneManager(); manager.ID = long.Parse(item.Attributes["room_id"].Value); //manager.Type = item.Attributes["SceneType"].Value; manager.HouseID = long.Parse(item.Attributes["scene_id"].Value); manager.Idx = int.Parse(item.Attributes["room_code"].Value); //manager.ScenePos = new Vector2(float.Parse(temp[0]), float.Parse(temp[1])); float X = float.Parse(item.Attributes["room_x"].Value); float Y = float.Parse(item.Attributes["room_y"].Value); manager.ScenePos = new Vector2(X, Y); //string[] temp; //temp = item.Attributes["WindowID"].Value.Split('_'); //manager.WindowID = temp; //temp = new string[3]; //temp[0] = item.Attributes["DiaoDing"].Value; //temp[1] = item.Attributes["DiMian"].Value; //temp[2] = item.Attributes["QiangMian"].Value; //manager.QiuURL = temp; scene.Add(manager); } } return(scene); } else { return(null); } }
/// <summary> /// 读取地址信息 /// </summary> /// <param name="fileInfo"></param> /// <returns></returns> public static fileData ReadFile(string fileInfo) { System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); //stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; XmlElement item = Xmlroot["file"] as XmlElement; fileData file = new fileData(); file.file = item.GetAttribute("real_file"); file.fileName = item.GetAttribute("file_name"); return(file); }
private static HttpResponse Parse(string responseString) { HttpResponse response = new HttpResponse(); StringReader reader = new StringReader(responseString); string line = reader.ReadLine(); string[] firstLine = line.Split(' '); //VERSION RESPONSECODE RESPONSEMESSAGE response.HttpVersion = HttpVersion.HTTP11; response.ResponseCode = (HttpStatusCode)int.Parse(firstLine[1]); response.ResponseMessage = string.Join(" ", firstLine, 2, firstLine.Length - 2); response.ReadHeaders(reader); StreamWriter sw = new StreamWriter(response.Body); sw.Write(reader.ReadToEnd()); response.Body.Seek(0, SeekOrigin.Begin); return response; }
public string ExtractReplacementDefinitions(string originalText, out string replacementDefinitions) { var reader = new StringReader(originalText); string line; while ((line = reader.ReadLine()) != null) { if (string.IsNullOrWhiteSpace(line)) continue; if (!IsStartOfBlock(line)) break; var definitionsBuilder = new StringBuilder(); ReadReplacements(reader, definitionsBuilder); replacementDefinitions = definitionsBuilder.ToString(); return reader.ReadToEnd(); } replacementDefinitions = null; return originalText; }
}//ReadXMLConfigByWWW_End /// <summary> /// 初始化XML配置(必须要有参数) /// </summary> /// <param name="www"></param> /// <param name="rootNodeName"></param> private void InitXMLConfig(WWW www, string rootNodeName) { //参数检查 if (_LiDiaLogDataArray == null || string.IsNullOrEmpty(www.text)) { Debug.LogError(GetType() + "/InitXMLConfig()/_LiDiaLogDataArray == null or rootNodeName is null!,Plsase check"); return; } Debug.Log("123"); //XML解析程序 XmlDocument xmlDoc = new XmlDocument(); //xmlDoc.LoadXml(www.text); //发现这种方式,发布到ANDROID手机端,不能正确的输出中文 //先用StringReader读取www.text /*以下四行代码代替上面注释掉的内容,解决正在发布手机端解析输出中文问题*/ System.IO.StringReader stringReader = new System.IO.StringReader(www.text); stringReader.Read(); System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); xmlDoc.LoadXml(stringReader.ReadToEnd()); //读取"<Dialogs_CN>"单个节点的名称每个节点都读出来 XmlNodeList nodes = xmlDoc.SelectSingleNode(_StrXMLRootNodeName).ChildNodes;; //循环读取XML属性"xe"读取每个属性 foreach (XmlElement xe in nodes) { //实例化“XML解析实例类” DialogDataFormat data = new DialogDataFormat(); //段落编号需要转换字符串到整形 data.DialogSecNum = Convert.ToInt32(xe.GetAttribute("DialogSecNum")); //段落名称 data.DialogSecName = xe.GetAttribute("DialogSecName"); //段落内符号 data.SectionIndex = Convert.ToInt32(xe.GetAttribute("SectionIndex")); //对话双方 data.DialogSide = xe.GetAttribute("DialogSide"); //对话人名 data.DialogPerson = xe.GetAttribute("DialogPerson"); //对话内容 data.DialogContent = xe.GetAttribute("DialogContent"); //加入集合 _LiDiaLogDataArray.Add(data); } //foreach_End } //InitXMLConfig_End
public void Load(string message, bool headersonly) { Raw = message; _HeadersOnly = headersonly; if (headersonly) { RawHeaders = message; } else { var headers = new StringBuilder(); using (var reader = new System.IO.StringReader(message)) { string line; do { line = reader.ReadLine(); headers.AppendLine(line); } while (line != string.Empty); RawHeaders = headers.ToString(); string boundary = Headers.GetBoundary(); if (!string.IsNullOrEmpty(boundary)) { //else this is a multipart Mime Message ParseMime(reader, boundary); } else { _Body = reader.ReadToEnd(); } } } Date = Headers.GetDate("Date"); To = Headers.GetAddresses("To"); Cc = Headers.GetAddresses("Cc"); Bcc = Headers.GetAddresses("Bcc"); Sender = Headers.GetAddresses("Sender").FirstOrDefault(); ReplyTo = Headers.GetAddresses("Reply-To").FirstOrDefault(); From = Headers.GetAddresses("From").FirstOrDefault(); MessageID = Headers["Message-ID"].RawValue; Importance = Headers.GetEnum <MailPriority>("Importance"); Subject = Utilities.DecodeWords(Headers["Subject"].RawValue); }
public static void ReadSceneStyle(string fileInfo) { System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); //stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["dict_list"].ChildNodes) { if (!MsgCenter._instance.FengGe.ContainsKey(item.Attributes["dict_name"].Value)) { MsgCenter._instance.SceneStyle.Add(item.Attributes["dict_name"].Value, item.Attributes["dict_id"].Value); } } }
/// <summary> /// 错误检测 /// </summary> /// <param name="fileInfo"></param> /// <returns></returns> public static string Result(string fileInfo) { System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); //stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; string temp = ""; if (Xmlroot["err_msg"] != null) { temp = Xmlroot["err_msg"].InnerText; } return(temp); }
public string ResolveDOM() { using (var client = new WebClient()) { if (String.IsNullOrEmpty(App.EMAIL_USUARIO)) return String.Empty; var data = client .DownloadString(String.Format("http://cpro21201.publiccloud.com.br/bu-bling/mobile/carga_campanhas.aspx?email={0}", App.EMAIL_USUARIO)); using (var stream = new StringReader(data)) { var _DOM = stream.ReadToEnd(); return _DOM; } } }
public XmlElement GetXmlElement(string xmlStr) { StringReader strRead = new StringReader(xmlStr); XmlReader reader = XmlReader.Create(strRead); System.IO.StringReader stringReader = new System.IO.StringReader(xmlStr); //stringReader.Read(); // 跳过 BOM //System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlDocument xml = new XmlDocument(); xml.LoadXml(strRead.ReadToEnd()); XmlElement xmlRoot = xml.DocumentElement; return(xmlRoot); }
/// <summary> /// 初始化XML文档配置 /// </summary> /// <param name="www"></param> /// <param name="rootNodeName"></param> private void InitXMLConfig(WWW www, string rootNodeName) { //参数检查 if (_DialogDataArray == null || string.IsNullOrEmpty(www.text)) { Debug.LogError(GetType() + "/InitXMLConfig()" + "\t空参数异常"); return; } //XML解析程序 XmlDocument xmlDoc = new XmlDocument(); //发现这种方式,发布到Android手机端,不能正确输出中文 //xmlDoc.LoadXml(www.text); //读取XML文档 /* 使用以下四行代码,来代替上面注释掉的内容,解决正确输出中文的问题 */ System.IO.StringReader stringReader = new System.IO.StringReader(www.text); stringReader.Read(); //用于跳过首行? System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader); //这到底有什么用? xmlDoc.LoadXml(stringReader.ReadToEnd()); //选择单个结点 XmlNodeList nodes = xmlDoc.SelectSingleNode(rootNodeName).ChildNodes; foreach (XmlElement xe in nodes) { //实例化“XML解析实体类” DialogDataFormat data = new DialogDataFormat { /* 得到属性 */ DiaSectionNum = Convert.ToInt32(xe.GetAttribute(XML_ATTR_1)), DiaSectionName = xe.GetAttribute(XML_ATTR_2), DiaIndex = Convert.ToInt32(xe.GetAttribute(XML_ATTR_3)), DiaSide = xe.GetAttribute(XML_ATTR_4), DiaPerson = xe.GetAttribute(XML_ATTR_5), DiaContent = xe.GetAttribute(XML_ATTR_6) }; //写入缓存数组 _DialogDataArray.Add(data); } }
// 解析整体XML public static List <AssetInfo> ReadAllAsset(string fileInfo) { List <AssetInfo> LoadList = new List <AssetInfo>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { AssetInfo myasset = new AssetInfo(); myasset.DefaultTexture = item.Attributes["Icon"].Value; foreach (XmlNode data in item.ChildNodes) { myasset.ModelPath.Add(data.InnerText); Material temp = new Material(Resources.Load <Shader>("Standard")); string[] rgba = data.Attributes["RGB"].InnerText.Split('.'); if (rgba[0] != "") { float r = float.Parse(rgba[0]); float g = float.Parse(rgba[1]); float b = float.Parse(rgba[2]); float a = float.Parse(rgba[3]); temp.color = new Color(r / 255, g / 255, b / 255, a / 255); } myasset.material.Add(temp); myasset.Texture.Add(data.Attributes["TextureUrl"].Value); } LoadList.Add(myasset); } return(LoadList); }
//房子户型XMl public static List <HouseManager> ReadHouseXml(string fileInfo) { List <HouseManager> House = new List <HouseManager>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["program"].ChildNodes) { HouseManager temp = new HouseManager(); temp.ID = int.Parse(item.Attributes["HouseID"].Value); temp.Icon = item.Attributes["HouseIcon"].Value; temp.M_default = item.Attributes["DefaultSence"].Value; temp.Map = item.Attributes["HouseMap"].Value; House.Add(temp); } return(House); }
// 单个窗帘组件解析XML public static List <Curtain> ReadInfo(int id, string fileInfo) { List <Curtain> LoadList = new List <Curtain>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["Info"].ChildNodes) { Curtain newExcel = new Curtain(); newExcel.IsModel = bool.Parse(item.Attributes["IsModel"].Value); newExcel.ModelUrl = item.Attributes["ModelUrl"].Value; //newExcel.MatID = int.Parse(item["ModelUrl"].Attributes["ID"].Value); newExcel.TextureUrl = item.Attributes["TextureUrl"].Value; newExcel.IconUrl = item.Attributes["Icon"].Value; Material temp = new Material(Resources.Load <Shader>("Standard")); string[] rgba = item.Attributes["RGB"].Value.Split('.'); if (rgba[0] != "") { float r = float.Parse(rgba[0]); float g = float.Parse(rgba[1]); float b = float.Parse(rgba[2]); float a = float.Parse(rgba[3]); temp.color = new Color(r / 255, g / 255, b / 255, a / 255); } newExcel.Material = temp; LoadList.Add(newExcel); } return(LoadList); }
// 单独展示时解析XML public static List <SingleCurtain> SingleReadInfo(string fileInfo) { List <SingleCurtain> LoadList = new List <SingleCurtain>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { SingleCurtain newExcel = new SingleCurtain(); //newExcel.IsModel = bool.Parse(item["IsModel"].InnerText); newExcel.TextureUrl = item["TextureUrl"].InnerText; LoadList.Add(newExcel); } return(LoadList); }
//public static List<string> ReadInfo(string fileInfo) //{ // List<string> LoadList = new List<string>(); // System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); // stringReader.Read(); // 跳过 BOM // System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); // XmlDocument myXML = new XmlDocument(); // myXML.LoadXml(stringReader.ReadToEnd()); // XmlElement Xmlroot = myXML.DocumentElement; // foreach (XmlNode item in Xmlroot.ChildNodes) // { // Infomation newExcel = new Infomation(); // newExcel.URL = item["URL"].InnerText; // newExcel.description = item["Description"].InnerText; // LoadList.Add(newExcel.URL); // } // return LoadList; //} #endregion //场景Xml public static List <SceneManager> ReadSceneXml(int windowID, string fileInfo) { List <SceneManager> scene = new List <SceneManager>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["program"].ChildNodes) { if (item.Attributes["HouseID"].Value == windowID.ToString()) { SceneManager manager = new SceneManager(); manager.ID = int.Parse(item.Attributes["SceneID"].Value); manager.Type = item.Attributes["SceneType"].Value; string[] temp = item.Attributes["Pos"].Value.Split('_'); manager.ScenePos = new Vector2(float.Parse(temp[0]), float.Parse(temp[1])); temp = item.Attributes["WindowID"].Value.Split('_'); manager.WindowID = temp; temp = new string[3]; temp[0] = item.Attributes["DiaoDing"].Value; temp[1] = item.Attributes["DiMian"].Value; temp[2] = item.Attributes["QiangMian"].Value; manager.QiuURL = temp; scene.Add(manager); } } return(scene); }
// 解析窗户的XML public static List <WindoManager> ReadWindowXml(string[] WindowsID, string path) { int index = -1; int Inde = 0; MsgCenter._instance.CleanList(); //MsgCenter._instance.CleanAllList(MsgCenter._instance.nowWidow); MsgCenter._instance.TempDisctionary.Clear(); List <WindoManager> AllWindow = new List <WindoManager>(); System.IO.StringReader stringReader = new System.IO.StringReader(path); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { Debug.Log(WindowsID[0]); if (((IList)WindowsID).Contains(item.Attributes["ID"].Value)) { index++; MsgCenter._instance.AddWindowList(Inde.ToString(), new Dictionary <string, GameObject>()); WindoManager newExcel = new WindoManager(); newExcel.WindowPictureUrl = item["WindowPictureUrl"].InnerText; newExcel.ID = index; float Scalex = float.Parse(item["WindowScale"].Attributes["X"].Value); float Scaley = float.Parse(item["WindowScale"].Attributes["Y"].Value); float Scalez = float.Parse(item["WindowScale"].Attributes["Z"].Value); float Positionx = float.Parse(item["WindowPosition"].Attributes["X"].Value); float Positiony = float.Parse(item["WindowPosition"].Attributes["Y"].Value); float Positionz = float.Parse(item["WindowPosition"].Attributes["Z"].Value); float Rotationx = float.Parse(item["WindowRotation"].Attributes["X"].Value); float Rotationy = float.Parse(item["WindowRotation"].Attributes["Y"].Value); float Rotationz = float.Parse(item["WindowRotation"].Attributes["Z"].Value); MsgCenter._instance.ModuleCount = (index + 1) * item["Model"].ChildNodes.Count; for (int i = 0; i < item["Model"].ChildNodes.Count; i++) { Curtain temp = new Curtain(); temp.IsModel = true; temp.ModelUrl = item["Model"].ChildNodes[i].InnerText; temp.ScaleParameters = float.Parse(item["Model"].Attributes["CurtainScale"].Value); Debug.Log(" index " + index); temp.Id = index; string Stemp = temp.Id + temp.ModelUrl.Split('.')[0]; if (!MsgCenter._instance.TempDisctionary.ContainsKey(Stemp)) { MsgCenter._instance.TempDisctionary.Add(Stemp, false); } temp.TextureUrl = item["Model"].ChildNodes[i].Attributes["TextureUrl"].InnerText; temp.Material = new Material(Resources.Load <Shader>("Standard")); string[] rgba = item["Model"].ChildNodes[i].Attributes["RGB"].InnerText.Split('.'); if (rgba[0] != "") { float r = float.Parse(rgba[0]); float g = float.Parse(rgba[1]); float b = float.Parse(rgba[2]); float a = float.Parse(rgba[3]); temp.Material.color = new Color(r / 255, g / 255, b / 255, a / 255); } newExcel.Curtain.Add(temp); } newExcel.Scale = new Vector3(Scalex, Scaley, Scalez); newExcel.Position = new Vector3(Positionx, Positiony, Positionz); newExcel.Rotation = new Vector3(Rotationx, Rotationy, Rotationz); AllWindow.Add(newExcel); Inde++; } } index = 0; Inde = 0; return(AllWindow); }
/// <summary> /// Description: /// Start Crittercism for Unity, will start crittercism for ios if it is not already active. /// Parameters: /// appID: Crittercisms Provided App ID for this application /// key: Crittercisms Provided Key for this application /// secret: Crittercisms Provided Secret for this application /// loadFromResources: Attempt to load the appID, key, and secret from the CrittercismIDs.text file. /// handleUnityExceptions: Allow crittercisms to recieve unity handled exceptions. /// </summary> public static void Init(string appID, bool loadFromResources, bool handleUnityExceptions) { _IsPluginInited = Crittercism_IsInited(); if (_IsUnityPluginInited && _IsPluginInited) { Crittercism_RefreshSignalRegister(); return; } _HandleUnityExceptions = handleUnityExceptions; if (!_IsPluginInited) { if (loadFromResources) { string appData = null; try { TextAsset text = (TextAsset)Resources.Load(_KeyResources); if (text != null) { System.IO.StringReader reader = new System.IO.StringReader(text.text); if (reader == null) { throw new System.Exception(); } appData = reader.ReadToEnd(); appData = WWW.EscapeURL(appData); } } catch { appData = null; } try { if (appData == null) { throw new System.Exception(); } Crittercism_EnableWithAppID(appData); _IsPluginInited = Crittercism_IsInited(); //_IsPluginInited = true; } catch { if (Debug.isDebugBuild == true || _ShowDebugOnOnRelease == true) { Debug.Log("CrittercismIOS: Failed to start Crittercism for ios"); } } } if (!_IsPluginInited) { if (appID == null) { appID = ""; } // if(key == null) { key = ""; } // if(secret == null) { secret = ""; } try { Crittercism_EnableWithAppID(appID); _IsPluginInited = Crittercism_IsInited(); //_IsPluginInited = true; } catch { if (Debug.isDebugBuild == true || _ShowDebugOnOnRelease == true) { Debug.Log("CrittercismIOS: Failed to start Crittercism for ios"); } } } } else { Debug.Log("CrittercismIPS: already initialized"); } if (_IsUnityPluginInited == false && _IsPluginInited) { System.AppDomain.CurrentDomain.UnhandledException += _OnUnresolvedExceptionHandler; Application.RegisterLogCallback(_OnDebugLogCallbackHandler); _IsUnityPluginInited = true; Debug.Log("CrittercismIOS: Sucessfully Initialized"); } }
/// <summary> /// Converts a string to a number (used in type coercion). /// </summary> /// <returns> The result of parsing the string as a number. </returns> internal static double CoerceToNumber(string input) { var reader = new System.IO.StringReader(input); // Skip whitespace and line terminators. while (IsWhiteSpaceOrLineTerminator(reader.Peek())) { reader.Read(); } // Empty strings return 0. int firstChar = reader.Read(); if (firstChar == -1) { return(0.0); } // The number can start with a plus or minus sign. bool negative = false; switch (firstChar) { case '-': negative = true; firstChar = reader.Read(); break; case '+': firstChar = reader.Read(); break; } // Infinity or -Infinity are also valid. if (firstChar == 'I') { string restOfString1 = reader.ReadToEnd(); if (restOfString1.StartsWith("nfinity", StringComparison.Ordinal) == true) { // Check the end of the string for junk. for (int i = 7; i < restOfString1.Length; i++) { if (IsWhiteSpaceOrLineTerminator(restOfString1[i]) == false) { return(double.NaN); } } return(negative ? double.NegativeInfinity : double.PositiveInfinity); } } // Return NaN if the first digit is not a number or a period. if ((firstChar < '0' || firstChar > '9') && firstChar != '.') { return(double.NaN); } // Parse the number. NumberParser.ParseCoreStatus status; double result = NumberParser.ParseCore(reader, (char)firstChar, out status, allowHex: true, allowOctal: false); // Handle various error cases. switch (status) { case ParseCoreStatus.NoDigits: case ParseCoreStatus.NoExponent: return(double.NaN); } // Check the end of the string for junk. string restOfString2 = reader.ReadToEnd(); for (int i = 0; i < restOfString2.Length; i++) { if (IsWhiteSpaceOrLineTerminator(restOfString2[i]) == false) { return(double.NaN); } } return(negative ? -result : result); }
public void M(bool b) { // Assignment, tainted var sink0 = "taint source"; Check(sink0); // Assignment, not tainted var nonSink0 = ""; Check(nonSink0); // Assignment (concatenation), tainted var sink1 = "abc"; sink1 += sink0; Check(sink1); // Assignment (concatenation), not tainted nonSink0 += "abc"; Check(nonSink0); // Concatenation, tainted var sink5 = sink1 + "ok"; Check(sink5); // Concatenation, not tainted nonSink0 = nonSink0 + "test"; Check(nonSink0); // Parenthesized expression, tainted var sink6 = (sink5); Check(sink6); // Parenthesized expression, not tainted nonSink0 = (nonSink0); Check(nonSink0); // Conditional expression, tainted var sink7 = b ? "a" : sink6; Check(sink7); // Conditional expression, not tainted nonSink0 = b ? "abc" : "def"; Check(nonSink0); // Cast, tainted var sink8 = (object)sink7; Check(sink8); // Cast, not tainted var nonSink3 = (object)nonSink0; Check(nonSink3); // Cast, tainted var sink9 = sink8 as string; Check(sink9); // Cast, not tainted nonSink3 = nonSink0 as object; Check(nonSink3); // Standard method with a tainted argument, tainted var sink15 = Int32.Parse(sink9); Check(sink15); int nonSink2; var sink16 = Int32.TryParse(sink9, out nonSink2); Check(sink16); var sink17 = nonSink0.Replace(" ", sink9); Check(sink17); var sink18 = String.Format(nonSink0, sink9); Check(sink18); var sink19 = String.Format(sink18, nonSink0); Check(sink19); var sink45 = bool.Parse(sink9); Check(sink45); bool nonSink13; var sink46 = bool.TryParse(sink9, out nonSink13); Check(sink46); var sink47 = Convert.ToByte(sink46); Check(sink47); var sink49 = String.Concat("", sink47); Check(sink49); var sink50 = String.Copy(sink49); Check(sink50); var sink51 = String.Join(", ", new string[] { "", sink50, "" }); Check(sink51); var sink52 = "".Insert(0, sink51); Check(sink52); // Standard method with a non-tainted argument, not tainted nonSink2 = Int32.Parse(nonSink0); Check(nonSink2); var nonSink7 = Int32.TryParse(nonSink0, out nonSink2); Check(nonSink7); nonSink0 = nonSink0.Replace(" ", nonSink0); Check(nonSink0); nonSink0 = String.Format(nonSink0, nonSink0); Check(nonSink0); nonSink7 = bool.Parse(nonSink0); Check(nonSink7); nonSink7 = bool.TryParse(nonSink0, out nonSink13); Check(nonSink7); var nonSink14 = Convert.ToByte(nonSink7); Check(nonSink14); nonSink0 = String.Concat("", nonSink7); Check(nonSink0); nonSink0 = String.Copy(nonSink0); Check(nonSink0); nonSink0 = String.Join(", ", new string[] { "", nonSink0, "" }); Check(nonSink0); nonSink0 = "".Insert(0, nonSink0); Check(nonSink0); // Comparison with constant, tainted var sink20 = sink15 > 42; Check(sink20); var sink21 = sink9.Equals("abc"); Check(sink21); var sink22 = sink8.Equals((object)41); Check(sink22); // Comparison with non-constant, not tainted nonSink7 = sink0.Equals(sink1); Check(nonSink7); nonSink7 = sink8.Equals(nonSink3); Check(nonSink7); // Logical operation using tainted operand, tainted var sink25 = sink20 || false; Check(sink25); // Logical operation using non-tainted operands, not tainted nonSink7 = nonSink7 || false; Check(nonSink7); // Ad hoc tracking (System.Uri), tainted var sink26 = new System.Uri(sink9); Check(sink26); var sink27 = sink26.ToString(); Check(sink27); var sink28 = sink26.PathAndQuery; Check(sink28); var sink29 = sink26.Query; Check(sink29); var sink30 = sink26.OriginalString; Check(sink30); // Ad hoc tracking (System.Uri), not tainted var nonSink8 = new System.Uri(nonSink0); Check(nonSink8); nonSink0 = nonSink8.ToString(); Check(nonSink0); nonSink0 = nonSink8.PathAndQuery; Check(nonSink0); nonSink0 = nonSink8.Query; Check(nonSink0); nonSink0 = nonSink8.OriginalString; Check(nonSink0); // Ad hoc tracking (System.IO.StringReader), tainted var sink31 = new System.IO.StringReader(sink30); Check(sink31); var sink32 = sink31.ReadToEnd(); Check(sink32); // Ad hoc tracking (System.IO.StringReader), not tainted var nonSink9 = new System.IO.StringReader(nonSink0); Check(nonSink9); nonSink0 = nonSink9.ReadToEnd(); Check(nonSink0); // Ad hoc tracking (System.String), tainted var sink33 = (string)sink32.Substring(0).ToLowerInvariant().ToUpper().Trim(' ').Replace("a", "b").Insert(0, "").Clone(); Check(sink33); var sink48 = sink33.Normalize().Remove(4, 5); Check(sink48); // Ad hoc tracking (System.String), not tainted nonSink0 = (string)nonSink0.Substring(0).ToLowerInvariant().ToUpper().Trim(' ').Replace("a", "b").Insert(0, "").Clone(); Check(nonSink0); var nonSink15 = nonSink0.Normalize().Remove(4, 5); Check(nonSink15); // Ad hoc tracking (System.Text.StringBuilder), tainted var sink34 = new StringBuilder(sink33); Check(sink34); var sink35 = sink34.ToString(); Check(sink35); var sink36 = new StringBuilder(""); sink36.AppendLine(sink35); Check(sink36); // Ad hoc tracking (System.Text.StringBuilder), not tainted var nonSink10 = new StringBuilder(nonSink0); Check(nonSink10); nonSink0 = nonSink10.ToString(); Check(nonSink0); nonSink10.AppendLine(nonSink0); Check(nonSink10); // Ad hoc tracking (data contracts), tainted var taintedDataContract = new DataContract(); var sink53 = taintedDataContract.AString; Check(sink53); var sink54 = taintedDataContract.AList[0].AString; Check(sink54); // Ad hoc tracking (data contracts), not tainted var nonTaintedDataContract = new DataContract(); nonSink0 = nonTaintedDataContract.AString; Check(nonSink0); nonSink2 = taintedDataContract.AnInt; Check(nonSink2); nonSink2 = taintedDataContract.AList[0].AnInt; Check(nonSink2); // Ad hoc tracking (TextBox), tainted TextBox taintedTextBox = null; var sink60 = taintedTextBox.Text; Check(sink60); // Ad hoc tracking (HttpRequest), not tainted TextBox nonTaintedTextBox = null; nonSink0 = nonTaintedTextBox.Text; Check(nonSink0); // Interpolated string, tainted var sink69 = $"test {sink1}"; Check(sink69); // Interpolated string, not tainted nonSink0 = $"test {nonSink0}"; Check(nonSink0); // Assignment expression, exact var sink70 = sink0 = sink0; Check(sink70); // Assignment expression, not tainted nonSink0 = nonSink0 = nonSink0; Check(nonSink0); // `is` pattern, tainted if (sink70 is string sink71) { Check(sink71); } // `is` pattern, not tainted if (nonSink0 is string nonSink16) { Check(nonSink16); } // `switch` pattern, tainted switch (sink70) { case string sink72: Check(sink72); break; } // `switch` pattern, not tainted switch (nonSink0) { case string nonSink17: Check(nonSink17); break; } // Null-coalescing expressions var sink73 = nonSink0 ?? sink0; var sink74 = sink0 ?? nonSink0; Check(sink73); Check(sink74); }
public static List <Module> ReadInfo(string path, string Name) { List <Module> Info = new List <Module>(); System.IO.StringReader stringReader = new System.IO.StringReader(path); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; UImanager._instance.teliphonenumber = Xmlroot.Attributes["Teliphonenumber"].Value; Debug.Log(Xmlroot[Name].ChildNodes.Count); foreach (XmlNode item in Xmlroot[Name].ChildNodes) { Module info = new Module(); //info.Englishname = item.Attributes["englishname"].Value; info.Name = item.Attributes["name"].Value; if (item.Attributes["ismodle"] != null) { info.IsModle = item.Attributes["ismodle"].Value == "0" ? true : false; } if (item.Attributes["modle"] != null) { info.URL = item.Attributes["modle"].Value; } info.SubList = new List <Sub>(); foreach (XmlNode item1 in item.ChildNodes) { Sub sub = new Sub(); sub.Name = item1.Attributes["name"].Value; if (item1.Attributes["ismodle"] != null) { sub.IsModle = item1.Attributes["ismodle"].Value == "0" ? true : false; } if (item1.Attributes["modle"] != null) { sub.URL = item1.Attributes["modle"].Value; } //sub.ENglishname = item1.Attributes["englishname"].Value; info.SubList.Add(sub); sub.ProductList = new List <Product>(); foreach (XmlNode item2 in item1.ChildNodes) { Product prod = new Product(); prod.Name = item2.Attributes["name"].Value; prod.ModleURL = item2.Attributes["modle"].Value; prod.IsModle = item2.Attributes["ismodle"].Value == "0" ? true : false; prod.TextureURL = item2.Attributes["texture"].Value; prod.Description = item2.Attributes["description"].Value; sub.ProductList.Add(prod); } } Info.Add(info); } return(Info); }
public async void M(bool b) { // Assignment, tainted var sink0 = "taint source"; Check(sink0); // Assignment, not tainted var nonSink0 = ""; Check(nonSink0); // Assignment (concatenation), tainted var sink1 = "abc"; sink1 += sink0; Check(sink1); // Assignment (concatenation), not tainted nonSink0 += "abc"; Check(nonSink0); // Assignment (indexer), tainted var sink2 = new Dictionary <int, string[]>(); sink2[0][1] = sink1; Check(sink2); // Assignment (indexer), not tainted var nonSink1 = new Dictionary <string, string>(); nonSink1[""] = nonSink0; nonSink1[sink1] = ""; // do not track tainted keys Check(nonSink1); // Concatenation, tainted var sink5 = sink1 + "ok"; Check(sink5); // Concatenation, not tainted nonSink0 = nonSink0 + "test"; Check(nonSink0); // Parenthesized expression, tainted var sink6 = (sink5); Check(sink6); // Parenthesized expression, not tainted nonSink0 = (nonSink0); Check(nonSink0); // Conditional expression, tainted var sink7 = b ? "a" : sink6; Check(sink7); // Conditional expression, not tainted nonSink0 = b ? "abc" : "def"; Check(nonSink0); // Cast, tainted var sink8 = (object)sink7; Check(sink8); // Cast, not tainted var nonSink3 = (object)nonSink0; Check(nonSink3); // Cast, tainted var sink9 = sink8 as string; Check(sink9); // Cast, not tainted nonSink3 = nonSink0 as object; Check(nonSink3); // Array creation (initializer), tainted var sink10 = new object[] { sink9 }; Check(sink10); // Array creation (initializer), not tainted var nonSink4 = new object[] { 42 }; Check(nonSink4); // Object creation (collection initializer), tainted var sink11 = new Dictionary <string, string> { { "", sink9 } }; Check(sink11); // Object creation (collection initializer), not tainted nonSink1 = new Dictionary <string, string> { { sink9, "" } }; Check(nonSink1); // Data-preserving LINQ, tainted var sink14 = sink11.First(x => x.Value != null); Check(sink14); // Data-preserving LINQ, not tainted nonSink3 = nonSink1.First(x => x.Value != null); Check(nonSink1); // Standard method with a tainted argument, tainted var sink15 = Int32.Parse(sink9); Check(sink15); int nonSink2; var sink16 = Int32.TryParse(sink9, out nonSink2); Check(sink16); var sink17 = nonSink0.Replace(" ", sink9); Check(sink17); var sink18 = String.Format(nonSink0, sink9); Check(sink18); var sink19 = String.Format(sink18, nonSink0); Check(sink19); var sink45 = bool.Parse(sink9); Check(sink45); bool nonSink13; var sink46 = bool.TryParse(sink9, out nonSink13); Check(sink46); var sink47 = Convert.ToByte(sink46); Check(sink47); var sink49 = String.Concat("", sink47); Check(sink49); var sink50 = String.Copy(sink49); Check(sink50); var sink51 = String.Join(", ", "", sink50, ""); Check(sink51); var sink52 = "".Insert(0, sink51); Check(sink52); // Standard method with a non-tainted argument, not tainted nonSink2 = Int32.Parse(nonSink0); Check(nonSink2); var nonSink7 = Int32.TryParse(nonSink0, out nonSink2); Check(nonSink7); nonSink0 = nonSink0.Replace(" ", nonSink0); Check(nonSink0); nonSink0 = String.Format(nonSink0, nonSink0); Check(nonSink0); nonSink7 = bool.Parse(nonSink0); Check(nonSink7); nonSink7 = bool.TryParse(nonSink0, out nonSink13); Check(nonSink7); var nonSink14 = Convert.ToByte(nonSink7); Check(nonSink14); nonSink0 = String.Concat("", nonSink7); Check(nonSink0); nonSink0 = String.Copy(nonSink0); Check(nonSink0); nonSink0 = String.Join(", ", "", nonSink0, ""); Check(nonSink0); nonSink0 = "".Insert(0, nonSink0); Check(nonSink0); // Comparison with constant, tainted var sink20 = sink15 > 42; Check(sink20); var sink21 = sink9.Equals("abc"); Check(sink21); var sink22 = sink8.Equals((object)41); Check(sink22); // Comparison with non-constant, not tainted nonSink7 = sink0.Equals(sink1); Check(nonSink7); nonSink7 = sink8.Equals(nonSink3); Check(nonSink7); // Indexer access, tainted var sink23 = sink11[""]; Check(sink23); // Indexer access, not tainted nonSink0 = nonSink1[""]; Check(nonSink0); // Array access, tainted var sink24 = sink10[0]; Check(sink24); // Array access, not tainted nonSink3 = nonSink4[0]; Check(nonSink3); // Logical operation using tainted operand, tainted var sink25 = sink20 || false; Check(sink25); // Logical operation using non-tainted operands, not tainted nonSink7 = nonSink7 || false; Check(nonSink7); // Ad hoc tracking (System.Uri), tainted var sink26 = new System.Uri(sink23); Check(sink26); var sink27 = sink26.ToString(); Check(sink27); var sink28 = sink26.PathAndQuery; Check(sink28); var sink29 = sink26.Query; Check(sink29); var sink30 = sink26.OriginalString; Check(sink30); // Ad hoc tracking (System.Uri), not tainted var nonSink8 = new System.Uri(nonSink0); Check(nonSink8); nonSink0 = nonSink8.ToString(); Check(nonSink0); nonSink0 = nonSink8.PathAndQuery; Check(nonSink0); nonSink0 = nonSink8.Query; Check(nonSink0); nonSink0 = nonSink8.OriginalString; Check(nonSink0); // Ad hoc tracking (System.IO.StringReader), tainted var sink31 = new System.IO.StringReader(sink30); Check(sink31); var sink32 = sink31.ReadToEnd(); Check(sink32); // Ad hoc tracking (System.IO.StringReader), not tainted var nonSink9 = new System.IO.StringReader(nonSink0); Check(nonSink9); nonSink0 = nonSink9.ReadToEnd(); Check(nonSink0); // Ad hoc tracking (System.String), tainted var sink33 = (string)sink32.Substring(0).ToLowerInvariant().ToUpper().Trim(' ').Replace("a", "b").Insert(0, "").Clone(); Check(sink33); var sink48 = sink33.Normalize().Remove(4, 5).Split(' '); Check(sink48); // Ad hoc tracking (System.String), not tainted nonSink0 = (string)nonSink0.Substring(0).ToLowerInvariant().ToUpper().Trim(' ').Replace("a", "b").Insert(0, "").Clone(); Check(nonSink0); var nonSink15 = nonSink0.Normalize().Remove(4, 5).Split(' '); Check(nonSink15); // Ad hoc tracking (System.Text.StringBuilder), tainted var sink34 = new StringBuilder(sink33); Check(sink34); var sink35 = sink34.ToString(); Check(sink35); var sink36 = new StringBuilder(""); sink36.AppendLine(sink35); Check(sink36); // Ad hoc tracking (System.Text.StringBuilder), not tainted var nonSink10 = new StringBuilder(nonSink0); Check(nonSink10); nonSink0 = nonSink10.ToString(); Check(nonSink0); nonSink10.AppendLine(nonSink0); Check(nonSink10); // Ad hoc tracking (System.Lazy), tainted var sink40 = new Lazy <string>(TaintedMethod); Check(sink40); var sink41 = sink40.Value; Check(sink41); var sink42 = new Lazy <string>(() => "taint source"); Check(sink42); var sink43 = sink42.Value; Check(sink43); // Ad hoc tracking (System.Lazy), not tainted var nonSink12 = new Lazy <string>(NonTaintedMethod); Check(nonSink12); nonSink0 = nonSink12.Value; Check(nonSink0); nonSink12 = new Lazy <string>(() => ""); Check(nonSink12); nonSink0 = nonSink12.Value; Check(nonSink0); // Ad hoc tracking (collections), tainted var sink3 = new Dictionary <int, string>(); sink3.Add(0, sink1); Check(sink3); var sink12 = sink3.Values; Check(sink12); var sink13 = sink12.Reverse(); Check(sink13); // Ad hoc tracking (collections), not tainted nonSink1.Add("", nonSink0); nonSink1.Add(sink1, ""); // do not track tainted keys Check(nonSink1); var nonSink5 = nonSink1.Values; Check(nonSink5); var nonSink6 = nonSink5.Reverse(); Check(nonSink6); // Ad hoc tracking (data contracts), tainted var taintedDataContract = new DataContract(); var sink53 = taintedDataContract.AString; Check(sink53); var sink54 = taintedDataContract.AList[0].AString; Check(sink54); // Ad hoc tracking (data contracts), not tainted var nonTaintedDataContract = new DataContract(); nonSink0 = nonTaintedDataContract.AString; Check(nonSink0); nonSink2 = taintedDataContract.AnInt; Check(nonSink2); nonSink2 = taintedDataContract.AList[0].AnInt; Check(nonSink2); // Ad hoc tracking (TextBox), tainted TextBox taintedTextBox = null; var sink60 = taintedTextBox.Text; Check(sink60); // Ad hoc tracking (HttpRequest), not tainted TextBox nonTaintedTextBox = null; nonSink0 = nonTaintedTextBox.Text; Check(nonSink0); // Iteration over a tracked expression, tainted foreach (var sink61 in sink10) { Check(sink61); } IEnumerator sink62 = sink10.GetEnumerator(); Check(sink62); var sink63 = sink62.Current; Check(sink63); IEnumerator <KeyValuePair <int, string> > sink64 = sink3.GetEnumerator(); Check(sink64); var sink65 = sink64.Current; Check(sink65); var sink66 = sink65.Value; Check(sink66); // Iteration over a tracked expression, not tainted foreach (var nonSink17 in nonSink4) { Check(nonSink17); } IEnumerator nonSink18 = nonSink4.GetEnumerator(); Check(nonSink18); nonSink3 = nonSink18.Current; Check(nonSink3); IEnumerator <KeyValuePair <string, string> > nonSink19 = nonSink1.GetEnumerator(); Check(nonSink19); var nonSink20 = nonSink19.Current; Check(nonSink20); nonSink0 = nonSink20.Value; Check(nonSink0); // async await, tainted var sink67 = Task.Run(() => "taint source"); Check(sink67); var sink68 = await sink67; Check(sink68); // async await, not tainted var nonSink21 = Task.Run(() => ""); Check(nonSink21); nonSink0 = await nonSink21; Check(nonSink0); // Interpolated string, tainted var sink69 = $"test {sink1}"; Check(sink69); // Interpolated string, not tainted nonSink0 = $"test {nonSink0}"; Check(nonSink0); // Assignment expression, exact var sink70 = sink0 = sink0; Check(sink70); // Assignment expression, not tainted nonSink0 = nonSink0 = nonSink0; Check(nonSink0); // `is` pattern, tainted if (sink70 is string sink71) { Check(sink71); } // `is` pattern, not tainted if (nonSink0 is string nonSink16) { Check(nonSink16); } // `switch` pattern, tainted switch (sink70) { case string sink72: Check(sink72); break; } // `switch` pattern, not tainted switch (nonSink0) { case string nonSink17: Check(nonSink17); break; } // Null-coalescing expressions var sink73 = nonSink0 ?? sink0; var sink74 = sink0 ?? nonSink0; Check(sink73); Check(sink74); }